diff --git a/.github/ISSUE_TEMPLATE/Bug_report.md b/.github/ISSUE_TEMPLATE/Bug_report.md new file mode 100644 index 0000000000..4d054a0f2e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Bug_report.md @@ -0,0 +1,38 @@ +--- +name: Report a bug +about: Instructions on how to report pgModeler bugs. Before report any bug please + check if someone already has submited issues similiar to yours. Duplicated issues + will be ignored. + +--- + +**Bug description** +_A clear and concise description of what the bug is._ + +**How to reproduce** +_Please, if the bug can be reproduceable describe the steps in full details. If possible provide a sample model and/or a SQL dump for test purposes._ + +**Expected behavior** +_A clear and concise description of what you expected to happen._ + +**Screenshots** +_If applicable, add screenshots to help explain your problem._ + +**Info about your desktop** + - OS: + - Version: + - Window manager: + - pgModeler version: + - Qt version: + +**Stacktrace / Debug info** +_If pgModeler crashed after the bug raised attach the stacktrace below_ + +``` + + Put the stacktrace here! + +``` + +**Additional info** +_Add any other information that you may find useful to help in the problem solving._ diff --git a/.github/ISSUE_TEMPLATE/Custom.md b/.github/ISSUE_TEMPLATE/Custom.md new file mode 100644 index 0000000000..219c04f5c1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Custom.md @@ -0,0 +1,8 @@ +--- +name: General discussion +about: For any discussion not related to bugs or feature requests please use this + one. + +--- + + diff --git a/.github/ISSUE_TEMPLATE/Feature_request.md b/.github/ISSUE_TEMPLATE/Feature_request.md new file mode 100644 index 0000000000..f3ad5eb15b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Feature_request.md @@ -0,0 +1,14 @@ +--- +name: Feature request / improvement +about: Give your suggestions for improvements to this project. + +--- + +**Feature description** +_A clear and concise description of what the problem is._ + +**Sample image** +_If the feature requested is a visual improvement, please, attach some images to make it clear._ + +**Additional info** +_Add any other context or screenshots about the feature request here._ diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ac057b6c7..e1f0ae95f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,339 @@ Change Log --------- +v0.9.2-beta1 +------ +Release date: September 2, 2019
+ +* [New] Added a routine to write a backup file during the saving of model files in order to avoid data loss in some rare cases. +* [New] Added a new action on DataManipulationForm to clear the selected items by pressing Ctrl+R. +* [New] Enabling/disabling the save model action according to the model's modified status. +* [New] The main window instance is now exposed to plugins to make the extra features development more flexible. +* [New] Avoiding selecting table items in BaseTableView::mousePressEvent which doens't contain an underlying (source) object. +* [New] Adding support to duplicate several table objects at once. +* [New] Added support to table children multiselection by using Ctrl+Shift+Click on them. +* [New] Added support to load the generated diff code in the SQL tool and automatically browsing the destination server for manual diff applying. +* [New] Added a button to create a new data manipulation form from within another data manipulation form. +* [New] Added a confirmation message before closing a database explorer widget. +* [Change] Minor adjustments in PgModelerUiNs::createOutputListItem and PgModelerUiNs::createOutputTreeItem to better display formatted messages. +* [Change] Minor improvement on CSV text copying to exclude from the buffer the hidden columns. +* [Change] Adjusted the font weight on WelcomeWidget (only for Linux). +* [Change] Minor adjustment on tool buttons font size on DataManipulationForm. +* [Change] Improved the UI of the DataManipulationForm by rearranging the tool buttons to the left of the dialog. +* [Change] Improved the clipboard text pasting on DataManipulationForm in order to parse the text as CSV when Ctrl+Shift+V is pressed. +* [Change] The filter input on SQLExecutionWidget is now automatically focused when toggling the filter widget. +* [Change] Changed the default behavior of result set filtering to Qt::MatchContains on SQLExecutionWidget. +* [Change] Avoiding showing the "Swap ids" action in popup menu when we have only columns/constraints selected +* [Change] Minor adjustment on SceneInfoWidget to avoid display dimensions of selected columns/constraints on the canvas. +* [Change] Renamed the method BaseGraphicObject::getReceiverObject to getOverlyingObject (to make sense with its counter part BaseObjctView::getUnderlyingObject) +* [Change] Avoiding clear the whole scene selection when the table is already selected and the user requested popup menu. +* [Change] Renamed BaseObjectView::getSourceObject to getUnderlyingObject. +* [Change] Improved the object protection action in ModelWidget in order to accept the multi item selection on tables. +* [Change] Changed the way the PSVI attribute is handled in xmlparser to retrieve big line numbers on a xml document. +* [Change] Improved the diff code preview allowing the user to close the dialog without going back to previous tab and click 'Cancel'. +* [Change] Minor adjustment on buttons shortcuts/tooltips on DataManipulationForm. +* [Change] Changed the way the model saving timers are controlled to avoid infinity savings on the model (when the auto saving option is disabled) making the application unusable. +* [Change] Making the mime update operation return exit code 0 even if there was errors (still displayed in the console). This will avoid the installer to abort installation when the dbm mime update fails. +* [Change] Avoiding applying fillfactor to gin indexes. +* [Change] Moved the method DatabaseImportHelper::parseIndexExpressions to Catalog class. +* [Fix] Fixed a broken diff code generation for policies. +* [Fix] Fixed the object duplication action when only a single table object is selected. +* [Fix] Fixed a bug in ModelWidget::removeObjects that was causing the removal of relationship added columns +* [Fix] Fixed the ModelWidget::configurePopupMenu to consider the table's multi item selection. +* [Fix] Fixed a false-positive diff result when dealing with timestamptz. +* [Fix] Fixed the progress calculation of dbm files loading. +* [Fix] Fixed a bug that was causing the generation of broken view code. +* [Fix] Fixed the display of index expressions on DatabaseExplorerWidget. +* [Fix] Minor fix on SQLExecutionWidget to avoid results grid to overlap command execution history widget in certain cases. + +v0.9.2-beta +------ +Release date: May 31, 2019
+ +* [New] Added support to user mapping. +* [New] Added support to foreign server. +* [New] Added support to foreign data wrapper. +* [New] Added support to reduced verbosity on diff, export and import processes in order to improve performance. +* [New] Adding missing tootip on ObjectFinderWidget. +* [New] Generic SQL objects now support dynamic references to objects which can be used in the definition code. +* [New] Added support to compare foreign servers on diff process. +* [New] Created a generic getAlterDefinition on ForeignObject. +* [New] Added ForeignServer toolbutton in NewObjectOverlayWidget. +* [New] Added support to the reverse engineering user mapping objects. +* [New] Added support to the reverse engineering foreign server objects. +* [New] Added code snippets for foreign data wrapper and foreign server. +* [New] Added support to diff user mapping. +* [New] Added support to diff foreign data wrappers. +* [New] Added support to set permissions to foreign data wrapper. +* [New] Added the WRAPPER, SERVER and MAPPING key words to sql-highlight.conf. +* [New] Added the method PgSqlType::isExactTo in order to do a full comparison (all attributes) between two data types. +* [New] Added the ability to view references to store referenced tables. This feature will cause relationships to be created between the view and the referenced tables. This is useful when we're using reverse engineering feature in which, in previous versions, couldn't determine the tables that were linked to a view. Now, with this feature a relationship is created between the view and all involved tables. +* [New] Added missing data type macaddr8. +* [New] Enabling quick clear button on several input fields. +* [New] Added support to result set filtering in the SQL execution widget. +* [New] Adding a column labeled "Comment" in TableWidget and ViewWidget to hold comments of children objects. +* [Change] Changed the shortcut of run SQL action in SQLExecutionWidget to F5. +* [Change] Changed the shortcut of tree update action in DatabaseExplorerWidget to F6. +* [Change] Change "New object" action in popup menu in order categorize object types when clicking the database object diminishing the amount of items displayed on the screen. +* [Change] Improved the object search mechanism in such way that various attributes of the object can be matched. New searchable attribute may be added in the future. +* [Change] Added missing code documentation. +* [Change] Minor adjustment on ForeignDataWrapper::getAlterDefinition. +* [Change] Minor improvement on ModelDatabaseDiffForm to show the connection id of the databases being imported in the output tree. +* [Change] Formatting server objects' attributes on DatabaseExplorerWidget. +* [Change] Minor adjustments on the icons of the buttons in ObjectsTableWidget. +* [Change] Improved the method DatabaseModel::getObjectReferences to detected foreign data wrappers as functions' references. +* [Change] Minor code refactoring on Table and View classes. +* [Change] Renamed the method Exception::getErrorType to Exception::getErrorCode. +* [Change] Improved the ModelValidationWidget in such way that is possible to operate over objects on the output list through their respective context menu (the same as in the ModelWidget). +* [Change] Now its possible to trigger the swap ids dialog for two selected objects, causing their ids to be swapped more quickly. +* [Change] Minor refactor on schema files. +* [Change] Minor attributes refactoring on several classes. +* [Change] Minor change in the PgSqlType constructor by turning some parameters optional in order to facilitate the creation of array only types. +* [Change] Minor update on disclaimer text at start of the source files. +* [Change] Allowing copied object to be pasted multiple times. This feature works only with copy/paste operation without remove the pasted objects from the clipboard, for cut/paste the behaviour is unchanged. +* [Change] Increased the maximum limit of SQL history. +* [Change] Updated the windeploy.sh and the installer scripts. +* [Change] Adjusted the installer scripts. +* [Change] Changed the windows deploy script to use Qt Installer Framework. +* [Change] Adjusted the deploy script to use Qt 5.12. +* [Change] Fixed the windows deploy script to use newer version of the compiler in 64 bits environment. +* [Change] Minor improvements in SQLToolWidget and SQLExecutionWidget to avoid segmentation faults when trying to close a execution tab while the command is still running. +* [Change] Adjusted the resize parameters in DataManipulationForm to avoid wrong dialog resizings mainly on Windows. +* [Fix] Fixed a bug in DataManipulationForm that was deleting new rows wrongly. +* [Fix] Fixed a bug that was causing domain constraints not to be extracted correctly during reverse engineering. +* [Fix] Fixed a bug that was causing a fk relationship not to be deleted if the fk tied to it was changed by the user. +* [Fix] Fixed a bug on CLI that was not fixing broken models correctly when they had no role declaration. +* [Fix] Fixed a bug that was causing tables not to be moved on the canvas using mouse. +* [Fix] Fixed a crash related to destruction of special objects on DatabaseModel::destroyObjects. +* [Fix] Fixed a bug that could crash the application when no language was specified to a funcion and the SQL/XML code was being generated. +* [Fix] Minor fix a bug on index importing. +* [Fix] Minor fix on View::isReferencingTable. +* [Fix] Fixed a crash when a query executed in SQLExecutionWidget was a DDL one or was not returning results. +* [Fix] Fixed a bug in CLI that was failing to fix model in certain cases. +* [Fix] Minor fix on buttons tooltips. +* [Fix] Fixed a bug that was causing syntax error if the last column of a table had the SQL code disabled. +* [Fix] Fixed a bug on diff process due to a missing attribute on the generation of diff code for inheritance relationships. +* [Fix] Fixed a bug when rendering several self relationships attached to the same table. +* [Fix] Fixed the CLI in order to restore the layers information when fixing a broken model. +* [Fix] Fixed a bug in object finder that was causing objects from a hidden layer to be displayed causing inconsistency on the layer state. + + +v0.9.2-alpha1 +------ +Release date: December 17, 2018
+ +* [New] Added support to scene layers. +* [New] Added support to view's columns importing in DatabaseImportHelper. +* [New] Added the ability to load view columns from database model file in DatabaseModel::createView. +* [New] Added a tab "Columns" in ReferenceWidget where the user will be able to insert columns to be used as view columns. +* [New] Added support to pagination of tables and views columns pagination. +* [New] Added a pagination toggler action on context menu at ModelWidget. +* [New] Added a fix step on CLI to remove the deprecated attribute hide-ext-attribs from tables and views xml code. +* [New] Added a configuration option to control attributes per pages in tables and views. +* [New] Added support to save collapsing states and current attributes pages to the database model file. +* [New] Added constants to reference child objects of TableObjectView. +* [New] Added the class TextPolygonItem which can be used to draw a text over a background polygon. +* [New] Added support to OLD/NEW tables aliases on triggers. +* [New] Added a hint text on RelationshipWidget to document the correct usage of default partitions. +* [New] Added support for partition attaching/detaching detection in diff process. +* [New] Added auxiliary methods in Table class in order to add/remove and retrieve partition tables. +* [New] Added support to importing partitioned/partition tables on DatabaseImportHelper. +* [New] Added a missing validation in Relationship to avoid creating other types of relationships involving partitioned or partition tables. +* [New] Added support to specify partition bounding expression on partitioning relationships. +* [New] Added support to resize grid cells to fit contents on ObjectsTableWidget. +* [New] Added a tab "Partition keys" that will handle partitioning configuration on TableWidget. +* [New] Added a method in ObjectsTableWidget to hide some horizontal header sections. +* [New] Added some validations when creating partitioning relationships. +* [New] Added support to hide columns on data manipulation dialog. +* [New] Added a transient attribute to objects DatabaseModel, Table and View in order to give a hint on the maximum count of objects held. This attribute is used to preallocate the vectors which store the children objects in order to avoid excessive memory allocation/deallocation due to vector resizing. +* [New] Added a column labeled "Alias" on all objects tables in TableWidget so the aliases of children can be displayed. +* [New] Added support to adding tabs via shortcut or corner button in the SQL Execution panel. +* [Change] Minor adjustments on MainWindow to make the overview widget to update its contents whenever the active layers change on the current model. +* [Change] Minor adjusment in ObjectsScene::addItem to make the item (in)visible according to the visibility of its related layer. +* [Change] Minor fix in AttributesTogglerItem in order to consider the parent's opacity during painting. +* [Change] Minor fixes in OperationList in order to force views to be updated correctly when operating over a table which is referenced by those objects. +* [Change] Minor adjustments on SchemaView and BaseTableView (and its children classes) to update the geometry when they switch from invisble to visible state. +* [Change] Changed views in such way so they can use the struct SimpleColumn to represent their deduced columns. +* [Change] Improved the update of views when referenced columns and tables change their structure. +* [Change] Improved database model loading times by avoiding the rendering of tables while the children objects (indexes, trigger, rules, etc) are being added. +* [Change] Removed the several operators ~ overloading that statically cast enums to their underlying type and created a template function called enum_cast in C++14 syntax. +* [Change] The zoom in/out level is now sensible on how much the user rolls the mouse wheel. +* [Change] Move the default implementation of configureObjectShadow and configureObjectSelection from BaseObjectView to BaseTableView. +* [Change] Disabling configureObjectSelection and configureObjectShadow on TableObjectView and RelationshipView. +* [Change] Minor adjustment on protected icon position on TableTitleView and TextboxView. +* [Change] Minor performance adjustments in ModelWidget. +* [Change] Minor improvement in TextboxView to use only a TextPolygonItem to hold text and the object's rectangle instead of a box and a text items. +* [Change] Replaced the sql_info_txt and sql_info_box items by a single instance of TextPolygonItem to denote SQL disabled status. +* [Change] Replace the tag_body and tag_name elements on BaseTableView by the tag_item which is a instance of TextPolygonItem. +* [Change] Improved the TableObjectView to avoid adding extra scene items. +* [Change] Improved the TableTitleView to avoid adding children items. A custom paint() method now draws them. +* [Change] Removing unused fr_FR UI translations. +* [Change] Minor update on known issues sections at README.md. +* [Change] Renamed the namespace ParsersAttributes to Attributes and its attributes has been refactored. +* [Change] Refactored all static const attributes of the classes present in pgsqltypes.h. +* [Change] Renamed PgModelerNS to PgModelerNs. +* [Change] Renamed PgModelerUiNs to PgModelerUiNs. +* [Change] Renamed XMLParser to XmlParser. +* [Change] Removing uneeded temporary QString instance created from Exception::getErroMessage call before throwing exceptions. +* [Change] Refactored static const attributes of BaseObject. +* [Change] Refactored the items in the enum ObjectType by removing the prefix 'OBJ'. +* [Change] The enums ErrorType and ObjectType were transformed into scoped enums. Also the ErrorType enum was renamed to ErrorCode. +* [Change] Code refactoring done in order to make it more close to C++14 in order to take advantage of new features introduced by that standard. +* [Change] Removed unused labels and fixed warning frame on ModelWidget. +* [Change] Minor improvements on table's attributes displaying on DatabaseExplorerWidget. +* [Change] Improved the diff process in such way to avoid generating unnecessary/noise commands related to changing types of columns to integer and setting nextval() call as default value. +* [Change] Partition tables are now displayed in the "Tables" tab at TableWidget. +* [Change] Removed the cached catalog query test feature from Catalog. +* [Change] Fine tuning on the validation of the entities used in the partitioning relationship creation. +* [Change] Forcing the partitioning relationship to be invalidated when the reference table (partitioned) partitioning type is set to null (no partitioning). +* [Change] Move the FK settings, copy options and name patterns group boxes to a dedicated tab on RelationshipWidget. +* [Change] Improved the models destruction when closing the application. +* [Change] Improved the Index/Exclude/ParitionKey elements handling by creating a generic form/grid that handles these kinds of objects (ElementsTableWidget). +* [Change] Modified the RelationshipWidget in order to handle partitioning relationships. +* [Change] Modified RelationshipConfigWidget in order to write name partterns for partitioning relationships. +* [Change] Improved the column copying and validation on class Relationship to include partitioning relationship logics. +* [Change] Improved the reverse engineering performance by avoiding update relationships as they are being imported. +* [Change] Improved the object duplication feature in ModelWidget. +* [Change] When the model is loaded it is copied to the temporary models storage as a first version of the temporary dbm file. +* [Change] Simplified the temporary models saving process by removing the thread that was controlling it. Actually the thread was unnacessary because the process was being executed in the main thread no matter if there was another thread to control the saving. +* [Change] Minor adjustment on the hint text resizing. +* [Change] Increasing to 5 minutes the period in which the temporary model saving will be executed. +* [Change] pgModeler will now use the official docs url in the help buttons. +* [Fix] Fixed a minor bug that was preventing the copy action to be enabled in DataManipulationForm. +* [Fix] Fixed some sample models to remove deprecated attributes. +* [Fix] Fixed a crash while renaming view's children objects. +* [Fix] Fixed the rendering of views which contain only a single reference that is the whole object's defintion. +* [Fix] Fixed the column name deduction for recursive views. +* [Fix] Fixed a bug that was causing crashes while configure new constraints on tables. +* [Fix] Fixed the view's resizing. +* [Fix] Fixed a regression in schema's rectangle selection. +* [Fix] Fixed the StyledTextboxView bounding rectangle. +* [Fix] Fixed an artifact when user switched on and off the compact view. +* [Fix] Fixed the Linux deploy script. +* [Fix] Fixed the macOs deploy script. +* [Fix] Fixed some compilation problems on macOs due to the usage of C++14. +* [Fix] Fixed some compilation problems on Windows due to the usage of C++14. +* [Fix] Fixed a bug in DatabaseModel::destroyObjects that could lead to segfault when the destroyed model had permissions on it. +* [Fix] Fixed a bug when importing columns which data types is some user defined type in form of array, e.g., custom_type[]. +* [Fix] Fixed a bug in SchemaParser that was causing only the first %set line in a if block to be parsed no matter that there were others %set below the same block. +* [Fix] Fixed the tooltip of some graphical objects by adding their comments and aliases. +* [Fix] Fixed the catalog query for tables to select partitioned tables correctly. +* [Fix] Fixed the catalog query for types to avoid selecting partitioned tables as being data types. +* [Fix] Fixed a bug that was causing special primary key configured on a relationship to make the original primary key of the table to disappear after disconnect the relationship. Now pgModeler stores in memory the original PK prior the connection of relationship and creation of the special PK. When disconnected the relationship, the original primary key is restored on its parent table. +* [Fix] Fixed the creation of elements (index, exclude, patition key) on DatabaseModel. +* [Fix] Fixed the class Relationship to reuse compatible columns when handling partitioning relationships. +* [Fix] Fixed the diff process in such way to create new columns with their respective COMMENT ON statement when present. +* [Fix] Fixed the detection of comment changes for columns on diff process. +* [Fix] Fixed the order of recent models saved on the file pgmodeler.conf. +* [Fix] Fixed a bug when creating a view reference as the whole view definition. +* [Fix] Minor tooltip fix on DatabaseExplorerWidget. +* [Fix] Making pgModeler honor the columns arrangement in primary keys. +* [Fix] Fixed a bug that was causing FK relationship deletion to crash the application sometimes. +* [Fix] Some fixes were done in the ModelOverviewWidget in order to support large models without exceed the screen size when configuring the size of the overall widget. +* [Fix] Fixes a bad erase in View::removeReference. +* [Fix] Fixed some bugs related to dialog size restoration in DataManipulationForm and TableWidget. + +v0.9.2-alpha +------ +Release date: August 20, 2018
+ +* [New] Added the support to cancelling SQL execution in SQLExecutionWidget. +* [New] Added support to save/restore the dialogs sizes and positions. +* [New] Added support to truncate tables in DataManipulationForm. +* [New] Added support to aliases on some graphical objects that is used in the compact view mode. +* [New] Added support to save/load object's metadata containing aliases information. +* [New] Added support to compact view of the model where graphical objects can have a more friendly name for a reduced view as well for those who don't need to see details about tables (clients of the business, for instance). +* [New] Added support to sequence options for identity columns. +* [New] Added the ability to paste CSV text from clipboard into the TableDataWidget. +* [New] Added support to bulk data edit in TableDataWidget. +* [Change] Added missing copy options on copy relationships. +* [Change] Minor adjustments on the item delegates in order draw text in the right alignment. +* [Change] Minor adjustment on buttons style in DatabaseExplorerWidget, DataManipulationForm and SQLExecutionWidget. +* [Change] Minor adjustment on OperationList::removeFromPool to avoid throw an exception when an invalid index is passed. +* [Change] Changed the behaviour of the fade in/out of relationships linked to a table by applying the effect on the other tables that are related to the selected one. +* [Change] Refactored the view editing dialog by moving the references handling form to a dedicated modal dialog. +* [Change] Improved the model loading from file by blocking signals of relationships avoiding excessive/repetive rendering of objects. The whole model is fully rendered when the file was completely loaded. +* [Change] Minor adjustment on constraints rendering at extended attributes section of tables. +* [Change] French translation update. +* [Change] Updated the other lang dictionaries with the new text brought by new releases. +* [Change] Removing icons at the top of the dialogs: DatabaseImportForm, MetaDataHandlingForm, ModelDatabaseDiffForm, ModelExportForm, ModelFixForm. +* [Change] Minor adjustments in the features of the demo version. +* [Change] Minor adjustments in the UI stylesheet. +* [Change] In DatabaseExplorerWidget the root item will come automatically selcted when browsing a database. +* [Change] Minor performance tuning when handling big models. +* [Change] Added some statistics attributes for tables on DatabaseExplorerWidget. +* [Change] Minor adjustment in NewObjectOverlayWidget by putting the tool buttons under categories. +* [Fix] Fixed a bug in ObjectFinderWidget that was forcing schemas rectangles to appear even if the flag indicating them to be visible was set to false. +* [Fix] Fixed the editing form cancel operation. Now operations done when the form was active are undone correctly. +* [Fix] Fixed a bug that was preventing to create a view containing the same name as a table but in different schema. +* [Fix] Fixed a regression that caused notices not to be shown in the output panel at SQLExecutionWidget. +* [Fix] Fixed the query catalog for policies which was causing syntax error when combining import system objects and extension objects options. +* [Fix] Fixed the disabling of some actions related to design when switching to manage view. +* [Fix] Minor fix on stylesheet in order to display the extended button on general toolbar. +* [Fix] Fix a shortcut conflict in DataManipulationform. +* [Fix] Fixed the offset of strings composing the StorageType. +* [Fix] Minor form size adjustments. +* [Fix] Minor fix in sqlexecutionwidget.ui to force the exhibition of grid headers +* [Fix] Minor fix in SQLExecutionWidget allowing the output widget to be resized to a size lower than the default one. +* [Fix] Fixed the tab order in PolicyWidget. +* [Fix] Fixed the generation of Database object source in DatabaseExplorerWidget. +* [Fix] Fixed the method BaseObjectWidget::setRequiredField to make object selector fields as required correctly. +* [Fix] Minor fix in HintTextWidget to stay on top of all widget when being displayed. +* [Fix] Fixed a bug that was not quoting extension name when needed. +* [Fix] Fixed a crash when trying to remove a fk relationship when it was created from a foreign key which references protected columns (added by relationship). +* [Fix] Fix a crash when importing CSV files into DataManipulationForm. +* [Fix] Minor typo in TableDataWidget. +* [Fix] Minor fix on schema file sql/table.sch. + +v0.9.1 +------ +Release date: May 14, 2018
+ +* [New] Added support to line selection by clicking and moving the mouse over the line numbers widget in any source code field. +* [New] The validator now checks if the model has columns referencing spatial data types and creates the postgis extension automatically when fixing the model. +* [New] Added support to RESTART IDENTITY on truncate tables in DatabaseExplorerWidget. +* [New] Added an custom option checkbox in Messagebox for general purpose usage. +* [New] Added support to diff operation in CLI. +* [New] Added support to import database from CLI. +* [New] Adding missing types regrole and regnamespace. +* [Change] Improved the copy/duplicate operation in order to copy rules, index, trigger and policies together to their parents. +* [Change] Added column names to the code completion widget used in the filter widget at DataManipulationForm. +* [Change] Improved the SQLExecutionWidget in such way that it'll display large amount of data more quickly and consuming less memory. +* [Change] Minor improvement in SQLExecutionWidget to show the amount of time took to run a query. +* [Change] Minor improvement in the text find widgets in SQL tool in order to make them closable via dedicated button. +* [Change] Improved the set tag operation in ModelWidget in order to cleanup the assigned tags to a set of objects. +* [Change] Minor improvement on DatabaseExplorerWidget to show the rls attributes labels correctly in the attributes grid. +* [Change] Refactored all the CLI options. +* [Change] Minor change in Connection::generateConnectionString in order to put the dbname param in the start of the string. +* [Change] Improved the performance of the row duplication action in DataManipulationForm. +* [Change] Minor improvement in order to update the schemas boxes when the tables have their extended attributes box toggled. +* [Change] Improved the performance of "Move to schema" operation. +* [Change] Added an busy cursor while closing a model. +* [Change] Improved the object selection in object finder. +* [Change] Changed the behaviour of select and fade buttons in ObjectFinderWidget in such way to enable the user to select/fade the objects in the listing (or not included in the results). +* [Fix] Fixed a bug when import identity columns in certain cases when the identity column was followed by another column which data type was not accepted for identity, e.g, text after smallint. +* [Fix] Fixed the check boxes disabling when dealing with identifier relationships. +* [Fix] Disabled the drag & drop for items in the side listing at ConfigurationForm. +* [Fix] Fixed the tab behavior on comment box in all editing forms of database objects. +* [Fix] Fixed the catalog query for user defined types. +* [Fix] Fixed the import of user defined types which names contains uppercase characters. +* [Fix] Minor typo fixes in CLI. +* [Fix] Fix window scaling on HiDPI/Retina screens. +* [Fix] Minor fix in Connection::getConnectionId in order to omit port when that parameter is not configured in the connection. +* [Fix] Fixed a bug in ModelExportHelper that was failing to remane the database when the command appeared. +* [Fix] Fixed a bug in CollationWidget that was referencing the collation attributes LC_??? using the wrong constant. +* [Fix] Fixed the behaviour of the message box that warns about the need of validate the model prior to export, save or diff. Now rejecting the dialog (i.e. closing it) will be considered that the user wants to proceed with the pending operation even with an invalid model. +* [Fix] Fixed the import of comments for constraints,triggers, index and rules. +* [Fix] The value input in BulkDataEditWidget will be focused as soon as the widget appears. +* [Fix] Fixed a bug in the aggregate import process. +* [Fix] Minor fix in DataManipulationForm to avoid the generation of a where clause when the filter is filled only with spaces. +* [Fix] Minor fix in the magnfier tool to use the same render hints as the canvas viewport. +* [Fix] Fixed a bug in the diff process that was trying to recreate the whole database when the "Force recreation" option was set. +* [Fix] Fixed a bug when showing the source of tables in DatabaseExplorerWidget when these objects have permissions assigned. +* [Fix] Adjusting tables position when the parent schema is moved and the alignment to grid is enabled. +* [Fix] Minor fix in the CLI menu. +* [Fix] Fixed the saving process for large models by stopping the threads related to temp models saving while the model file is being written. + v0.9.1-beta1 ------ Release date: April 6, 2018
diff --git a/README.md b/README.md index 0eff748b78..b61f33a6c2 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,11 @@ +[![](https://img.shields.io/github/license/pgmodeler/pgmodeler.svg)](https://github.com/pgmodeler/pgmodeler/blob/master/LICENSE) +[![](https://img.shields.io/github/issues-raw/pgmodeler/pgmodeler.svg)](https://github.com/pgmodeler/pgmodeler/issues) +[![](https://img.shields.io/github/issues-closed-raw/pgmodeler/pgmodeler.svg)](https://github.com/pgmodeler/pgmodeler/issues?q=is%3Aissue+is%3Aclosed) +
+![](https://img.shields.io/github/languages/code-size/pgmodeler/pgmodeler.svg) +[![](https://img.shields.io/github/tag-date/pgmodeler/pgmodeler.svg)](https://github.com/pgmodeler/pgmodeler/tags) +[![](https://img.shields.io/github/last-commit/pgmodeler/pgmodeler/0.9.2-beta.svg)](https://github.com/pgmodeler/pgmodeler/commits/0.9.2-beta) + Introduction ------------ @@ -17,7 +25,7 @@ See [LICENSE](https://github.com/pgmodeler/pgmodeler/blob/master/LICENSE) for de Donate to pgModeler ------------------- -Much effort, coffee, chocolate, time and knowledge has been devoted to this project so that a usable and constantly improved product could be delivered to the community. If you liked pgModeler and think it deserves a contribution please donate any amount (via PayPal) at [project's official site](http://pgmodeler.com.br). +Much effort, coffee, chocolate, time and knowledge is being devoted to this project so that a reliable and constantly improved product can be delivered to the community. If you liked pgModeler and think it deserves a contribution please donate any amount (via PayPal) at [project's official site](https://pgmodeler.io). Developers and Reviewers wanted! -------------------------------- @@ -27,16 +35,18 @@ pgModeler grown bigger and reached a state that its lonely developer cannot hand Compiling/Installation ---------------------- -For details about installation process from source code visit the [Installation](http://www.pgmodeler.com.br/support/installation) section. If you don't want to compile pgModeler there are binaries available for purchase at [official site](http://www.pgmodeler.com.br/download). +For details about installation process from source code visit the [Installation](https://www.pgmodeler.io/support/installation) section. If you don't want to compile pgModeler there are binaries available for purchase at [official site](http://www.pgmodeler.io/purchase). Known Issues ----------- +* pgModeler can't handle correctly the importing of complex CSV files (multilined cell values) in data manipulation form or pasting CSV content of that complexity on that dialog. +* Due to the usage of Qt's raster engine to draw objects, the process of handling objects on the canvas tends to get slower as lots of objects are created causing constant CPU usage. A heavy performance degradation can be noticed when dealing with models with ~500+ tables and/or relationships. There're plans to improve the speed of drawing operations for large models for future releases. * The diff process still presents false-positive results due its limitations. Sometimes, there is the need to run the process twice to get the full changes. * pgModeler does not fully supports the [quoted identifier notation](http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS). When using quoted identifiers only the following characters are accepted in the middle of names: a-z A-Z 0-9 _ . @ $ - / \ space. * pgModeler is unusable in sandboxed Mac OS X installations. To workaround this issue you'll need to deactivate sandbox usage to run pgModeler properly. There is no planning to adapt this tool for sandbox feature in Mac OS X. * pgModeler can't be compiled in Microsoft Visual Studio due to use of some gcc/clang extensions. -* Compiling the source using '-Wconversion' (disabled by Qt in its default) generates a lot of warnings. These warnings are harmless in 99% of times but we can't just ignore them but I don't plan to fix them in a near future (mail me for more details). +* Compiling the source using '-Wconversion' (disabled by Qt in its defaults) generates a lot of warnings. These warnings are harmless in 99% of times but we can't just ignore them but I don't plan to fix them in a near future. * pgModeler sometimes can crash during the export, import or validation process due to some threaded operations that, depending on size and arrange of the model, causes race conditions. * Due to particularities on executing bundles on MacOSX the file association does not work correctly on this system. So it's not possible to open a model file by clicking it on Finder. diff --git a/RELEASENOTES.md b/RELEASENOTES.md index 3840d69f48..4768815981 100644 --- a/RELEASENOTES.md +++ b/RELEASENOTES.md @@ -1,50 +1,40 @@ -v0.9.1-beta1 +v0.9.2-beta1 ------ -Release date: April 6, 2018
-Changes since: v0.9.1-beta
- -Summary: finally we've reached the last beta release of the 0.9.1! This time pgModeler brings important fixes and new features requested long ago which are finally implemented in experimental stage.
- -The first new feature we have in this release is the support to multiples relationships for the same pair of tables. In previous versions, pgModeler would refuse to create a second relationship between the tables A and B. From now on, pgModeler will accept the creation of one-to-many and many-to-many relationships linking A and B more then once. For the other kinds of relationships (generalization, copy, one-to-one) the old rule is still valid: only one relationship per table pair is accepted.
- -Some missing features of PostgreSQL are present in this version too being them: row level security (RLS) and identity columns. For RLS, introduced in PostgreSQL 9.5, we have added the related options to toggle it in tables (ENABLE|FORCE RLS) as well the support to policy objects which are the main part of this new security modality. The identity columns, introduced in PostgreSQL 10, are now fully supported by pgModeler and you can make use of them from the column editing form.
- -Other new feature is the support to multiple check constraints by domains. Actually, this is more a patch than a new feature because pgModeler was unaware that domains could support more than one check constraint, so we have fixed that now.
- -Now, talking about changes, we fixed an old missinterpretation of the PostgreSQL's documentations by changing the way extensions are stored in the database model. Previously, this kind of objects were stored at schemas level but the right way to store them is at database level. So now instead of seeing extensions in the schema's subtree you'll see them in the database subtree. All validation rules, export, import and diff processes were fixed in such way to reflect the right way to treat these objects.
- -Another important change, and that one is related to an annoying behaviour of the tool, is that pgModeler will silently ignore the absence of the plugins folder and proceed with the normal startup avoiding the display of a message box regarding the missing folder and automatically disabling the plugins search mechanism.
- -In the fixes section, we've included a patch for a bug that was causing recurrent crashes on macOS when the user tried to load a second model file making almost impossible the working on two or more database models at once. Also, we've patched the reverse engineering in such way to avoid the duplication of data types related to tables, sequences and views which was causing problems in the validation process. Another fix was done in the diff process that was generating a malformed DROP command for extensions.
- -The set of changes of this release has 47 entries between new features, changes, improvements and bug fixes. Below we highlight some of them, for the complete list, please, consider reading the CHANGELOG.md.
- -* [New] Added the ability to create multiples one-to-many and many-to-many relatationships between the same pair of tables. -* [New] Added the ability to use more special ascii chars in the middle of object names. -* [New] Added support to multi line comments in UI. -* [New] Added full support to row level security (RLS), including export, import and diff of this kind of object. -* [New] Added support to bulk data editing in DataManipulationForm. -* [New] Added an option to diff process to force the generation of DROP commands for columns and constraints even if the missing objects need to be preserved. This is useful to work with partial models and the user need to remove columns/constraints and preserve the rest of objects. -* [New] Added support to identity columns (PostgreSQL 10). -* [New] Added the support to BYPASSRLS option on roles. -* [New] Added support to IS_TEMPLATE and ALLOW_CONNECTIONS options in database object. -* [New] Added the procedures to fix old style domains in CLI. -* [New] Added support to multiple check constraint in domains. -* [New] Added support to sort items alphabetically (ascending) or by oid in DatabaseExplorerWidget. -* [Change] Changed the input mode of the password field in ConnectionsConfigWidget in order to hide the passwords in the form. NOTE: the passwords are still in plain text in the config file. -* [Change] Moved extensions from schema level to database level in order to reproduce better the PostgreSQL's behavior. -* [Change] In GeneralConfigWidget when restoring default settings the default settings for syntax highlight are restored as well. -* [Change] pgModeler will not try to create the plugins path anymore. This will avoid constant error messages during startup. Now, it'll silently ignore the absence of that folder and skip the plugin loading. -* [Change] Improved the source editing in external application. The use is informed about the app running state and the contents for the source editor field are locked until the user closes the external app. -* [Fix] Fixed the query catalog for built-in types to include the types related to domains. -* [Fix] Fixed the extension creation, allowing only one instance of the named extension per database no matter the schema used to allocate its children objects. -* [Fix] Fixed a bug when dropping Functions in DatabaseExplorerWidget. -* [Fix] Fixed a bug that was causing the disabling of connections for database models created prior to 0.9.1-beta1. -* [Fix] Fixed a bug on import process that was wrongly creating types derivated from tables/sequence/views causing duplication problems during validation. -* [Fix] Fixed a crash on macOs when opening a second model. -* [Fix] Fixed an issue in diff process that was generating a malformed DROP command for extensions. -* [Fix] Fixed the diff for domains which contain multiple check constraints. -* [Fix] Fixed a bug that was not selecting the correct spatial type in the widget. -* [Fix] Fixed a conflict of shortcuts in DatabaseExplorerWidget. Now F5 updates a leaf/subtree and Alt+F5 performs quick refresh of the tree. -* [Fix] Fixed a problem with sqlexecutionwidget.ui that is not building properly in Qt 5.10. +Release date: September 2, 2019
+Changes since: v0.9.2-beta
+ +Summary: this release brings a few improvements as we're starting to deaccelarate the development of new features and concentrating on minor changes and bug fixes until the stable 0.9.2 is done.
+ +The main focus was to improve the data manipulation form, fix some small UI problems and bugs on some features detected previously.
+ +The file saving was patched in such way to write a backup file prior to the saving of a model to avoid data loss in rare circumstances (mainly on macOS systems).
+ +The diff process was also fixed due to a bug that was returning some false-positive results when dealing with timestamptz columns.
+ +This version also brings the ability to select multiple table children (columns, contraints, triggers, etc) and operate over them by using the design popup menu.
+ +Finally, some changes of this version are detailed below. For the complete list of changes/fixes, please, read the CHANGELOG.md.
+ +* [New] Added a routine to write a backup file during the saving of model files in order to avoid data loss in some rare cases. +* [New] Added a new action on DataManipulationForm to clear the selected items by pressing Ctrl+R. +* [New] Adding support to duplicate several table objects at once. +* [New] Added support to table children multiselection by using Ctrl+Shift+Click on them. +* [New] Added support to load the generated diff code in the SQL tool and automatically browsing the destination server for manual diff applying. +* [New] Added a button to create a new data manipulation form from within another data manipulation form. +* [Change] Minor improvement on CSV text copying to exclude from the buffer the hidden columns. +* [Change] Improved the UI of the DataManipulationForm by rearranging the tool buttons to the left of the dialog. +* [Change] Improved the clipboard text pasting on DataManipulationForm in order to parse the text as CSV when Ctrl+Shift+V is pressed. +* [Change] Minor adjustment on SceneInfoWidget to avoid display dimensions of selected columns/constraints on the canvas. +* [Change] Improved the object protection action in ModelWidget in order to accept the multi item selection on tables. +* [Change] Improved the diff code preview allowing the user to close the dialog without going back to previous tab and click 'Cancel'. +* [Change] Changed the way the model saving timers are controlled to avoid infinity savings on the model (when the auto saving option is disabled) making the application unusable. +* [Fix] Fixed a broken diff code generation for policies. +* [Fix] Fixed the object duplication action when only a single table object is selected. +* [Fix] Fixed a bug in ModelWidget::removeObjects that was causing the removal of relationship added columns +* [Fix] Fixed the ModelWidget::configurePopupMenu to consider the table's multi item selection. +* [Fix] Fixed a false-positive diff result when dealing with timestamptz. +* [Fix] Fixed the progress calculation of dbm files loading. +* [Fix] Fixed a bug that was causing the generation of broken view code. +* [Fix] Fixed the display of index expressions on DatabaseExplorerWidget. +* [Fix] Minor fix on SQLExecutionWidget to avoid results grid to overlap command execution history widget in certain cases. diff --git a/conf/defaults/example.dbm b/conf/defaults/example.dbm index 38f936f7ce..91f607f44e 100644 --- a/conf/defaults/example.dbm +++ b/conf/defaults/example.dbm @@ -36,7 +36,7 @@ CAUTION: Do not modify this file unless you know what you are doing. - +
@@ -65,7 +65,7 @@ CAUTION: Do not modify this file unless you know what you are doing. -
+
@@ -159,7 +159,7 @@ CAUTION: Do not modify this file unless you know what you are doing. -
+
diff --git a/conf/defaults/objects-style.conf b/conf/defaults/objects-style.conf index 79480a3415..5cc006fef7 100644 --- a/conf/defaults/objects-style.conf +++ b/conf/defaults/objects-style.conf @@ -19,6 +19,7 @@ + @@ -51,6 +52,7 @@ + diff --git a/conf/defaults/pgmodeler.conf b/conf/defaults/pgmodeler.conf index 0d280ddfa2..e4436cd3b6 100644 --- a/conf/defaults/pgmodeler.conf +++ b/conf/defaults/pgmodeler.conf @@ -36,9 +36,13 @@ show-page-delimiters="true" align-objs-to-grid="true" min-object-opacity="10" + attribs-per-page="10" + ext-attribs-per-page="5" history-max-length="1000" use-curved-lines="true" - max-result-rows="20000"/> + compact-view="false" + save-restore-geometry="true" + low-verbosity="false"/> diff --git a/conf/defaults/relationships.conf b/conf/defaults/relationships.conf index 11e005177f..65fadde900 100644 --- a/conf/defaults/relationships.conf +++ b/conf/defaults/relationships.conf @@ -4,7 +4,7 @@ Unexpected results may occur if the code is changed deliberately. --> - + @@ -12,5 +12,6 @@ + diff --git a/conf/defaults/snippets.conf b/conf/defaults/snippets.conf index b53b039f9b..fa4075ff22 100644 --- a/conf/defaults/snippets.conf +++ b/conf/defaults/snippets.conf @@ -1,9 +1,167 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + - - - + + + @@ -59,56 +323,50 @@ $ob [ DEFAULT ] {default-value} $cb $br $ob [ CONSTRAINT ] {constraint} $cb $br $ob [ NOT NULL | NULL | CHECK ] ({expression}) $cb $br]]> - - - + + + - - - - - - - - - - - - - + + + + + + + + + - + - + + + + + - - - - - - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $br $br [-- Function returns a single result or results of the same type ] $br -RETURNS $ob [ SET OF ] $cb $sp {return-type} $br +RETURNS $ob [ SET OF ] $cb $sp {return-type} $br [-- Function returns a table ] $br [RETURNS TABLE (] {col-name} $sp {col-type} $ob [, ...] $cb ) $br $br [-- Definition for C based function ] $br -[AS ] '{library}' [, ] '{definition}' $br +[AS ] '{library}' [, ] '{definition}' $br [-- Definition for SQL or PL/PGSQL based function ] $br [AS $$] $br @@ -149,22 +467,12 @@ $ob [ NOT ] $cb LEAKPROOF $br [ROWS ] {row-amount} $br [LANGUAGE ] {language} $br]]> - - - + + + - + +[LANGUAGE plpgsql] $br]]> - + - - - - - - - - - - - - - - - - - - - - +[LANGUAGE sql] $br]]> - - - - - - + + - + - - - - - - - - - - - - - + - + - + - - + + - + + + + - +$ob [ ENCRYPTED | UNENCRYPTED ] $cb [ PASSWORD ] '{new-password}' $br +[VALID UNTIL ] '{validity}' $br]]> - + - - + +$ob [ ENCRYPTED | UNENCRYPTED ] $cb [ PASSWORD ] '{password}' $br +[VALID UNTIL ] '{validity}' $br +[IN ROLE ] {ref-roles} $br +[ROLE ] {member-roles} $br +[ADMIN ] {admin-roles} $br]]> - + - - + - - - - - - + %if ({cycle}=="false") %then [NO ] %end CYCLE $br [OWNED BY ] %if {owner-col} %then {owner-col} %else [ NONE] %end $br]]> - - - - + + + [OWNED BY ] %if {owner-col} %then {owner-col} %else [ NONE] %end $br]]> - - - + + + - - + + - - + + -%if ({constraint}=="true") %then - [ CONSTRAINT ] -%end + + + -[ TRIGGER ] {name} $br + + + -{firing-type} + + + + + + + + + + - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - + + - - - - - - - - - - - - - - + + - - + + - - - - - - - - - - - - + + - - - - - - + + - - + + - - + + - - - - - - - - diff --git a/conf/defaults/sql-highlight.conf b/conf/defaults/sql-highlight.conf index b02abf0314..432039a509 100644 --- a/conf/defaults/sql-highlight.conf +++ b/conf/defaults/sql-highlight.conf @@ -9,7 +9,7 @@ --> - + @@ -17,7 +17,6 @@ - @@ -85,19 +84,14 @@ - + - - - - + + @@ -123,6 +117,7 @@ + @@ -146,6 +141,7 @@ + @@ -164,6 +160,7 @@ + @@ -185,6 +182,7 @@ + @@ -198,6 +196,8 @@ + + @@ -206,6 +206,7 @@ + @@ -234,6 +235,7 @@ + @@ -245,18 +247,22 @@ + + + + @@ -276,10 +282,12 @@ + + @@ -287,6 +295,7 @@ + @@ -306,7 +315,9 @@ + + @@ -328,6 +339,7 @@ + @@ -339,6 +351,7 @@ + @@ -351,6 +364,8 @@ + + @@ -374,6 +389,7 @@ + @@ -382,13 +398,16 @@ + + + QWidget } BaseForm, MessageBox, ConfigurationForm, ModelExportForm, ModelDatabaseDiffForm, DatabaseImportForm { - /*background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #F6F5F4, stop: 1 #E0DFDE);*/ padding-bottom: 2px; } @@ -33,13 +32,15 @@ UpdateNotifierWidget > QFrame border-radius: 5px; } -AboutWidget > QFrame > QLabel#title_lbl, -AboutWidget > QFrame > QLabel#slogan_lbl, +AboutWidget > QFrame > QLabel#title_lbl, AboutWidget > QFrame > QLabel#about_lbl, -AboutWidget > QFrame > QLabel#pgmodeler_ver_lbl, AboutWidget > QFrame > QLabel#build_lbl, AboutWidget > QFrame > QLabel#copyright_lbl { - color: #000; + color: #000; +} + +AboutWidget > QFrame > QLabel#pgmodeler_ver_lbl { + color: #4C7DD0; } DonateWidget > QFrame > QLabel#title_lbl, @@ -75,25 +76,24 @@ NewObjectOverlayWidget > QFrame { border-radius: 6px } -NewObjectOverlayWidget > QFrame > QWidget > QToolButton +NewObjectOverlayWidget > QFrame > QGroupBox > QWidget > QToolButton { color: #000; font-style: italic; - /*font-size: 8pt;*/ border-radius: 6px; min-width: 110px } -NewObjectOverlayWidget > QFrame > QWidget > QToolButton:hover +NewObjectOverlayWidget > QFrame > QGroupBox > QWidget > QToolButton:hover { font-weight: bold; background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #80e0e0e0 , stop: 1 #80ffffff); border: 1px solid #c0a0a0a0; - color: #000; + color: #000; } -NewObjectOverlayWidget > QFrame > QWidget > QToolButton:pressed +NewObjectOverlayWidget > QFrame > QGroupBox > QWidget > QToolButton:pressed { background-color: #80023d86; border: 1px solid #012149; @@ -105,7 +105,7 @@ QWidget#bg_widget { background-repeat: repeat-xy; } -QMenuBar { +QMenuBar { background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #6394DE, stop: 1 #4C7DD0); border: transparent; } @@ -137,7 +137,7 @@ QMenuBar::item:disabled { color: #505050; } -QToolBar#general_tb { +QToolBar#general_tb { background-image: url(":/styles/styles/toolbar_bg.png"); background-repeat: repeat-y; border-bottom: 1px solid #505050; @@ -155,10 +155,6 @@ QToolBar#control_tb > QToolButton::menu-indicator border: transparent; } -QHeaderView { - /*font-size: 8pt;*/ -} - WelcomeWidget > QToolButton { border: transparent; @@ -177,18 +173,39 @@ WelcomeWidget > QToolButton::menu-indicator } QToolBar#general_tb > QToolButton -{ - /*font-size: 7.5pt;*/ - font-weight: bold; +{ color: #f0f0f0; min-width: 65px; - margin-bottom: 8px; - margin-left: 0; - margin-right: 0; + margin-bottom: 2px; + margin-top: 2px; + margin-left: 3px; + margin-right: 3px; +} + +QToolBar#general_tb +{ + border-right: 1px solid #202020; } -QToolBar#general_tb > QToolButton:hover, WelcomeWidget > QToolButton:hover -{ +QToolBar#general_tb::separator +{ + background-color: #80404040; + border-top: 1px solid #202020; + border-left: 1px solid #202020; + border-right: 1px solid #606060; + border-bottom: 1px solid #606060; + height: 1px; +} + +QToolBar#general_tb > QToolButton#qt_toolbar_ext_button +{ + min-height: 20px; +} + +QToolBar#general_tb > QToolButton:hover, +WelcomeWidget > QToolButton:hover, +QToolBar#general_tb > QToolButton#qt_toolbar_ext_button +{ color: #fff; background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #80606060 , stop: 1 #80A0A0A0); border-top: 1px solid qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #A0A0A0 , stop: 1 #606060); @@ -197,23 +214,27 @@ QToolBar#general_tb > QToolButton:hover, WelcomeWidget > QToolButton:hover border-bottom: 1px solid #606060; } -QToolBar#general_tb > QToolButton:pressed, WelcomeWidget > QToolButton:pressed, QToolBar#general_tb > QToolButton:checked -{ - background-image: url(":/styles/styles/btn_checked_bg.png"); - border-right: 1px solid #404040; - border-bottom: 1px solid #404040; - border-left: 1px solid #404040; - border-top: 1px solid #404040; - padding: 0; - color: #000 +QToolBar#general_tb > QToolButton:checked, +QToolBar#general_tb > QToolButton:pressed, +WelcomeWidget > QToolButton:pressed, +QToolBar#general_tb > QToolButton#qt_toolbar_ext_button:hover, +QToolBar#general_tb > QToolButton#qt_toolbar_ext_button:pressed +{ + color: #fff; + background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #804aa5ff , stop: 1 #8081cdff); + border-top: 1px solid qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #48a5fc , stop: 1 #3a86cc); + border-left: 1px solid qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #48a5fc , stop: 1 #3a86cc); + border-right: 1px solid #3a86cc; + border-bottom: 1px solid #3a86cc; } WelcomeWidget > QToolButton:disabled { color: #404040; } + QToolBar#general_tb > QToolButton:disabled -{ +{ color: #808080; } @@ -283,7 +304,7 @@ QToolBar#update_tb { border-color: #808080; } -QToolBar#update_tb > QToolButton +QToolBar#update_tb > QToolButton { min-width: 25px; max-width: 200px; @@ -321,67 +342,7 @@ QToolBar#update_tb::separator { margin-right: 2px; } - -/* QWidget#tool_btns_bar_wgt { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #FFFFFF , stop: 1 #E6E6E6); - border-top: 1px solid #808080; - border-right: 1px solid #808080; - border-bottom: 1px solid #808080; - margin: 0; -} */ - -/* QWidget#tool_btns_bar_wgt > QPushButton { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #F1F1F1, stop: 1 #A1A1A1); - margin-top: 5px; - margin-bottom: 5px; - padding: 2px; - padding-left: 5px; - padding-right: 5px; - border: 1px solid #a0a0a0; - border-radius: 2px; - font-size: 8pt; - color: #000; -} */ - -/*QWidget#tool_btns_bar_wgt > QPushButton:hover { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #1E65AB, stop: 1 #257BD1); - border: 1px solid #175089; - color: #FFFFFF; -} */ - -/*QWidget#tool_btns_bar_wgt > QPushButton#validation_btn { - margin-left: 5px; -} - -QWidget#tool_btns_bar_wgt > QPushButton#find_obj_btn { - margin-left: 5px; -} - -QWidget#tool_btns_bar_wgt > QPushButton#sql_tool_btn { - margin-left: 5px; -} - -QWidget#tool_btns_bar_wgt > QPushButton#objects_btn{ - margin-right: 5px; -} - -QWidget#tool_btns_bar_wgt > QPushButton#operations_btn{ - margin-right: 5px; -} */ - -/*QWidget#tool_btns_bar_wgt > QPushButton:checked { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #606060, stop: 1 #A0A0A0); - border-color: #808080; - color: #000; -} - -QWidget#tool_btns_bar_wgt > QPushButton:checked:hover { - color: #ffffff; -} */ - QTabWidget#models_tbw::pane { - /*background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #FFFFFF , stop: 1 #E6E6E6);*/ - /*border-bottom: 1px solid #d0d0d0;*/ border-top: transparent; } @@ -403,7 +364,6 @@ QTabWidget#models_tbw > QTabBar::close-button:hover { QTabWidget#models_tbw > QTabBar::tab { border: 1px solid #C4C4C4; text-align: center; - /*font-size: 8.5pt;*/ min-height: 30px; min-width: 50px; padding-left: 5; @@ -436,25 +396,6 @@ QTabWidget#models_tbw > QTabBar::tab:selected { margin-top: 0px; } -/*QSplitter#h_splitter::handle { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #FAFAFA , stop: 1 #E0E0E0); -} */ - -/*QSplitter#h_splitter_opr_objs::handle { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #FAFAFA , stop: 1 #E0E0E0); - border-left: 1px solid #404040; -}*/ - -/*QSplitter#v_splitter::handle, QSplitter#v_splitter1::handle,QSplitter#v_splitter2::handle { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #FAFAFA , stop: 1 #E0E0E0); -} */ - -SQLToolWidget > QWidget#bg_frame { - /*background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #FAFAFA , stop: 1 #E0E0E0);*/ - /*border-bottom: 1px solid #d0d0d0; - border-top: transparent;*/ -} - /* Floating hint widget member of HintTextWidget */ HintTextWidget { @@ -471,7 +412,6 @@ HintTextWidget > QWidget HintTextWidget > QWidget > QLabel { color: #0000c0; - /*font-size: 8pt;*/ } QTabWidget#databases_tbw > QTabBar::close-button { @@ -503,3 +443,60 @@ QTabWidget#sql_exec_tbw > QTabBar::close-button:hover { height: 16px; image: url(':/styles/styles/close_tab_hover.png'); } + +QWidget#menu_title_wgt { + background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffffff , stop: 1 #E6E6E6); + border: 1px solid #c0a0a0a0; +} + +/* DataManipulationForm styles */ +QWidget#bnts_parent_wgt { + background-image: url(":/styles/styles/toolbar_bg.png"); + background-repeat: repeat-y; + border: 1px solid #202020; + padding: 0; + margin: 0; +} + +QWidget#bnts_parent_wgt > QToolButton +{ + color: #fff; + margin-left: 3px; + margin-right: 3px; +} + +QWidget#bnts_parent_wgt > QToolButton:disabled +{ + color: #808080; +} + +QWidget#bnts_parent_wgt > QToolButton:hover +{ + color: #fff; + background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #80606060 , stop: 1 #80A0A0A0); + border-top: 1px solid qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #A0A0A0 , stop: 1 #606060); + border-left: 1px solid qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #A0A0A0 , stop: 1 #606060); + border-right: 1px solid #808080; + border-bottom: 1px solid #606060; +} + +QWidget#bnts_parent_wgt > QToolButton:checked, +QWidget#bnts_parent_wgt > QToolButton:pressed +{ + color: #fff; + background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #804aa5ff , stop: 1 #8081cdff); + border-top: 1px solid qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #48a5fc , stop: 1 #3a86cc); + border-left: 1px solid qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #48a5fc , stop: 1 #3a86cc); + border-right: 1px solid #3a86cc; + border-bottom: 1px solid #3a86cc; +} + +QWidget#bnts_parent_wgt > QFrame +{ + background-color: #80404040; + border-top: 1px solid #202020; + border-left: 1px solid #202020; + border-right: 1px solid #606060; + border-bottom: 1px solid #606060; + height: 1px; +} diff --git a/conf/dtd/objects-style.dtd b/conf/dtd/objects-style.dtd index 52e2f8d93e..0f913cbfda 100644 --- a/conf/dtd/objects-style.dtd +++ b/conf/dtd/objects-style.dtd @@ -15,7 +15,7 @@ + constraints|object-type|ref-table|ref-column|alias|pos-info|tag|policy) "table-name"> @@ -23,4 +23,4 @@ + pos-info|tag|placeholder|policy) "table-title"> diff --git a/conf/dtd/pgmodeler.dtd b/conf/dtd/pgmodeler.dtd index cdea216667..8d829ddb6a 100644 --- a/conf/dtd/pgmodeler.dtd +++ b/conf/dtd/pgmodeler.dtd @@ -2,7 +2,7 @@ CAUTION: Do not modify this file directly on it's code unless you know what you are doing. Unexpected results may occur if the code is changed deliberately. --> - + @@ -39,23 +39,28 @@ + + - + + + + - + @@ -66,5 +71,11 @@ + + + + + + diff --git a/conf/dtd/relationships.dtd b/conf/dtd/relationships.dtd index 08590b5ebb..5d68890dd6 100644 --- a/conf/dtd/relationships.dtd +++ b/conf/dtd/relationships.dtd @@ -16,7 +16,7 @@ - + diff --git a/conf/dtd/snippets.dtd b/conf/dtd/snippets.dtd index 56ec1c01a9..cd4831a649 100644 --- a/conf/dtd/snippets.dtd +++ b/conf/dtd/snippets.dtd @@ -13,5 +13,5 @@ + extension|eventtrigger|general|policy|foreigndatawrapper|foreignserver|usermapping) "general"> diff --git a/conf/example.dbm b/conf/example.dbm index 38f936f7ce..91f607f44e 100644 --- a/conf/example.dbm +++ b/conf/example.dbm @@ -36,7 +36,7 @@ CAUTION: Do not modify this file unless you know what you are doing. -
+
@@ -65,7 +65,7 @@ CAUTION: Do not modify this file unless you know what you are doing. -
+
@@ -159,7 +159,7 @@ CAUTION: Do not modify this file unless you know what you are doing. -
+
diff --git a/conf/objects-style.conf b/conf/objects-style.conf index 79480a3415..5cc006fef7 100644 --- a/conf/objects-style.conf +++ b/conf/objects-style.conf @@ -19,6 +19,7 @@ + @@ -51,6 +52,7 @@ + diff --git a/conf/pgmodeler.conf b/conf/pgmodeler.conf index 0d280ddfa2..e4436cd3b6 100644 --- a/conf/pgmodeler.conf +++ b/conf/pgmodeler.conf @@ -36,9 +36,13 @@ show-page-delimiters="true" align-objs-to-grid="true" min-object-opacity="10" + attribs-per-page="10" + ext-attribs-per-page="5" history-max-length="1000" use-curved-lines="true" - max-result-rows="20000"/> + compact-view="false" + save-restore-geometry="true" + low-verbosity="false"/> diff --git a/conf/relationships.conf b/conf/relationships.conf index 586d01f869..2714c6e59f 100644 --- a/conf/relationships.conf +++ b/conf/relationships.conf @@ -4,7 +4,7 @@ Unexpected results may occur if the code is changed deliberately. --> - + @@ -12,5 +12,6 @@ + diff --git a/conf/schemas/objects-style.sch b/conf/schemas/objects-style.sch index 51079b3b24..e23da22923 100644 --- a/conf/schemas/objects-style.sch +++ b/conf/schemas/objects-style.sch @@ -21,6 +21,7 @@ [ ] $br [ ] $br [ ] $br +[ ] $br [ ] $br [ ] $br [ ] $br @@ -52,6 +53,7 @@ $br [ ] $br [ ] $br [ ] $br +[ ] $br [ ] $br [ ] $br [ ] $br diff --git a/conf/schemas/pgmodeler.sch b/conf/schemas/pgmodeler.sch index d68dd6ad17..ead482f0f1 100644 --- a/conf/schemas/pgmodeler.sch +++ b/conf/schemas/pgmodeler.sch @@ -45,12 +45,13 @@ $sp [ $br %end +%if {widgets-geometry} %then + $sp $br + $sp {widgets-geometry} + $sp $br +%end + $br diff --git a/conf/schemas/widget.sch b/conf/schemas/widget.sch index 95626c56fd..a76f05a063 100644 --- a/conf/schemas/widget.sch +++ b/conf/schemas/widget.sch @@ -20,6 +20,19 @@ $tb [ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + - - - + + + @@ -59,56 +323,50 @@ $ob [ DEFAULT ] {default-value} $cb $br $ob [ CONSTRAINT ] {constraint} $cb $br $ob [ NOT NULL | NULL | CHECK ] ({expression}) $cb $br]]> - - - + + + - - - - - - - - - - - - - + + + + + + + + + - + - + + + + + - - - - - - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $br $br [-- Function returns a single result or results of the same type ] $br -RETURNS $ob [ SET OF ] $cb $sp {return-type} $br +RETURNS $ob [ SET OF ] $cb $sp {return-type} $br [-- Function returns a table ] $br [RETURNS TABLE (] {col-name} $sp {col-type} $ob [, ...] $cb ) $br $br [-- Definition for C based function ] $br -[AS ] '{library}' [, ] '{definition}' $br +[AS ] '{library}' [, ] '{definition}' $br [-- Definition for SQL or PL/PGSQL based function ] $br [AS $$] $br @@ -149,22 +467,12 @@ $ob [ NOT ] $cb LEAKPROOF $br [ROWS ] {row-amount} $br [LANGUAGE ] {language} $br]]> - - - + + + - + +[LANGUAGE plpgsql] $br]]> - + - - - - - - - - - - - - - - - - - - - - +[LANGUAGE sql] $br]]> - - - - - - + + - + - - - - - - - - - - - - - + - + - + - - + + - + + + + - +$ob [ ENCRYPTED | UNENCRYPTED ] $cb [ PASSWORD ] '{new-password}' $br +[VALID UNTIL ] '{validity}' $br]]> - + - - + +$ob [ ENCRYPTED | UNENCRYPTED ] $cb [ PASSWORD ] '{password}' $br +[VALID UNTIL ] '{validity}' $br +[IN ROLE ] {ref-roles} $br +[ROLE ] {member-roles} $br +[ADMIN ] {admin-roles} $br]]> - + - - + - - - - - - + %if ({cycle}=="false") %then [NO ] %end CYCLE $br [OWNED BY ] %if {owner-col} %then {owner-col} %else [ NONE] %end $br]]> - - - - + + + [OWNED BY ] %if {owner-col} %then {owner-col} %else [ NONE] %end $br]]> - - - + + + - - + + - - + + -%if ({constraint}=="true") %then - [ CONSTRAINT ] -%end + + + -[ TRIGGER ] {name} $br + + + -{firing-type} + + + + + + + + + + - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - + + - - - - - - - - - - - - - - + + - - + + - - - - - - - - - - - - + + - - - - - - + + - - + + - - + + - - - - - - - - diff --git a/conf/sql-highlight.conf b/conf/sql-highlight.conf index b02abf0314..432039a509 100644 --- a/conf/sql-highlight.conf +++ b/conf/sql-highlight.conf @@ -9,7 +9,7 @@ --> - + @@ -17,7 +17,6 @@ - @@ -85,19 +84,14 @@ - + - - - - + + @@ -123,6 +117,7 @@ + @@ -146,6 +141,7 @@ + @@ -164,6 +160,7 @@ + @@ -185,6 +182,7 @@ + @@ -198,6 +196,8 @@ + + @@ -206,6 +206,7 @@ + @@ -234,6 +235,7 @@ + @@ -245,18 +247,22 @@ + + + + @@ -276,10 +282,12 @@ + + @@ -287,6 +295,7 @@ + @@ -306,7 +315,9 @@ + + @@ -328,6 +339,7 @@ + @@ -339,6 +351,7 @@ + @@ -351,6 +364,8 @@ + + @@ -374,6 +389,7 @@ + @@ -382,13 +398,16 @@ + + + QWidget } BaseForm, MessageBox, ConfigurationForm, ModelExportForm, ModelDatabaseDiffForm, DatabaseImportForm { - /*background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #F6F5F4, stop: 1 #E0DFDE);*/ padding-bottom: 2px; } @@ -34,12 +33,14 @@ UpdateNotifierWidget > QFrame } AboutWidget > QFrame > QLabel#title_lbl, -AboutWidget > QFrame > QLabel#slogan_lbl, AboutWidget > QFrame > QLabel#about_lbl, -AboutWidget > QFrame > QLabel#pgmodeler_ver_lbl, AboutWidget > QFrame > QLabel#build_lbl, AboutWidget > QFrame > QLabel#copyright_lbl { - color: #000; + color: #000; +} + +AboutWidget > QFrame > QLabel#pgmodeler_ver_lbl { + color: #4C7DD0; } DonateWidget > QFrame > QLabel#title_lbl, @@ -75,16 +76,15 @@ NewObjectOverlayWidget > QFrame { border-radius: 6px } -NewObjectOverlayWidget > QFrame > QWidget > QToolButton +NewObjectOverlayWidget > QFrame > QGroupBox > QWidget > QToolButton { color: #000; font-style: italic; - /*font-size: 8pt;*/ border-radius: 6px; min-width: 110px } -NewObjectOverlayWidget > QFrame > QWidget > QToolButton:hover +NewObjectOverlayWidget > QFrame > QGroupBox > QWidget > QToolButton:hover { font-weight: bold; background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #80e0e0e0 , stop: 1 #80ffffff); @@ -93,7 +93,7 @@ NewObjectOverlayWidget > QFrame > QWidget > QToolButton:hover } -NewObjectOverlayWidget > QFrame > QWidget > QToolButton:pressed +NewObjectOverlayWidget > QFrame > QGroupBox > QWidget > QToolButton:pressed { background-color: #80023d86; border: 1px solid #012149; @@ -155,10 +155,6 @@ QToolBar#control_tb > QToolButton::menu-indicator border: transparent; } -QHeaderView { - /*font-size: 8pt;*/ -} - WelcomeWidget > QToolButton { border: transparent; @@ -178,16 +174,37 @@ WelcomeWidget > QToolButton::menu-indicator QToolBar#general_tb > QToolButton { - /*font-size: 7.5pt;*/ - font-weight: bold; color: #f0f0f0; min-width: 65px; - margin-bottom: 8px; - margin-left: 0; - margin-right: 0; + margin-bottom: 2px; + margin-top: 2px; + margin-left: 3px; + margin-right: 3px; +} + +QToolBar#general_tb +{ + border-right: 1px solid #202020; +} + +QToolBar#general_tb::separator +{ + background-color: #80404040; + border-top: 1px solid #202020; + border-left: 1px solid #202020; + border-right: 1px solid #606060; + border-bottom: 1px solid #606060; + height: 1px; +} + +QToolBar#general_tb > QToolButton#qt_toolbar_ext_button +{ + min-height: 20px; } -QToolBar#general_tb > QToolButton:hover, WelcomeWidget > QToolButton:hover +QToolBar#general_tb > QToolButton:hover, +WelcomeWidget > QToolButton:hover, +QToolBar#general_tb > QToolButton#qt_toolbar_ext_button { color: #fff; background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #80606060 , stop: 1 #80A0A0A0); @@ -197,21 +214,25 @@ QToolBar#general_tb > QToolButton:hover, WelcomeWidget > QToolButton:hover border-bottom: 1px solid #606060; } -QToolBar#general_tb > QToolButton:pressed, WelcomeWidget > QToolButton:pressed, QToolBar#general_tb > QToolButton:checked +QToolBar#general_tb > QToolButton:checked, +QToolBar#general_tb > QToolButton:pressed, +WelcomeWidget > QToolButton:pressed, +QToolBar#general_tb > QToolButton#qt_toolbar_ext_button:hover, +QToolBar#general_tb > QToolButton#qt_toolbar_ext_button:pressed { - background-image: url(":/styles/styles/btn_checked_bg.png"); - border-right: 1px solid #404040; - border-bottom: 1px solid #404040; - border-left: 1px solid #404040; - border-top: 1px solid #404040; - padding: 0; - color: #000 + color: #fff; + background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #804aa5ff , stop: 1 #8081cdff); + border-top: 1px solid qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #48a5fc , stop: 1 #3a86cc); + border-left: 1px solid qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #48a5fc , stop: 1 #3a86cc); + border-right: 1px solid #3a86cc; + border-bottom: 1px solid #3a86cc; } WelcomeWidget > QToolButton:disabled { color: #404040; } + QToolBar#general_tb > QToolButton:disabled { color: #808080; @@ -321,67 +342,7 @@ QToolBar#update_tb::separator { margin-right: 2px; } - -/* QWidget#tool_btns_bar_wgt { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #FFFFFF , stop: 1 #E6E6E6); - border-top: 1px solid #808080; - border-right: 1px solid #808080; - border-bottom: 1px solid #808080; - margin: 0; -} */ - -/* QWidget#tool_btns_bar_wgt > QPushButton { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #F1F1F1, stop: 1 #A1A1A1); - margin-top: 5px; - margin-bottom: 5px; - padding: 2px; - padding-left: 5px; - padding-right: 5px; - border: 1px solid #a0a0a0; - border-radius: 2px; - font-size: 8pt; - color: #000; -} */ - -/*QWidget#tool_btns_bar_wgt > QPushButton:hover { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #1E65AB, stop: 1 #257BD1); - border: 1px solid #175089; - color: #FFFFFF; -} */ - -/*QWidget#tool_btns_bar_wgt > QPushButton#validation_btn { - margin-left: 5px; -} - -QWidget#tool_btns_bar_wgt > QPushButton#find_obj_btn { - margin-left: 5px; -} - -QWidget#tool_btns_bar_wgt > QPushButton#sql_tool_btn { - margin-left: 5px; -} - -QWidget#tool_btns_bar_wgt > QPushButton#objects_btn{ - margin-right: 5px; -} - -QWidget#tool_btns_bar_wgt > QPushButton#operations_btn{ - margin-right: 5px; -} */ - -/*QWidget#tool_btns_bar_wgt > QPushButton:checked { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #606060, stop: 1 #A0A0A0); - border-color: #808080; - color: #000; -} - -QWidget#tool_btns_bar_wgt > QPushButton:checked:hover { - color: #ffffff; -} */ - QTabWidget#models_tbw::pane { - /*background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #FFFFFF , stop: 1 #E6E6E6);*/ - /*border-bottom: 1px solid #d0d0d0;*/ border-top: transparent; } @@ -403,7 +364,6 @@ QTabWidget#models_tbw > QTabBar::close-button:hover { QTabWidget#models_tbw > QTabBar::tab { border: 1px solid #C4C4C4; text-align: center; - /*font-size: 8.5pt;*/ min-height: 30px; min-width: 50px; padding-left: 5; @@ -436,25 +396,6 @@ QTabWidget#models_tbw > QTabBar::tab:selected { margin-top: 0px; } -/*QSplitter#h_splitter::handle { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #FAFAFA , stop: 1 #E0E0E0); -} */ - -/*QSplitter#h_splitter_opr_objs::handle { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #FAFAFA , stop: 1 #E0E0E0); - border-left: 1px solid #404040; -}*/ - -/*QSplitter#v_splitter::handle, QSplitter#v_splitter1::handle,QSplitter#v_splitter2::handle { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #FAFAFA , stop: 1 #E0E0E0); -} */ - -SQLToolWidget > QWidget#bg_frame { - /*background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #FAFAFA , stop: 1 #E0E0E0);*/ - /*border-bottom: 1px solid #d0d0d0; - border-top: transparent;*/ -} - /* Floating hint widget member of HintTextWidget */ HintTextWidget { @@ -471,7 +412,6 @@ HintTextWidget > QWidget HintTextWidget > QWidget > QLabel { color: #0000c0; - /*font-size: 8pt;*/ } QTabWidget#databases_tbw > QTabBar::close-button { @@ -508,3 +448,55 @@ QWidget#menu_title_wgt { background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffffff , stop: 1 #E6E6E6); border: 1px solid #c0a0a0a0; } + +/* DataManipulationForm styles */ +QWidget#bnts_parent_wgt { + background-image: url(":/styles/styles/toolbar_bg.png"); + background-repeat: repeat-y; + border: 1px solid #202020; + padding: 0; + margin: 0; +} + +QWidget#bnts_parent_wgt > QToolButton +{ + color: #fff; + margin-left: 3px; + margin-right: 3px; +} + +QWidget#bnts_parent_wgt > QToolButton:disabled +{ + color: #808080; +} + +QWidget#bnts_parent_wgt > QToolButton:hover +{ + color: #fff; + background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #80606060 , stop: 1 #80A0A0A0); + border-top: 1px solid qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #A0A0A0 , stop: 1 #606060); + border-left: 1px solid qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #A0A0A0 , stop: 1 #606060); + border-right: 1px solid #808080; + border-bottom: 1px solid #606060; +} + +QWidget#bnts_parent_wgt > QToolButton:checked, +QWidget#bnts_parent_wgt > QToolButton:pressed +{ + color: #fff; + background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #804aa5ff , stop: 1 #8081cdff); + border-top: 1px solid qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #48a5fc , stop: 1 #3a86cc); + border-left: 1px solid qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #48a5fc , stop: 1 #3a86cc); + border-right: 1px solid #3a86cc; + border-bottom: 1px solid #3a86cc; +} + +QWidget#bnts_parent_wgt > QFrame +{ + background-color: #80404040; + border-top: 1px solid #202020; + border-left: 1px solid #202020; + border-right: 1px solid #606060; + border-bottom: 1px solid #606060; + height: 1px; +} diff --git a/crashhandler/src/crashhandlerform.cpp b/crashhandler/src/crashhandlerform.cpp index 64452c5fad..f4ee8f7606 100644 --- a/crashhandler/src/crashhandlerform.cpp +++ b/crashhandler/src/crashhandlerform.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,7 +20,7 @@ #include "messagebox.h" #include "pgmodeleruins.h" -const QString CrashHandlerForm::ANALYSIS_MODE=QString("-analysis-mode"); +const QString CrashHandlerForm::AnalysisMode=QString("-analysis-mode"); CrashHandlerForm::CrashHandlerForm(bool analysis_mode, QWidget *parent, Qt::WindowFlags f) : BugReportForm(parent, f) { @@ -44,9 +44,9 @@ CrashHandlerForm::CrashHandlerForm(bool analysis_mode, QWidget *parent, Qt::Wind report_twg->addTab(wgt, trUtf8("Stack trace")); //Open for reading the stack trace file generated on the last crash - input.setFileName(GlobalAttributes::TEMPORARY_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::STACKTRACE_FILE); + input.setFileName(GlobalAttributes::TemporaryDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::StacktraceFile); input.open(QFile::ReadOnly); if(input.isOpen()) @@ -56,9 +56,9 @@ CrashHandlerForm::CrashHandlerForm(bool analysis_mode, QWidget *parent, Qt::Wind //Removes the stack trace file QDir stack_file; - stack_file.remove(GlobalAttributes::TEMPORARY_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::STACKTRACE_FILE); + stack_file.remove(GlobalAttributes::TemporaryDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::StacktraceFile); //Shows the stacktrace loaded on the widget stack_txt->setPlainText(buf); @@ -82,7 +82,7 @@ CrashHandlerForm::CrashHandlerForm(bool analysis_mode, QWidget *parent, Qt::Wind layout->addWidget(input_edt); load_tb=new QToolButton(input_wgt); - load_tb->setIcon(QPixmap(PgModelerUiNS::getIconPath("abrir"))); + load_tb->setIcon(QPixmap(PgModelerUiNs::getIconPath("abrir"))); load_tb->setSizePolicy(output_tb->sizePolicy()); load_tb->setToolButtonStyle(output_tb->toolButtonStyle()); load_tb->setIconSize(output_tb->iconSize()); @@ -90,7 +90,7 @@ CrashHandlerForm::CrashHandlerForm(bool analysis_mode, QWidget *parent, Qt::Wind layout->addWidget(load_tb); save_tb=new QToolButton(input_wgt); - save_tb->setIcon(QPixmap(PgModelerUiNS::getIconPath("salvar"))); + save_tb->setIcon(QPixmap(PgModelerUiNs::getIconPath("salvar"))); save_tb->setSizePolicy(output_tb->sizePolicy()); save_tb->setToolButtonStyle(output_tb->toolButtonStyle()); save_tb->setIconSize(output_tb->iconSize()); @@ -125,7 +125,7 @@ void CrashHandlerForm::loadReport(const QString &filename) //Raises an error if the file could not be opened if(!input.isOpen()) - msgbox.show(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED).arg(filename), Messagebox::ERROR_ICON); + msgbox.show(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed).arg(filename), Messagebox::ErrorIcon); else { QByteArray uncomp_buf; @@ -153,7 +153,7 @@ void CrashHandlerForm::loadReport(const QString &filename) //Showing the sections of the uncompressed buffer on the respective widgets while(i < buf_aux.size() && idx <= 2) { - if(buf_aux.at(i).toLatin1()!=CHR_DELIMITER) + if(buf_aux.at(i).toLatin1()!=CharDelimiter) str_aux.append(buf_aux.at(i)); else { @@ -210,8 +210,8 @@ void CrashHandlerForm::saveModel(void) output.open(QFile::WriteOnly); if(!output.isOpen()) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(file_dlg.selectedFiles().at(0)), - ERR_FILE_DIR_NOT_WRITTEN,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotWritten).arg(file_dlg.selectedFiles().at(0)), + ErrorCode::FileDirectoryNotWritten,__PRETTY_FUNCTION__,__FILE__,__LINE__); buf.append(model_txt->toPlainText()); output.write(buf.data(),buf.size()); @@ -251,7 +251,7 @@ QByteArray CrashHandlerForm::generateReportBuffer(void) { QByteArray buf=BugReportForm::generateReportBuffer(); buf.append(stack_txt->toPlainText().toUtf8()); - buf.append(CHR_DELIMITER); + buf.append(CharDelimiter); return(buf); } diff --git a/crashhandler/src/crashhandlerform.h b/crashhandler/src/crashhandlerform.h index c30f913798..f6c1190707 100644 --- a/crashhandler/src/crashhandlerform.h +++ b/crashhandler/src/crashhandlerform.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -59,9 +59,9 @@ class CrashHandlerForm: public BugReportForm { public: //! \brief Analysis mode argument - const static QString ANALYSIS_MODE; + static const QString AnalysisMode; - CrashHandlerForm(bool analysis_mode=false, QWidget * parent = 0, Qt::WindowFlags f = 0); + CrashHandlerForm(bool analysis_mode=false, QWidget * parent = nullptr, Qt::WindowFlags f = Qt::Widget); private slots: void loadReport(void); diff --git a/crashhandler/src/main.cpp b/crashhandler/src/main.cpp index 902b7ca630..349bb13c53 100644 --- a/crashhandler/src/main.cpp +++ b/crashhandler/src/main.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -30,11 +30,11 @@ int main(int argc, char **argv) QTranslator translator; //Loads the ui translation for crashhandler - translator.load(QLocale::system().name(), GlobalAttributes::LANGUAGES_DIR); + translator.load(QLocale::system().name(), GlobalAttributes::LanguagesDir); app.installTranslator(&translator); - CrashHandlerForm crashhandler(args.size() > 1 && args[1]==CrashHandlerForm::ANALYSIS_MODE); - PgModelerUiNS::resizeDialog(&crashhandler); + CrashHandlerForm crashhandler(args.size() > 1 && args[1]==CrashHandlerForm::AnalysisMode); + PgModelerUiNs::resizeDialog(&crashhandler); crashhandler.show(); app.exec(); @@ -44,6 +44,6 @@ int main(int argc, char **argv) { QTextStream out(stdout); out << e.getExceptionsText(); - return(e.getErrorType()); + return(enum_cast(e.getErrorCode())); } } diff --git a/installer/linux/packages/br.com.pgmodeler/meta/finishmessagewidget.ui b/installer/linux/packages/br.com.pgmodeler/meta/finishmessagewidget.ui index ec28890c6b..287bea8fb8 100644 --- a/installer/linux/packages/br.com.pgmodeler/meta/finishmessagewidget.ui +++ b/installer/linux/packages/br.com.pgmodeler/meta/finishmessagewidget.ui @@ -7,7 +7,7 @@ 0 0 548 - 385 + 502 @@ -42,7 +42,6 @@ - 11 75 true @@ -66,11 +65,6 @@ 0 - - - 10 - - Please, read the instructions below to see how to run it. @@ -96,7 +90,6 @@ Courier 10 Pitch - 11 @@ -143,15 +136,7 @@ p, li { white-space: pre-wrap; } - You can find more information about pgModeler on:<br/> -<br/>Official site:<br/> -<a href="http://pgmodeler.com.br"><span style=" text-decoration: underline; color:#0000ff;">http://pgmodeler.com.br</span></a><br/> -<br/>GitHub repository:<br/> -<a href="https://github.com/pgmodeler"><span style=" text-decoration: underline; color:#0000ff;">https://github.com/pgmodeler</span></a><br/> -<br/>Social Networks:<br/> -<a href="http://twitter.com/pgmodeler"><span style=" text-decoration: underline; color:#0000ff;">http://twitter.com/pgmodeler</span></a><br/> -<a href="http://facebook.com/pgmodeler"><span style=" text-decoration: underline; color:#0000ff;">http://facebook.com/pgmodeler</span></a><br/> -<a href="https://plus.google.com/u/0/communities/114191031055593275754"><span style=" text-decoration: underline; color:#0000ff;">https://plus.google.com/u/0/communities/114191031055593275754</span></a><br/> + <html><head/><body><p>You can find more information about pgModeler on:<br/><br/>Official site:<br/><a href="https://pgmodeler.io"><span style=" text-decoration: underline; color:#2980b9;">https://pgmodeler.io</span></a><br/><br/>GitHub repository:<br/><a href="https://github.com/pgmodeler"><span style=" text-decoration: underline; color:#2980b9;">https://github.com/pgmodeler</span></a><br/><br/>Social Networks:<br/><a href="https://twitter.com/pgmodeler"><span style=" text-decoration: underline; color:#2980b9;">https://twitter.com/pgmodeler</span></a><br/><a href="https://facebook.com/pgmodeler"><span style=" text-decoration: underline; color:#2980b9;">https://facebook.com/pgmodeler</span></a></p></body></html> Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse diff --git a/installer/template/config/config.xml.tmpl b/installer/template/config/config.xml.tmpl new file mode 100644 index 0000000000..94cba3422c --- /dev/null +++ b/installer/template/config/config.xml.tmpl @@ -0,0 +1,20 @@ + + + PostgreSQL Database Modeler + {version} + pgModeler + Raphael Araújo e Silva (raphael@pgmodeler.io) + {prefix} + installer_icon + installer_icon + installer_logo.png + watermark.png + true + true + 400 + 500 + Classic + False + uninstall + pgModeler + diff --git a/installer/template/config/installer_icon.icns b/installer/template/config/installer_icon.icns new file mode 100644 index 0000000000..7b0bf7a624 Binary files /dev/null and b/installer/template/config/installer_icon.icns differ diff --git a/installer/template/config/installer_icon.ico b/installer/template/config/installer_icon.ico new file mode 100644 index 0000000000..2b12da009d Binary files /dev/null and b/installer/template/config/installer_icon.ico differ diff --git a/installer/template/config/installer_icon.png b/installer/template/config/installer_icon.png new file mode 100644 index 0000000000..7156e48a63 Binary files /dev/null and b/installer/template/config/installer_icon.png differ diff --git a/installer/template/config/installer_logo.png b/installer/template/config/installer_logo.png new file mode 100644 index 0000000000..5c285d1dbe Binary files /dev/null and b/installer/template/config/installer_logo.png differ diff --git a/installer/template/config/watermark.png b/installer/template/config/watermark.png new file mode 100644 index 0000000000..51eb36fa69 Binary files /dev/null and b/installer/template/config/watermark.png differ diff --git a/installer/template/packages/io.pgmodeler/meta/LICENSE b/installer/template/packages/io.pgmodeler/meta/LICENSE new file mode 100644 index 0000000000..63df97bb01 --- /dev/null +++ b/installer/template/packages/io.pgmodeler/meta/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation version 3., or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/installer/template/packages/io.pgmodeler/meta/finishmessagewidget.ui b/installer/template/packages/io.pgmodeler/meta/finishmessagewidget.ui new file mode 100644 index 0000000000..ab00a70305 --- /dev/null +++ b/installer/template/packages/io.pgmodeler/meta/finishmessagewidget.ui @@ -0,0 +1,125 @@ + + + FinishMessageWidget + + + + 0 + 0 + 489 + 443 + + + + + 0 + 0 + + + + + 16777215 + 470 + + + + Installation finished + + + + 2 + + + 2 + + + 2 + + + 2 + + + 2 + + + + + + 0 + 0 + + + + Please, read the instructions below to see how to run it. + + + true + + + + + + + + 0 + 0 + + + + + 75 + true + + + + Thank you for using pgModeler! + + + Qt::AlignCenter + + + 16 + + + + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + + Courier 10 Pitch + + + + true + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Courier 10 Pitch'; font-size:11pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:10pt; color:#55aa00;"># From console run:</span><span style=" font-size:10pt;"> </span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:10pt;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:10pt; color:#7d7d7d;">$&gt;</span><span style=" font-size:10pt;"> cd {installdir} </span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:10pt; color:#7d7d7d;">$&gt;</span><span style=" font-size:10pt;"> ./start-pgmodeler.sh </span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:10pt;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:10pt; color:#55aa00;"># </span><span style=" font-size:10pt; font-weight:600; color:#55aa00;">NOTE:</span><span style=" font-size:10pt; color:#55aa00;"> if you have installed pgModeler on the default destination </span><span style=" font-size:10pt; font-weight:600; color:#55aa00;">/opt/pgmodeler</span><span style=" font-size:10pt; color:#55aa00;"> you don't need to use the startup script, just call the executable </span><span style=" font-size:10pt; font-weight:600; color:#55aa00;">pgmodeler </span><span style=" font-size:10pt; color:#55aa00;">from</span><span style=" font-size:10pt; font-weight:600; color:#55aa00;"> </span><span style=" font-size:10pt; color:#55aa00;">the default installation folder</span><span style=" font-size:10pt; font-weight:600; color:#55aa00;">. </span><span style=" font-size:10pt; color:#55aa00;">Take a look on </span><span style=" font-size:10pt; font-weight:600; color:#55aa00;">pgmodeler.vars</span><span style=" font-size:10pt; color:#55aa00;"> file to see how to run pgModeler for non standard installations.</span></p></body></html> + + + + + + + + diff --git a/installer/template/packages/io.pgmodeler/meta/installscript-macos.qs b/installer/template/packages/io.pgmodeler/meta/installscript-macos.qs new file mode 100644 index 0000000000..b46031a895 --- /dev/null +++ b/installer/template/packages/io.pgmodeler/meta/installscript-macos.qs @@ -0,0 +1,55 @@ +function Component() +{ + // constructor + installer.installationFinished.connect(this, finishInstall); + installer.addWizardPageItem( component, "FinishMessageWidget", QInstaller.InstallationFinished ); +} + +Component.prototype.isDefault = function() +{ + // select the component by default + return true; +} + +Component.prototype.createOperations = function() +{ + try { + // call the base create operations function + component.createOperations(); + + var installdir=installer.value("TargetDir"); + + start_script=installdir + "/" + "start-pgmodeler.sh"; + mime_update=installdir + "/" + "dbm-mime-type.sh"; + + component.addOperation("Execute", "chmod", "+x", start_script, "errormessage=** Could not set executable flag for file " + start_script); + component.addOperation("Execute", "chmod", "+x", mime_update, "errormessage=** Could not set executable flag for file " + mime_update); + + component.addOperation("Execute", "{0,255}", mime_update, "uninstall"); + component.addOperation("Execute", mime_update, "install", "errormessage=** Could not install file association."); + + } catch (e) { + print(e); + } +} + +// called after everything is set up, but before any fie is written +Component.prototype.beginInstallation = function() +{ + // call default implementation which is necessary for most hooks + // in beginInstallation case it makes nothing + component.beginInstallation(); +} + +finishInstall = function() +{ + //Getting the "Finished" page in order to detect if the "Run program" check box is marked + var page = gui.pageWidgetByObjectName( "FinishedPage" ); + + if(installer.status == QInstaller.Success) + { + var page = gui.pageWidgetByObjectName( "FinishedPage" ); + var info_txt=page.FinishMessageWidget.textEdit.html.replace("{installdir}",installer.value("TargetDir")) + page.FinishMessageWidget.textEdit.html=info_txt + } +} diff --git a/installer/template/packages/io.pgmodeler/meta/installscript-windows.qs b/installer/template/packages/io.pgmodeler/meta/installscript-windows.qs new file mode 100644 index 0000000000..b524e76b5b --- /dev/null +++ b/installer/template/packages/io.pgmodeler/meta/installscript-windows.qs @@ -0,0 +1,50 @@ +function Component() +{ + // constructor + installer.installationFinished.connect(this, finishInstall); + installer.addWizardPageItem( component, "FinishMessageWidget", QInstaller.InstallationFinished ); +} + +Component.prototype.isDefault = function() +{ + // select the component by default + return true; +} + +Component.prototype.createOperations = function() +{ + try { + // call the base create operations function + component.createOperations(); + + var installdir=installer.value("TargetDir"); + + mime_update=installdir + "/" + "pgmodeler-cli.exe -mt"; + component.addOperation("Execute", "{0,255}", mime_update, "uninstall"); + component.addOperation("Execute", mime_update, "install", "errormessage=** Could not install file association."); + + } catch (e) { + print(e); + } +} + +// called after everything is set up, but before any file is written +Component.prototype.beginInstallation = function() +{ + // call default implementation which is necessary for most hooks + // in beginInstallation case it makes nothing + component.beginInstallation(); +} + +finishInstall = function() +{ + //Getting the "Finished" page in order to detect if the "Run program" check box is marked + var page = gui.pageWidgetByObjectName( "FinishedPage" ); + + if(installer.status == QInstaller.Success) + { + var page = gui.pageWidgetByObjectName( "FinishedPage" ); + page.FinishMessageWidget.textEdit.visible=false; + page.FinishMessageWidget.label.visible=false; + } +} diff --git a/installer/template/packages/io.pgmodeler/meta/installscript.qs b/installer/template/packages/io.pgmodeler/meta/installscript.qs new file mode 100644 index 0000000000..30eebce13d --- /dev/null +++ b/installer/template/packages/io.pgmodeler/meta/installscript.qs @@ -0,0 +1,74 @@ +function Component() +{ + // constructor + installer.installationFinished.connect(this, finishInstall); + installer.addWizardPageItem( component, "FinishMessageWidget", QInstaller.InstallationFinished ); +} + +Component.prototype.isDefault = function() +{ + // select the component by default + return true; +} + +Component.prototype.createOperations = function() +{ + try { + // call the base create operations function + component.createOperations(); + + var installdir=installer.value("TargetDir"); + + if(systemInfo.productType === "osx") { + return; + } + else if (systemInfo.productType === "windows") { + + component.addOperation("CreateShortcut", "@TargetDir@/pgmodeler.exe", "@StartMenuDir@/pgModeler.lnk", + "workingDirectory=@TargetDir@", "iconPath=@TargetDir@/pgmodeler.exe", + "iconId=0", "description=PostgreSQL Database Modeler"); + + mime_update=installdir + "/" + "pgmodeler-cli.exe"; + component.addOperation("Execute", "{-1,0,127,255}", mime_update, "-mt", "uninstall"); + component.addOperation("Execute", "{-1,0,127,255}", mime_update, "-mt", "install"); + } + else { + start_script=installdir + "/" + "start-pgmodeler.sh"; + mime_update=installdir + "/" + "dbm-mime-type.sh"; + component.addOperation("Execute", "chmod", "+x", start_script, "errormessage=** Could not set executable flag for file " + start_script); + component.addOperation("Execute", "chmod", "+x", mime_update, "errormessage=** Could not set executable flag for file " + mime_update); + component.addOperation("Execute", "{-1,0,127,255}", mime_update, "uninstall"); + component.addOperation("Execute", "{-1,0,127,255}", mime_update, "install"); + } + } catch (e) { + print(e); + } +} + +// called after everything is set up, but before any file is written +Component.prototype.beginInstallation = function() +{ + // call default implementation which is necessary for most hooks + // in beginInstallation case it makes nothing + component.beginInstallation(); +} + +finishInstall = function() +{ + //Getting the "Finished" page in order to detect if the "Run program" check box is marked + var page = gui.pageWidgetByObjectName( "FinishedPage" ); + + if(installer.status == QInstaller.Success) + { + var page = gui.pageWidgetByObjectName( "FinishedPage" ); + + if (systemInfo.productType === "windows" || systemInfo.productType === "osx") { + page.FinishMessageWidget.textEdit.visible=false; + page.FinishMessageWidget.label.visible=false; + } + else { + var info_txt=page.FinishMessageWidget.textEdit.html.replace("{installdir}",installer.value("TargetDir")); + page.FinishMessageWidget.textEdit.html=info_txt; + } + } +} diff --git a/installer/template/packages/io.pgmodeler/meta/package.xml.tmpl b/installer/template/packages/io.pgmodeler/meta/package.xml.tmpl new file mode 100644 index 0000000000..b2b17a78f8 --- /dev/null +++ b/installer/template/packages/io.pgmodeler/meta/package.xml.tmpl @@ -0,0 +1,17 @@ + + + pgModeler components + Install all required files to run pgModeler + {version} + {date} + io.pgmodeler + + + + script + + + finishmessagewidget.ui + + true + diff --git a/lang/es_ES.qm b/lang/es_ES.qm index 15fab2a28b..782ea80bfc 100644 Binary files a/lang/es_ES.qm and b/lang/es_ES.qm differ diff --git a/lang/es_ES.ts b/lang/es_ES.ts index 2ea09f6e30..dd32426573 100644 --- a/lang/es_ES.ts +++ b/lang/es_ES.ts @@ -9,259 +9,60 @@ Acerca de pgModeler - + + 0.0.0 + 0.0.0 + + + + build: + + + + PostgreSQL Database Modeler Modelador para Bases de Datos PostgreSQL - + Open source data modeling tool designed for PostgreSQL. No more DDL commands written by hand, let pgModeler do the job for you! This software reunites the concepts of entity-relationship diagrams and the features that PostgreSQL implements as extensions of SQL standards. Herramienta de modelado de datos de código abierto diseñada para PostgreSQL. ¡No más comandos de DDL escritos a mano, deje a pgModeler hacer el trabajo para usted! Este software reúne los conceptos de diagramas entidad-relación y las características que PostgreSQL implementa como extensiones de estándares SQL. - - Design, configure, deploy - Diseño, configurar, implementar - - - - pgModeler is proudly a brazilian software! - pgModeler es orgullosamente un programa brasileño! + + <html><head/><body><p><a href="http://pgmodeler.com.br"><span style=" text-decoration: underline; color:#2980b9;">https://pgmodeler.io</span></a></p></body></html> + - - <a href="http://pgmodeler.com.br">http://pgmodeler.com.br</a> + + <html><head/><body><p>Copyright 2006-2018 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.io</span></a>&gt;</p></body></html> - - <html><head/><body><p>Copyright 2006-2016 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.com.br</span></a>&gt;</p></body></html> - <html><head/><body><p>Copyright 2006-2015 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.com.br</span></a>&gt;</p></body></html> + + pgModeler is proudly a brazilian software! + pgModeler es orgullosamente un programa brasileño! - + Hide this widget Ocultar este widget - + ... ... - - 0.0.0.0 - 0.0.0.0 - - - - Build: - Contruido: - - - + (BUILD_NUM) (NUM_CONSTRUIDO) - + License Licencia - - - Contributors - Colaboradores - - - - <html><head/><body><p>This page is dedicated to all contributors who gave a bit of their time in make pgModeler a better software somehow. The complete list of people that helped pgModeler can be found at <a href="https://github.com/pgmodeler/pgmodeler/graphs/contributors"><span style=" text-decoration: underline; color:#00a489;">GitHub</span></a>.</p><p>If you have a great idea to improve pgModeler please submit it <a href="http://github.com/pgmodeler/pgmodeler/issues"><span style=" text-decoration: underline; color:#00a489;">here</span></a>. No ideas for now but want to help? Why not donate a few bucks <a href="http://pgmodeler.com.br/#donate"><span style=" text-decoration: underline; color:#00a489;">here</span></a>!?</p></body></html> - <html><head/><body><p>Esta página está dedicada a todos los colaboradores que dieron un poco de su tiempo en hacer pgModeler un mejor software de alguna manera. La lista completa de las personas que ayudó pgModeler se puede encontrar en <a href="https://github.com/pgmodeler/pgmodeler/graphs/contributors"><span style=" text-decoration: underline; color:#00a489;">GitHub</span></a>.</p><p>Si usted tiene una gran idea para mejorar pgModeler favor enviarlo <a href="http://github.com/pgmodeler/pgmodeler/issues"><span style=" text-decoration: underline; color:#00a489;">aquí</span></a>. ¿Sin ideas por ahora, pero quiere ayudar? Por qué no donar un poco de dinero <a href="http://pgmodeler.com.br/#donate"><span style=" text-decoration: underline; color:#00a489;">aquí</span></a>!?</p></body></html> - - - - 1 - 1 - - - - 2 - 2 - - - - 3 - 3 - - - - 4 - 4 - - - - 5 - 5 - - - - 6 - 6 - - - - 7 - 7 - - - - 8 - 8 - - - - 9 - 9 - - - - Name - Nombre - - - - Country - País - - - - Contribution - Contribución - - - - Damien Degois - Damien Degois - - - - - - France - Francia - - - - French UI translation and several improvements in auxiliary scripts. - Traducción de IU francés y varias mejoras en scripts auxiliares. - - - - Ji Bin - Ji Bin - - - - China - China - - - - Chinese UI translation and small fixes. - Traducción de IU chino y pequeñas correcciones. - - - - Pierre-Samuel LE STANG - Pierre-Samuel LE STANG - - - - - French UI translation. - Traducción de IU al francés. - - - - Lisandro Damián Nicanor - Lisandro Damián Nicanor - - - - Argentina - Argentina - - - - Improvements on build scripts enabling the custom packaging in Linux distros; Per-user settings; pgModeler's package maintainer in Debian Linux. - Mejoras en scripts de construcción que permitan el embalaje personalizado en distribuciones de Linux; Por usuario ajustes; pgModeler y apos; s mantenedor de paquetes en Debian Linux. - - - - Pavel Alexeev - Pavel Alexeev - - - - Russia - Rusia - - - - Additional work for packaging in Linux distros; pgModeler's package maintainer in Fedora Linux. - El trabajo adicional para el empaquetado en la distribuciones de Linux; pgModeler's empaquetador de paquetes en Fedora Linux. - - - - Mariusz Fik - Mariusz Fik - - - - Poland - Polonia - - - - Custom packaging first ideas. Tester of first version of custom packaging patch. - Empaquetados hechos a medida primeras ideas. Probador de primera versión del parche de empaquetados personalizados. - - - - Jonathan DUPRE - - - - - Gilberto Castillo - - - - - Cuba - - - - - Spanish UI translation. - - - - - -Danúbio Viana Nogueira - - - - - Brazil - - - - - Brazilian Portuguese UI translation. - - AggregateWidget @@ -612,12 +413,12 @@ Danúbio Viana Nogueira Application - + Unknown exception caught! Excepción desconocida capturada! - + Failed to create initial configuration in `%1'! Check if the current user has write permission over that path and at least read permission over `%2'. No se pudo crear la configuración inicial en `%1'! Compruebe si el usuario actual tiene permiso de escritura sobre ese camino y al menos permiso de lectura sobre `%2'. @@ -654,7 +455,7 @@ Danúbio Viana Nogueira &Ok - + %1 properties %1 propiedades @@ -662,172 +463,177 @@ Danúbio Viana Nogueira BaseObject - + Column Columna - + Constraint Restricción - + Function Función - + Trigger Trigger - + Index Índice - + Rule Regla - + Table Tabla - + View Vista - + Domain Domínio - + Schema Esquema - + Aggregate Agregado - + Operator Operador - + Sequence Secuencia - + Role Rol - + Conversion Conversión - + Cast Cast - + Language Lenguaje - + Type Tipo - + Tablespace Tablespace - + Operator Family Família de Operadores - + Operator Class Operador de Clases - + Database Base de Dados - + Collation Colación - + Extension Extensión - + Event Trigger Evento Trigger - + Relationship Relación - + + Policy + + + + Textbox Cuadro de Texto - + Permission Permisos - + Parameter Parámetro - + Type Attribute Tipo atributo - + Tag Tag - + Basic Relationship Relación básica - + Generic SQL - + new_object nuevo_objecto @@ -856,89 +662,89 @@ Danúbio Viana Nogueira Comentario: - + Tablespace: Tablespace: - + Schema: Esquema: - + Edit object's permissions Editar permisos del objeto - + Edit permissions Editar permisos - + This object is protected thus no change in form will be applied to it. - + Disables the generated SQL code using comment tokens (--). This will disable the code of all child and referrer objects. Desactiva el código SQL generado utilizando fichas comentario (-). Esto desactivará el código de todos los objetos secundarios y referenciales. - + Disable SQL code Desactivar Código SQL - + Collation: Colación: - + Append or prepend a set of SQL commands to the object's definition. Anexar o anteponer un conjunto de comandos SQL para la definicióno bjeto's. - + Custom SQL SQL personalizado - + Owner: Propietario: - + ID: ID: - + icone icone - + Required field. Leaving this empty will raise errors! Campo requerido. Dejando este vacío elevará errores! - + Value(s) Valor(es) - + Version Versión - + The <em style='color: %1'><strong>highlighted</strong></em> fields in the form or one of their values are available only on specific PostgreSQL versions. Generating SQL code for versions other than those specified in the fields' tooltips may create incompatible code. Los campos <em style ='color: %1'><strong>resaltados</strong></em> en el formulario o uno de sus valores sólo están disponibles en versiones específicas de PostgreSQL. Generar código SQL para versiones distintas a las especificadas en las sugerencias de los campos puede crear código incompatible. @@ -947,7 +753,7 @@ Esto desactivará el código de todos los objetos secundarios y referenciales. BaseRelationship - + rel_%1_%2 rel_%1_%2 @@ -955,12 +761,12 @@ Esto desactivará el código de todos los objetos secundarios y referenciales. BaseTableView - + Toggles the extended attributes display - + Connected rels: %1 Rels conectados: %1 @@ -1059,6 +865,14 @@ Esto desactivará el código de todos los objetos secundarios y referenciales.Seleccione carpeta de destino del informe + + BulkDataEditWidget + + + Bulk data edit + + + CastWidget @@ -1120,12 +934,12 @@ Esto desactivará el código de todos los objetos secundarios y referenciales.Hace que el widget se puede cerrar solamente por tecla ESC o clic del ratón sobre otros controles. - + SQL Keyword Palabra clave SQL - + (no items found.) (No se encontraron items.) (No se encontró ninguna.) @@ -1196,17 +1010,32 @@ Esto desactivará el código de todos los objetos secundarios y referenciales.Valor por Defecto: - + + Edit the underlying sequence's attributes + + + + + Edit sequence + + + + + Identity: + + + + E&xpression: E&xpresión: - + &NOT NULL - + Se&quence: @@ -1229,37 +1058,37 @@ Esto desactivará el código de todos los objetos secundarios y referenciales.Relaciones - + Appearance Apariencia - + Connections Conexiones - + Snippets Snippets - + Plug-ins Plug-ins - + Defaults Valores por Defecto - + &Apply &Aplicar - + &Cancel &Cancelar @@ -1287,22 +1116,22 @@ Esto desactivará el código de todos los objetos secundarios y referenciales.Contraseña: - + Connection Alias: Alias de Conexión: - + Connection DB: BD Conexión: - + Host/Port: Host/Puerto: - + User: Usuario: @@ -1312,87 +1141,87 @@ Esto desactivará el código de todos los objetos secundarios y referenciales.Timeout: - + SSL Mode: Modo SSL: - + Disable Desactivado - + Diff Diff - + Export Exportar - + Import Importar - + Validation Validación - + Security Seguridad - + Allow Permitir - + Require Requerido - + AC verification Verificación de AC - + Full verification Verificación Completa - + Kerberos Server: Servidor Kerberos: - + Client Certificate: Certificado Cliente: - + Revoked Certs.: Cert. Revocados: - + Client Key: Clave Cliente: - + Root Certificate: Certificado Root: - + ~/.postgresql/root.crt ~/.postgresql/root.crt @@ -1402,17 +1231,17 @@ Esto desactivará el código de todos los objetos secundarios y referenciales.Conexiones: - + second(s) segundo(s) - + Force GSSAPI Forzar a GSSAPI - + ~/.postgresql/postgresql.crt ~/.postgresql/postgresql.crt @@ -1432,12 +1261,12 @@ Esto desactivará el código de todos los objetos secundarios y referenciales.Testear - + ~/.postgresql/root.crl ~/.postgresql/root.crl - + ~/.postgresql/postgresql.key ~/.postgresql/postgresql.key @@ -1478,12 +1307,12 @@ Esto desactivará el código de todos los objetos secundarios y referenciales.General - + Other params: Otros parámetros: - + Specify additional connection parameters in the form [param]=[value]. These parameters are described in the <strong>libpq</strong> chapter at PostgreSQL docs. Especifique los parámetros de conexión adicionales en la forma [param]=[valor]. Estos parámetros se describen en el capítulo <strong> libpq </strong> en la documentación de PostgreSQL. @@ -1493,12 +1322,12 @@ Esto desactivará el código de todos los objetos secundarios y referenciales. - + Automatically browses the named database when using this connection to manage databases on <strong>Manage</strong> view. Busca automáticamente la base de datos llamada cuando se utiliza esta conexión para administrar bases de datos en la vista <strong>Manage</strong>. - + Auto browse Auto explorar @@ -1931,51 +1760,46 @@ Desmarcando esto hará que el SQL que se adjunta al final del mandato CREATE DAT - Type: - Tipo: - - - Generic INSERT INSERT genérico - + Include serial columns Incluir columnas serial - + Exclude serial columns Excluir columnas serial - + Generic SELECT SELECT genérico - + Table SELECT SELECT tabla - + Generic UPDATE - + Table UPDATE UPDATE genérico - + Generic DELETE DELETE genérico - + Table DELETE DELETE tabla @@ -2019,97 +1843,106 @@ Desmarcando esto hará que el SQL que se adjunta al final del mandato CREATE DAT - Ctrl+X Ctrl+X - + Undo modifications Deshacer modificaciones - + Ctrl+Z Ctrl+Z - - + + Ins Ins - + Mark the selected rows to be deleted Marque las filas seleccionadas para ser borradas - - - - - + + + + + Del Del - + + Change the values of all selected cells at once + + + + + Ctrl+E + Ctrl+E + + + Duplicate the selected rows - + Ctrl+D - + Add new rows from a CSV file - + Filter the result set Filtrar el conjunto de resultados - + Table: Tabla: - + Schema: Esquema: - + in in - + Hide views Ocultar vista - + Filter expression Filtrar expresión - + Order && Limit Order && Límite - + results (Use <strong>0</strong> for no limit) - + Column: Columna: @@ -2139,183 +1972,193 @@ Desmarcando esto hará que el SQL que se adjunta al final del mandato CREATE DAT - + ASC ASC - + Add empty rows - + DESC DESC - + Limit in: Límite en: - + Add Item Añadir Item - + Remove Item Eliminar Item - + Clear the order by columns list Desactive el orden de lista columnas - + Move selected item up Mover arriba el item seleccionado - + Move selected item down Mover abajo el item seleccionado - + Copy as CSV - + Copy as text - + Copy items - + Pase items - + Browse tables - + Duplicate row(s) - + Delete row(s) - + + Edit cell(s) + + + + <strong>WARNING: </strong> There are some changed rows waiting the commit! Do you really want to discard them and retrieve the data now? - + Rows returned: <strong>%1</strong>&nbsp;&nbsp;&nbsp; - + <em>(Limit: <strong>%1</strong>)</em> <em>(Límite: <strong>%1</strong>)</em> - + none - + + Column + + + + No objects found Objects no encontrado - + Found %1 object(s) Encontrado %1 objecto(s) - + Views can't have their data handled through this grid, this way, all operations are disabled. Las vistas no pueden tener sus datos manejados a través de esta red, de esta manera, todas las operaciones están desactivadas. - + The selected table doesn't owns a primary key! Updates and deletes will be performed by considering all columns as primary key. <strong>WARNING:</strong> those operations can affect more than one row. La tabla seleccionada no posee una clave primaria! Las actualizaciones y eliminaciones se realizarán teniendo en cuenta todas las columnas como clave primaria. <strong>WARNING:</strong> estas operaciones pueden afectar a más de una fila. - + Referenced tables - - + + (none) - + Referrer tables - + This row is marked to be %1 Esta fila se marca para ser %1 - + deleted eliminado - + updated actualizado - + inserted insertado - + [binary data] [datos binarios] - + <strong>WARNING:</strong> Once commited its not possible to undo the changes! Proceed with saving? <strong>WARNING:</strong> Una vez que su cometido no es posible deshacer los cambios! Procedo con salvar? - + delete eliminar - + update actualizar - + insert insertar @@ -2328,112 +2171,104 @@ Desmarcando esto hará que el SQL que se adjunta al final del mandato CREATE DAT Formulario - - Toggles the display of extension objects - Cambia la visualización de extensión de objetos - - - + + Data &Grid Datos &Cuadrícula - + + Alt+G Alt+G - - - - - + + + + + ... ... - - Toggles the display of system objects. - - - - - System - - - - - Extension - Extensión - - - + Open the grid to visualize or edit data - + Open a new SQL execution pane Abrir un nuevo panel de ejecución de SQL - + Ctrl+F6 Ctrl+F6 - + Update the objects tree Actualizar el árbol de objetos - - Ctrl+S - Ctrl+S + + Toggle the display of filter widget as well the system/extension objects. + + + + + Sort items alphabetically. When unchecked, items are sorted by OID. + - + + Sort alphabetically + + + + Drop this database Eliminar esta base de datos - + Expands all items Expande todos los item - + Collapses all items Contrae todos los item - + Filters the currently loaded items in the tree by using a pattern and matching their names. If <strong>By OID</strong> is checked the pattern is interpreted as an integer value that represents the object id (OID). <br><br/><strong>HINT:</strong> if you need to search the entire database use the full refresh (<strong>Ctrl+F5</strong>) prior the filtering. - + Filter: Filtro: - + By OID Por OID - + Attribute Atributo - + Value Valor - + Show raw attributes @@ -3328,141 +3163,186 @@ Desmarcando esto hará que el SQL que se adjunta al final del mandato CREATE DAT - - Snippets - Snippets + + Identity + - - Drop object - Drop object + + Command + - - Drop cascade + + USING expr. + + + + + CHECK expr. + + + + + Roles + Roles + + + + RLS enabled + + + + + RLS forced + + + + + Show objects filter + + + + + Show system objects + + + + + Show extension objects + + + + + Snippets + Snippets + + + + Drop object + Drop object + + + + Drop cascade Drop cascade - + Truncate Truncate - + Trunc. cascade Trunc. cascade - + Show data Mostrar dato - + Reload properties Recargar propiedades - + Update Actualizar - + Rename Renombrar - + Source code Código fuente - + Quick refresh - + Full refresh - + -- Source code unavailable for this kind of object -- - + Do you really want to drop the object <strong>%1</strong> <em>(%2)</em>? ¿De verdad quiere borrar el objeto <strong>%1</strong> <em>(%2)</em>? - + Do you really want to <strong>cascade</strong> drop the object <strong>%1</strong> <em>(%2)</em>? This action will drop all the other objects that depends on it. - + + Also restart sequences + + + + Src. table: %1 Src. column(s): %2 - + Ref. table: %1 Ref. column(s): %2 - + -- Source code genaration for buil-in and base types currently unavailable -- - + -- Source code unavailable for the object %1 (%2). -- - - + + Warning Advertencia - + You're running a demonstration version! The data manipulation feature is available only in the full version! Usted está ejecutando una versión de demostración! La función de manipulación de datos sólo está disponible en la versión completa! - + <strong>CAUTION:</strong> You are about to drop the entire database <strong>%1</strong>! All data will be completely wiped out. Do you really want to proceed? <strong>ATENCION:</strong> Vas a dejar toda la base de datos <strong>%1</strong>! Todos los datos serán completamente eliminados. ¿Realmente desea continuar? - + Do you really want to truncate the table <strong>%1</strong>? ¿De verdad quiere truncar la tabla <strong>%1</strong>? - + Do you really want to <strong>cascade</strong> truncate the table <strong>%1</strong>? This action will truncate all the tables that depends on it? ¿De verdad quieres truncar en <strong>cascade</strong> la tabla <strong>%1</strong>? ¿Esta acción truncar todas las tablas que depende de ella? DatabaseImportForm - - - Database Import - Importar Bases de Datos - - - - Database import - Importar bases de datos - Settings @@ -3479,185 +3359,151 @@ Ref. column(s): %2 Conexión: - - Origin point: - Punto de origen: - - - - Starting point where objects will be put. - Punto inicial donde se colocarán el objetos. - - - - Tables per row: - Tablas por fila: - - - - Tables per row - Tablas por fila - - - - Spacing: - Espaciado: - - - - Spacing between objects - Espaciado entre objeto - - - - Schemas per row: - Esquema por fila: - - - + Automatically resolve dependencies Resolver dependencias automáticamente - - - - + + + + ... ... - + Random colors will be assigned to imported relationships facilitating the identification of links between tables mainly in large models. Colores al azar serán asignados a las relaciones importados que faciliten la identificación de los vínculos entre las tablas, principalmente en modelos de gran tamaño. - - Schemas per row - - - - + Resolve some of the object's dependencies by querying the catalog when a needed object does not exists on the loaded set. In some cases it's necessary to combine this option with others below. This option does not applies to database level objects like role, tablespace and language as well for data types, extensions. - + Random colors for relationships Colores aleatorios para las relaciones - + Enables the import of system built-in objects. It's recommend to select only those objects that are directly referenced by the ones to be imported. WARNING: Try to import a huge set of system objects can bloat the resultant model or even crash pgModeler due to memory/cpu overuse. Permite la importación de sistema de objetos integrados. Se recomienda seleccionar sólo aquellos objetos que se hace referencia directamente por las que ser importados. ADVERTENCIA: Trate de importar un enorme conjunto de objetos del sistema puede inflar el modelo resultante o incluso estrellarse pgModeler debido a la memoria / CPU uso excesivo. - + Import system objects Importa objeto del sistema - + Enables the import of objects created by extensions. Generally there is no need to check this option but if there are objects in the database that directly references this category of objects this mode must be enabled. Permite la importación de objetos creados por las extensiones. Generalmente no hay necesidad de revisar esta opción, pero si hay objetos en la base de datos que hace referencia directa a esta categoría de objetos de este modo debe estar habilitado. - + Import extension objects Importar extensiones de objetos - + pgModeler ignores import errors and will try to create as many as possible objects. By checking this option the import operation will be not aborted but an incomplete model will be constructed. This option generates a log file on pgModeler's temp directory. pgModeler ignora los errores de importación y tratará de crear el mayor número posible de objetos. Al marcar esta opción, la operación de importación no se concluye, pero un modelo incompleto se construirá. Esta opción genera un archivo de registro en el directorio temporal de pgModeler. - + Ignore import errors Ignorar errores de importación - + All catalog queries as well the created objects' source code are printed to standard output (stdout). - + + + Import database + + + + Debug mode Modo depurarión - + Create all imported objects in the current working model instead of create a new one. Crear todos los objetos importados en el modelo de trabajo actual en lugar de crear uno nuevo. - + Import objects to the working model Importar objetos al modelo de trabajo - + Database Base de datos - + Filter: Filtrar: - + Filter object by it's OID Filtrar objeto por OID - + By OID Por OID - + Select all objects Seleccionar todos los objetos - + Clear object selection Limpiar los objetos seleccionados - + Expands all items Expandir todos los item - + Collapses all items Contrae todos los item - + Output Salida - + Progress label... Etiqueta de Progreso... - + Cancel Cancelar - + &Import &Importar - + &Close &Cerrar @@ -3667,57 +3513,57 @@ Ref. column(s): %2 <strong>ATENCIÓN:</strong> Estás a punto de importar objetos al modelo actual de trabajo! Esta acción provocará cambios irreversibles a él, incluso en caso de errores críticos durante el proceso. ¿Quieres proceder? - + Importing process aborted! Proceso de Importación abortado! - + Importing process canceled by user! Proceso de Importación cancelado por usuario! - + Importing process sucessfuly ended! Proceso de Importación terminado satisfactoriamente! - + No databases found Base de datos no encontrada - + Found %1 database(s) Encontrada %1 bases de dato(s) - + Retrieving objects from database... Recuperando objetos de base de datos... - + Retrieving cluster level objects... Recuperando objetos a nivel de clúster... - + Retrieving objects of schema `%1'... Recuperando objetos del esquema `%1'... - + Retrieving objects of `%1' (%2)... - + This is a PostgreSQL built-in data type and cannot be imported. Esta es una tipo de datos incorporado PostgreSQL y no se puede importar. - + This is a pgModeler's built-in object. It will be ignored if checked by user. Esta es objeto incorporado del pgModeler. Se ignora si se activa por el usuario. @@ -3776,7 +3622,7 @@ Ref. column(s): %2 - + Assigning sequences to columns... @@ -3786,12 +3632,12 @@ Ref. column(s): %2 La importación de base de datos terminó pero algunos errores se genera y se guarda en el archivo de registro `%1'. Este archivo se prolongará hasta salga de pgModeler. - + Destroying unused detached columns... Destruyendo columnas separadas no utilizados... - + Creating table inheritances... Creación de herencias de tabla... @@ -3799,68 +3645,68 @@ Ref. column(s): %2 DatabaseModel - + The demonstration version can create only `%1' instances of each object type! You've reach this limit for the type: `%2' La versión de demostración sólo puede crear `%1' instancias de cada tipo de objeto! Tienes que llegar a este límite para el tipo: `%2' - + Loading: `%1' (%2) Cargando: `%1' (%2) - - + + Validating relationships... - - Generating %1 of the object `%2' (%3) - Generando %1 del objecto `%2' (%3) + + Generating %1 code: `%2' (%3) + - + Saving object `%1' (%2) - + Saving metadata of the object `%1' (%2) - + Metadata file successfully saved! - + Process successfully ended but no metadata was saved! - + Creating object `%1' (%2) Creando objecto `%1' (%2) - + Object `%1' (%2) already exists. Ignoring. - + Loading metadata for object `%1' (%2) - + Object `%1' (%2) not found. Ignoring metadata. - + Metadata file successfully loaded! @@ -3873,57 +3719,72 @@ Ref. column(s): %2 Atributos - + LC_COLLATE: LC_COLLATE: - + LC_CTYPE: LC_CTYPE: - + Template DB: DB Modelo: - + Model Author: Autor del Modelo: - + Encoding: Codificación: - + Connections: Conexiones: - + + Options: + Opciones: + + + + Allow connections + + + + + Is template + + + + Default Objects Objectos por Defecto - + Tablespace: Tablespace: - + Schema: Esquema: - + Collation: Colación: - + Owner: Propietario: @@ -3940,8 +3801,8 @@ Ref. column(s): %2 - - + + Default Por Defecto @@ -3949,29 +3810,44 @@ Ref. column(s): %2 DomainWidget - + + Attributes + Atributos + + + Default Value: Valor Por Defecto: - - Constraint - Resticción + + Not null + No null + + + + Check constraints + - + + Expression: + Expresión: + + + Name: Nombre: - - Not Null: - No Nulo: + + Name + Nombre - - Check Expr.: - Expr. Chequeo: + + Expression + Expresión @@ -4002,7 +3878,7 @@ Ref. column(s): %2 <html><head/><body><p>pgModeler es traído a usted gracias a un <span style=" font-style:italic;">gran esfuerzo para crear y distribuir un producto de calidad</span>. Este proyecto está alcanzando niveles de madurez nunca imaginados. Todo esto es el resultado de un trabajo conjunto entre su autor y la <span style=" font-weight:600;">comunidad Open Source </span>. <br/><br/>Este software tiene un largo camino por recorrer y con su ayuda seguiremos manteniendo el buen trabajo y trayendo nuevas mejoras en cada versión. Si te gustó pgModeler y cree que merece una contribución, haz una donación!</p></body></html> - + I want to help! ¡Quiero ayudar! @@ -4480,6 +4356,11 @@ Ref. column(s): %2 Unable to write the file `%1' due to one or more errors in the definition generation process! + + + There is already a relationship between `%1' (%2) and `%3' (%4) in the model! When using relationships of the type generalization, copy and one-to-one there can't be other relationships linked to the pair of tables. + + The configuration of the relationship `%1' generates a redundancy between the relationships `%2'. Redundancy on identifier or generalization/copy relationships are not accepted since they result in incorrect column spreading making the model inconsistent! @@ -4615,6 +4496,26 @@ Ref. column(s): %2 Failed to drop the database `%1' because it is defined as the default database for the connection `%2'! + + + The column `%1' must be `NOT NULL' because it composes the primary key of the table `%2'. You need to remove the column from the mentioned contraint in order to disable the `NOT NULL' on it! + + + + + The identity column `%1' has an invalid data type! The data type must be `smallint', `integer' or `bigint'. + + + + + Reference to an invalid affected command in policy `%1'! + + + + + Reference to an invalid special role in policy `%1'! + + Assignment of invalid type to the object! @@ -4805,11 +4706,6 @@ Ref. column(s): %2 Unable to write the file or directory `%1'! Make sure the output directory exists, or if the user has write permissions over it! Imposible escribir en el archivo `%1'! Asegurase de que el diretório existe o si el usuário tiene permisos de aceso al mismo! - - - There is already a relationship between `%1' (%2) and `%3' (%4) in the model! - Ya existe una Relación entre `%1' (%2) y `%3' (%4) en el modelo! - One or more objects were invalidated and automatically removed because they were referencing table columns which were included through relationships and which no longer exists due to disconnection of relationships or exclusion of such generated columns! @@ -5336,37 +5232,47 @@ Mensage retornada por el SGBD: `%1' Formulario - + + Hide this widget + Ocultar este widget + + + + ... + ... + + + Replace one occurrence Reemplazar una ocurrencia - + Replace Reemplazar - + Replace all occurrences Reemplazar todas las ocurrencias - + Replace All Reemplazar todas - + Replace the selection and find the next one Reemplace la selección y buscar la siguiente - + Replace && Find Reemplazar && Buscar - + Replace: Reemplazar: @@ -5434,82 +5340,82 @@ Mensage retornada por el SGBD: `%1' Filas Retornadas: - + Return Method: Método de Retorno: - + Behavior: Comportamiento: - + Set Conjunto - + Language: - + Si&mple - + Tab&le - + Return Table Tabla de retorno - + Execution Cost: Costo ejecución: - + Windown Func. Func. Ventana. - + Leakproof Prueba de fugas - + Parameters Parámetros - + Definition Definición - + Dynamic Library: Biblioteca Dinámica: - + Symbol: Símbolo: - + Library: Biblioteca: - + Source code: Código fuente: @@ -5563,7 +5469,7 @@ Mensage retornada por el SGBD: `%1' Histórico de operaciones: - + Check if there is a new version on server Compruebe si hay una nueva versión en el servidor @@ -5760,62 +5666,62 @@ Mensage retornada por el SGBD: `%1' - + SQL history max. length: - + Souce code editor: - + lines lineas - + Clear the entire SQL comand history. - + Clear history Limpiar historial - + Configurations directory: Directorio de configuraciones: - + Browse the source code editor application Examinar la aplicación del editor de código fuente - + Open in file manager Abrir en el administrador de archivos - + Check updates at startup Comprobar actualizaciones al inicio - + Souce code editor args: - + User interface language: Idioma de la interfaz de usuario: - + Overrides the default user interface language defined by the system. Requires restarting the program. <strong>NOTE:</strong> UI translations are third party collaborations thus any typo or mistake should be reported directly to their respective maintainers. @@ -6140,12 +6046,12 @@ Mensage retornada por el SGBD: `%1' - + All files (*.*) - + Load file @@ -6464,6 +6370,11 @@ Mensage retornada por el SGBD: `%1' &Diff &Diff + + + Determine the changes between model/database and another database + + Design database models @@ -6516,8 +6427,8 @@ Mensage retornada por el SGBD: `%1' - Rearrange objects on the canvas hierarchically - Reorganizar los objetos en el lienzo jerárquicamente + Rearrange objects over the canvas + @@ -6799,11 +6710,6 @@ Mensage retornada por el SGBD: `%1' Ctrl+Shift+H Ctrl+Shift+H - - - Determine the changes between model and database - Determinar los cambios entre el modelo y la base de datos - Ctrl+Shift+D @@ -6840,7 +6746,7 @@ Mensage retornada por el SGBD: `%1' Administrar base de datos existentes - + (Demo) (Demo) @@ -6850,174 +6756,189 @@ Mensage retornada por el SGBD: `%1' Guardando modelos temp - + Clear Menu Limpiar Menú - + The demonstration version can create only `one' instance of database model! La versión de demostración sólo puede crear `una' instancia de modelo de base de datos! - + Save model Guardar Modelo - + Save modified model(s) Guardar modelo(s) modificado(s) - + The following models were modified but not saved: %1. Do you really want to quit pgModeler? Los siguientes modelos fueron modificados pero no guardados: %1. ¿De verdad quieres salir de pgModeler? - + The model <strong>%1</strong> was modified! Do you really want to close without save it? Se ha modificado el modelo <strong>%1</strong>. ¿Realmente quieres cerrar sin guardarlo? - - + + Warning Advertencia - + You're running a demonstration version! The model saving feature is available only in the full version! Usted está ejecutando una versión de demostración! La función de ahorro de modelo está disponible sólo en la versión completa! - - - + + + Confirmation Confirmación - + <strong>WARNING:</strong> The model <strong>%1</strong> is invalidated! It's recommended to validate it before save in order to create a consistent model otherwise the generated file will be broken demanding manual fixes to be loadable again! <strong>ADVERTENCIA:</strong> El modelo <strong>%1</strong> está invalidado! Se recomienda para validarlo antes de guardar con el fin de crear un modelo coherente de lo contrario el archivo generado se romperá exigiendo correcciones manuales que sea cargable de nuevo! - + Save anyway Guardar de todos modos - - - + + + Validate Validar - + Save '%1' as... Guardar '%1' como... - - + + Database model (*.dbm);;All files (*.*) Modelo de base de datos (*.dbm);; Todos los arquivos (*.*) - + Access support page - + You're running a demonstration version! Note that you'll be able to create only <strong>%1</strong> instances of each type of object and some key features will be disabled or limited!<br/><br/>You can purchase a full binary copy or get the source code at <a href='http://pgmodeler.com.br'>pgmodeler.com.br</a>. <strong>NOTE:</strong> pgModeler is an open source software, but purchasing binary copies or providing some donations will support the project and cover all development costs.<br/><br/> <strong>HINT:</strong> in order to test all features it's recommended to use the <strong>demo.dbm</strong> model located in </strong>Sample models</strong> at <strong>Welcome</strong> view.<br/><br/><br/><br/> - + Rearrange objects over the canvas is an irreversible operation! Would like to proceed? - + <strong>WARNING:</strong> The model <strong>%1</strong> is invalidated! Before run the export process it's recommended to validate in order to correctly create the objects on database server! <strong>ADVERTENCIA:</strong> El modelo <strong>%1</strong> está invalidado. Antes de ejecutar el proceso de exportación se recomienda validar para crear correctamente los objetos en el servidor de base de datos! - + + Grid + + + + + Hierarchical + + + + + Scattered + + + + Export anyway Exportar de todas modos - + <strong>WARNING:</strong> The model <strong>%1</strong> is invalidated! Before run the diff process it's recommended to validate in order to correctly analyze and generate the difference between the model and a database! <strong>ADVERTENCIA:</strong> El modelo <strong>%1</strong> está invalidado! Antes ejecutar el proceso diff se recomienda para validar el fin de analizar correctamente y generar la diferencia entre el modelo y una base de datos! - + Diff anyway Diff de todas modo - + Database model printing Imprimir modelo de Base de datos - + Changes were detected in the definitions of paper/margin of the model which may cause the incorrect print of the objects. Do you want to continue printing using the new settings? To use the default settings click 'No' or 'Cancel' to abort printing. Se detectaron cambios en las definiciones de papel / margen del modelo que pueden causar la impresión incorrecta de los objetos. ¿Quieres continuar con la impresión utilizando la nueva configuración? Para utilizar la configuración predeterminada, haga clic 'No' o 'Cancel' para abortar la impresión. - + Load model Cargar modelo - + Could not load the database model file `%1'. Check the error stack to see details. You can try to fix it in order to make it loadable again. No se pudo cargar el archivo de modelo de base de datos `%1'. Compruebe la pila de errores para ver los detalles. Usted puede tratar de arreglarlo con el fin de hacer que se puede cargar de nuevo. - + Fix model Fijar modelo - + Cancel Cancelar - + This action will open a web browser window! Want to proceed? Esta acción abrirá una ventana del navegador web! ¿Quieres continuar? - + (no samples found) (no hay ejemplos encontrados) - + save guardar - + export exportar - + diff diff - + Executing pending <strong>%1</strong> operation... Ejecución de operarienes pendientes <strong>%1</strong>... @@ -7030,74 +6951,74 @@ Mensage retornada por el SGBD: `%1' Diálogo - + msg msg - + Exceptions Excepciones - + Show raw text errors or information. Mostrar errores de texto crudos o información. - + Show/hide exceptions stack. Mostrar/ocultar pila excepciones. - + ... ... - - + + &Yes &Si - - + + &No &No - + Cancel Cancelar - + &Ok &Ok - + &Cancel &Cancelar - + Error Error - + Alert Alerta - + Information Información - + Confirmation Confirmación @@ -7359,415 +7280,453 @@ Mensage retornada por el SGBD: `%1' ModelDatabaseDiffForm - - - Database model diff - Diff de modelo de base de datos - - - - Generate diff from model - Generar diff del modelo - Settings Configuraciones - - Input database - Base de datos de entrada - - - + + Connection: Conexión: - + ... ... - + + + Database: bases de datos: - + Ignore import errors Ignorar errores de importación - - Trucate tables before alter columns - Trucate tablas antes alterar las columnas - - - + Import system objects Importar objectos del sistema - + Import extension objects Importar extensión de objecto - + For DROP command, the objects that depends on an object to be dropped will be deleted as well. For TRUNCATE command, tables that are linked to a table to be truncated will be truncate too. <strong>NOTE:</strong> this option can affect more objects than listed in the output or diff preview. Para comando DROP, los objetos que depende de un objeto que se retiren serán eliminados también. Para comando TRUNCATE, tablas que están vinculadas a una mesa para truncar se truncará también. <strong>NOTA:</strong> esta opción puede afectar a varios objetos que se enumeran en la salida o diff vista previa. - + Drop or truncate in cascade mode Drop o truncate en cascada mode - + Permissions already set on database objects will be kept.The ones configured on the model will be applied to the database. Permisos ya establecidos en los objetos de base de datos serán los kept.The configuradas en el modelo se puede aplicar a la base de datos. - + Keep object's permissions Mantenga los permisos del objeto - + Database cluster level objects like roles and tablespaces will not be dropped. No se cayeron objetos de base de datos a nivel de grupo como los roles y espacios de tabla. - + Keep cluster objects Mantenga objetos clúster - + Recreate only unmodifiable objects Recrear objetos sólo no modificables - + Force recreation of objects Forzar recreación de objetos - + Ignores errors generated by duplicated objects when exporting the diff to database. Ignora errores generados por objetos duplicados cuando se exporta el diff de base de datos. - + Ignore duplicity errors Ignorar duplicidad de errores - + Serial columns are converted to integer and having the default value changed to <strong>nextval(sequence)</strong> function call. By default, a new sequence is created for each serial column but checking this option sequences matching the name on column's default value will be reused and will not be dropped. Columnas de serie se convierten a entero y haber cambiado el valor predeterminado para llamada a la función <strong>nextval(sequence)</strong>. De forma predeterminada, se crea una nueva secuencia para cada columna de serie, pero marcando esta opción secuencias que coinciden con el nombre en valor por defecto de la columna se volverá a utilizar y no se borró. - + Reuse sequences on serial columns Reciclar secuencias sobre columnas de serial - + Diff mode Modo diff - + Override the PostgreSQL version when generating the diff. The default is to use the same version as the input database. Anular la versión de PostgreSQL al generar el diff. El valor por defecto es usar la misma versión que la base de datos de entrada. - + Use PostgreSQL: Use PostgreSQL: - + Compares the model and the input database storing the diff in a SQL file for later usage. Compara el modelo y la base de datos de entrada almacenar el diff en un archivo SQL para un uso posterior. - + File: Archivo: - + Select output file Seleccionar archivo de salida - + Compares the model and the input database generating a diff and applying it directly to the latter. <strong>WARNING:</strong> this mode causes irreversible changes on the database and in case of failure the original structure is not restored, so make sure to have a backup before proceed. Compara el modelo y la base de datos de entrada generar un diff y aplicándolo directamente a éste. < strong>ADVERTENCIA:</strong> este modo provoca cambios irreversibles en la base de datos y en caso de fallo de la estructura original no se restablece, así que asegúrese de tener una copia de seguridad antes de proceder. - + Ignores as many as possible errors on import step. This option generates an incomplete diff. - + Clears the data of all tables which will have columns modified. This is useful to avoid errors related to type casting. <strong>WARNING:</strong> DO NOT use this option on production servers and always make a backup before use it. - + Import system (built-in) objects. Use this if the import step is returning errors related to missing objects. - + Import objects created by extensions. Use this if the import step is returning errors even importing built in ones. - + Instead of use an ALTER command to modify certain kind of objects a DROP and CREATE will be used in order to do a full modification. This option does not affects the database object. - + No command to rename the destination database will be generated even the model's name differ from database name. - + Preserve database name - + Avoid the generation of DROP commands for objects that exists in database but not in the model. This is useful when diff a partial model against the complete database. - + Do not drop missing objects - + Store in S&QL file - + + Diff tool + + + + + Generate diff code + + + + + Source database + + + + + Current model: + + + + + (model) + + + + + Compare to + + + + Appl&y on server - + Diff Diff - + + Froce the generation of DROP commands for columns and constraints that exist in database but not in the model. This is useful when diff a partial model against the complete database and the user needs to drop columns and constraint but preserve the rest of the objects. + + + + + Drop missing columns and constraints + + + + + Truncate tables before alter columns + + + + Import && Export - + Import Importar - + Export Exportar - + This advanced option causes pgModeler to ignore extra errors by their numeric codes. These errors must be informed in the input below and separeted by space. For the complete list of error codes check the PostgreSQL docs, section <strong> Appendix A. PostgreSQL Error Codes</strong>. <strong>WARNING:</strong> use this option with extreme care since it can interfere in final export result. - + Ignore error codes - + Output Salida - + Changes: Cambios: - + Cancel Cancelar - + Progress label... Etiqueta de progreso... - + Step label... Etiqueta de pasos... - + <html><head/><body><p>Objects marked with an <span style=" font-weight:600;">ALTER</span> may not be effectively changed unless that the differences detected are in attributes that can be modified through ALTER commands otherwise no operationwill be performed or, if the force recreation is checked, the object will be dropped and created again.</p></body></html> <html><head/><body><p>Objetos marcados con un <span style=" font-weight:600;">ALTER</span> No se puede cambiar de manera efectiva a menos que las diferencias detectadas son en los atributos que se pueden modificar a través de comandos ALTER de lo contrario no se realizará ninguna operationwill o, si la fuerza de la recreación está marcada, el objeto será dado de baja y creó de nuevo.</p></body></html> - + Objects to be created Objetos que se creen - - - - + + + + 0 0 - + Objects to be dropped Objetos que se borran - + Possible objects to be changed Objetos posibles de ser cambiados - + Ignored objects (system ones or with sql disabled) Objetos ignorados (los del sistema o con sql disabilitado) - + Diff Preview Vista previa Diff - + &Apply diff &Aplicar diff - + &Generate &Generar - + &Close &Cerrar - - + + Waiting process to start... Proceso en espera para iniciar... - - Importing database <strong>%1</strong>... - Importando base de datos <strong>%1</strong>... - - - - Comparing the model <strong>%1</strong> and database <strong>%2</strong>... - Comparando el modelo <strong>%1</strong> y la base de datos <strong>%2</strong>... - - - + Confirmation Confirmación - + <strong>WARNING:</strong> The generated diff is ready to be exported! Once started this process will cause irreversible changes on the database. Do you really want to proceed? <strong>ADVERTENCIA:</strong> El diff generada está listo para ser exportado! Una vez iniciado este proceso provocará cambios irreversibles en la base de datos. ¿Realmente desea continuar? - + Apply diff Aplicar diff - + Preview diff Vista previa Diff - - Exporting diff to database <strong>%1</strong>... - Exportando diff a base de datos <strong>%1</strong>... + + model not saved yet + + + + + (none) + + + + + Step %1/%2: Importing database <strong>%3</strong>... + + + + + Step %1/%2: Comparing <strong>%3</strong> and <strong>%4</strong>... + + + + + Step %1/%2: Exporting diff to database <strong>%3</strong>... + - + Diff process paused. Waiting user action... Proceso Diff en pausa. Esperando acción del usuario... - + Saving diff to file <strong>%1</strong> Guardando diff a archivo <strong>%1</strong> - + Diff process sucessfully ended! Proceso Diff finalizado satisfactoriamente! - - + + No operations left. No hay operaciones a la izquierda. - + Operation cancelled by the user. Operación cancelada por el usuario. - + Process aborted due to errors! Proceso abortado debido a errores! - + -- SQL code purposely truncated at this point in demo version! - + -- No differences were detected between model and database. -- -- No se detectaron diferencias entre el modelo y la base de datos. -- - + Error code <strong>%1</strong> found and ignored. Proceeding with export. Error de código encontrado <strong>%1</strong> y ignorado. Procediendo con la exportación. - + Save diff as... Salvar diff como... - + SQL code (*.sql);;All files (*.*) Código SQL (*.sql);;Todos los archivos (*.*) @@ -7776,10 +7735,6 @@ Mensage retornada por el SGBD: `%1' ModelExportForm - Model Export - Exportar Modelo - - Export model Exportar Modelo @@ -8033,17 +7988,17 @@ Mensage retornada por el SGBD: `%1' - + SVG representation of database model - + SVG file generated by pgModeler - + Output file `%1' successfully written. @@ -8093,55 +8048,55 @@ Mensage retornada por el SGBD: `%1' Modo de simulación activado. - + Generating SQL for `%1' objects... Generación de SQL para los objetos `%1'... - + Destroying objects created on the server. Destruyendo los objetos creados en el servidor. - + Restoring original names of database, roles and tablespaces. Restauración de los nombres originales de base de datos, roles y tablespaces. - - + + Creating object `%1' (%2) Creando objecto `%1' (%2) - + Creating database `%1' - + Connecting to database `%1' - + Renaming `%1' (%2) to `%3' - - + + Dropping object `%1' (%2) Borrando objetos `%1' (%2) - + Changing object `%1' (%2) Cambiando objecto `%1' (%2) - + Running auxiliary command. Ejecución de comandos auxiliar. @@ -8307,127 +8262,131 @@ p, li { white-space: pre-wrap; } ModelObjectsWidget - Model Objects Modelo Objetos - + + Visible object types + + + + Hide this widget Ocultar este widget - - - - - - + + + + + + ... ... - + 1 1 - + ID ID - + Object Objecto - + Type Tipo - + Parent Object Objeto Padre - + Parent Type Tipo del Padre - - Visible Object Types - Tipos de objetos visibles - - - + Select All Marcar Todos - + Clear All Desmarcar Todos - + + Model objects + + + + Select Selecionar - + Return Retorno - + Cancel Cancelar - + Esc Esc - + Tree view Vista en árbol - + List view Vista en lista - + Objects view configuration Configuración de la Vista de objetos - + Expands all items Expande todos los items - + Collapses all items Contrae todos los items - + Filter: Filtrar: - + By ID Por ID - + New Nuevo @@ -8502,12 +8461,12 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca ModelValidationHelper - + There are pending errors! SQL validation will not be executed. Hay errores pendientes! No se ejecutará la validación de SQL. - + Operation canceled by the user. Operación cancelada por el usuario. @@ -8565,6 +8524,11 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca ... ... + + + Swap ids + + SQL Validation: @@ -8580,11 +8544,6 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca Try to resolve the reported issues. Trate de resolver los problemas comunicados. - - - Apply Fix - Aplicar Fijar - Ctrl+S @@ -8625,16 +8584,16 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca Esc Esc + + + Apply fixes + + Change the creation order for two objects by swapping their ids Cambiar el orden de la creación de dos objetos mediante el canje de sus ids - - - Swap Ids - Intercambiar Ids - Va&lidate @@ -8666,17 +8625,27 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca - + + The column <strong>%1</strong> on <strong>%2</strong> <em>(%3)</em> is referencing the geospatial data type <strong>%4</strong> but the <strong>postgis</strong> extension is not present in the model! + + + + <strong>HINT:</strong> try to swap the relationship by another ones that somehow are linked to it through generated columns or constraints to solve this issue. Note that other objects may be lost in the swap process. - + + <strong>HINT:</strong> Create the extension in the model or let it be created by applying the needed fixes. + + + + SQL validation not executed! No connection defined. - + Database model successfully validated. @@ -8686,32 +8655,32 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca Validación de SQL ha fallado debido a un error (s) a continuación. <strong>NOTA:</strong><em> Estos errores no invalida el modelo, pero pueden afectar a las operaciones como <strong>export</strong> and <strong>diff</strong>.</em> - + <em>The above object was created by a relationship. Change the name pattern on it's generator relationship. Fix will not be applied!</em> <em>El objetivo anterior fue creado por una relación. Cambiar el patrón de nombre en él la relación de generador. Fijar no se aplicará!</em> - + Conflicting object: <strong>%1</strong> <em>(%2)</em>. Objeto en conflicto: <strong>%1</strong> <em>(%2)</em>. - + Relationship: <strong>%1</strong> [id: %2]. Relación: <strong>%1</strong> [id: %2]. - + Referrer object: <strong>%1</strong> <em>(%2)</em> [id: %3]. Objeto referente:: <strong>%1</strong> <em>(%2)</em> [id: %3]. - + Running SQL commands on server... Ejecución de comandos SQL en el servidor... - + Processing object: %1 Procesando object: %1 @@ -8719,408 +8688,420 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca ModelWidget - + One to One (1-1) Uno a Uno (1-1) - + One to Many (1-n) Uno a Muchos (1-n) - + Many to Many (n-n) Mucho a Mucho (n-n) - - + + Copy Copiar - + Inheritance Herencia - + <strong>ATTENTION:</strong> The database model is protected! Operations that could modify it are disabled! <strong>ATENCIÓN:</strong> El modelo de base de datos está protegida! Operaciones que podrían modificar la misma son habilitado! - + Source Fuente - + Alt+S Alt+S - + Show object source code Exibir el código-Fuente del objeto - - + + Properties Propiedades - + Space Espacio - + Edit the object properties Edita las propriedades del objeto - - + + Protect Proteger - - + + Unprotect Desproteger - + Protects object(s) from modifications Protege objeto(s) a partir de las modificaciones - - + + Delete Eliminar - + Del Del - - + + Del. cascade Del. cascada - + Shift+Del Shift+Del - + Select all Seleccionar todos - + + Select + Selecionar + + + Ctrl+A Ctrl+A - + Selects all the graphical objects in the model Selecciona todos los objetos gráficos en el modelo - + + Edit data + Editar datos + + + Convert Convertir - + Ctrl+C Ctrl+C - + Paste Pegar - + Ctrl+V Ctrl+V - + Cut Cortar - + Ctrl+X Ctrl+X - + Deps && Referrers Deps && Referreridos - + New Nuevo - + Add a new object in the model Adicionar un nuevo objeto en el modelo - + Quick Rápido - + Quick action for the selected object Acciones rápidas para la selección de objecto - + Rename Renombrar - + F2 F2 - + Quick rename the object Renombrar rápida del objeto - + Move to schema Mover al esquema - + Set tag Configurar tag - + Edit permissions Editar permisos - + Ctrl+E Ctrl+E - + Change owner Cambiar propietario - + Select children Seleccione los hijos - + Select tagged - - Highlight - Aspecto interesante - - - + Open relationship Abrir relación - + Custom SQL Personalizar SQL - + Alt+Q Alt+Q - + Convert to sequence Converir a secuencia - + Convert to serial Converir a serial - + Break line Saltos de líena - + Remove points Remover puntos - + Enable SQL Habilitar SQL - + Disable SQL Deshabilitar SQL - + Duplicate Duplicar - + Ctrl+D - + Extended attributes Atributos extendidos - + + Show Mostrar - + + Hide Ocultar - + Jump to table Ir a tabla - + + Schemas rectangles + + + + Fade in/out - - + + Fade in - - + + Fade out - - - + + + Relationships Relaciones - + Swap ids - + Edit the objects creation order by swapping their ids - + 90° (vertical) 90° (vertical) - + 90° (horizontal) 90° (horizontal) - + 90° + 90° (vertical) 90° + 90° (vertical) - + 90° + 90° (horizontal) 90° + 90° (horizontal) - - - + + + All objects Todos los objetos - - + + Schemas - - + + Tables Tablas - - + + Views Vistas - - + + Textboxes - + Zoom: %1% Zoom: %1% - + Do you really want to convert the relationship into an intermediate table? ¿Realmente desea convertir la relación en una tabla intermedia? - + Loading database model Cargando modelo de base de datos - + Saving database model Guardando modelo de base de datos @@ -9145,67 +9126,72 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca También copiar todas las dependencias de los objetos seleccionados? Esto minimiza la ruptura de referencias cuando los objetos copiados se pegan en otro modelo. - + Pasting objects... Pegar Objetos... - + Validating object: `%1' (%2) Validando El objeto: `%1' (%2) - + Generating XML for: `%1' (%2) Generando código XML del objeto: `%1' (%2) - + Pasting object: `%1' (%2) Pegar Objetos: `%1' (%2) - + Not all objects were pasted to the model due to errors returned during the process! Refer to error stack for more details! No todos los objetos se pegan a la modelo debido a errores devueltos durante el proceso! Consulte a un error de pila para más detalles! - + <strong>CAUTION:</strong> You are about to delete objects in cascade mode which means more objects than the selected will be dropped too. Do you really want to proceed? <strong>PRECAUCIÓN:</strong> Estás a punto de eliminar objetos en modo de cascada que significa más objetos que el seleccionado se redujo también. ¿Realmente desea continuar? - + <strong>CAUTION:</strong> Remove multiple objects at once can cause irreversible invalidations to other objects in the model causing such invalid objects to be deleted too. Do you really want to proceed? <strong>PRECAUCIÓN:</strong> Eliminar varios objetos a la vez puede causar invalidaciones irreversibles a otros objetos en el modelo que causa este tipo de objetos no válidos para ser borrados también. ¿Realmente desea continuar? - + <strong>CAUTION:</strong> Remove a relationship can cause irreversible invalidations to other objects in the model causing such invalid objects to be deleted too. Do you really want to proceed? <strong>PRECAUCIÓN:</strong> Eliminar una relación puede causar invalidaciones irreversibles a otros objetos en el modelo que causa este tipo de objetos no válidos para ser borrados también. ¿Realmente desea continuar? - + Do you really want to delete the selected object? ¿Realmente desea eliminar el objeto seleccionado? - + The cascade deletion found some problems when running! Some objects could not be deleted or registered in the operation's history! Please, refer to error stack for more details. La eliminación en cascada encontró algunos problemas al ejecutar! Algunos objetos no podían ser borrados o registrados en la historia de la operación! Por favor, consulte a un error de la pila para obtener más detalles. - + (no objects) (no hay objetos) - + + None + + + + Source code Código fuente - + Constraints Restricciones @@ -9213,32 +9199,32 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca ModelsDiffHelper - + Processing object `%1' (%2)... Procesando objecto `%1' (%2)... - + Skipping object `%1' (%2)... Omitiendo objeto `%1' (%2)... - + Processing diff infos... Procesando diff infos... - + Processing `%1' info for object `%2' (%3)... - + No differences between the model and database. - + Preparing diff code... @@ -9251,78 +9237,78 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca Formulario - + Role Rol - + Tag Tag - + Cast Cast - + A A - + Language Lenguaje - + Textbox Textbox - + Event Trigger Evento Trigger - + Tablespace Tablespace - + Schema Esquema - + Domain Dominio - + Conversion Conversión - + Aggregate Agregado - + Collation Collation - + Table Tabla - + Type Tipo @@ -9332,12 +9318,12 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca Op. Familia - + Sequence Sequencia - + Extension Extensión @@ -9347,12 +9333,12 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca Función - + Op. Class Op. Clase - + Operator Operador @@ -9362,13 +9348,13 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca Vista - + Permissions Permisos - + Rule Regla @@ -9388,37 +9374,42 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca Restricción - + Generic SQL - + Trigger Trigger - + + Policy + + + + Many-to-many Muchos-a-muchos - + One-to-many Uno-a-muchos - + One-to-one Uno-a-uno - + Inheritance Herencia - + Copy Copia @@ -9519,6 +9510,7 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca + 9 9 @@ -9548,37 +9540,37 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca B - + 8 8 - + 1 1 - + 2 2 - + 3 3 - + 5 5 - + 4 4 - + 0 0 @@ -9586,63 +9578,67 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca NumberedTextEditor - - + Load file - + Load the object's source code from an external file - - Edit source + + Load + Cargar + + + + Edit - + Edit the source code in the preferred external editor - + Clear Limpiar - + Upper case - + Lower case - + Ident right - + Ident left - + SQL file (*.sql);;All files (*.*) Archivo SQL (*.sql);;Todos los archivos (*.*) - - The source code is currently being edited in the application `%1' (pid: %2)! Only one instance of the source code editor application is allowed. + + The source editor `%1' is running on `pid: %2'. - + Could not start the source code editor application `%1'! Make to sure that the source editor path defined in the general settings points to a valid executable and the current user has permission to run the application. Error message returned: `%2' @@ -9718,113 +9714,135 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca Formulario - + Pattern: Patrón: - + Find Buscar - + Defines the search filter Define el filtro de búsqueda - + Filter Filtro - + Clears the search results Limpiar los resultados de la búsqueda - + Clear Limpiar - - Highlight graphical objects when selecting them or their children on the result list - Resaltar objetos gráficos al seleccionar a ellos oa sus hijos en la lista de resultados - - - - Highlight - Resaltar - - - - + + ... ... - + Hide this widget Ocultar este widget - + + (Un)selects the graphical objects in the results grid + + + + + Select + Selecionar + + + Regular Expression Expresión Regular - + Exact Match Resultado Exacto - + Select All Selecionar todos - + Clear All Limpiar Todos - + Case Sensitive Sensible Case - + ID ID - + Object Objecto - + Type Tipo - + Parent Object Objecto Padre - + Parent Type Tipo del Padre - + + Fades outs all the graphical objects in the results grid (or those not listed). The current fade in/out state of all objects is modified. + + + + + Fade out + + + + + + Listed + + + + + + Not listed + + + + Found <strong>%1</strong> object(s). Encontrado objecto(s) <strong>%1</strong>. - + No objects found. Objetos no encontrados. @@ -9876,131 +9894,131 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca Seleccionar Objecto - + Select %1 - ObjectTableWidget + ObjectsTableWidget - + Form - Formulario + Formulario - + Add Item - Adicionar Item + - + Ins - Ins + Ins - + Remove Item - Remover Item + - + Del - Del + Del - + Update Item - Actualizar Item + Actualizar Item - + Alt+R - Alt+R + Alt+R - + Remove All - Remover Todo + - + Shift+Del - Shift+Del + Shift+Del - + Duplicate item - + Ctrl+D - + Edit Item - Editar Item + Editar Item - + Space - Espacio + Espacio - + Move Up - Mover Arriba + Mover Arriba - + Ctrl+Up - Ctrl+Up + Ctrl+Up - + Move Down - Mover Abajo + Mover Abajo - + Ctrl+Down - Ctrl+Down + Ctrl+Down - + Move to start - Mover al inicio + Mover al inicio - + Ctrl+Home - Ctrl+Home + Ctrl+Home - + Move to end - Mover al final + Mover al final - + Ctrl+End, Ctrl+S - Ctrl+End, Ctrl+S + Ctrl+End, Ctrl+S - - + + Confirmation - Confirmación + Confirmación - + Do you really want to remove the selected item? - ¿Realmente desea eliminar el elemento seleccionado? + ¿Realmente desea eliminar el elemento seleccionado? - + Do you really want to remove all the items? @@ -10321,13 +10339,13 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca - + Roles Roles - + Privileges Privilégios @@ -10382,32 +10400,27 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca Vista previa Código - - Type: - Tipo: - - - - Role - Rol - - - + Id Id - - Leave the <em><strong>Roles</strong></em> empty to create a permission applicable to <strong><em>PUBLIC</em></strong>. - Deje los <em><strong>Roles</strong></em> vacío para crear un permiso aplicable a <strong><em>PUBLIC</em></strong>. + + Name + Nombre - + + Leave the <em><strong>Roles</strong></em> grid empty in order to create a %1 applicable to <strong><em>PUBLIC</em></strong>. + + + + -- No permissions defined for the specified object! -- No hay permisos definidos para el objeto especificado! - + /* Could not generate the SQL code preview for permissions! / * No se pudo generar el código SQL para previsualización permisos! @@ -10415,384 +10428,674 @@ The requested size %1 x %2 was too big and there was not enough memory to alloca PgModelerCLI - + Unrecognized option '%1'. Opción no reconocido '%1'. - + Value not specified for option '%1'. El valor no se especifica para la opción '%1'. - + Option '%1' does not accept values. Opción '%1' no acepta valores. - - Connection aliased as '%1' was not found on configuration file. - Conexión con alias como '%1' no se ha encontrado en el archivo de configuración. - - - + Usage: pgmodeler-cli [OPTIONS] El uso: pgmodeler-cli [OPTIONS] - - + + command line interface. interfaz de línea de comandos. - - PostgreSQL Database Modeler Project - pgmodeler.com.br - Proyecto Modelador Base de datos PostgreSQL - pgmodeler.com.br - - - - Copyright 2006-2015 Raphael A. Silva <raphael@pgmodeler.com.br> - Copyright 2006-2013 Raphael A. Silva <rkhaotix@gmail.com> - - - - This CLI tool provides the operations to export pgModeler's database models without -the need to load them on graphical interface as well to fix model files to the most recent -accepted structure. All available options are described below. - Esta herramienta proporciona una manera de exportar pgModeler's modelos de base de datos sin -la necesidad de cargarlos en la interfaz gráfica. Todos los disponibles exportación -modos se describen a continuación. - - - + General options: Opciones Generales: - + DBMS export options: Opciones de exportación del SGDB: - + Miscellaneous options: Otros Opciones: - + There are no connections configured. No hay conexiones configuradas. - - Available connections (alias : conn. string) - Conexiones disponibles (alias:. Conn cadena) - - - - No export mode specified! - No se especifica el modo de exportación! - - - - Export, fix model and update mime operations can't be used at the same time! - Las operaciones de exportación, modelo fijo y actualización mime no se pueden utilizar al mismo tiempo! - - - - No input file specified! - Sin archivo de entrada especificado! - - - - No output file specified! - Sin archivo de salida especificado! - - - + Input file must be different from output! Archivo de entrada debe ser diferente de la salida! - + Incomplete connection information! Información de conexión incompleto! - + Invalid zoom specified! Inválido Zoom especificado! - + Invalid action specified to update mime option! Acción inválida para actualizar opción mimo! - + Starting model fixing... Iniciar fijación modelo... - + Starting mime update... Iniciar actualización de mime... - + Starting model export... Comenzando del modelo de exportación ... + + + Model successfully fixed! + Modelo fijado correctamente! + + + + PNG and SVG export options: + + + + + Connection aliased as '%1' was not found in the configuration file. + + + + + PostgreSQL Database Modeler Project - pgmodeler.io + + + + + Copyright 2006-2018 Raphael A. Silva <raphael@pgmodeler.io> + + + + + This CLI tool provides several operations over models and databases without the need to perform them +in pgModeler's graphical interface. All available options are described below. + + + + + %1, %2 [FILE] Input model file (.dbm). This is mandatory for fix, export operations. + + + + + %1, %2 [DBNAME] Input database name. This is mandatory for import operation. + + + + + %1, %2 [FILE] Output file. This is mandatory for fixing model or exporting to file, png or svg. + + + + + %1, %2 Try to fix the structure of the input model file in order to make it loadable again. + + + + + %1, %2 [NUMBER] Model fix tries. When reaching the maximum count the invalid objects will be discarded. + + + + + %1, %2 Export the input model to a sql script file. + + + + + %1, %2 Export the input model to a png image. + + + + + %1, %2 Export the input model to a svg file. + + + + + %1, %2 Export the input model directly to a PostgreSQL server. + + + + + %1, %2 Import a database to an output file. + + + + + %1, %2 Compares a model and a database or two databases generating the SQL script to synch the latter in relation to the first. + + + + + %1, %2 Force the PostgreSQL version of generated SQL code. + + + + + %1, %2 Silent execution. Only critical messages and errors are shown during process. + + + + + %1, %2 Show this help menu. + + + + + Connection options: + + + + + %1, %2 List available connections in file %3. + + + + + %1, %2 [ALIAS] Connection configuration alias to be used. + + + + + %1, %2 [HOST] PostgreSQL host in which a task will operate. + + + + + %1, %2 [PORT] PostgreSQL host listening port. + + + + + %1, %2 [USER] PostgreSQL username. + + + + + %1, %2 [PASSWORD] PostgreSQL user password. + + + + + %1, %2 [DBNAME] Connection's initial database. + + - Loading input file: - Cargando archivo de entrada: + %1, %2 Draws the grid in the exported image. + + + + + %1, %2 Draws the page delimiters in the exported image. + + + + + %1, %2 Each page will be exported in a separated png image. (Only for PNG images) + + + + + %1, %2 [FACTOR] Applies a zoom (in percent) before export to png image. Accepted zoom interval: %3-%4 (Only for PNG images) + - Fixed model file: - Fijando archivo de modelo: + %1, %2 Ignores errors related to duplicated objects that eventually exist in the server. + + + + + %1, %2 [CODES] Ignores additional errors by their codes. A comma-separated list of alphanumeric codes should be provided. + + + + + %1, %2 Drop the database before execute a export process. + + + + + %1, %2 Runs the DROP commands attached to SQL-enabled objects. + + + + + %1, %2 Simulates an export process by executing all steps but undoing any modification in the end. + + + + + %1, %2 Generates temporary names for database, roles and tablespaces when in simulation mode. + + + + + Database import options: + - Model successfully fixed! - Modelo fijado correctamente! + %1, %2 Ignore all errors and try to create as many as possible objects. + - - PNG and SVG export options: + + %1, %2 Import system built-in objects. This option causes the model bloating due to the importing of unneeded objects. - - %1, %2=[FILE] Input model file (.dbm). Mandatory use when fixing a model or exporting it. + + %1, %2 Import extension objects. This option causes the model bloating due to the importing of unneeded objects. - - %1, %2=[FILE] Output file. Mandatory use when fixing model or export to file or png. + + %1, %2 Run import in debug mode printing all queries executed in the server. - - %1, %2 Try to fix the structure of the input model file in order to make it loadable again. + + Diff options: - - %1, %2 Model fix tries. When reaching the maximum count the invalid objects will be discard. + + %1, %2 [DBNAME] The database used in the comparison. All the SQL code generated is applied to it. - - %1, %2 Export to a sql script file. + + %1, %2 Save the generated diff code to output file. - - %1, %2 Export to a png image. + + %1, %2 Apply the generated diff code on the database server. - - %1, %2 Export to a svg file. + + %1, %2 Don't preview the generated diff code when applying it to the server. - - %1, %2 Export directly to a PostgreSQL server. + + %1, %2 Drop cluster level objects like roles and tablespaces. - - %1, %2 List available connections on %3 file. + + %1, %2 Revoke permissions already set on the database. New permissions configured in the input model are still applied. - - %1, %2 Version of generated SQL code. Only for file or dbms export. + + %1, %2 Drop missing objects. Generates DROP commands for objects that are present in the input model but not in the compared database. - - %1, %2 Silent execution. Only critical errors are shown during process. + + %1, %2 Force the drop of missing columns and constraints. Causes only columns and constraints to be dropped, other missing objects aren't removed. - - %1, %2 Show this help menu. + + %1, %2 Rename the destination database when the names of the involved databases are different. - - %1, %2 Draws the grid on the exported png image. + + %1, %2 Don't drop or truncate objects in cascade mode. - - %1, %2 Draws the page delimiters on the exported png image. + + %1, %2 Truncate tables prior to alter columns. Avoids errors related to type casting when the new type of a column isn't compatible to the old one. - - %1, %2 Each page will be exported on a separated png image. (Only for PNG) + + %1, %2 Don't reuse sequences on serial columns. Drop the old sequence assigned to a serial column and creates a new one. - - %1, %2=[FACTOR] Applies a zoom (in percent) before export to png image. Accepted zoom interval: %3-%4 (Only for PNG) + + %1, %2 Don't force the recreation of objects. Avoids the usage of a DROP and CREATE commands to create a new version of the objects. - - %1, %2 Ignores errors related to duplicated objects that eventually exists on server side. + + %1, %2 Don't recreate the unmodifiable objects. These objects are the ones which can't be changed via ALTER command. - - %1, %2=[CODES] Ignores additional errors by their codes. A comma-separated list of alphanumeric codes should be provided. + + %1, %2 [ACTION] Handles the file association to .dbm files. The ACTION can be [%3 | %4]. - - %1, %2 Drop the database before execute a export process. + + ** The diff process allows the usage of the following options related to import and export operations: - - %1, %2 Runs the DROP commands attached to SQL-enabled objects. + + * Export: - - %1, %2 Simulates a export process. Actually executes all steps but undoing any modification. + + * Import: - - %1, %2 Generates temporary names for database, roles and tablespaces when in simulation mode. + + ** When running the diff using two databases (%1 and %2) there's the need to specify two connections/aliases. - - %1, %2=[ALIAS] Connection configuration alias to be used. + + If only one connection is set it will be used to import the input database as well to retrieve database used in the comparison. - - %1, %2=[HOST] PostgreSQL host which export will operate. + + A second connection can be specified by appending a 1 on any connection configuration parameter listed above. - - %1, %2=[PORT] PostgreSQL host listening port. + + Available connections (alias : connection string) - - %1, %2=[USER] PostgreSQL username. + + No operation mode was specified! - - %1, %2=[PASSWORD] PostgreSQL user password. + + Export, fix model, import database, diff and update mime operations can't be used at the same time! - - %1, %2=[DBNAME] Connection's initial database. + + Multiple export mode was specified! - - %1, %2=[ACTION] Handles the file association to .dbm files. The ACTION can be [%3 | %4]. + + No input file was specified! - - Multiple export mode specified! + + No input database was specified! - - Mime database successfully updated. + + No output file was specified! - - Export to PNG image: - Exportar a imagen PNG: + + No input file or database was specified! + + + + + The input file and database can't be used at the same time! + + + + + No database to be compared was specified! + - - Export to SVG file: + + No diff action (save or apply) was specified! - - Export to SQL script file: - Exportar a archivo de comandos SQL: + + No output file for the diff code was specified! + - - Export to DBMS: - Exportar a SGDB: + + ** Error code `%1' found and ignored. Proceeding with export. + - - Export successfully ended! - Exportación terminó correctamente! + + ** Command: %1 + - + Extracting objects' XML... Exportando objetos XML... - + Invalid input file! It seems that is not a pgModeler generated model or the file is corrupted! Archivo de entrada no es válido! Parece que no es un modelo pgModeler generada o el archivo está dañado! - + Recreating objects... Recreando objetos... - - -** Object(s) that couldn't fixed: - -** Objeto(s) que no podían ser fijado: + + +** Object(s) that couldn't fixed: + +** Objeto(s) que no podían ser fijado: + + + + WARNING: There are objects that maybe can't be fixed. Trying again... (tries %1/%2) + ADVERTENCIA: Hay objetos que tal vez no se pueden arreglar. Tratando de nuevo ... (Trata %1/%2) + + + + + Loading input file: %1 + + + + + Fixed model file: %1 + + + + + Export to PNG image: %1 + + + + + Export to SVG file: %1 + + + + + Export to SQL script file: %1 + + + + + Export to DBMS: %1 + + + + + Export successfully ended! + + + + + + Starting database import... + + + + + + Input database: %1 + + + + + Saving the imported database to file... + + + + + Import successfully ended! + + + + + + Starting diff process... + + + + + Input model: %1 + + + + + Compare to: %1 + + + + + Loading input model... + + + + + + Importing the database `%1'... + + + + + Comparing the generated models... + + + + + No differences were detected. + + + + + Saving diff to file `%1' + + + + + ** WARNING: You are about to apply the generated diff code to the server. Data can be lost in the process! + + + + + ** Proceed with the diff applying? (yes/no) > + + + + + yes + + + + + + no + + + + + Diff code not applied to the server. + + + + + Applying diff to the database `%1'... + + + + + Diff successfully ended! + + - - WARNING: There are objects that maybe can't be fixed. Trying again... (tries %1/%2) - ADVERTENCIA: Hay objetos que tal vez no se pueden arreglar. Tratando de nuevo ... (Trata %1/%2) + + Mime database successfully updated! + + - + Database model files (.dbm) are already associated to pgModeler! Archivos de modelo de base de datos (.dbm) ya están asociados a pgModeler! - + There is no file association related to pgModeler and .dbm files! No hay ninguna asociación de archivos relacionados con pgModeler y archivos .dbm! - + Mime database operation: %1 Operación Mime de base de datos: %1 - + Can't erase the file %1! Check if the current user has permissions to delete it and if the file exists. No se puede borrar el archivo% 1! Compruebe si el usuario actual tiene permisos para eliminarlo y si existe el archivo. - + Running update-mime-database command... Ejecución de comando update-mime-database... @@ -10818,17 +11121,17 @@ modos se describen a continuación. PgModelerUiNS - + Do you want to apply the <strong>SQL %1 status</strong> to the object's references too? This will avoid problems when exporting or validating the model. ¿Desea aplicar el <strong>SQL %1 estatus</strong> a las referencias del objeto también? Esto evitará problemas al exportar o validar el modelo. - + disabling deshabilitando - + enabling habilitando @@ -10967,18 +11270,66 @@ modos se describen a continuación. Biblioteca + + PolicyWidget + + + Basics + + + + + Command: + + + + + Permissive + + + + + Roles + Roles + + + + Expressions + Expresiones + + + + USING: + + + + + CHECK: + + + + + Name + Nombre + + + + Leave the <em><strong>Roles</strong></em> grid empty in order to create a %1 applicable to <strong><em>PUBLIC</em></strong>. + + + QObject - + new_database new_database - - - - + + + + %1 (line: %2) %1 (line: %2) @@ -11554,74 +11905,82 @@ modos se describen a continuación. por Defecto - + Referer View: Vista Intermedia: - + Referer view references one or more columns of a table to construct it's own columns. Vista Intermedia hace referencia a una o más columnas de una tabla de construir es propias columnas. - + Referenced table has its columns referenced by a view in order to construct the columns of this latter. Tabla referenciada tiene sus columnas referenciadas por una vista para construir las columnas de este último. - + Referer Table: Tabla Intermedia: - + Referer table references one or more columns of a table through foreign keys. This is the (n) side of relationship. Tabla intermedia referencia a una o más columnas de una tabla a través de claves externas. Este es el lado (n) de relación. - + Referenced table has its columns referenced by a table's foreign key. This is the (1) side of relationship. Tabla referenciada tiene sus columnas referenciadas por una mesa y apos; s clave externa. Esta es la (1) lado de relación. - + Referenced Table: Tabla Referenciada: - - - + + + Reference Table: Tabla Referencia: - + Reference table has the columns from its primary key will copied to the receiver table in order to represent the linking between them. This is the (1) side of relationship. Tabla de referencia tiene las columnas de su clave primaria se copian en la tabla del receptor con el fin de representar a la vinculación entre ellos. Esta es la (1) lado de relación. - + Receiver Table: Tabla Receptora: - + Receiver (or referer) table will receive the generated columns and the foreign key in order to represent the linking between them. This is the (n) side of relationship. Receptor tabla (o intermedia) recibirá las columnas generadas y la clave externa con el fin de representar a la vinculación entre ellos. Este es el lado (n) de relación. - + In many-to-many relationships both tables are used as reference to generate the table that represents the linking. Columns from both tables are copied to the resultant table and two foreign keys are created as well in order to reference each participant table. En muchos-a-muchos relación ambas tablas se utilizan como referencia para generar la tabla que representa la vinculación. Las columnas de ambas tablas se copian en la tabla resultante y dos claves externas se crean así con el fin de hacer referencia a cada mesa participante. - - + + is required es requerido + + ResultSetModel + + + [binary data] + [datos binarios] + + RoleWidget @@ -11631,7 +11990,7 @@ modos se describen a continuación. - + Validity Validez @@ -11652,54 +12011,59 @@ modos se describen a continuación. - Inherit Permissions - Heredar Permisos + Inherit permissions + - Can create Database - Puede Crear Base de Datos + Can create database + - Can Login - Permitir Login + Bypass RLS + - Can create Role - Puede Crear Rol + Can use replication + - Can use Replication - Puede usar Replicación + Can login + Puede login + + + + Can create role + - - + + Members Miembros - - + + Member of Miembro de - - + + Members (Admin.) Miembros (Admin.) - + Password: Contraseña: - + Encrypted Encriptada @@ -11709,7 +12073,7 @@ modos se describen a continuación. - + Role Rol @@ -11760,7 +12124,7 @@ modos se describen a continuación. Formulario - + Save SQL commands Guardar comandos SQL @@ -11805,218 +12169,221 @@ modos se describen a continuación. - - Ctrl+S - Ctrl+S - - - + Run the specified SQL command Ejecutar un comando SQL especificada - + Run SQL Ejecutar SQL - + F6 F6 - + Clear sql input field and results Limpiar campo de entrada de SQL y resultados - + Clear All Limpiar Todos - - + + Export results to a CSV file Exportar resultados a un acchivo CSV - + Snippe&ts Snippe&ts - + + Alt+T + + + + E&xport E&xportar - + + Alt+X + + + + Toggles the output pane - + &Output - + Alt+O Alt+O - + Current working database - - - + + + Results - + Messages - + History - - ... ... - + SQL file (*.sql);;All files (*.*) Archivo SQL (*.sql);;Todos los archivos (*.*) - + Load Cargar - + Save - + Save as Guardar como - + [binary data] [datos binarios] - + No results retrieved or changes done due to the error above. - - + + Messages (%1) - + Results (%1) - - [%1]: SQL command successfully executed. <em>%2 <strong>%3</strong></em> + + [%1]: SQL command successfully executed in <em><strong>%2</strong></em>. <em>%3 <strong>%4</strong></em> - + Rows affected - + Rows retrieved - + Load SQL commands Cargar comandos SQL - + Save CSV file Guardar archivos CSV - + Comma-separated values file (*.csv);;All files (*.*) Archivo de valores separados por comas (*.csv);;Todos los archivos (*.*) - + The SQL input field and the results grid will be cleared! Want to proceed? El campo de entrada de SQL y la cuadrícula de resultados se borrará! ¿Quieres continuar? - + Copy selection Copiar la selección - + Plain format - + CVS format - + This action will wipe out all the SQL commands history for all connections! Do you really want to proceed? - + Clear history Limpiar historial - + Save history - + Reload history - + Find in history - + Hide find tool - + This action will wipe out all the SQL commands history for the current connection! Do you really want to proceed? @@ -12113,20 +12480,20 @@ modos se describen a continuación. - - + + Currently selected object(s) - - + + Dimensions of the selected object(s) - - + + Current zoom factor @@ -12162,40 +12529,50 @@ modos se describen a continuación. SequenceWidget - + Cyclic: Cíclico: - + Start: Inicio: - + Maximum: Maximo: - + Minimum: Minimo: - + + Defualt values: + + + + Increment: Incremento: - + Cache: Cache: - + Owner Col.: Dueño Col.: + + + User defined + + SnippetsConfigWidget @@ -12372,82 +12749,77 @@ modos se describen a continuación. PostgreSQL - + iconecodigo iconecodigo - + SQL SQL - + Code display: Visualización de Código: - + Original Originales - + Original + depedencies' SQL Originales + SQL dependientes - + Original + children's SQL Originales + SQL hijos - + Save the SQL code to a file. Guardar el código SQL code para un archivo. - + Save SQL Guardar SQL - + XML XML - - - Type: - Tipo: - Source code visualization Visualización del código fuente - + <strong>Original:</strong> displays only the original object's SQL code.<br/><br/> <strong>Dependencies:</strong> displays the original code including all dependencies needed to properly create the selected object.<br/><br/> <strong>Children:</strong> displays the original code including all object's children SQL code. This option is used only by schemas, tables and views. - + Save SQL code as... Guardar código SQL como... - + SQL code (*.sql);;All files (*.*) Código SQL (*.sql);;Todos los archivos (*.*) - + Generating source code... Generación de código fuente... - + -- NOTE: the code below contains the SQL for the selected object -- as well for its dependencies and children (if applicable). -- @@ -12472,19 +12844,19 @@ modos se describen a continuación. - + -- SQL code purposely truncated at this point in demo version! - + -- SQL code unavailable for this type of object -- -- Código SQL disponible para este tipo de objeto -- - + <!-- XML code preview disabled in demonstration version --> <!-- Código XML previsualización desactivado en la versión de demostración --> @@ -12571,12 +12943,12 @@ modos se describen a continuación. Table - + new_table nueva_tabla - + In demonstration version tables can have only `%1' instances of each child object type or ancestor tables! You've reach this limit for the type: `%2' En la demostración mesas versión sólo pueden tener `%1' instancias de cada tipo de objeto hijo o antepasado de la tabla! Tienes que llegar a este límite para el tipo: `%2' @@ -12589,104 +12961,179 @@ modos se describen a continuación. - + + Copy items on the grid + + + + + Copy + + + + Add empty rows - + + Add row + + + + Ins Ins - + + Delete column + + + + + Paste items on the grid + + + + + Paste + Pegar + + + + Ctrl+V + Ctrl+V + + + Fills the grid using a CSV file - - <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in two slashes, e.g., <span style=" font-weight:600;">/value/</span>. To use a slash as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\/</span>.</p></body></html> + + <html><head/><body><p>Some invalid or duplicated columns were detected. In order to solve this issue double-click the header of the highlighted ones in order to define the correct name in which the data belongs to or delete the entire column. Note that these columns are completely ignored when generating the <span style=" font-weight:600;">INSERT</span> commands.</p></body></html> + + + + + Add column + + + + + Duplicate rows + + + + + Change the values of all selected cells at once + + + + + Bulk data edit + + + + + Ctrl+E + Ctrl+E + + + + Delete all columns + + + + + Delete rows - - Some invalid or duplicated columns were detected. In order to solve this issue double-click the header of the highlighted ones in order to define the correct name in which the data belongs to or delete the entire column. Note that these columns are completely igored when generating the <strong>INSERT</strong> commands. + + <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in two slashes, e.g., <span style=" font-weight:600;">/value/</span>. To use a slash as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\/</span>.</p></body></html> - + Add an empty column - + Remove all rows from the grid preserving columns - + + Delete all rows + + + + Shift+Del Shift+Del - + Delete the selected rows - - + + Del Del - + Duplicate the selected rows - + Ctrl+D - + Delete the selected columns - + Remove all columns (and rows) from the grid - + Ctrl+Shift+Del - + Delete columns is an irreversible action! Do you really want to proceed? - + Remove all rows is an irreversible action! Do you really want to proceed? - + Remove all columns is an irreversible action! Do you really want to proceed? - - + + Unknown column - + Duplicated column @@ -12694,7 +13141,7 @@ modos se describen a continuación. TableObjectView - + Relationship: %1 @@ -12709,162 +13156,213 @@ Relación: %1 Opciones - + Tag: Tag: - + With OID Con OIDs - + Generate ALTER for columns/constraints Generar ALTER para columnas/restricciones - + Unlogged Invitados - + + Enable row level security + + + + + Force RLS for owner + + + + &Columns &Columnas - + Co&nstraints - + Tri&ggers - + &Rules &Reglas - + &Indexes &Indíces - + + &Policies + + + + &Tables &Tablas - + Edit data Editar datos - + Define initial data for the table Definir los datos iniciales de la tabla - - - - - - + + + + + + + Name Nombre - + Schema Esquema - - - + + + Type Tipo - + PK - + Default Value Valor por defecto - + Attribute(s) Atributo(s) - + It is not possible to mark a column as primary key when the table already has a primary key which was created by a relationship! This action should be done in the section <strong>Primary key</strong> of the relationship's editing form. - + It is not possible to mark a column created by a relationship as primary key! This action should be done in the section <strong>Primary key</strong> of the relationship's editing form. - + ON DELETE ON DELETE - + ON UPDATE ON UPDATE - + Refer. Table Tabla Refer - + Firing Firing - + Events Eventos - + Execution Ejecución - + Event Evento - + Indexing Indezado - + + Command + + + + + Permissive + + + + + USING expression + + + + + CHECK expression + + + + + Roles + Roles + + + Parent Padre - + Copy Copia + + + Yes + Si + + + + No + No + TablespaceWidget @@ -12964,7 +13462,7 @@ Relación: %1 Subrayado - + Select text color Seleccionar color del texto @@ -13389,132 +13887,162 @@ Relación: %1 Referencias - + Expression Alias: Alias Expresión: - + Column: Columna: - + Table: Tabla: - + Table Alias: Alias Tabla: - + Used in: Usado en: - + Column Columna - + Expression Expresión - + Reference Type: Tipo de Referencia: - - SELECT-FROM - SELECT-FROM + + View Definition + Definición de Vista + + + + Expression: + Expresión: + + + + Column Alias: + Alias de Columna: + + + + The element will be used as part of the SELECT statement to retrieve columns or expressions that will compose the view's columns + - - FROM-WHERE - FROM-WHERE + + SELECT ... + - - After WHERE - After WHERE + + The element will be used as part of the WHERE clause in form of conditional expression + - View Definition - Definición de Vista + WHERE ... + - - Expression: - Expresión: + + The element is used in the FROM portion of the command in order to reference tables or construct JOIN statements + - Column Alias: - Alias de Columna: + FROM ... + + + + + The element's expression is used exclusively as the view's definition + + + + + The element will be appended to the very end of the view's definition. This is useful when using GROUP BY/HAVING statements + + + + + End expression + - + Triggers Triggers - + Rules Reglas - + Indexes Índices - + Table Expression Expresión de tabla - + Code Preview Vista previa código - + Options Opciones - + Tag: Tag: - + Mode: Modo: - + Ordinary Ordinario - + Recursi&ve - + &Materialized - + With no data Sin datos @@ -13535,8 +14063,8 @@ Relación: %1 - Flags: SF FW AW VD - Banderas: SF FW AW VD + Flags: SF FW AW EX VD + @@ -13581,7 +14109,7 @@ Relación: %1 Evento - + /* Could not generate the SQL code. Make sure all attributes are correctly filled! / * No se pudo generar el código SQL. Asegúrese de que todos los atributos se rellenan correctamente! diff --git a/lang/fr_FR.qm b/lang/fr_FR.qm index 7b1f0ecfd4..ebcebe06c4 100644 Binary files a/lang/fr_FR.qm and b/lang/fr_FR.qm differ diff --git a/lang/fr_FR.ts b/lang/fr_FR.ts index c10f2c124d..ba610dacee 100644 --- a/lang/fr_FR.ts +++ b/lang/fr_FR.ts @@ -4,661 +4,647 @@ AboutWidget + About pgModeler À propos de pgModeler - PostgreSQL Database Modeler - PostgreSQL Database Modeler - - - Open source data modeling tool designed for PostgreSQL. No more DDL commands written by hand, let pgModeler do the job for you! This software reunites the concepts of entity-relationship diagrams and the features that PostgreSQL implements as extensions of SQL standards. - Outil de modéliation entité-association pour PostgreSQL. Plus aucun ordre LDD à saisir à la main, laissez PgModeler le faire pour vous ! Ce logiciel fusionne le concept de modélisation entité-association et toutes les fonctionnalités étendues que propose PostgreSQL en plus des standards SQL. - - - Design, configure, deploy - Concevoir, configurer, déployer - - - <html><head/><body><p><a href="http://pgmodeler.com.br"><span style=" font-size:11pt; font-style:italic; text-decoration: underline; color:#0057ae;">http://pgmodeler.com.br</span></a></p></body></html> - <html><head/><body><p><a href="http://pgmodeler.com.br"><span style=" font-size:11pt; font-style:italic; text-decoration: underline; color:#0057ae;">http://pgmodeler.com.br</span></a></p></body></html> - - - pgModeler is proudly a brazilian software! - pgModeler est un logiciel brésilien et fier de l'être! - - - <html><head/><body><p>Copyright 2006-2015 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.com.br</span></a>&gt;</p></body></html> - <html><head/><body><p>Copyright 2006-2015 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.com.br</span></a>&gt;</p></body></html> - - - Contributors - Contributeurs - - - <html><head/><body><p>This page is dedicated to all contributors who gave a bit of their time in make pgModeler a better software somehow. The complete list of people that helped pgModeler can be found at <a href="https://github.com/pgmodeler/pgmodeler/graphs/contributors"><span style=" text-decoration: underline; color:#00a489;">GitHub</span></a>.</p><p>If you have a great idea to improve pgModeler please submit it <a href="http://github.com/pgmodeler/pgmodeler/issues"><span style=" text-decoration: underline; color:#00a489;">here</span></a>. No ideas for now but want to help? Why not donate a few bucks <a href="http://pgmodeler.com.br/#donate"><span style=" text-decoration: underline; color:#00a489;">here</span></a>!?</p></body></html> - <html><head/><body><p>Cette page est dédiée à tous les contributeurs qui ont donné un peu de leur temps afin de rendre ce logiciel meilleur d'une manière ou d'une autre. La liste complète des personnes est disponible sur <a href="https://github.com/pgmodeler/pgmodeler/graphs/contributors"><span style=" text-decoration: underline; color:#00a489;">GitHub</span></a>.</p><p>Si vous avez une idée géniable afin d'améliorer pgModeler n'hésitez pas à la soumettre <a href="http://github.com/pgmodeler/pgmodeler/issues"><span style=" text-decoration: underline; color:#00a489;">ici</span></a>. Vous n'avez pas d'idée mais vous voulez aider ? Pourquoi ne pas un don <a href="http://pgmodeler.com.br/#donate"><span style=" text-decoration: underline; color:#00a489;">ici</span></a> !?</p></body></html> - - - 1 - 1 - - - 2 - 2 - - - 3 - 3 - - - 4 - 4 - - - 5 - 5 - - - 6 - 6 - - - Name - Nom - - - Country - Pays - - - Contribution - Contribution - - - Damien Degois - Damien Degois - - - France - France - - - French UI translation and several improvements in auxiliary scripts. - Francisation IHM et amélioration de scripts. - - - Ji Bin - Ji Bin - - - China - Chine - - - Chinese UI translation and small fixes. - Traduction en lagnue chinoise et quelques corrections. - - - Pierre-Samuel LE STANG - Pierre-Samuel LE STANG + + 0.0.0 + 0.0.0 - French UI translation. - Francisation IHM. + + build: + - Lisandro Damián Nicanor - Lisandro Damián Nicanor + + PostgreSQL Database Modeler + Modeleur de base de données PostgreSQL - Argentina - Argentine + + Open source data modeling tool designed for PostgreSQL. No more DDL commands written by hand, let pgModeler do the job for you! This software reunites the concepts of entity-relationship diagrams and the features that PostgreSQL implements as extensions of SQL standards. + Outil open source de modélisation de bases de données PostgreSQL. Plus aucun ordre LDD à saisir à la main, laissez pgModeler le faire pour vous ! Ce logiciel fusionne le concept de modélisation entité-association et toutes les fonctionnalités étendues que propose PostgreSQL en plus des standards SQL. - Russia - Russie + + <html><head/><body><p>Copyright 2006-2018 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.io</span></a>&gt;</p></body></html> + - N/A - Inconnu + + pgModeler is proudly a brazilian software! + pgModeler est un logiciel brésilien et fier de l'être ! - Hide this widget - Cacher ce widget + + <html><head/><body><p><a href="http://pgmodeler.com.br"><span style=" text-decoration: underline; color:#2980b9;">https://pgmodeler.io</span></a></p></body></html> + + ... ... - 0.0.0.0 - 0.0.0.0 - - - License - Licence - - - Build: - Build: - - - (CODE_NAME) - - - + (BUILD_NUM) - - - - Improvements on build scripts enabling the custom packaging in Linux distros; Per-user settings; pgModeler's package maintainer in Debian Linux. - - - - Pavel Alexeev - - - - Additional work for packaging in Linux distros; pgModeler's package maintainer in Fedora Linux. - - - - Mariusz Fik - - - - Poland - - - - Custom packaging first ideas. Tester of first version of custom packaging patch. - - - - <a href="http://pgmodeler.com.br">http://pgmodeler.com.br</a> - - - - <html><head/><body><p>Copyright 2006-2016 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.com.br</span></a>&gt;</p></body></html> - <html><head/><body><p>Copyright 2006-2015 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.com.br</span></a>&gt;</p></body></html> {2006-2016 ?} {0057a?} - - - 7 - 7 - - - 8 - 8 - - - Jonathan DUPRE - - - - Gilberto Castillo - + - Cuba - + + License + - Spanish UI translation. - + + Hide this widget + Cacher ce widget AggregateWidget - Form - Formulaire - - + Final Function: - Fonction finale: + Fonction finale : + Sort Operator: - Opérateur de tri: + Opérateur de tri : + Initial Condition: - Condition initiale: + Condition initiale : + Funtion Inputs Entrées de la fonction + Function State État de la fonction + Transition Func.: - Fonction de transition: + Fonction de transition : + Input Data Type Type de donnée en entrée + State Data Type Type de donnée d'état + An aggregate function that accepts the types <em><strong>typeA</strong></em> and <em><strong>typeB</strong></em> as input types and which type of state is <em><strong>state_type</strong></em>, must obey the following rules: <br/><br/> <strong> &nbsp;&nbsp;&nbsp;• Final Function:</strong> <em>void final_function(<strong>state_type</strong>)</em><br/> <strong> &nbsp;&nbsp;&nbsp;• Transition Function:</strong> <em><strong>state_type</strong> transition_function(<strong>state_type</strong>, <strong>typeA</strong>, <strong>typeB</strong>)</em> - Une fonction d'agrégation qui accepte les types <em><strong>typeA</strong></em> et <em><strong>typeB</strong></em> comme types d'entrées et dont le type d'état est <em><strong>type_etat</strong></em>, doit obéir aux règles suivantes:<br/><br/> <strong> &nbsp;&nbsp;&nbsp;• Fonction Finale:</strong> <em>void fonction_finale(<strong>type_etat</strong>)</em><br/> <strong> &nbsp;&nbsp;&nbsp;• Fonction de Transition,:</strong> <em><strong>type_etat</strong> fonction_transition(<strong>type_etat</strong>, <strong>typeA</strong>, <strong>typeB</strong>)</em> + Une fonction d'agrégat qui accepte les types <em><strong>typeA</strong></em> et <em><strong>typeB</strong></em> en types d'entrée et dont le type d'état est <em><strong>state_type</strong></em>, vous devez respecter les règles suivantes : <br/> <strong>&nbsp;&nbsp;&nbsp;• Fonction finale : </strong><em>void final_function (<strong>state_type</strong>)</em><br/> <strong>&nbsp;&nbsp;&nbsp;• Fonction de transition: </strong><em><strong>state_type</strong> transition_function(<strong>state_type</strong>,<strong>typeA</strong>, <strong>typeB</strong>)</em> AppearanceConfigWidget + Form Formulaire + Element: - Élement: + Élément : + Global: Font style - Global: Style de police + Global : Style de police + Global: Constraints descriptor - Global: Marqueurs de contraintes + Global : Marqueurs de contraintes + Global: Object selection - Global: Selection d'objet + Global : Sélection d'objet + Global: Position hint text - Global: Texte de la boite de coordonées + Global : Texte de la boite de coordonnées + Global: Position hint box - Global: Fond de la boite de coordonées + Global : Fond de la boite de coordonnées + Global: Objects type - Global: Type de colonne + Global : Type de colonne + Global: Lock arc - Global: Cadenas (objet vérouillé, couleur de l'arceau) + Global : Cadenas (objet verrouillé, couleur de l'arceau) + Global: Lock body - Global: Cadenas (objet vérouillé, couleur du corps) + Global : Cadenas (objet verrouillé, couleur du corps) + Table: Schema name - Table: Nom du schema + Table : Nom du schéma + Table: Table name - Table: Nom de la table + Table : Nom de la table + Table: Columns box - Table: Zone des colonnes + Table : Zone des colonnes + Table: Extended attributes box - Table: Zone d'attributs étendus + Table : Zone d'attributs étendus + Table: Title box - Table: Zone de titre + Table : Zone de titre + Rule: Name - Règle: Nom + Règle : Nom + Rule: Descriptor - Règle: Couleur de l'icône + Règle : Couleur de l'icône + Index: Name - Index: Nom + Index : Nom + Index: Descriptor - Index: Couleur de l'icône + Index : Couleur de l'icône + Trigger: Name - Déclencheur: Nom + Déclencheur : Nom + Trigger: Descriptor - Déclencheur: Couleur de l'icône + Déclencheur : Couleur de l'icône + View: Schema name - Vue: Nom du schema + Vue : Nom du schéma + View: View name - Vue: Nom de la vue + Vue : Nom de la vue + View: References box - Vue: Couleur d'arriere plan + Vue : Couleur d'arrière plan + View: Extended attributes box - Vue: Dialogue des attributs étendus + Vue : Dialogue des attributs étendus + View: Title box - Vue: Couleur d'arriere plan de la barre de titre + Vue : Couleur d'arrière plan de la barre de titre + View: Table / columns alias - Vue: Alias de table / colonne + Vue : Alias de table / colonne + View: Referenced column - Vue: Colonne référencée + Vue : Colonne référencée + View: Referenced table - Vue: Table référencée + Vue : Table référencée + View: Reference descriptor - Vue: Couleur de l'icône des références + Vue : Couleur de l'icône des références + Textbox: Body - Zone de texte: Corps + Zone de texte : Corps + Column: Column name - Colonne: Nom de la colonne + Colonne : Nom de la colonne + Column: Descriptor - Colonne: Couleur de l'icône + Colonne : Couleur de l'icône + Column: Included / Inherited by relationship - Colonne: Incluses / Héritées par associations + Colonne : Incluses / Héritées par associations + Column: Protected - Colonne: Protégée + Colonne : Protégée + Column (pk): Column name - Colonne (pk): Nom de la colonne + Colonne (pk) : Nom de la colonne + Column (pk): Descriptor - Colonne (pk): Couleur de l'icône + Colonne (pk) : Couleur de l'icône + Column (fk): Column name - Colonne (fk): Nom de la colonne + Colonne (fk) : Nom de la colonne + Column (fk): Descriptor - Colonne (fk): Couleur de l'icône + Colonne (fk) : Couleur de l'icône + Column (uq): Column name - Colonne (uq): Nom de la colonne + Colonne (uq) : Nom de la colonne + Column (uq): Descriptor - Colonne (uq): Couleur de l'icône + Colonne (uq) : Couleur de l'icône + Column (nn): Column name - Colonne (nn): Nom de la colonne + Colonne (nn) : Nom de la colonne + Column (nn): Descriptor - Colnne (nn): Couleur de l'icône + Colonne (nn) : Couleur de l'icône + Relationship: Descriptor - Associations: Couleur de l'icône + Associations : Couleur de l'icône + Relationship: Label text - Associations: Texte de l'étiquette + Associations : Texte de l'étiquette + Relationship: Label box - Relations: Arrière plan de l'étiquette + Relations : Arrière plan de l'étiquette + Relationship: Attribute text - Relations: Texte des attributs + Relations : Texte des attributs + Relationship: Attribute descriptor - Relations: Couleur de l'icône des attributs + Relations : Couleur de l'icône des attributs + Tag: Name Nom + Tag: Body Corps + Font: - Police: + Police : + pt pt + Bold Gras + Italic Italique + Colors: - Couleur: + Couleur : + Underline Souligné + Placeholder: Body - + Placeholder : Corps + + + + Constraint: Name + Contrainte : Nom + + + + Constraint: Descriptor + Contrainte : Descripteur Application + Unknown exception caught! - Exception inconnue générée! + Exception inconnue générée ! + Failed to create initial configuration in `%1'! Check if the current user has write permission over that path and at least read permission over `%2'. - Impossible de créer les fichiers de configuration initiale dans `%1'! Vérifiez si vous avez la permission d'écriture dans ce dossier. Vérifiez l'existence et d'avoir les droits en lecture sur le dossier `%2'. + Impossible de créer les fichiers de configuration initiaux dans `%1' ! Vérifiez que le dossier existe que vous avez la permission d'écriture dans `%2'. + + + + BaseConfigWidget + + + A backup of the previous settings was saved into <strong>%1</strong>! + Une sauvegarde des paramètres précédents a été enregistrée dans <strong>%1</strong> ! BaseForm + Dialog Dialogue + + &Apply &Appliquer - &Cancel - A&nnuler - - + &Ok &Ok + + &Cancel + A&nnuler + + + %1 properties - + %1 propriétés BaseObject + Column Colonne + Constraint Contrainte + Function Fonction + Trigger Déclencheur + Index Index + Rule Règle + Table Table + View Vue + Domain Domaine + Schema Schéma + Aggregate Fonction d'agrégat + Operator Opérateur + Sequence Séquence + Role Rôle + Conversion Convertion + Cast Convertion de type + Language Langage + Type Type + Operator Family Famille d'opérateurs + Operator Class Classe d'opérateurs + Database Base de données + Extension Extension + Relationship Relation + Collation Collation + Textbox - Zone de texte + Boite de texte + Event Trigger Déclencheur sur évènement + + Policy + Politique + + + Permission Permission + Parameter Paramètre + Type Attribute Attribut de type + Basic Relationship Relation simple + Tag - Tag + Balise + + + + Generic SQL + SQL générique + new_object - IMPOSSIBLE ! PROBLEME AU LANCEMENT SI %N EST PRESENT nouvel_objet nouveaux_objets + Tablespace - Intuitif - Tablespace + Espace de stockage BaseObjectView + SQL off SQL désactivé @@ -666,287 +652,293 @@ BaseObjectWidget - Form - Formulaire - - + Name: - Nom: + Nom : + ID: - Identifiant: + Identifiant : + icone icône + Comment: - Commentaire: + Commentaire : + Tablespace: - Tablespace: + Espace de stockage : + Edit object's permissions - Editer les permissions de l'objet + Modifier les permissions de l'objet + Disables the generated SQL code using comment tokens (--). This will disable the code of all child and referrer objects. - Désactivez le SQL généré en utilisant les marqueurs de commentaire (--). -Ceci désactivera le SQL pour les objets enfants dont cet objet est le parent. + Désactivez le code SQL généré en utilisant les marqueurs de commentaire (--). +Ceci désactivera également le code SQL pour ses objets enfants. + Append or prepend a set of SQL commands to the object's definition. - Doutes Ajouter des commandes SQL avant ou après la définition de cet objet. + Custom SQL Code SQL Libre + Owner: - Propriétaire: + Propriétaire : + Schema: - Schéma: + Schéma : + Disable SQL code Désactiver le code SQL + Collation: - Collation: + Collation : + Edit permissions - Editer les permissions + Modifier les permissions + This object is protected thus no change in form will be applied to it. - L'objet est vérouillé, par conséquent aucun changement dans le formulaire ne lui sera appliqué. - - - Create / Edit: - Créer / Éditer: + L'objet est verrouillé, par conséquent aucun changement dans le formulaire ne lui sera appliqué. + Required field. Leaving this empty will raise errors! - Champ requis. Laisser ce champ vide génèrera une erreur! + Champ requis. Laisser ce champ vide génèrera une erreur ! + Value(s) Valeur(s) + Version - Version - - - The <em style='color: %1'><strong>highlighted</strong></em> fields on the form are available only on specific PostgreSQL versions. When generating SQL code for versions other than those specified on fields' tooltips pgModeler will ignore their values. - Les champs en <em style='color: %1'><strong>surbrillance</strong></em> dans le formulaire sont disponibles pour certaines versions de PostgreSQL uniquement. Ils seront ignorés s'il est demandé un export SQL pour une version de PostgreSQL non spécifiée dans l'infobulle du champ. + + The <em style='color: %1'><strong>highlighted</strong></em> fields in the form or one of their values are available only on specific PostgreSQL versions. Generating SQL code for versions other than those specified in the fields' tooltips may create incompatible code. - + Les champs <em style='color:%1'><strong>en surbrillance</strong></em> dans le formulaire ou de l'une des valeurs ne sont disponibles que sur des versions spécifiques de PostgreSQL. La génération de code SQL pour des versions autres que celles spécifiées dans les info-bulles des champs peut créer un code incompatible. BaseRelationship + rel_%1_%2 rel_%1_%2 + + BaseTableView + + + Toggles the extended attributes display + (Dés)activer l'affichage des attributs étendus + + + + Connected rels: %1 + Rels connectés : %1 + + BugReportForm + Bug Report Signaler un bug + Bug report Signaler un bug + Create Créer + &Cancel A&nnuler + Use the form below to generate a complete bug report. Please, try to be as clear as possible when describing the actions that can reproduce the bug. Additionally, it's important to attach a sample database model so that the bug can be quickly discovered and fixed! Utilisez le formulaire ci-dessous pour générer un rapport d'erreur complet. Merci d'être le plus clair possible dans la description de vos actions afin que le bug puisse être reproduit. De plus, il est important de joindre un modèle de base dans lequel le bug puisse être rapidement découvert, et par la même occasion rapidement corrigé ! + Report Rapport + Issue details Détails du problème + Output: Sortie : + Select the report's output folder Sélectionnez un dossier de sortie pour écrire le rapport d'erreur + + ... ... + <html><head/><body><p>If you prefer it's possible to report this issue anytime on pgModeler's project repository at <a href="http://github.com/pgmodeler/pgmodeler/issues"><span style=" text-decoration: underline; color:#0057ae;">GitHub</span></a>. </p></body></html> - <html><head/><body><p>Il vous est également possible de signaler un bug à tout moment via le dépôt du projet pgModeler sur <a href="http://github.com/pgmodeler/pgmodeler/issues"><span style=" text-decoration: underline; color:#0057ae;">GitHub</span></a>. </p></body></html> + <html><head/><body><p>Il vous est également possible de signaler un bug à tout moment via le dépôt du projet pgModeler sur <a href="http ://github.com/pgmodeler/pgmodeler/issues"><span style=" text-decoration : underline; color :#0057ae;">GitHub</span></a>. </p></body></html> + Database Model Modèle de base - In none occasion the models sent within the report will be published. They are kept safe and are used only for debug purpose. - Les modèles de base de données joints avec les rapports d'erreur NE SONT EN AUCUN CAS publiés. Ils ne sont utilisés qu'à des fins de debogage. - - + Attach the below database model file to be debugged. Joindre le fichier modèle ci-dessous pour débogage. + Attach a different database model Joindre un autre modèle de base + Bug report successfuly generated! Please, send the file <strong>%1</strong> to <em>%2</em> in order be analyzed. Thank you for the collaboration! Le rapport de bug a été généré avec succès ! S'il vous plait, veuillez envoyer le fichier <strong>%1</strong> à <em>%2</em> pour expertise. Merci de votre collaboration ! + Load model - Sélectionner un modèle + Charger un modèle + Database model (*.dbm);;All files (*.*) Modèle de base de données (*.dbm);; Tous les fichiers (*.*) + Select report output folder - Sélection du dossier de sortie + Sélectionner le dossier de sortie du rapport - CastWidget + BulkDataEditWidget - Form - Formulaire + + Bulk data edit + Modification de données en masse + + + CastWidget + Conversion Func.: - Fonction de conversion: + Fonction de conversion : + Cast Type: - Conversion de type: - - - Explicit - Explicite - - - Implicit - Implicite + Conversion de type : + Assignment Affectation + Input / Output Entrée / Sortie + Source data type Type de donnée source + Target data type Type de donnée cible + The function to be assigned to a cast from <em><strong>typeA</strong></em> to <em><strong>typeB</strong></em> must have the following signature: <em><strong>typeB</strong> function(<strong>typeA</strong>, integer, boolean)</em>. - La fonction à affecter à une convertion de <em><strong>typeA</strong></em> vers <em><strong>typeB</strong></em> doit avoir la signature suivante: <em><strong>typeB</strong> fonction(<strong>typeA</strong>, integer, boolean)</em>. + La fonction convertissant de <em><strong>typeA</strong></em> vers <em><strong>typeB</strong></em> doit avoir la signature suivante : <em><strong>typeB</strong> function(<strong>typeA</strong>, integer, boolean)</em>. + I&mplicit - + I&mplicite + E&xplicit - - - - - Catalog - - Object type: %1 - ? - - Type d'objet: %1 - Types d'objets: %1 - - - - - CentralWidget - - Form - Formulaire - - - New model - Nouveau modèle - - - Open model - Ouvrir modèle - - - Sample models - Modèles de démo - - - Recent models - Modèles récents - - - Last session - Dernière session + E&xplicite CodeCompletionWidget - Make persistent - Rentre persistant + + Make &persistent + Rendre &persistant + Makes the widget closable only by ESC key or mouse click on other controls. Rendre ce widget refermable uniquement par la touche Échap ou par un clic sur les autres contrôles. + SQL Keyword Mot-clé SQL + (no items found.) (aucun élément trouvé.) @@ -954,30 +946,33 @@ Ceci désactivera le SQL pour les objets enfants dont cet objet est le parent. CollationWidget - Form - Formulaire - - + Locale: - Locale: + Locale : + Encoding: - Encodage: + Encodage : + LC_COLLATE: - LC_COLLATE: + LC_COLLATE : + LC_CTYPE: - LC_CTYPE: + LC_CTYPE : + The fields <strong><em>Collation</em></strong>, <strong><em>Locale</em></strong>, <strong><em>LC_COLLATE & LC_CTYPE</em></strong> are mutually exclusive, so you have to set only one of them in order to properly handle a collation. - Les champs <strong><em>Collation</em></strong>, <strong><em>Locale</em></strong> et <strong><em>LC_COLLATE & LC_CTYPE</em></strong> sont mutuellement exclusifs, vous ne devez en définir qu'un de manière à gérer correctement la collation. + Les champs <strong><em>Collation</em></strong>, <strong><em>Locale</em></strong> et <strong><em>LC_COLLATE & LC_CTYPE</em></strong> sont mutuellement exclusifs, vous ne devez en définir qu'un seul de manière à gérer correctement la collation. + + Not defined Non défini @@ -985,18 +980,22 @@ Ceci désactivera le SQL pour les objets enfants dont cet objet est le parent. ColorPickerWidget + Form Formulaire + Generate random color(s) Génération aléatoire de couleur(s) + Alt+R Alt+R + Select color Sélectionner une couleur @@ -1004,2272 +1003,3003 @@ Ceci désactivera le SQL pour les objets enfants dont cet objet est le parent. ColumnWidget - Form - Formulaire - - + Default Value: - Valeur par défaut: + Valeur par défaut : - Expression: - Expression: + + E&xpression: + E&xpression : - NOT NULL - Non-Null + + &NOT NULL + &NON NULL - Sequence: - Séquence: + + Se&quence: + Sé&quence : - E&xpression: + + Edit the underlying sequence's attributes - &NOT NULL + + Edit sequence - Se&quence: - + + Identity: + Identité : ConfigurationForm + pgModeler Configuration Paramètres de pgModeler + Relationships Associations + Appearance Apparence + Connections Connexions + Snippets - Snippets + Extraits de code + &Apply &Appliquer + &Cancel A&nnuler + Defaults Défauts + General Général + Plug-ins Extensions - Any modification made until now in the current section will be lost! Do you really want to restore default settings? - Toutes les modifications réalisées jusqu'à présent dans la section actuelle seront perdues! Souhaitez vous réellement restaurer les paramètres par défaut? + + In some cases restore the default settings related to it may solve the problem. Would like to do that? + Dans certains cas, restaurer les paramètres liés par défaut peut résoudre le problème. Voulez-vous le faire ? + + + + Restore + Restaurer - - - Connection - ERROR: trying to open an already stablished connection. - ERREUR: impossible de démarrer une connection déjà établie. + + Any modification made until now in the current section will be lost! Do you really want to restore default settings? + Toutes les modifications réalisées jusqu'à maintenant dans la section actuelle seront perdues ! Souhaitez-vous réellement restaurer les paramètres par défaut ? ConnectionsConfigWidget - Form - Formulaire - - + Connections: - Connexions: + Connexions : + Create new connection Créer une nouvelle connexion + Cancel edition Annuler l'édition + Duplicate the selected connection Dupliquer la connexion sélectionnée + Edit selected connection - Editer la connexion sélectionnée + Modifier la connexion sélectionnée + Delete selected connection Supprimer la connexion sélectionnée + Connection Alias: - Alias de la connexion: + Alias de la connexion : + Connection DB: - Nom de la base: + Nom de la base : + Host/Port: - Hôte/Port: + Hôte/Port : + User: - Utilisateur: + Utilisateur : + Password: - Mot de passe: + Mot de passe : + Timeout: - Délai d'expiration: + Délai d'expiration : + second(s) seconde(s) + SSL Mode: - Mode SSL: + Mode SSL : + Disable Désactivé + Allow Autorisé + Require Requis + AC verification Vérification des AC + Full verification Vérification complète + Client Certificate: - Certificat Client: + Certificat client : + ~/.postgresql/postgresql.crt ~/.postgresql/postgresql.crt + Automatically browses the named database when using this connection to manage databases on <strong>Manage</strong> view. - Parcourir et afficher automatiquement le contenu de la base de données indiquée ci-contre lors de l'utilisation de cette connexion dans le <strong>Manager</strong>. + Parcourt automatiquement la base de données nommée lors de l'utilisation de cette connexion pour gérer les bases de données dans la vue <strong>Gérer</strong>. + Auto browse Toujours montrer + Client Key: - Clef client: + Clé client : + ~/.postgresql/postgresql.key ~/.postgresql/postgresql.key + Root Certificate: - Certificat racine: + Certificat racine : + ~/.postgresql/root.crt ~/.postgresql/root.crt + Revoked Certs.: - Liste de révocations: + Liste de révocations : + ~/.postgresql/root.crl ~/.postgresql/root.crl - Kerberus Server: - Serveur Kerberos: - - + Force GSSAPI Forcer GSSAPI - Options: - Options: - - + Add Ajouter + Update Mettre à jour + Test Tester + Success Succès - Connection successfuly stablished! - -Server details: - -PID: `%1' -Protocol: `%2' -Version: `%3' - Connexion établie avec succès! - -Détails du serveur : - -PID: `%1' -Protocole: `%2' -Version: `%3' - - - There is an unsaved connection! Want to save it? - Le paramétrage de la connexion n'a pas été sauvegardé! Voulez-vous enregistrer les changements? - - + + Edit database connections - + Modifier les connexions de la base de données + General - Général + Général + Other params: - + Autres paramètres : + Specify additional connection parameters in the form [param]=[value]. These parameters are described in the <strong>libpq</strong> chapter at PostgreSQL docs. - + Spécifier des paramètres de connexion supplémentaires sous la forme [param]=[valeur]. Ces paramètres sont décrits dans le chapitre <strong>libpq</strong> de la doc de PostgreSQL. + Default for: - + Par défaut pour : + Diff - Différencier + Différencier + Export - Exporter + Exporter + Import - Importer + Importer + Validation - + Validation + Security - + Sécurité + Kerberos Server: - + Serveur Kerberos : + Indicates in which operations (diff, export, import or validation) the connection is used if none is explicitly specified by the user. - + Indique dans quelles opérations (differencier, exporter, importer ou validation) la connexion est utilisée si aucune n'est explicitement spécifiée par l'utilisateur. - There is a connection being created or edited! Do you want to save it? - - + + Connection successfully established! + +Server details: + +PID: `%1' +Protocol: `%2' +Version: `%3' + Connexion établie avec succès ! + +Détails du serveur : + +PID : `%1' +Protocole : `%2' +Version : `%3' + + + + There is a connection being created or edited! Do you want to save it? + Une connexion est en cours de création ou d'édition ! Voulez-vous la sauvegarder ? + + Found %1 connection(s) - + %1 connexion(s) trouvée(s) + No connections found - + Aucune connexion trouvée + Edit connections - + Modifier les connexions ConstraintWidget - Form - Formulaire - - + Constraint Type: - Type de contrainte: + Type de contrainte : + Fill Factor: - Taux de remplissage: + Taux de remplissage : + Match: - Comparaison: + Comparaison : + This attribute cannot be changed once the object is created. Cet attribut ne peut pas être modifié une fois l'objet créé. + Expression: - Expression: + Expression : + Deferrable: - Différable: + Reportable : + Deferral: - Report: + Report : + ON DELETE: - ON DELETE: + ON DELETE : + ON UPDATE: - ON UPDATE: + ON UPDATE : + Columns Colonnes + + Column: - Colonne: + Colonne : + Referenced Columns Colonnes référencées + Table: - Table: + Table : + Indexing: - Indexation: + Indexation : + Exclude Elements - Élements exclus + Éléments exclus + No inherit: - Pas d'héritage: + Pas d'héritage : + + Column Colonne + + Type Type + Columns which were included by relationship can not be added / removed manually from the primary key. If done such changes they can raise errors. To create primary key using columns included by relationship use the following options: identifier field, attributes & constraints tab or primary key tab on the relationship form. - Les colonnes inclues dans la relation de peuvent être ajoutées/retirés manuellement de la clef primaire sous peine d’erreur. Pour créer une clef primaire utilisant des colonnes contenues dans une relation, veuillez utiliser une des options suivantes: champ identifiant, l'onglet attributs et contraintes ou l'onglet clef primaire du formulaire de la relation. + Les colonnes inclues dans la relation ne peuvent être ajoutées/retirées manuellement de la clé primaire sous peine d’erreur. Pour créer une clé primaire utilisant des colonnes contenues dans une relation, veuillez utiliser une des options suivantes: champ identifiant, l'onglet attributs et contraintes ou l'onglet clé primaire du formulaire de la relation. ConversionWidget - Form - Formulaire - - + Source Encoding: - Encodage de la source: + Encodage de la source : + Target Encoding: - Encodage de la destination: + Encodage de la destination : + Conversion Func.: - Fonction de conversion: + Fonction de conversion : + Default Conversion: - Convertion par défaut: + Conversion par défaut : + The function to be assigned to an encoding conversion must have the following signature: <em>void function(integer, integer, cstring, internal, integer)</em>. - La fonction à affecter à une convertion d'encodage doit avoir la signature suivante: <em>void function(integer, integer, cstring, internal, integer)</em>. + La fonction de convertion d'encodage doit avoir la signature suivante : <em>void function(integer, integer, cstring, internal, integer)</em>. CrashHandlerForm + Crash Handler Gestionnaire d'incident + Stack trace - Piles d'exécution + Pile d'exécution + Input: - Entrée: + Entrée : + Load report file for analysis - Ouvrir un rapport d'erreur pour analyse + Charger un rapport d'erreur pour analyse + Save the attached model file on the filesystem - Sauvegarder le modèle joint sur le système de fichiers + Enregistrer le modèle joint sur le système de fichiers + pgModeler bug report (*.bug);;All files (*.*) Rapport de bug pgModeler (*.bug);;Tous les fichiers (*.*) + Load report - Ouvrir un rapport d'erreur + Charger un rapport + Save model Enregistrer le modèle + Database model (*.dbm);;All files (*.*) Modèle de base de données (*.dbm);; Tous les fichiers (*.*) + Crash handler Gestionnaire d'incident + Bug report analysis mode activated. Mode d'analyse de rapport d'erreur activé. + Oops! pgModeler just crashed! - Oh oh! pgModeler s'est planté ! + Oups ! pgModeler a planté ! + We apologize for what happened! It is clear that a nasty bug caused that. Please fill out the form below describing your actions before pgModeler quit unexpectedly. This will help on bug extermination and improve the software. - Nous vous prions de nous excuser pour ce qui vient de se passer ! Il est clair qu'un vilain bug soit à l'origine de tout cela. Veuillez renseigner le formulaire ci-dessous en décrivant les actions qui vous avez faites avant que pgModeler ne sombre de manière inopinée. Ceci nous aidera à exterminer ce bug et ainsi améliorer le logiciel. + Veuillez nous excuser pour ce qui vient de se passer ! Il est clair qu'un vilain bug est à l'origine de tout cela. Veuillez renseigner le formulaire ci-dessous en décrivant les actions que vous avez faites avant que pgModeler ne sombre de manière inopinée. Cela nous aidera à exterminer ce bug et ainsi, à améliorer le logiciel. - CustomSQLWidget + CsvLoadWidget + Form - Formulaire + Formulaire + + + + Load CSV + Charger un fichier CSV + + + + CSV File: + Fichier CSV : + + + + Select output file + Sélectionner un fichier de sortie + + + + ... + + + + + Separator: + Séparateur : + + + + Use the first row as column names in the CSV file. By unchecking this option the first row is used as data. + Utiliser la 1ère ligne comme noms de colonne pour le fichier CSV. En décochant cette option, la 1ère ligne est utilisée comme données. + + + + Columns in the first row + Colonnes dans la 1ère ligne + + + + Load + Charger + + + + Semicolon (;) + Point virgule (;) + + + + Comma (,) + Virgule (,) + + + + Space + Espace + + + + Tabulation + + + + + Other + Autre + + + + ; + + + + + Text delimiter: + Délimiteur : + + + + " + + + + + Load CSV file + Charger un fichier CSV + + Comma-separted values (*.csv);;All files (*.*) + Valeurs séparées par une virgule (*.csv);;Tous les fichiers (*.*) + + + + CustomSQLWidget + + SQL code Code SQL + Puts an SELECT command template at current cursor position. Insère une commande SELECT à la position courante du curseur. + &SELECT &SELECT + Puts an INSERT command template at current cursor position. Insère une commande INSERT à la position courante du curseur. + &INSERT &INSERT + Puts an UPDATE command template at current cursor position. Insère une commande UPDATE à la position courante du curseur. + Puts an DELETE command template at current cursor position. Insère une commande DELETE à la position courante du curseur. + &DELETE &DELETE + &Clear E&ffacer + Append SQL Code SQL suffixé + + Append the SQL code at the very end of model definition. Unchecking this will cause the SQL to be appended at the end of CREATE DATABASE command. Ajouter le code SQL à la toute fin de la définition du modèle Sinon (décoché) pgModeler ajoutera ce code après la commande SQL CREATE DATABASE. + Append at end of model definition. Suffixer à la fin de la définition du modèle. + Prepend SQL Code SQL préfixé + Prepend at beginning of model definition. Préfixer au tout début de la définition du modèle. + <html><head/><body><p>Use custom commands with extreme caution because you can change the semantics of the entire model when running SQL validation or export processes. Additionally, depending on the amount of commands, those processes can have their performance sensibly degradated.</p></body></html> <html><head/><body><p>Utilisez cet espace pour y inscrire vos commandes SQL personnalisées avec précaution. Vous pourriez créer des incohérences qui peuvent interférer avec les fonctionnalités de validation et d'export du modèle. De plus, selon la nature des commandes entrées ces fonctionnalités peuvent être ralenties.</p></body></html> - Append / Prepend SQL code - Code SQL préfixé/suffixé - - - Type: - Type: - - + Generic INSERT INSERT générique + Include serial columns - Inclure les colonnes de type "serial" + Inclure les colonnes en série + Exclude serial columns - Exclure les colonnes de type "serial" + Exclure les colonnes en série + Generic SELECT - SELECT générique + Faut-il le traduire ? + + Table SELECT - Table SELECT + Faut-il le traduire ? + + Generic UPDATE - UPDATE générique + Faut-il le traduire ? + + Table UPDATE - Table UPDATE + Faut-il le traduire ? + + Generic DELETE - DELETE générique + Faut-il le traduire ? + + Table DELETE - Table DELETE + Faut-il le traduire ? + + &UPDATE - &UPDATE + Faut-il le traduire ? + + Add custom SQL code - + Ajouter un code SQL personnalisé DataManipulationForm + Data Manipulation Édition des données + &Close &Fermer - Rows returned: - Lignes retournées: - - - 0 - 0 - - - Maximum limit of listed rows - Nombre maximum de lignes en retour de résulat - - - (Limit: 0) - (Limit: 0) - - - Empty values are assumed as <strong>DEFAULT</strong>. To use special values like <strong>NULL</strong>, a function call like <strong>now()</strong> or a specific data escaping, enclose values in <strong>&lt;&gt;</strong>. To use <strong>&lt;</strong> or <strong>&gt;</strong> as part of the value prepend the backslash character, e.g., <strong>\&lt;</strong> or <strong>\&gt;</strong>. - Les valeurs vides sont affichées en tant que <strong>DEFAULT</strong>. Pour utiliser les valeurs spéciales telles que <strong>NULL</strong>, un appel à une fonction comme <strong>now()</strong> ou toute autre fonction d'échappement spécifique, entourez ces valeurs/fonctions avec <strong>&lt;&gt;</strong>. Pour utiliser <strong>&lt;</strong> ou <strong>&gt;</strong> en tant que caractères à part entière, protégez-les avec un antislash : <strong>\&lt;</strong> ou <strong>\&gt;</strong>. - - + Refresh listing Actualiser la liste - Refresh - Actualiser - - + F5 F5 + Save changes Enregistrer les changements - Save - Enregistrer - - + Ctrl+S Ctrl+S - Copy the selection as CSV buffer - Copier la sélection avec un formatage de type CSV - - - Copy - Copier - - - Ctrl+C - Ctrl+C - - + Export results to CSV file Exporter les résultats vers un fichier CSV - Export - Exporter - - + Ctrl+X Ctrl+X + Undo modifications Annuler les modifications - Undo - Annuler - - + Ctrl+Z Ctrl+Z - Add data - Ajouter une ligne - - - Add - Ajouter - - + + Ins Ins + Mark the selected rows to be deleted Marquer les lignes sélectionner pour suppression - Delete - Supprimer - - + + + + + Del Suppr + Filter the result set Filtrer les résultats + Table: - Table: + Table : + Schema: - Schéma: + Schéma : + in dans + Hide views Masquer les vues + Filter expression Expression pour filtrer + Order && Limit - Order && Limit + Ordre && Limite + Column: - Colonne: + Colonne : + Limit in: - Limit : - - - 000000 - 000000 - - - 100 - 100 - - - results - lignes + Limite : + Add Item Ajouter un élément + Remove Item Supprimer un élément + Clear the order by columns list Effacer la liste + Move selected item up Déplacer vers le haut + Move selected item down Déplacer vers le bas + + Copy as CSV + Copier en CSV + + + + Copy as text + Copier en texte + + + + Copy items + Copier les éléments + + + + Pase items + Coller les éléments + + + + Browse tables + Navigateur de tables + + + + Duplicate row(s) + Dupliquer ligne(s) + + + + Delete row(s) + Effacer ligne(s) + + + + Edit cell(s) + Modifier cellule(s) + + + <em>(Limit: <strong>%1</strong>)</em> - <em>(Limit: <strong>%1</strong>)</em> + <em>(Limite : <strong>%1</strong>)</em> + + + + Column + Colonne + No objects found Aucun objet trouvé + Found %1 object(s) - %1 objets trouvés + %1 objet(s) trouvé(s) + Views can't have their data handled through this grid, this way, all operations are disabled. - Les données des vues ne sont pas modifiables par le biais de cette grille de résultats, de ce fait, aucune opération de modification n'est permise. + Les données des vues ne sont pas modifiables via cette grille, de ce fait, toutes les opérations sont bloquées. + The selected table doesn't owns a primary key! Updates and deletes will be performed by considering all columns as primary key. <strong>WARNING:</strong> those operations can affect more than one row. - La table sélectionnée ne comporte pas de clé primaire ! Les mises à jour et les suppressions seront réalisées en considérant que l'ensemble des colonnes constitue une clé primaire. <strong>ATTENTION:</strong> ces opérations peuvent affecter plus d'une ligne. + La table sélectionnée n'a pas sa propre clé primaire ! Les mises à jour et les suppressions seront réalisées en considérant que l'ensemble des colonnes constitue une clé primaire. <strong>ATTENTION :</strong> ces opérations peuvent affecter plus d'une ligne. + + + + Referenced tables + Tables référencées + + + + + (none) + (aucun) + + + + Referrer tables + Tables de référence + This row is marked to be %1 - Cette ligne est estampillée pour être %1 + Cette ligne est marquée pour être %1 + deleted - supprimée + supprimé + updated mise à jour + inserted - insérée + inséré + [binary data] [données binaires] + <strong>WARNING:</strong> Once commited its not possible to undo the changes! Proceed with saving? - <strong>ATTENTION:</strong> Une fois validés (Commit), il ne sera plus possible d'annuler les changements ! Sauvegarder les changements ? + <strong>ATTENTION :</strong> Une fois validés, il ne sera plus possible d'annuler les changements ! Sauvegarder les changements ? + + + + delete + effacer + update - update + mettre à jour + insert - insert + inserer + ASC - Intuitif ASC + DESC - Intuitif DESC - delete - delete - - - <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in <span style=" font-weight:600;">{}</span>. To use <span style=" font-weight:600;">{</span> or <span style=" font-weight:600;">}</span> as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\{</span> or <span style=" font-weight:600;">\}</span>.</p></body></html> - - - + Add empty rows - + Ajouter des lignes vides + Duplicate the selected rows - - - - Duplicate - + Dupliquer les lignes sélectionnées + Ctrl+D - + Ctrl+D + results (Use <strong>0</strong> for no limit) - + résultats (Utiliser <strong>0</strong> pour ne pas limiter) + <strong>WARNING: </strong> There are some changed rows waiting the commit! Do you really want to discard them and retrieve the data now? - + <strong>ALERTE :</strong> Des lignes modifiées attendent d'être soumises ! Voulez-vous vraiment les jeter et récupérer les données maintenant ? + Rows returned: <strong>%1</strong>&nbsp;&nbsp;&nbsp; - + Lignes retournées : <strong>%1</strong>&nbsp;&nbsp;&nbsp; + none - + aucun - - - DatabaseExplorerWidget - Form - Formulaire + + <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in two slashes, e.g., <span style=" font-weight:600;">/value/</span>. To use a slash as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\/</span>.</p></body></html> + <html><head/><body><p>Les valeurs vides sont supposées être <span style="font-weight :600;">DEFAULT</span>. Pour utiliser des valeurs spéciales comme <span style="font-weight :600;">NULL</span>, un appel de fonction comme <span style="font-weight :600;">now()</span> ou un échappement des données spécifiques, entourer les valeurs de deux barres obliques, par exemple <span style="font-weight :600;">/valeur/</span>. Pour utiliser une barre oblique dans le cadre de la valeur, ajouter le caractère barre oblique inverse, par exemple <span style="font-weight :600;">/</span>.</p></body></html> - Toggles the display of system objects. - Basculer l'affichage des objets système. + + Copy items on the grid + Copier les éléments sur la grille - Sys. objects - Objets syst. + + Paste items on the grid + Copier les éléments sur la grille - Toggles the display of extension objects - Basculer l'affichage des objets issus des extensions + + Ctrl+V + - Ext. objects - Objets ext. + + Browse referenced tables + Parcourir les tables référencées - Open the grid to visualize or edit data. - Ouvre l'éditeur de données. + + Add new rows from a CSV file + Ajouter de nouvelles lignes depuis un fichier CSV - Data &Grid - &Grille des données + + Change the values of all selected cells at once + Modifier d'un coup les valeurs de toutes les cellules sélectionnées - Alt+G - Alt+G + + Ctrl+E + Ctrl+E + + + DatabaseExplorerWidget - Open a new SQL execution pane. - Ouvre un nouvel onglet d'exécution SQL. + + Form + Formulaire - ... - ... + + + Data &Grid + &Grille des données - Ctrl+F5 - Ctrl+F5 + + + Alt+G + Alt+G - Update the objects tree. - Actualiser l'arbre des objets. + + + + + + ... + ... + Expands all items Ouvre tous les nœuds de l'arborescence + Collapses all items Ferme tous les nœuds de l'arborescence + Filter: - Filtrer: + Filtrer : + By OID Par OID + + Attribute Attribut + Value Valeur - Show raw attributes names - Afficher le nom réel des attributs - - + (not found, OID: %1) - (inconnu, OID: %1) + (OID: %1 non trouvé) + By value - Par valeur + Par valeur + Collatable - Collatable - - - Collation - Collation + Assemblable + + Constraint - Contrainte + Contrainte + Default - Défaut + Défaut + Definition - Définition - - - Dimension - Dimension + Définition + Element - Élement + Élément + Encrypted - Encrypté + Chiffré + Enumerations - Énumérations - - - Expression - Expression + Énumérations + Function - Fonction + Fonction + Language - Langage + Langage + Length - Longueur + Longueur + Library - Bibliothèque + Bibliothèque + Materialized - Matérialisée + Matérialisée + Name - Nom - - - Permissions - Permissions + Nom + Precision - Précision + Précision + Preferred - Préféré + Préféré + Schema - Schéma + Schéma + Storage Stockage + Superuser Super utilisateur + Tablespace - Espace de stockage logique - - - Type - Type + Espace de stockage + Unlogged - Unlogged + Déconnecté + Validity - Validité + Validité + Subtype - Sous-type + Sous-type - Arguments - Arguments + + + + Columns + Colonnes - Table - Table + + Event + Évènement - Columns - Colonnes + + Client encoding + Codage du client - Event - Evènement + + Configuration file + Fichier de configuration - Unique - Unique + + Data directory + Dossier de données - Snippets - Snippets + + Dynamic library path + Chemin de la bibliothèque dynamique - Drop object - Supprimer l'objet + + Dynamic shared memory + Mémoire partagée dynamique - Drop cascade - Supprimer en cascade + + Hba file + Fichier hba - Truncate - Truncate + + Listen addresses + Écouter des adresses - Trunc. cascade - Trunc. cascade + + Max. connections + Connexions max. - Show data + + Listen port + Écouter port + + + + Server encoding + Encodage serveur + + + + SSL ca file + Fichier ca SSL + + + + SSL cert file + Fichier cert SSL + + + + SSL crl file + Fichier crl SSL + + + + SSL key file + Fichier clé SSL + + + + Server version + Version serveur + + + + Ident file + Fichier d'identité + + + + Password encryption + Mot de passe de chiffrement + + + + Connection ID + ID connexion + + + + Server PID + PID serveur + + + + Server protocol + Protocole serveur + + + + Identity + Identité + + + + Command + Commande + + + + Roles + Rôles + + + + Show objects filter + Afficher les objets filtrés + + + + Show system objects + Afficher les objets système + + + + Show extension objects + Afficher les objets d'extension + + + + Snippets + Bouts de code + + + + Drop object + Supprimer l'objet + + + + Drop cascade + Supprimer en cascade + + + + Truncate + Tronquer + + + + Trunc. cascade + Tronquer en cascade + + + + Show data Afficher les données + Reload properties Recharger les propriétés + Update Mettre à jour - Do you really want to drop the object <strong>%1</strong> <em>(%2)</em>? - Voulez-vous vraiment supprimer l'objet <strong>%1</strong> <em>(%2)</em> ? + + -- Source code unavailable for this kind of object -- + -- Code source indisponible pour ce type d'objet -- - Do you really want to <strong>cascade</strong> drop the object <strong>%1</strong> <em>(%2)</em>? This action will drop all the other objects that depends on it? - Voulez-vous vraiment supprimer EN CASCADE l'objet <strong>%1</strong> <em>(%2)</em>? Cette action sera susceptible de supprimer en plus d'autres objets qui en dépendent. + + Do you really want to drop the object <strong>%1</strong> <em>(%2)</em>? + Voulez-vous vraiment supprimer l'objet <strong>%1</strong> <em>(%2)</em> ? + Do you really want to truncate the table <strong>%1</strong>? - Voulez-vous vraiment vider la table <strong>%1</strong> ? + Voulez-vous vraiment tronquer la table <strong>%1</strong> ? + Do you really want to <strong>cascade</strong> truncate the table <strong>%1</strong>? This action will truncate all the tables that depends on it? - Voulez-vous vraiment vider EN CASCADE la table <strong>%1</strong> <em>(%2)</em>? Cette action sera susceptible de supprimer d'autres lignes dans les tables qui en dépendent. + Voulez-vous vraiment tronquer en <strong>cascade</strong> la table <strong>%1</strong> ? Cette action tronquera toutes les tables qui en dépendent ! + Admin. roles - + Rôles admin. + Alignment - + Alignement + Analyze func. - + Fonc. d'analyse + Arg. count - + Nombre d'arg. + Arg. default count - + Nombre d'arg. par défaut + Arg. defaults - + Arg. par défaut + Arg. modes - + Modes des arg. + Arg. names - + Noms des arg. + Arg. types - + Types des arg. + Behavior type - + Type de comportement + Cast type - + Type de conversion + Category - + Catégorie + Comment - + Commentaire + Commutator Op. - + Commutateur Op. - Configuration - + + Collation + + Conn. limit - + Limite conn. + + + + Configuration + + Create DB - + Créer DB + Create role - + Créer rôle + Curr. version - + Version courante + Default value - + Valeur par défaut + Delimiter - + Délimiteur + Dest. type - + Type de dest. + + + + Dimension + + Directory - + Répertoire + Dest. encoding - + Encodage de dest. + Encoding - + Encodage + Exec. cost - + Exec. du coût + Op. family - + Famille d'op. + + + + Expression + + Final func. - + Fonc. finale + Func. type - + Type de fonc. + Handler func. - + Gestionnaire de fonc. + Handles type - + Type de poignées + Hashes + Index type - + Type d'index + Inherit - + Hérité + Ini. condition - + Condition ini. + Inline func. - + Func. en ligne + Input func. - + Fonc. d'entrée + Internal length - + Longueur interne + Interval type - + Type d'interval + I/O cast - + Conversion E/S + Join func. - + Fonc. de jointure + LC COLLATE + Faut-il le traduire ? + LC CTYPE + Faut-il le traduire ? + Leak proof - + Étanche + Left type - + Type gauche + Can login - + Peut se connecter + Member roles - + Rôles des membres + Merges - + Fusionne + Negator op. - + Négateur op. + Not null - + Non nul + Object type - - - - OID - + Type d'objet + With OIDs - + Avec OIDs + Old version + Ancienne version + + + + OID + Faut-il le traduire ? + Operator - + Opérateur + Operator func. - + Fonc. de l'opérateur + Output func. - + Func. de sortie + Owner - + Propriétaire + Owner column - + Colonne propriétaire + Parents - + + Password - + Mot de passe + + + + Permissions + + Range attributes - + Attributs de plage + Receive func. - + Fonc. de réception + Ref. roles - + Rôles de ref. + Replication - + Reproduction + Restriction func. - + Fonc. de restriction + Return type - + Type de retour + Returns SETOF - + Retours SETOF + Right type - + Type droit + Rows amount - + Montant des lignes + Security type - + Type de sécurité + Send func. - + Fonc. d'envoi + Sort op. - + Op. de tri + Source type - + Type de source + Src. encoding - + Encodage de la src. + State type - + Type d'état + Type mod. in func. - + Type de mod. dans la fonc. + Type mod. out func. - + Type de mod. hors fonc. + Transition func. - + Fonc. de transition + Trusted - + Fiable + Type attribute - + Attribut de type + + + + Type + + Types - + + Validator func. - + Fonc. de validateur + Windows func. - + Fonc. de fenêtre + false - + faux + true - + vrai + Cache value - + Valeur du cache - Cycle - + + Increment + Incrément - Increment - + + Cycle + + Max. value - + Valeur max + Min. value - + Valeur min + Start value - + Valeur de départ + Last value - + Dernière valeure + Op. class - + Classe d'op. + Canonical func. - + Fonc. de Canonical + Subtype diff func. - + Fonc de comparaison de sous-type + Deferrable - + Reportable + For each row - + Pour chaque ligne + Firing - + Déclencheur + On insert - + À l'insertion + + On delete - + À la suppression + + On update - + À la mise à jour + On truncate - + Au tronquage + + + + Arguments + + + + + Table + + Trigger func. - + Fonc. de déclenchement + Condition - + + Deferment - + Ajournement + Execution mode - + Mode d'exécution + Commands - Commandes + Commandes - Position - + + Comparison type + Type de comparaison - Comparison type - + + Position + + Ref. columns - + Colonnes de ref. + Expressions - + + Fill factor - + Facteur de remplissage + No inherit - + Non hérité + Op. classes - + Classes op. + Operators - + Opérateurs + Ref. table - + Table de ref. - Predicate - + + Unique + - Collations - + + Predicate + Prédicat + Inherited - + Hérité - System - + + Collations + - Extension - Extension + + SSL + - Open the grid to visualize or edit data - + + Referrers + Référents - Open a new SQL execution pane + + USING expr. + Faut-il le traduire ? - Ctrl+F6 - Ctrl+F6 - - - Update the objects tree + + CHECK expr. + Faut-il le traduire ? - Ctrl+S - Ctrl+S - - - Drop this database + + RLS enabled - Filters the currently loaded items in the tree by using a pattern and matching their names. If <strong>By OID</strong> is checked the pattern is interpreted as an integer value that represents the object id (OID). <br><br/><strong>HINT:</strong> if you need to search the entire database use the full refresh (<strong>Ctrl+F5</strong>) prior the filtering. + + RLS forced - Show raw attributes + + Also restart sequences - -- Source code not generated! Hit F7 or middle-click the item to load it. -- - + + + Warning + Avertissement + + + + You're running a demonstration version! The data manipulation feature is available only in the full version! + Vous utilisez une version de démonstration ! Cette fonctionnalité de manipulation de données est uniquement disponible dans la version complète ! + + + + <strong>CAUTION:</strong> You are about to drop the entire database <strong>%1</strong>! All data will be completely wiped out. Do you really want to proceed? + <strong>ATTENTION :</strong> Vous êtes sur le point de supprimer l'intégralité de la base de données <strong>%1</strong> ! Toutes les données seront définitivement détruites. Voulez-vous vraiment le faire ? + + + + Open the grid to visualize or edit data + Ouvrir la grille pour visualiser ou modifier les données + + + + Open a new SQL execution pane + Ouvrir un nouveau panneau d'exécution de code SQL + + + + Ctrl+F6 + + + + + Update the objects tree + Mettre à jour l'arborescence des objets + + + + Drop this database + Supprimer cette base de données + + + + Filters the currently loaded items in the tree by using a pattern and matching their names. If <strong>By OID</strong> is checked the pattern is interpreted as an integer value that represents the object id (OID). <br><br/><strong>HINT:</strong> if you need to search the entire database use the full refresh (<strong>Ctrl+F5</strong>) prior the filtering. + Filtre les éléments actuellement chargés dans l'arborescence en utilisant un motif et en faisant correspondre leurs noms. Si <strong>Par OID</strong> est coché, le motif est interprété comme une valeur entière qui représente l'identifiant de l'objet (OID).<br><br/><strong>ASTUCE :</strong> si vous devez effectuer une recherche dans toute la base de données, utilisez l'actualisation complète (<strong>Ctrl+F5</strong>) avant le filtrage. + + + + Show raw attributes + Afficher les attributs brutes + + + + -- Source code not generated! Hit F7 or middle-click the item to load it. -- + -- Code source non généré ! Appuyer sur F7 ou faire un clic molette sur l'élément pour le charger. -- + Rename - Renommer + Renommer + Source code - Code source + Code source + Quick refresh - + Rafraîchissement rapide + Full refresh - + Rafraîchissement complet + Do you really want to <strong>cascade</strong> drop the object <strong>%1</strong> <em>(%2)</em>? This action will drop all the other objects that depends on it. - + Voulez-vous vraiment supprimer en <strong>cascade</strong> l'objet <strong>%1</strong><em> (%2)</em> ? Cette action supprimera tous les autres objets qui en dépendent. + Src. table: %1 Src. column(s): %2 - + Table src. : %1 +Colonne(s) src. : %2 + Ref. table: %1 Ref. column(s): %2 - + Table de ref. : %1 +Colonne(s) de ref. : %2 + -- Source code genaration for buil-in and base types currently unavailable -- - + -- Génération de code source pour les types intégrés et les type de base actuellement indisponibles -- + -- Source code unavailable for the object %1 (%2). -- - + -- Code source indisponible pour l'objet %1 (%2). -- + + + + Toggle the display of filter widget as well the system/extension objects. + (Dés)activer l'affichage du widget de filtre ainsi que les objets système/extension. + + + + Sort items alphabetically. When unchecked, items are sorted by OID. + Trier les éléments par ordre alphabétique. Lorsque ce n'est pas coché, les éléments sont triés par OID. + + + + Sort alphabetically + Trier par ordre alphabétique DatabaseImportForm - Database Import - Import d'une base de données - - + &Import &Importer + &Close &Fermer + Options Options - Starting point where objects will be put. - Point d'origine à partir duquel les objets seront créés sur le schéma. - - - Spacing: - Espacement: - - + Enables the import of objects created by extensions. Generally there is no need to check this option but if there are objects in the database that directly references this category of objects this mode must be enabled. - Active l'importation des objets créés par les extensions. Généralement il n'y a pas lieu d'activer cette option sauf si des objets en base référencent directement ce type d'objet. + Active l'import des objets créés par les extensions. Généralement il n'y a pas lieu d'activer cette option sauf si des objets en base référencent directement ce type d'objet. + Import extension objects Importer les objets des extensions + Connection: - Connexion: + Connexion : + Ignore import errors Ignorer les erreurs + pgModeler ignores import errors and will try to create as many as possible objects. By checking this option the import operation will be not aborted but an incomplete model will be constructed. This option generates a log file on pgModeler's temp directory. - pgModeler ignorera les erreurs qui pourront survenir lors de l'importation et essayera de créer autant d'objets qui lui sera possible. En activant cette fonction le processus d'importation ne sera pas interrompu, toutefois vous pourrez vous retrouver avec un modèle incomplet. Cette option active la génération d'un fichier log dans le dossier temporaire de pgModeler. + pgModeler ignorera les erreurs qui pourront survenir lors de l'import et essayera de créer autant d'objets qui lui sera possible. En activant cette fonction le processus d'import ne sera pas interrompu, toutefois vous pourrez vous retrouver avec un modèle incomplet. Cette option active la génération d'un fichier log dans le dossier temporaire de pgModeler. + Enables the import of system built-in objects. It's recommend to select only those objects that are directly referenced by the ones to be imported. WARNING: Try to import a huge set of system objects can bloat the resultant model or even crash pgModeler due to memory/cpu overuse. - Active l'importation des objets système. Il est recommandé d'utiliser ce mode uniquement lorsque le reste du modèle y fait directement référence (afin de conserver une intégrité). ATTENTION : Ceci va entrainer la création de beaucoup d'élements qui peuvent rendre difficile la lecture du schéma, voir même provoquer un plantage de pgModeler en cas de saturation mémoire ou CPU. + Active l'importation d'objets intégrés au système. Il est recommandé de sélectionner uniquement les objets directement référencés par ceux à importer. AVERTISSEMENT : Essayer d'importer un grand nombre d'objets système peut gonfler le modèle résultant ou même planter pgModeler en raison de la surutilisation de la mémoire/cpu. + Import system objects Importer les objets système + Automatically resolve dependencies Résoudre automatiquement les dépendances - Resolve some of the object's dependencies by query the catalog when a needed object does not exists on the loaded set. In some cases it's necessary to combine this option with others below. This option does not applies to database level objects like role, tablespace and language as well for data types and extensions. - Résoudre certaines dépendances entre les objets en interrogeant le catalogue lorsqu'un objet n'existe pas dans la base à importer. Dans certains cas il vous sera nécessaire de combiner cette option avec celles ci-dessous. Cette option ne s'applique pas aux objets situés au niveau du cluster tels que les rôles, les tablespaces, les langues, les types de données ou encore les extentions. - - - Origin point: - Point d'origine: - - - Connect and list available databases - Connecter et lister les bases de données disponibles - - + + + + ... ... + Debug mode Activer le mode debug - All catalog queries as well the created objects' source code are printed to standard outupt (stdout). - Toutes les requêtes effectuées sur le catalogue ainsi que le code source de tous les objets créés sera affiché sur la sortie standard (stdout). - - - Spacing between objects - Espacement inter-objets - - - Schemas per row - Nombre maximal de schémas pouvant être placés sur une seule ligne (en longueur) - - - Tables per row: - Tables sur une ligne: - - - Schemas per row: - Schémas sur une ligne: - - - Tables per row - Nombre maximal de tables pouvant être placées sur une seule ligne (en longueur) - - - Database import - Importation d'une base (Base existante vers modèle) - - + Settings Paramètres + Random colors will be assigned to imported relationships facilitating the identification of links between tables mainly in large models. - Coloriser les associations de manière aléatoire afin de faciliter l'identification des liens entre les tables, cela peut être utile sur de grands modèles. + Colorer les associations de manière aléatoire afin de faciliter l'identification des liens entre les tables, cela peut être utile sur de grands modèles. + Random colors for relationships - Coloriser les associations de manière aléatoire + Colorer les associations de manière aléatoire + Database Base de données + Select all objects Tout cocher + Clear object selection Tout décocher + Expands all items Développer tous les éléments + Collapses all items Replier tous les éléments + Filter: - Filtrer: + Filtrer : + Filter object by it's OID Filtrer un objet par son OID + By OID Par OID + Output Sortie + Progress label... Indicateur de progression... + Cancel Annuler + Retrieving objects from database... - Récupération des objets à partir de la base de données... + Récupération des objets depuis la base de données... + Importing process aborted! - Processus d'importation en erreur ! + Processus d'import abandonnée ! + Importing process canceled by user! - Processus d'importation interrompu par l'utilisateur ! + Processus d'import interrompu par l'utilisateur ! + Importing process sucessfuly ended! - Processus d'importation terminé avec succès ! + Processus d'import terminé avec succès ! + No databases found Aucune base de données trouvée + Found %1 database(s) %1 base(s) de données trouvée(s) + Retrieving cluster level objects... Récupération des objets du cluster... + Retrieving objects of schema `%1'... Récupération des objets du schéma `%1'... - Retrieving objects of table `%1'... - Récupération des objets de la table `%1'... + + Retrieving objects of `%1' (%2)... + Réccupération des objets de `%1' (%2)... + This is a PostgreSQL built-in data type and cannot be imported. - Ce type de données est déjà intégré nativement dans PostgreSQL. Il ne peut être importé. + C'est un type de données nativement intégré à PostgreSQL. Il ne peut être importé. + This is a pgModeler's built-in object. It will be ignored if checked by user. - Cet objet fait partie intégrante de pgModeler. Il sera ignoré même si vous le cochez. + C'est un objet nativement intégré à pgModeler. Il sera ignoré s'il est coché par l'utilisateur. + Create all imported objects in the current working model instead of create a new one. - + Créer tous les objets importés dans le modèle de travail actuel au lieu d'en créer un nouveau. + Import objects to the working model - + Importer les objets dans le modèle de travail en cours + <strong>ATTENTION:</strong> You are about to import objects to the current working model! This action will cause irreversible changes to it even in case of critical errors during the process. Do you want to proceed? - - - - Schemas per row - + <strong>ATTENTION :</strong> Vous êtes sur le point d'importer des objets dans le modèle de travail actuel ! Cette action entraînera des modifications irréversibles même en cas d'erreurs critiques au cours du processus. Voulez-vous poursuivre ? + Resolve some of the object's dependencies by querying the catalog when a needed object does not exists on the loaded set. In some cases it's necessary to combine this option with others below. This option does not applies to database level objects like role, tablespace and language as well for data types, extensions. - + Résoudre certaines dépendances de l'objet en interrogeant le catalogue. Dans certains cas, il est nécessaire de combiner cette option avec les autres ci-dessous. Cette option ne s'applique pas aux objets du niveau de la base de données, tels que le rôle, l'espace de stockage et la langue, pour les types de données et les extensions. + All catalog queries as well the created objects' source code are printed to standard output (stdout). - + Toutes les requêtes de catalogue ainsi que le code source des objets créés sont imprimés sur la sortie standard (stdout). + + + + + Import database + Importer une base de données DatabaseImportHelper + Retrieving system objects... `%1' Récupération des objets système... `%1' + + Retrieving objects... `%1' Récupération des objets... `%1' + Creating table inheritances... Création des tables héritées... - Creating objects permissions... - Création des permissions... - - + Creating object `%1' (%2)... Création de l'objet `%1' (%2)... - Trying to recreate object `%1' (%2)... - Tentative de recréation de l'objet `%1' (%2)... - - + Creating columns permissions... Création des permissions sur les champs... - Update relationships of `%1' (%2)... - Mise à jour des associations de `%1' (%2)... - - + Destroying unused detached columns... - Suppression des colonnes détachées de la table parent (héritage)... + Destruction des colonnes détachées inutilisées... + The database import ended but some errors were generated and saved into the log file `%1'. This file will last until pgModeler quit. - L'import de la base a échoué mais les erreurs rencontrées ont été sauvegardées dans le fichier journal `%1'. Ce fichier sera disponible jusqu'à la fermeture de pgModeler. + L'import de la base de données est términée mais des erreurs ont été générées et sauvegardées dans le journal `%1'. Ce fichier sera disponible jusqu'à la fermeture de pgModeler. + + + + Creating object `%1' (%2), oid `%3'... + Création de l'objet `%1' (%2), oid `%3'... + + + + Trying to recreate object `%1' (%2), oid `%3'... + Tentative de création de l'objet `%1' (%2), oid `%3'... + Import failed to recreate some objects in `%1' tries. - + L'import a échoué à recréer certains objets à `%1' reprise(s). + Creating permissions for object `%1' (%2)... - + Création des autorisations pour l'objet `%1' (%2)... + Updating relationships of `%1' (%2)... - + Mise à jour des relations de `%1' (%2)... + Validating relationships... - + Validation des relations... + Assigning sequences to columns... - + Affectation des séquences aux colonnes... DatabaseModel + The demonstration version can create only `%1' instances of each object type! You've reach this limit for the type: `%2' - Cette version de démonstration peut créer seulement `%1' instances pour chaque type d'objet ! Cette limite a été atteinte pour les objets de type : `%2' + Cette version de démonstration peut seulement créer `%1' instances pour chaque type d'objet ! Cette limite a été atteinte pour les objets de type : `%2' + Loading: `%1' (%2) - Chargement: `%1' (%2) + Chargement : `%1' (%2) - Generating %1 of the object `%2' (%3) - Génération %1 de l'objet `%2' (%3) + + + Validating relationships... + Validation des relations... - Validating relationships... + + Generating %1 code: `%2' (%3) + Saving object `%1' (%2) - + Enregistrement de l'objet `%1' (%2) + Saving metadata of the object `%1' (%2) - + Enregistrement des métadonnées de l'objet `%1' (%2) + Metadata file successfully saved! - + Fichier de métadonnées enregistré avec succès ! + Process successfully ended but no metadata was saved! - + Le processus s'est terminé avec succès mais aucune métadonnée n'a été enregistrée ! + Creating object `%1' (%2) - + Création de l'objet `%1' (%2) + Object `%1' (%2) already exists. Ignoring. - + L'objet `%1' (%2) existe déjà et a été ignoré. + Loading metadata for object `%1' (%2) - + Chargement des métadonnées de l'objet `%1' (%2) + Object `%1' (%2) not found. Ignoring metadata. - + Objet`%1' (%2) introuvable. Métadonnée ignorée. + Metadata file successfully loaded! - + Fichier de métadonnées chargé avec succès ! DatabaseWidget - Form - Formulaire - - + Attributes Attributs + Template DB: - Modèle de BDD: + Modèle de BDD : + Model Author: - Auteur du modèle: + Auteur du modèle : + Encoding: - Encodage: + Encodage : + Default Objects Attributs par défaut des objets + Tablespace: - Tablespace: + Espace de stockage : + Schema: - Schéma: + Schéma : + Collation: - Collation: + Collation : + Owner: - Propriétaire: + Propriétaire : + LC_COLLATE: - LC_COLLATE: + LC_COLLATE : + Connections: - Connexions: + Connexions : + LC_CTYPE: - LC_CTYPE: + LC_CTYPE : + The fields <strong>LC_COLLATE</strong> and <strong>LC_CTYPE</strong> have pre-configured values based upon the running system. You can freely modify those values if you intend to export the model to another host. - Les champs <strong>LC_COLLATE</strong> et <strong>LC_CTYPE</strong> ont déjà des valeur pré-configurées basées sur le système. Vous pouvez librement les modifier si vous deviez exporter le modèle pour une autre machine hôte. + Les champs <strong>LC_COLLATE</strong> et <strong>LC_CTYPE</strong> ont déjà des valeurs pré-configurées basées sur le système. Vous pouvez librement les modifier si vous devez exporter le modèle vers une autre machine hôte. + Use the above fields to specify the default attributes assigned to new objects created on the database model. Leaving a field empty will cause PostgreSQL to use the default values when exporting the model. - Utilisez les champs ci-dessus pour spécifier les attributs par défaut à assigner aux futurs objets qui seront créés dans le modèle. Laisser ces champs vides fera en sorte que PostgreSQL utilise ses valeurs par défaut lors de l'exportation du modèle. + Utilisez les champs ci-dessus pour spécifier les attributs par défaut à assigner aux nouveaux objets créés dans le modèle. Laisser un champ vide fera que PostgreSQL utilisera ses valeurs par défaut lors de l'export du modèle. + + + + Default Défaut + + + Options: + Options : + + + + Allow connections + Autoriser les connexions + + + + Is template + Est le modèle + DomainWidget - Form - Formulaire + + Name: + Nom : - Constraint - Contrainte + + Default Value: + Valeur par défaut : - Name: - Nom: + + Attributes + Attributs - Not Null: - Non Null: + + Not null + Non nulle - Check Expr.: - Expr. de vérif.: + + Check constraints + Vérifier les contraintes - Default Value: - Valeur par défaut: + + Expression: + Expression : + + + + Name + Nom + + + + Expression + DonateWidget + Form - Formulaire + Formulaire + Donate to pgModeler - + Faire un don à pgModeler + Hide this widget - + Cacher ce widget + ... - ... + ... + <html><head/><body><p>pgModeler is brought to you thanks to a <span style=" font-style:italic;">great effort to create and distribute a quality product</span>. This project is reaching out levels of maturity never imagined. All this is the result of a joint work between its author and the <span style=" font-weight:600;">Open Source community</span>. <br/><br/>This software has a long way to go yet and with your help we'll keep maintaining the good job and bringing new improvements on each release. If you did like pgModeler and thinks it deserves a contribution please make a donation!</p></body></html> - + <html><head/><body><p>pgModeler vous est offert grâce à un <span style=" font-style :italic;">gros effort pour créer et distribuer un produit de qualité </span>. Ce projet atteint un niveau de maturité jamais imaginé. Tout ceci est le résultat d'un travail conjoint entre son auteur et la <span style="font-weight :600;">Communauté Open Source</span>.<br/><br/>Ce logiciel a encore un long chemin à parcourir mais avec votre aide, nous continuerons à faire du bon travail et à apporter de nouvelles améliorations à chaque version. Si vous avez aimé pgModeler et pensez qu'il mérite une contribution, faites un don ! </p></body></html> + I want to help! - + Je veux aider ! ElementsWidget + Form Formulaire + Column: - Colonne: + Colonne : + Expression: - Expression: + Expression : + Collation: - Collation: + Collation : + Operator Class: - Classe d'opérateurs: + Classe d'opérateurs : + Operator: - Opérateur: + Opérateur : + Sorting: - Tri: + Tri : + Ascending Ascendant + Descending Descendant + Nulls first Null en premier + Element - Élement + Élément + Type - Type + + Operator Class Classe d'opérateur + Sorting Tri + Nulls First - Null en premier + Vides en premier + Collation - Collation + + Operator Operateur + Expression - Expression + + Yes Oui + No Non @@ -3277,1069 +4007,1330 @@ Ref. column(s): %2 EventTriggerWidget - Form - Formulaire - - + Event: - Evènement: + Évènement : + Function: - Fonction: + Fonction : + Filter Filtrer + Tag: - Tag: + Étiquette : + Tag command - Commande de déclenchement + Balise de la commande Exception + Assignment of a pseudo-type to the type of the column! - Utilisation d'un pseudo-type comme type de la colonne! - - - Zero length assignment! - Affectation de longueur nulle! + Utilisation d'un pseudo-type comme type de la colonne ! + Assignment of a precision greater than the length of the type! - Utilisation d'une précision est plus grande que la longueur du type! + Utilisation d'une précision est plus grande que la longueur du type ! + Assignment of an invalid precision to type time, timestamp or interval. The precision in this case must be equal to or less than 6! - Utilisation d'une précision de type time, timestamp ou interval invalide. La précision de ces types doit être inférieure ou égale à 6! + Utilisation d'une précision de type time, timestamp ou interval invalide. La précision de ces types doit être inférieure ou égale à 6 ! + Reference to a column which index is out of the capacity of the column list! - Référence à une colonne dont l'index dépasse la capacité de la liste des colonnes! + Référence à une colonne dont l'index dépasse la capacité de la liste des colonnes ! + Assignment of not allocated object! - Indefini ? - Utilisation d'un objet non référencé! + Utilisation d'un objet non référencé ! + Assigning object of an invalid type! - Assignation d'un objet dont le type est invalide! + Assignation d'un objet dont le type est invalide ! + Removing an object of an invalid type! - Suppression d'un objet dont le type est invalide! + Suppression d'un objet dont le type est invalide ! + Obtaining an object of an invalid type! - L'objet obtenu est de type invalide! + L'objet obtenu est de type invalide ! + Assignment of empty name to table return type! - Affectation d'un nom vide au type retourné par la table! + Affectation d'un nom vide au type retourné par la table ! + Reference to an event which does not belongs to trigger! - Qui ne provient ? - Référence à un évènement qui n'appartient pas au déclencheur! + Référence à un évènement qui n'appartient pas au déclencheur ! + Assignment of a function which language is invalid! - Définition d'une fonction dont le langage est invalide! + Définition d'une fonction dont le langage est invalide ! + Assignment of empty name to an object! - Affectation d'un nom vide à l'objet! + Affectation d'un nom vide à l'objet ! + Assignment of schema object which type is invalid! - Affectation d'un schema dont le type est invalide! + Affectation d'un schema dont le type est invalide ! + Assignment of tablespace object with invalid type! - Utilisation d'un tablespace dont le type est invalide! + Utilisation d'un espace logique dont le type est invalide ! + Assignment of tablespace to an invalid object! - Affectation d'un tablespace à un objet invalide! + Affectation d'un espace logique à un objet invalide ! + Assignment of tablespace to a constraint which type is invalid! To belong to a tablespace the constraint must be a primary key or unique! - Affectation d'un tablespace à une contrainte dont le type est invalide! Pour appartenir à un tablespace une contrainte doit être une clef primaire ou unique! + Affectation d'un espace logique à une contrainte dont le type est invalide ! Pour appartenir à un espace logique une contrainte doit être une clé primaire ou unique ! + Assignment of owner object which type is invalid! - Affectation d'un propiétaire dont le type est invalide! + Affectation d'un propiétaire dont le type est invalide ! + Assignment of owner to an invalid object! - Affectation d'un propriétaire à un objet invalide! + Affectation d'un propriétaire à un objet invalide ! + Reference to a function with invalid type! - Référence à une fonction dont le type est invalide! + Référence à une fonction dont le type est invalide ! + Reference to an argument of the operator with invalid type! - Référence à un argument de l'opérateur dont le type est invalide! + Référence à un argument de l'opérateur dont le type est invalide ! + Reference to an operator with invalid type! - Référence à un opérateur dont le type est invalide! + Référence à un opérateur dont le type est invalide ! + Assignment of value to an invalid option type on role! - Utilisation d'un attribut invalide pour un rôle! + Utilisation d'un attribut invalide pour un rôle ! + Reference to an invalid role type! - Référence à un type de rôle invalide! + Référence à un type de rôle invalide ! + Insertion of empty command to the rule! - Ajout d'une commande vide dans cette règle! + Insertion d'une commande vide dans cette règle ! + Is not possible to create a self generalization/copy relationship! The table can not inherit or copy their own attributes! - Impossible de créer une association de généralisation/copie avec elle même! Une table ne peut hériter ou copier ses propres attributs! + Impossible de créer une association de généralisation/copie de relation avec elle même ! Une table ne peut hériter ou copier ses propres attributs ! + Assignment of an object that already belongs to another table! - Utilisation d'un objet appartenant déjà à une autre table! + Utilisation d'un objet appartenant déjà à une autre table ! + Assignment of a schema to the sequence which differs from the schema of the owner table! - Affectation d'un schéma à la séquence diffèrent du schéma de la table! + Affectation d'un schéma à la séquence diffèrent du schéma de la table ! + Assignment of an invalid value to one of the sequence attributes! - Utilisation d'une valeur invalide comme attribut de séquence! + Utilisation d'une valeur invalide comme attribut de séquence ! + Assignment of a minimum value to the sequence which is greater than the maximum value! - La valeur minimale de la séquence est supérieure à la valeur maximale! + La valeur minimale de la séquence est supérieure à la valeur maximale ! + Assignment of a null increment value to the sequence! - La valeur de l'incrément de la séquence est nulle! + La valeur de l'incrément de la séquence est nulle ! + Assignment of null cache value to the sequence! - La valeur cache de la séquence est nul! + La valeur cache de la séquence est nulle ! + Allocation of object with invalid type! - Le type de l'objet alloué est invalide! + Le type de l'objet alloué est invalide ! + Assignment of not allocated language! - Indéfini ? - Utilisation d'un langage inconnu! + Utilisation d'un langage inconnu ! + Assignment of language object which type is invalid! - Définition d'un objet langage dont le type est invalide! + Définition d'un objet langage dont le type est invalide ! + Reference to data type with an index outside the capacity of data types list! - Référence à un type de donnée dont l'index est en dehors de la capacité de la liste des types de données! + Référence à un type de donnée dont l'index est en dehors de la capacité de la liste des types de données ! + Assignment of invalid type to the object! - Affectation d'un type invalide à l'objet! + Affectation d'un type invalide à l'objet ! + Obtaining types with invalid quantity! - Utilisation d'une quantité de types invalide! + Utilisation d'une quantité de types invalide ! + Insertion of item which already exists in the attributes list of the type! - Ajout d'un attribut déjà présent dans la définition de ce type! + Insertion d'un attribut déjà présent dans la définition de ce type ! + Insertion of invalid item in the attributes list of the type! - Ajout d'un attribut invalide à la liste des attributs de ce type! + Insertion d'un attribut invalide à la liste des attributs de ce type ! + Insertion of item which already exists in the enumarations list of the type! - Ajout d'un élément déjà existant dans l'énumeration! + Insertion d'un élément déjà existant dans l'énumeration ! + Insertion of invalid item in the enumerations list of the type! - Ajout d'un élément invlaide dans l'énumeration! + Insertion d'un élément invlaide dans l'énumeration ! + Assignment of invalid configuration to the type! - La configuration assigné au type est invalide! + La configuration assigné au type est invalide ! + Assignment of an operator which input type count is invalid to aggregate function! - Utilisation d'un opérateur dont le nombre d'argument est invalide avec une fonction d'agrégation (un et seulement un)! + Utilisation d'un opérateur dont le nombre d'argument est invalide avec une fonction d'agrégation ! + Assignment of an operator which types of arguments is invalid! - Utilisation d'un opérateur dont le type des arguments est invalide! + Utilisation d'un opérateur dont le type des arguments est invalide ! + + There is already a relationship between `%1' (%2) and `%3' (%4) in the model! When using relationships of the type generalization, copy and one-to-one there can't be other relationships linked to the pair of tables. + Il y a déjà une relation entre `%1 '(%2) et `%3' (%4) dans le modèle ! Lors de l'utilisation de relations de type généralisation, copie et un-à-un, il ne peut y avoir d'autres relations liées à la paire de tables. + + + A view reference must be used in at least one these SQL scopes: View Definition, SELECT-FROM, FROM-WHERE or After WHERE! - Lors de la définition d'une vue, une référence doit utiliser au moins une des options suivantes:SELECT-FROM, FROM-WHERE ou Après WHERE! + Lors de la définition d'une vue, une référence doit utiliser au moins un des champs SQL : SELECT-FROM, FROM-WHERE ou après WHERE ! + + + + Unable to load the configuration file `%1'! Please check if file exists in its folder and/or if it is not corrupted! + Impossible de charger le fichier de configuration `%1'! Merci de vérifier que le fichier existe dans son dossier et / ou s'il n'est pas corrompu ! + Could not find the default settings file `%1'! To restore default settings check the existence of the file and try again! Impossible de trouver le fichier des préférences par défaut `%1' ! Pour restaurer les préférences par défaut veuillez vérifier l'existance de ce fichier et réessayez ! + Could not load the plugin `%1' from the library `%2'! Message returned by plugin manager: `%3' Impossible de charger l'extension `%1' depuis la bibliothèque`%2' ! Message retourné par le gestionnaire d'extension : `%3' - Unknown attribute `%1' in file %2, line %3, column %4! - Attribut `%1' incconu dans le fichier %2, ligne %3, colonne %4 ! + + Failed to drop the database `%1' because it is defined as the default database for the connection `%2'! + Impossible de supprimer la base de données `%1 'car elle est définie comme base de données par défaut pour la connexion`%2' ! + + + + The column `%1' must be `NOT NULL' because it composes the primary key of the table `%2'. You need to remove the column from the mentioned contraint in order to disable the `NOT NULL' on it! + La colonne `%1' doit être `NOT NULL' car elle compose la clé primaire de la table `%2'. Vous devez supprimer la colonne de la contrainte mentionnée afin de désactiver le `NOT NULL' dessus ! + + + + The identity column `%1' has an invalid data type! The data type must be `smallint', `integer' or `bigint'. + La colonne d'identité `%1' a un type de données invalide ! Le type de données doit être `smallint', `integer' ou `bigint'. - Invalid use of a view referece as whole SQL definition! The assigned reference must be an expression! - À contrôler - Utilisation invalide d'une vue en tant que définition SQL! La référence doit être une expression! + + Reference to an invalid affected command in policy `%1'! + Référence à une commande affectée invalide dans la règle `%1' ! + + Reference to an invalid special role in policy `%1'! + Référence à un rôle spécial invalide dans la politique `%1' ! + + + Assignment of a second definition expression to the view! - Assignation d'une seconde expression à la vue! + Assignation d'une seconde expression à la vue ! + Assignment of collation object which type is invalid! - À contrôler - Utilisation d'un objet collation invlaide! + Utilisation d'un objet collation invalide ! + Collations must be created at least with attributes LC_COLLATE and LC_CTYPE defined! - Les collations doivent être définies avec les attributs LC_COLLATE et LC_CTYPE renseignés! + Les collations doivent être définies avec les attributs LC_COLLATE et LC_CTYPE renseignés ! + Reference to an invalid copy table option! - Référence à une option invalide de copie de table! + Référence à une option invalide de copie de table ! + The INSTEAD OF mode cannot be used on triggers that belongs to tables! This is available only for view triggers! - Le mode AU LIEU DE (INSTEAD OF) ne peut être utilisé comme trigger de table! Ce n'est valable que pour les triggers de vue! + Le mode AU LIEU DE (INSTEAD OF) ne peut être utilisé comme déclencheur de table ! Ce n'est valable que pour les déclencheurs de vue ! + The TRUNCATE event can only be used when the trigger executes for each statement and belongs to a table! - L'événement TRUNCATE ne peut être utilisé que lors d'un trigger sur chaque ligne et qu'il appartient à une table! + L'événement TRUNCATE ne peut être utilisé que lors d'un déclencheur sur chaque ligne et que s'il appartient à une table ! + The INSTEAD OF mode cannot be used on view triggers that executes for each statement! - Le mode AU LIEU DE (INSTEAD OF) ne peut être utilisé avec triggeurs de vues qui s’exécutent à chaque requête! + Le mode AU LIEU DE (INSTEAD OF) ne peut être utilisé avec des déclencheurs de vues qui s’exécutent à chaque requête ! + Constraint triggers can only be executed on AFTER events and for each row! - Les triggeurs de contraintes ne peuvent être exécutés qu'après (AFTER) et pour chaque lignes! + Les déclencheurs de contraintes ne peuvent être exécutés qu'APRÈS les événements et pour chaque ligne ! + A view trigger cannot be AFTER/BEFORE when it executes for each row! - Les triggeurs de vues ne peuvent être AFTER/BEFORE quand il sont configuré pour une exécution sur chaque ligne! + Les déclencheurs de vues ne peuvent être AFTER/BEFORE quand il sont configurés pour une exécution sur chaque ligne ! + A trigger cannot make reference to columns when using INSTEAD OF mode and UPDATE event! - Un triggeur ne peut faire référence aux colonnes quand il est utilisé en mode INSTEAD OF sur un événement de type UPDATE! + Un déclencheur ne peut faire référence aux colonnes quand il est utilisé en mode INSTEAD OF sur un événement de type UPDATE ! + Only constraint triggers can be deferrable or reference another table! - Seuls les déclencheurs de contraintes peuvent être déférés ou référencer une autre table! - - - Reference to a function id which is incompatible whit the user define type configuration! - Doutes - Référence faite à un identifiant de fonction incompatible avec le type configuré! + Seuls les déclencheurs de contraintes peuvent être déférés ou référencer une autre table ! + The validation process failed due to an error triggered by the validation helper. For more details about the error check the exception stack! - La procédure de validation a échouée à cause d'une erreur levée par l'assistant de validation. Pour de plus amples informations, referez vous à la pile des exceptions! + La procédure de validation a échouée à cause d'une erreur levée par l'assistant de validation. Pour de plus d'informations, referez-vous à la pile des exceptions ! + Assignment of an invalid strategy/support number to an operator class element! - Hum ... numéro de stratégie/support ? - Affectation d'un numéro de stratégie/support invalide à un élément de la classe 'operator'! + Affectation d'un numéro de stratégie/support invalide à un élément de la classe 'operator' ! + Insertion of element which already exists in the element list! - Insertion d'un élément déjà existant dans la liste des éléments! + Insertion d'un élément déjà existant dans la liste des éléments ! + Reference to a parameter which index is out of the parameter list bounds! - Référence un paramètre dont l'index est hors des limites de la liste de ces derniers! + Référence un paramètre dont l'index est hors des limites de la liste de ces derniers ! + Reference to an argument which index is out of argument list bounds! - Référence un argument dont l'index est hors des limites de la liste de ces derniers! + Référence un argument dont l'index est hors des limites de la liste de ces derniers ! + Assignment of a name which contains invalid characters! - Utilisation de caractères invalides dans le nom! + Utilisation de caractères invalides dans le nom ! + Assignment of a name which length exceeds the maximum of 63 characters! - Utilisation de plus de 63 caractères dans le nom! + Utilisation de plus de 63 caractères dans le nom ! + Reference to a role which index is out of role list bounds! - Référence un rôle dont l'index est hors des limites de la liste de ces derniers! + Référence un rôle dont l'index est hors des limites de la liste de ces derniers ! + Reference to a command which index is out of the command list bounds! - Référence une commande dont l'index est hors des limites de la liste de ces dernières! + Référence une commande dont l'index est hors des limites de la liste de ces dernières ! + Assignment of a start value to the sequence which is extrapolating the range defined by minimum and maximum values! - À contrôler. - Affectation de la valeur de départ de la séquence en dehors des limites de cette dernière (min et max)! + Affectation de la valeur de départ de la séquence en dehors de la plage de cette dernière définie par les valeurs min et max ! + Reference to a label which index is out of labels list bounds! - Référence un label dont l'index est hors des limites de la liste de ces derniers! + Référence un label dont l'index est hors des limites de la liste de ces derniers ! + Reference to an attribute which index is out of the attributes list bounds! - Référence un attribut dont l'index est hors des limites de la liste de ces derniers! + Référence un attribut dont l'index est hors des limites de la liste de ces derniers ! + Reference to an enumeration which index is out of the enumerations list bounds! - Référence une énumération dont l'index est hors des limites de la liste de ces dernières! + Référence une énumération dont l'index est hors des limites de la liste de ces dernières ! + Reference to an element which index is out of element list bounds! - Référence un élément dont l'index est hors des limites de la liste de ces derniers! + Référence un élément dont l'index est hors des limites de la liste de ces derniers ! + Reference to an object which index is out of object list bounds! - Référence un objet dont l'index est hors des limites de la liste de ces derniers! + Référence un objet dont l'index est hors des limites de la liste de ces derniers ! + Removal of an object not allocated! - Suppression d'un objet non alloué! + Suppression d'un objet non alloué ! + The object `%1' (%2) can not be manipulated because it is reserved to PostgreSQL! This object is present in the database model only as a reference! - L'objet `%1' (%2) ne peut être modifié car il est est réservé à PostgreSQL! Cet objet apparaît dans le modèle uniquement comme référence! - - - Unsupported PostgreSQL version (%1) detected! Valid versions are: %2 - Une version non supportée de PostgreSQL (%1) a été détectée! Les versions supportées sont: %2 + L'objet `%1' (%2) ne peut être modifié car il est est réservé à PostgreSQL ! Cet objet apparaît dans le modèle uniquement comme référence ! + Operation with object(s) which type(s) is invalid! - Opérations sur des objet(s) dont le(s) type(s) sont invalides! + Opérations sur un ou des objets dont les types sont invalides ! + Reference to object with invalid type! - Référence à un objet ayant un type invalide! + Référence à un objet ayant un type invalide ! + Operation with object not allocated! - Opération sur des objets non alloués! + Opération sur des objets non alloués ! + The relationship of the type 1-1 where both tables are mandatory participation is not implemented because it requires fusion between the tables that breaks the modeling done by the user! - Une association de type 1-1, quand les deux tables sont obligatoires, n'est pas implémentée car celà requiert la fusion des tables, ce qui casse le modèle réalisé par l'utilisateur! + Une association de type 1-1, quand les deux tables sont obligatoires, n'est pas implémentée car cela requiert la fusion des tables, ce qui casse le modèle réalisé par l'utilisateur ! + Assignment of an invalid expression to the object! - Affectation d'une expression invalide à l'objet! + Affectation d'une expression invalide à l'objet ! + Assignment of a primary key to a table which already has one! - Impossible de définir une clef primaire à une table qui en possède déjà une! + Impossible de définir une clé primaire à une table qui en possède déjà une ! + Identifier relationship can not be created for a self relationship, relationships of the type n-n, copy or generalization! - Review needed ! Doutes ... - Seules des associations de type 1:1 ou 1:n peuvents être utilisé comme identifiant. En aucun cas les autoassociations, associations n:n, généralisations ou copies ne le peuvent! + La relation d'identifiant ne peut pas être créée pour une relation vers elle même, pour les relations de type n-n, pour la copie ou pour la généralisation! + An attribute can not be added to a copy or generalization relationship! - Un attribut ne peut être ajouté à une relation copie ou généralisation! + Un attribut ne peut être ajouté à une relation copie ou généralisation ! + A foreign key can not be added to a relationship because is created automatically when this is connected! - Une clef étrangère ne peut être ajoutée à une relation car elle est créée automatiquement lors de la mise en relation! + Une clé étrangère ne peut être ajoutée à une relation car elle est créée automatiquement lors de la mise en relation ! + Reference to an user-defined data type that not exists in the model! - Référence à un type de donné défini par l'utilisateur qui n'existe pas dans le modèle! + Référence à un type de donné défini par l'utilisateur qui n'existe pas dans le modèle ! + Assignment of invalid maximum size to operation list! - La taille maximum affectée à la liste d'opérations est invalide! + La taille maximum affectée à la liste d'opérations est invalide ! + One or more objects were invalidated and automatically removed because they were referencing table columns which were included through relationships and which no longer exists due to disconnection of relationships or exclusion of such generated columns! - Un ou plusieurs objets ont été invalidés et automatiquement supprimés car ils référençaient des colonnes qui étaient incluses dans des relations et qui n'existaient plus du fait de la suppression de relation ou d'exclusion de ces colonnes! + Un ou plusieurs objets ont été invalidés et automatiquement supprimés car ils référençaient des colonnes qui étaient incluses dans des associations et qui n'existaient plus du fait de la suppression de l'associations ou de l'exclusion de ces colonnes ! + Reference to an invalid privilege type! - Référence à un type de privilège invalide! + Référence à un type de privilège invalide ! + Insertion of a role which already exists in the role list of the permission! - Ajout d'un rôle déjà existant dans la liste de cette permission! + Insertion d'un rôle déjà existant dans la liste de cette permission ! + Assignment of privilege incompatible with the type of object referenced by permission! - Utilisation d'un privilège incompatible avec le type d'objet référencé par la permission! + Utilisation d'un privilège incompatible avec le type d'objet référencé par la permission ! + It is not possible to create arrays of domains or sequences (dimension >= 1)! PostgreSQL does not yet implement this feature! - Il est impossible de créer des tableaux de domaines ou séquences (dimension >= 1)! PostgreSQL n'inplémente pas encore cette fonctionnalité! + Il est impossible de créer des tableaux de domaines ou de séquences (dimension >= 1) ! PostgreSQL n'inplémente pas encore cette fonctionnalité ! + Assignment of invalid name to the table generated from N-N relationship! - Le nom de la table générée par la relation N-N est invalide! + Le nom de la table générée par la relation N-N est invalide ! + Reference to a column of the objects table with invalid index! - Référence à une colonne de la table ayant un index invalide! + Référence à une colonne de la table ayant un index invalide ! + Reference to a row of the objects table with invalid index! - Référence à une ligne de la table ayant un index invalide! + Référence à une ligne de la table ayant un index invalide ! + Constraints like primary key, foreign key or unique must have at least one column related to them! For foreign keys must be selected, in addition, the referenced columns! - Les contraintes telles que clef primaire, clef étrangère ou l'unicité doivent avoir au moins une colonne associée! Pour les clefs étrangères, les colonnes référencées doivent également être sélectionnées! - - - Unable to load one or more configuration files! Please check if files exists in the configuration folder and if they are not corrupted to preventing this error to occur again on the next startup! - Impossible de charger un ou plusieurs fichiers de configuration! Veuillez vérifier que les fichiers existent bien dans le dossier de configuration et qu'ils ne soient pas corrompus pour éviter que l'erreur ne se produise à nouveau au prochain lancement! + Les contraintes telles que clé primaire, clé étrangère ou unicité doivent avoir au moins une colonne associée ! Pour les clés étrangères, les colonnes référencées doivent également être sélectionnées ! + The export process failed due to an error triggered by the PostgreSQL server in an attempt to execute a SQL command. For more details about the error check the exception stack! ** Executed SQL command: ** %1 - Le process d'exportation a échoué suite à une erreur déclenchée par le serveur PostgreSQL lors de la tentative d'exécution d'une commande SQL. Pour plus de détails concernant l'erreur vérifiez la pile d'exceptions! + Le process d'exportat a échoué suite à une erreur déclenchée par le serveur PostgreSQL lors de la tentative d'exécution d'une commande SQL. Pour plus de détails concernant l'erreur vérifiez la pile d'exceptions ! ** Commande SQL exécutée: ** %1 + One or more plugins were not activated due to errors during the loading process! Check the exception stack for more details. - Une ou plusieurs extensions n'ont pas été activée(s) car des erreurs sont apparues lors du processus de chargment. Pour plus de détails, consultez la pile d'exceptions. - - - Invalid syntax in file %1, line %2, column %3! - Syntaxe invalide dans le fichier %1, ligne %2, colonne %3! + Une ou plusieurs extensions n'ont pas été activées suite à la survenue d'erreurs lors du chargement. Pour plus de détails, consultez la pile d'exceptions. + Assignment of empty XML buffer to parser! - Passage d'un tampon XML vide au parseur! - - - Could not access the file or directory %1! Make sure that it exists or if the user has access permissions on it! - Impossible d'accéder au fichier ou dossier %1! Assurez vous qu'il existe et que l'utilisateur a le droit d'y accéder! + Passage d'un tampon XML vide à l'analyseur ! + Assignment of empty DTD file name! - Le nom du fichier DTD est vide! + Le nom du fichier DTD est vide ! + Assignment of empty name to the DTD declaration! - Le nom de la DTD est vide! + Le nom de la déclaration DTD est vide ! + Operation on unallocated element tree! It is necessary to load the XML parser buffer and interpret it so that the tree is generated! - Opération sur un élément de l'arbre XML non initialisé! Il est nécessaire de remplir le tampon de l'analyseur XML et de lancer l'interprétation pour que l'arbre soit généré! - - - Could not load file %1. The same appears to be inconsistent or one of its dependencies (DTD files) has errors or is missing! - Impossible de charger le fichier %1. Le fichier semble incohérent ou une de ses dépendances (fichiers DTD) contient des erreurs ou est manquantes! + Opération sur l'arbre d'élément non alloué ! Il est nécessaire de charger le tampon d'analyseur XML et de l'interpréter pour que l'arbre soit généré ! + Operation with unallocated tree element! - Opération sur un élément non alloué de l'arbre! + Opération avec un élément de l'arbre non alloué ! + Operation with element which does not exists in the element tree currently loaded! - Opération sur un élément inexistant dans l'arbre des élément actullement chargé! + Opération avec un élément inexistant dans l'arbre des éléments actullement chargé ! + Assignment of a value to an invalid connection parameter! - Affectation d'une valeur à un paramètre de connexion invalide! + Affectation d'une valeur à un paramètre de connexion invalide ! + Operation on connection not established! - Opération sur une connexion non établie! + Opération sur une connexion non établie ! + Attempt to connect without define configuration parameters! - Tentative de connexion sans paramètre de configuration défini! + Tentative de connexion sans paramètre de configuration défini ! + Assignment of not allocated SQL command result! - indéfini ? - Affectation d'un résultat de commande SQL non alloué! + Affectation d'un résultat de commande SQL non alloué ! + Unable to allocate the result of the SQL command because the response from the DBMS was not understood by the client! - Impossible de retourner le résultat de la commande SQL car la réponse du SGBD n'a pas été comprise par le client! + Impossible de retourner le résultat de la commande SQL car la réponse du SGBD n'a pas été comprise par le client ! + Reference to a column of tuple with invalid index! - Référence à une colonne de tuple dont l'index est invalide! + Référence à une colonne de tuple dont l'index est invalide ! + Reference to a column of tuple with invalid name! - Référence à une colonne de tuple dont le nom est invalide! - - - Reference to a tuple with index invalid or the result is empty (no tuples)! - Référence à un tuple avec un index invalide ou le résultat est vide (pas de tuple)! + Référence à une colonne de tuple dont le nom est invalide ! + Assignment of a not allocated column to object `%1' (%2)! - + Affectation d'une colonne non allouée à l'objet `%1 '(%2) ! + Assignment of a not allocated schema to object `%1' (%2)! - + Affectation d'un schéma non allouée à l'objet `%1 '(%2) ! + The object `%1' (%2) has inconsistent SQL or XML definition! - + L'objet `%1 '(%2) a une définition SQL ou XML incohérente ! + The object `%1' (%2) already exists on `%3' (%4)! - + L'objet `%1 '(%2) existe déjà sur `%3' (%4) ! + The object `%1' (%2) cannot be assigned because there is already exists in the container object `%3'! - + L'objet `%1 '(%2) ne peut être assigné car il existe déjà dans l'objet conteneur `%3' ! + The insertion of the parameter `%1' will not be possible because there is another parameter with same name in the function `%2'! - + L'insertion du paramètre `%1' ne sera pas possible car il existe un autre paramètre avec le même nom dans la fonction `%2' ! + The insertion of the table return type `%1' will not be possible because there is another return type with the same name in the `%2'! - + L'insertion du type de retour de la table `%1' ne sera pas possible car il existe un autre type de retour avec le même nom dans le`%2' ! + The column `%1' cannot be assigned to the trigger `%2' because they belongs to different parent tables! - + La colonne `%1' ne peut pas être affectée au déclencheur `%2' car ils appartiennent à des tables parentes différentes ! + Assignment of a not allocated function to object `%1' (%2)! - + Affectation d'une fonction non allouée à l'objet `%1' (%2) ! + Assignment of a function which return type is different from `%1'! - + Affectation d'une fonction dont le type de retour est différent de `%1' ! + Assignment of a function which parameter count is invalid to the object `%1' (%2)! - + Affectation d'une fonction dont le nombre de paramètres n'est pas valide pour l'objet `%1' (%2) ! + Event trigger function must be coded in any language other than SQL! - + La fonction de déclenchement d'événement doit être codée dans n'importe quelle langue autre que SQL ! + Assignment of not allocated table to object `%1' (%2)! - + Affectation de la table non allouée à l'objet `%1' (%2) ! + Assignment of appended or prepended SQL to an invalid object! - + Affectation de code SQL ajouté ou préfixé à un objet invalide ! + The insertion of the role `%1' is not possible because this is already being referenced by role `%2'! - + L'insertion du rôle `%1 n'est pas possible car il est déjà référencé par le rôle `%2' ! + Reference redundancy detected by having the role `%1' referencing the role `%2'! - + Redondance de références détectée en ayant le rôle `%1' référençant le rôle `%2' ! + The role `%1' can not be listed as a member of itself! - + Le rôle `%1' ne peut pas être listé comme un membre de lui-même ! + Assignment of owner table which is not in the same schema as the sequence `%1'! - + Affectation de la table propriétaire qui n'est pas dans le même schéma que la séquence `%1' ! + Assignment of owner table which does not belong to the same owner of the sequence `%1'! - + Affectation de la table propriétaire qui n'appartient pas au même propriétaire de la séquence `%1' ! + Assignment of a nonexistent owner column to the sequence `%1'! - + Affectation d'une colonne propriétaire inexistante à la séquence `%1' ! + Assignment of an owner column to the sequence `%1' that is not related to any table! - + Affectation d'une colonne propriétaire à la séquence `%1' qui n'est liée à aucune table ! + Assignment of a function with invalid return type to object `%1' (%2)! - + Affectation d'une fonction avec un type de retour invalide à l'objet `%1' (%2) ! + Assignment of a function with invalid parameter(s) type(s) to object `%1' (%2)! - + Affectation d'une fonction avec un (des) paramètre(s) non valide(s) à l'objet `%1' (%2) ! + Assignment of an empty directory to object `%1' (%2)! - + Affectation d'un répertoire vide à l'objet `%1' (%2) ! + Assignment of system reserved name to the object `%1' (%2)! - + Affectation du nom réservé au système à l'objet `%1' (%2) ! + One function with invalid configuration is been used by the object `%1' (%2)! - + Une fonction avec une configuration invalide est utilisée par l'objet `%1' (%2) ! + The object `%1' (%2) can not be removed because it is being referenced by object `%3' (%4)! - + L'objet `%1' (%2) ne peut pas être supprimé car il est référencé par l'objet `%3' (%4) ! + The object `%1' (%2) can not be removed because it is being referenced by object `%3' (%4) that belongs to `%5' (%6)! - + L'objet `%1' (%2) ne peut pas être supprimé car il est référencé par l'objet `%3' (%4) appartenant à `%5' (%6) ! + The creation of the relationship `%1' between the table `%2' and `%3' can not be done because one does not have a primary key. If the relationship is of the type n-n both tables must have primary keys! - + La création de la relation `%1' entre la table `%2' et `%3' ne peut pas être effectuée car il n'y a pas de clé primaire. Si la relation est du type n-n, les deux tables doivent avoir des clés primaires ! + Unable to create a copy relationship because the column `%1' in table `%2' already exists in table `%3'! - + Impossible de créer une relation de copie car la colonne `%1' de la table `%2' existe déjà dans la table `%3' ! + Unable to create the generalization relationship because the column `%1' in table `%2' can not be merged with the column `%3' of table `%4' because they have incompatible types! - + Impossible de créer la relation de généralisation car la colonne `%1' de la table `%2' ne peut pas être fusionnée avec la colonne `%3' de la table `%4' car ils ont des types incompatibles ! + The object `%1' (%2) is referencing the object `%3' (%4) which was not found in the model! - + L'objet `%1' (%2) fait référence à l'objet `%3' (%4) qui n'a pas été trouvé dans le modèle ! + Unable to write the file or directory `%1'! Make sure the output directory exists, or if the user has write permissions over it! - - - - There is already a relationship between `%1' (%2) and `%3' (%4) in the model! - + Impossible d'écrire le fichier ou le répertoire `%1' ! Assurez-vous que le répertoire de sortie existe et que l'utilisateur a les droits d'écriture dedans ! + The primary key `%1' can only be allocated if declared within a block of code that defines a table or relationship! - + La clé primaire `%1' ne peut être allouée que si elle est déclarée dans un bloc de code qui définit une table ou une relation ! + There is already a permission on object `%1' (%2) which has one or more equal roles from those present on permission to be assigned to the object! - + Il y a déjà une permission sur l'objet `%1' (%2) qui a un ou plusieurs rôles égaux à ceux présents dans l'autorisation à assigner à l'objet ! + A permission is referencing the object `%1' (%2) which was not found in the model! - + Une permission fait référence à l'objet `%1' (%2) qui n'a pas été trouvé dans le modèle ! + The object `%1' (%2) can not be created because its not being assigned to any schema! - + L'objet `%1' (%2) ne peut pas être créé car il n'est affecté à aucun schéma ! + The tablespace `%1' can not be inserted into the model because it points to the same directory as the tablespace `%2'! - + L'espace de stockage `%1' ne peut pas être inséré dans le modèle car il pointe sur le même répertoire que l'espace de table `%2' ! + The function `%1' can not get a source code as a definition because its language is set to C. Use the attributes symbol and dynamic library instead! - + La fonction `%1' ne peut pas obtenir un code source en tant que définition car sa langue est définie sur C. Utilisez plutôt le symbole d'attributs et la bibliothèque dynamique ! + The function `%1' can have the attributes symbol and dynamic library configured only if the language is set to C. For all other cases you must specify a source code that defines it in the DBMS! - + La fonction `%1' peut avoir le symbole des attributs et la bibliothèque dynamique configurés uniquement si la langue est définie sur C. Dans tous les autres cas, il faut spécifier un code source qui le définit dans le SGBD ! + The operator `%1' can not be assigned as a comutator of operator `%2' because it has incompatible settings! - + L'opérateur `%1' ne peut pas être affecté en tant que commutateur de l'opérateur `%2'car il comporte des paramètres incompatibles ! + The operator `%1' can not be assigned as negator of operator `%2' because it has incompatible settings! - + L'opérateur `%1' ne peut pas être affecté en tant que négateur de l'opérateur `%2' car il a des paramètres incompatibles ! + The type `%1' can not self refer in the attributes `element' or `copy type' or be used as a data type of an attribute in the configuration of a composite type! - + Le type `%1' ne peut pas se référer à lui-même dans les attributs `element' ou `copy type' ou être utilisé comme type de données d'un attribut dans la configuration d'un type composite ! + Assignment of invalid element to type `%1'! - + Affectation d'un élément invalide de type `%1' ! + Assignment of invalid alignment to type `%1'! - + Affectation de l'alignement invalide de type `%1' ! + The relationship `%1' can not make use of the special primary key because it is marked as identifier or it is a self relationship! - + La relation `%1' ne peut pas utiliser la clé primaire spéciale car elle est marquée comme identifiant ou c'est une association d'elle-même ! + The object `%1' (%2) can not be edited or deleted because it was automatically included through a relationship! If the object is an attribute or constraint the modifications must be done on the relationship editing form. - + L'objet `%1' (%2) ne peut pas être modifié ou supprimé car il a été automatiquement inclus dans une association ! Si l'objet est un attribut ou une contrainte, les modifications doivent être effectuées sur le formulaire d'édition de la relation. + The object `%1' (%2) can not be deleted because it is protected! - + L'objet `%1' (%2) ne peut pas être supprimé car il est protégé ! + The group `%1' has already been declared earlier! - + Le groupe `%1' a déjà été déclaré ! + The group `%1' can not be built in the groups declaration block (%2)! - + Le groupe `%1' ne peut pas être construit dans le bloc de déclaration de groupe (%2) ! + The group `%1' was built but not declared in the groups declaration block (%2)! - + Le groupe `%1' a été construit mais pas déclaré dans le bloc de déclaration de groupe (%2) ! + The group `%1' can not be built without possessing child elements! - + Le groupe `%1' ne peut pas être construit sans posséder d'éléments enfants ! + The group `%1' can not be built once more because this was done in previous blocks! - + Le groupe `%1' ne peut pas être construit une fois de plus car cela a été fait dans les blocs précédents ! + The group `%1' has been declared but not built! - + Le groupe `%1' a été déclaré mais pas construit ! + The new configuration of the function invalidates the object `%1' (%2)! In this case it is needed to undo the relationship between the affected object and function in order to the new configuration to take effect! - + La nouvelle configuration de la fonction invalide l'objet `%1' (%2) ! Dans ce cas, il est nécessaire d'annuler la relation entre l'objet affecté et la fonction afin que la nouvelle configuration prenne effet ! - Invalid instruction `%1' on file %2, line %3, column %4! - + + Error while interpreting XML buffer at line %1 column %2. +Message generated by the parser: %3. %4 + Erreur lors de l'interprétation du tampon XML à la ligne %1, colonne %2. +Message généré par l'analyseur : %3. %4 - Invalid metacharacter `%1' in file %2, line %3, column %4! - + + Attempt to start a connection already stablished! + Tentative de lancement d'une connexion déjà établie ! - Invalid operator `%1' in comparison expression, file %2, line %3, column %4! - + + Could not connect to the database. +Message returned: `%1' + Impossible de se connecter à la base de données. +Message renvoyé : `%1' - Attribute `%1' with an undefined value in file %2, line %3, column %4! - + + Unable to allocate command result for the SQL because the server has generated a fatal error! +Message returned by the DBMS: `%1' + Impossible d'allouer le résultat de la commande SQL car le serveur a généré une erreur fatale ! +Message renvoyé par le SGBD : `%1' - Attribute `%1' with an invalid name in file %2, line %3, column %4! - - - - Error while interpreting XML buffer at line %1 column %2. -Message generated by the parser: %3. %4 - - - - Attempt to start a connection already stablished! - - - - Could not connect to the database. -Message returned: `%1' - - - - Unable to allocate command result for the SQL because the server has generated a fatal error! -Message returned by the DBMS: `%1' - - - - Reference to a column of a tuple which was not yet initialized (tuple navigation not started)! - + + Reference to a column of a tuple which was not yet initialized (tuple navigation not started)! + Référence à une colonne d'un tuple qui n'a pas encore été initialisé (navigation en tuple non démarrée) ! + Could not execute the SQL command. Message returned: `%1' - + Impossible d'exécuter la commande SQL. + Message renvoyé : `%1' + It is not possible mix ordinary references (SELECT-FROM, FROM-WHERE, After WHERE) with references used as view SQL definition! - + Il n'est pas possible de mélanger des références ordinaires (SELECT-FROM, FROM-WHERE, Après WHERE) avec des références utilisées comme vue de définition SQL ! + The object `%1' (%2) cannot reference itself! This operation is not permitted for this kind of object! - + L'objet `%1' (%2) ne peut pas se référencer lui-même ! Cette opération n'est pas autorisée pour ce genre d'objet ! + Only operator families which uses `btree' as indexing method are accepted by operator class elements! - + Seules les familles d'opérateurs qui utilisent `btree 'comme méthode d'indexation sont acceptées par les éléments de classe d'opérateur ! + Copy relationship between tables `%1' and `%2' cannot be done because the first one already copies attributes from `%3'! Tables can have only one copy table! - + L'association de copie entre les tables `%1' et `%2' ne peut pas être effectuée car la première copie déjà les attributs de `%3' ! Les tables ne peuvent avoir qu'une seule table de copie ! + Assignment of a column which has no parent table to the object `%1' (%2)! - + Affectation d'une colonne qui n'a pas de table parent à l'objet `%1' (%2) ! + The operator class assigned to the object `%1' (%2) must use `btree' as indexing method! - + La classe d'opérateur affectée à l'objet `%1' (%2) doit utiliser` btree' comme méthode d'indexation ! + The extension `%1' is registered as a data type and cannot have the attribute `handles datatype' modified! - + L'extension `%1' est enregistrée en tant que type de données et ne peut pas avoir l'attribut `handle datatype' modifié ! + The fk relationship `%1' cannot be created because the foreign-key that represents it was not created on table `%2'! - + L'association clé étrangère `%1' ne peut pas être créée car la clé étrangère qui la représente n'a pas été créée sur la table `%2' ! + Assignement of an invalid object name pattern to the relationship `%1'! - + Affectation d'un modèle de nom d'objet invalide à la relation `%1' ! + Reference to an invalid object name pattern id on the relationship `%1'! - + Référence à un identifiant de modèle de nom d'objet invalide sur la relation `%1' ! + Mixing incompatibles DBMS export modes: `ignore object duplications', `drop database' or `drop objects' cannot be used with `simulate export'! - + Mélange incompatibles des modes d'export du SGBD : `ignore object duplications', `drop database' ou `drop objects' ne peuvent être utilisés avec `simulate export' ! + Mixing incompatibles DROP options: `drop database' and `drop objects' cannot be used at the same time! - + Mixage incompatible des options DROP : `drop database' et `drop objects' ne peuvent pas être utilisés en même temps ! + Invalid object id swapping operation! The objects involved are the same! - + Opération d'échange d'identifiant d'objet invalide ! Les objets impliqués sont les mêmes ! + Invalid object id swapping operation! The database itself, tablespaces or roles cannot have the ids swapped! - + Opération d'échange d'identifiant d'objet invalide ! La base de données elle-même, les espaces de stockage ou les rôles ne peuvent pas échanger leurs identifiants ! + The widget already has a parent and cannot be assigned to a different object! - - - - The object `%1' (%2) could not be imported due to one or more errors! Check the exception stack for more details. - + Le widget a déjà un parent et ne peut pas être assigné à un objet différent ! + Could not load the database model file `%1'. Check the error stack to see details. Try to run `pgmodeler-cli --fix-model' in order to correct the structure of the file if that is the case. - + Impossible de charger le fichier de modèle de base de données `%1'. Vérifiez la pile d'erreurs pour plus de détails. Essayez d'exécuter `pgmodeler-cli --fix-model' afin de corriger la structure du fichier si besoin. + The column `%1' cannot reference it's parent table `%2' as data type! - + La colonne `%1' ne peut pas référencer sa table parent `%2' comme type de données ! + Operation with an invalid element id `%1'! - + Opération avec un identifiant d'élément invalide `%1' ! + Reference to an invalid color id `%1' for element `%2'! - + Référence à un identifiant de couleur invalide `%1' pour l'élément `%2' ! + The sequence `%1' can't be assigned to the column `%2' because the data type of the latter is incompatible. The type used must be an integer one! - + La séquence `%1' ne peut pas être affectée à la colonne `%2' car le type de données de cette dernière est incompatible. Le type utilisé doit être un entier ! + The option to generate temporary object names can only be used in simulation mode! - + L'option de génération de noms d'objets temporaires ne peut être utilisée qu'en mode simulation ! + Could not assign the variable `%1' to event trigger's filter. Currently, PostgreSQL supports only the `TAG' variable! - - - - Could not perform the `%1' operation on `%2' using the data on row `%3'! All changes were rolled back. - - ** Returned error ** - -%4 - + Impossible d'affecter la variable `%1 'au filtre du déclencheur d'événement. Actuellement, PostgreSQL supporte uniquement la variable `TAG' ! + Malformed unescaped value on row `%1' column `%2'! - + Valeur non echappée malformée à la ligne `%1', colonne `%2' ! + The object `%1' (%2) can't be handled because some needed fields are not set! Please, make sure to fill at least the requires fields in order to properly create or update the object. - + L'objet `%1' (%2) ne peut pas être manipulé car certains champs nécessaires ne sont pas définis ! Merci de vous assurer de remplir au moins les champs requis afin de créer ou de mettre à jour correctement l'objet. + A relationship can only be swapped by other object of the same kind! - + Une association ne peut être permutée que par un autre objet du même genre ! + Assignment of a null type to object `%1' (%2)! - + Affectation d'un type nul à l'objet `%1' (%2) ! + Unable to create the generalization relationship because the constraint `%1' in table `%2' can not be merged with the constraint `%3' of table `%4' due to their incompatible composition! - + Impossible de créer l'association de généralisation car la contrainte `%1' de la table `%2' ne peut pas être fusionnée avec la contrainte `%3' de la table `%4' en raison de leurs compositions incompatibles ! + Unable to write the file `%1' due to one or more errors in the definition generation process! - + Impossible d'écrire le fichier `%1' en raison d'une ou de plusieurs erreurs dans le processus de génération de définition ! + The configuration of the relationship `%1' generates a redundancy between the relationships `%2'. Redundancy on identifier or generalization/copy relationships are not accepted since they result in incorrect column spreading making the model inconsistent! - + La configuration de la relation `%1' génère une redondance entre les associations `%2 . La redondance sur l'identificateur ou les relations de généralisation/copie de l'association ne sont pas acceptées car elles entraînent une répartition incorrecte des colonnes, ce qui rend le modèle incohérent ! + + + + Invalid syntax in file `%1', line %2, column %3! + Syntaxe non valide dans le fichier `%1', ligne %2, colonne %3! + + + + Invalid instruction `%1' on file `%2', line %3, column %4! + Instruction invalide `%1' dans le fichier `%2', ligne `%3', colonne `%4' ! + + + + Unknown attribute `%1' in file `%2', line %3, column %4! + Attribut inconnu `%1' dans le fichier `%2', ligne `%3', colonne `%4' ! + + + + Invalid metacharacter `%1' in file `%2', line %3, column %4! + Métacaractère invalide `%1' dans le fichier `%2', ligne `%3', colonne `%4' ! + + + + Invalid operator `%1' in comparison expression, file `%2', line %3, column %4! + Opérateur invalide `%1' dans l'expression de comparaison, fichier `%2', ligne`%3', colonne `%4' ! + + + + Attribute `%1' with an undefined value in file `%2', line %3, column %4! + L'attribut `%1' a une valeur non définie dans le fichier `%2', ligne`%3', colonne `%4' ! + + + + Attribute `%1' with an invalid name in file `%2', line %3, column %4! + L'attribut `%1' a un nom invalide dans le fichier `%2', ligne`%3', colonne `%4' ! + + + + Could not access the file or directory `%1'! Make sure that it exists or if the user has access permissions on it! + Impossible d'acceder au fichier ou fossier `%1' ! Vérifiez qu'il existe et que l'utilisateur à les droits d'écritures ! + + + + Could not load file `%1'. The same appears to be inconsistent or one of its dependencies (DTD files) has errors or is missing! + Impossible de charger le fichier `%1'. La même chose semble être incohérente ou l'une de ses dépendances (fichiers DTD) a des erreurs ou est manquante ! + Reference to a tuple with an invalid index or the result is empty (no tuples)! - + Référence à un tuple avec un index invalide ou le résultat est vide (pas de tuple) ! + Invalid use of a view reference as whole SQL definition! The assigned reference must be an expression! - + Utilisation invalide d'une référence de vue comme définition SQL entière ! La référence affectée doit être une expression ! + At the moment pgModeler does not support the creation of primary keys which some columns were generated by relationship connection. To create primary keys with this feature you can use the field `Identifier' or the tab `Primary key' on relationship editing form! - + Actuellement pgModeler ne supporte pas la création de clés primaires dont certaines colonnes ont été générées par la connection d'associations. Pour créer des clés primaires avec cette fonctionnalité, vous pouvez utiliser le champ `Identifier' ou l'onglet `Primary key' sur le formulaire d'édition de relation ! + Reference to a function id which is incompatible with the user define type configuration! - + Référence à un identifiant de fonction incompatible avec la configuration du type de définition de l'utilisateur ! + + + + Unsupported PostgreSQL version (%1) detected! Valid versions are between %2 and %3. + Version PostgreSQL non prise en charge (%1) détectée! Les versions valides sont comprises entre %2 et %3. + Invalid use of variadic parameter mode! This mode can be used only with an array or "any" data type! - + Utilisation invalide du mode paramètre variadique ! Ce mode ne peut être utilisé qu'avec un tableau ou un type de données "any" ! + + The object `%1' (%2), oid `%3', could not be imported due to one or more errors! Check the exception stack for more details. `HINT:' if the object somehow references objects in `pg_catalog' or `information_schema' consider enable the importing of system objects. + L'objet `%1 '(%2), oid `%3', n'a pu être importé en raison d'au moins une erreur ! Vérifiez la pile d'exceptions pour plus de détails. `REMARQUE : 'Si l'objet référence d'une manière ou d'une autre les objets dans` pg_catalog' ou `information_schema ', envisagez d'importer les objets système. + + + Assignment of an invalid object to `%1' (%2)! The assigned object must be of type `%3'. - + Affectation d'un objet invalide à `%1' (%2) ! L'objet affecté doit être de type `%3'. + It's not possible convert the type of the column `%1' to serial! It must have an `integer' based type and its default value must be a call to `nextval(seq_name::regclass)' function or a sequence object must be directly assigned to the column! - + Il n'est pas possible de convertir le type de la colonne `%1' en série ! Il doit avoir un type basé sur `integer' et sa valeur par défaut doit être un appel à la fonction `nextval (seq_name::regclass)' ou un objet séquence doit être directement assigné à la colonne ! + + + + Could not perform the `%1' operation on `%2' using the data on row `%3'! All changes were rolled back. + + ** Returned error ** + +%4 + Impossible d'exécuter l'opération `%1 'sur `%2' en utilisant les données de la ligne `%3 '! Tous les changements ont été annulés. + + ** Erreur retournée ** + +%4 + Trying to undo/redo an invalid operation over an object that does not exists anymore or can't be handled! The operation history will be cleaned up. - + Tentative d'annulation/de rétablissement d'une opération invalide sur un objet qui n'existe plus ou ne peut plus être géré ! L'historique des opérations sera nettoyé. + A parent table of `%1' which OID is `%2' was not found in the set of imported objects! - + Une table parente de `%1' dont l'OID est `%2' n'a pas été trouvée dans l'ensemble des objets importés ! + The enumeration `%1' can't be assigned to the type `%2' because contains invalid characters! - + L'énumération `%1' ne peut pas être affectée au type `%2' car elle contient des caractères non valides ! + The enumeration `%1' can't be assigned to the type `%2' because is too long! - + L'énumération `%1' ne peut pas être affectée au type `%2' car elle est trop longue ! + The connection was idle for too long and was automatically closed! - + La connexion était inactive depuis trop longtemps et a été automatiquement fermée ! + The connection was unexpectedly closed by the database server `%1' at port `%2'! - + La connexion a été fermée de manière inattendue par le serveur de la base de données `%1' sur le port `%2' ! ExtensionWidget - Form - Formulaire - - + Version: - Version: + Version : + Old Version: - Ancienne version: + Ancienne version : + This attribute cannot be changed once the object is created. Cet attribut ne peut être modifié une fois l'objet créé. + Handles data type - Prendre en charge les types de données + Gérer les types de données FindReplaceWidget + Form Formulaire + + Hide this widget + + + + + ... + ... + + + Replace one occurrence Remplace une occurrence + Replace Remplacer + Replace all occurrences Remplace toutes les occurrences + Replace All Remplacer tout + Replace the selection and find the next one Remplacer l'occurrence courante et trouver le suivant + Replace && Find Remplacer && Suivant + Replace: - Remplacer par: + Remplacer par : + Find: - Recherche: + Recherche : + Find previous Précédent + Shift+F3 - Shift+F3 + Maj+F3 + Find next Suivant + F3 F3 + Case sensitive Respecter la casse + Regular expression Expression régulière + Whole words Mots entier @@ -4347,563 +5338,753 @@ Message returned by the DBMS: `%1' FunctionWidget - Form - Formulaire - - + Attributes Attributs - Langague: - Langage: - - + Function Type: - Type de fonction: + Type de fonction : + Execution Cost: - Coût d'exécution: + Coût d'exécution : + Rows Returned: - Lignes retournées: + Lignes retournées : + Behavior: - Comportement: + Comportement : + Security: - Sécurité: + Sécurité : + Return Method: - Type de retour: - - - Simple - Simple + Type de retour : + Set Multiple - Table - Table - - + Return Table Table de retour + Windown Func. - Fonct. fenêtrage + Fonct. fenêtrage. + Leakproof Leakproof + Parameters Arguments + Definition Définition + Dynamic Library: - Bibliotèque dynamique: + Bibliothèque dynamique : + Symbol: - Symbole: + Symbole : + Library: - Bibliotèque: + Bibliothèque : + Source code: - Code source: + Code source : + Column Colonne + + Type - Type + + Name Nom + Mode - Mode + + Default Value Valeur par défaut + Si&mple - + Si&mple + Tab&le - + Tab&le + + + + Language: + Langage : GeneralConfigWidget + Form Formulaire + Milimeters Millimètres + Pixels Pixels + Inches Pouces + Centimeter Centimètres + A0 (841 x 1189 mm) A0 (841 x 1189 mm) + General && Design Général && modélisation - The opened models will be saved periodically - Les modèles ouverts seront sauvegardés à interval régulier - - + Check if there is a new version on server Vérifier la présence d'une nouvelle version au lancement + Design Modélisation + Graphical objects (table, views and textboxes) will be created in a single step without the need to click on canvas - Les nouveaux objets graphiques (tables, vues, zones de textes) seront ajoutés au modèle sans avoir besoin d'effectuer un second clic sur le caneva pour les positionner + Les objets graphiques (tables, vues, zones de textes) seront créés en une seule étape sans avoir besoin de cliquer sur le canevas. + Simplify creation of graphical objects Créer les nouveaux objets en un clic + After loading the model the last zoom and position on canvas will be restored - Restaure la dernière position ainsi que le zoom sur le caneva à l'écran lors de l'ouverture d'un modèle + Après le chargement du modèle, le dernier zoom et la position du canevas seront restaurés. + Save and restore last position and zoom Sauvegarder la position et le zoom - Disable antialiasing for lines and texts improving performance on huge models (requires restart) - Désactive l'anticrénelage pour les lignes et les textes afin d'améliorer la réactivité de l'application sur des modèles très etoffés (nécessite un redémarrage) - - + Disable render smoothness Désactiver l'anticrénelage + Hide the object that represents the relationship name - Masque l'étiquette indiquant le nom de chaque association - - - Operations like save, export and diff will be executed without asking user to validate the model - Certaines opérations comme l'enregistrement du fichier, l'export ou encore le différenetiel seront lancées sans demander à l'utilisateur de valider le modèle avant + Masque l'étiquette indiquant le nom de chaque association. + Validate before save, export or diff Validation du modèle toujours requise + Hide the object which represents the tag assigned to the table - Masque l'étiquette indiquant le tag associé à chaque table + Masquer l'objet qui représente la balise affectée à la table. + Hide the portion of table which represent triggers, indexes and rules - Masque les règles, les déclencheurs et les index dans l'affichage des tables - - - Swap panning and range selection triggers - Inverser le comportement du clic gauche - - - Toggles the code completion in all fields that accepts the input of SQL commads. - Active la complétion du code SQL dans les zones de texte prévues à cet effet. + Masque les règles, les déclencheurs et les index dans l'affichage des tables. + Enable SQL code completion Activer la complétion du code SQL + Printing && Code Impression && édition + + Size: + Taille : + + + + pt + pt + + + + Font: + Police : + + + + Hide relationship name + Masquer le nom des associations + + + + Hide table extended attributes + Masquer les attributs étendus des tables + + + + Paper: + Papier : + + + + Orientation: + Orientation : + + + + General + Général + + + + Operation history: + Historique des opérations : + + + + Hide table tags + Masquer les balises des tables + + + + Printing + Impression + + + + + Options: + Options : + + + + Print grid + Imprimer la grille + + + A1 (594 x 841 mm) - A1 (594 x 841 mm) + + A2 (420 x 594 mm) - A2 (420 x 594 mm) + + A3 (297 x 420 mm) - A3 (297 x 420 mm) + + A4 (210 x 297 mm) - A4 (210 x 297 mm) + + A5 (148 x 210 mm) - A5 (148 x 210 mm) + + A6 (105 x 148 mm) - A6 (105 x 148 mm) + + A7 (74 x 105 mm) - A7 (74 x 105 mm) + + A8 (52 x 74 mm) - A8 (52 x 74 mm) + + A9 (37 x 52 mm) - A9 (37 x 52 mm) + + B0 (1030 x 1456 mm) - B0 (1030 x 1456 mm) + + B1 (728 x 1030 mm) - B1 (728 x 1030 mm) + + B10 (32 x 45 mm) - B10 (32 x 45 mm) + + B2 (515 x 728 mm) - B2 (515 x 728 mm) + + B3 (364 x 515 mm) - B3 (364 x 515 mm) + + B4 (257 x 364 mm) - B4 (257 x 364 mm) + + B5 (182 x 257 mm) - B5 (182 x 257 mm) + + B6 (128 x 182 mm) - B6 (128 x 182 mm) + + B7 (91 x 128 mm) - B7 (91 x 128 mm) + + B8 (64 x 91 mm) - B8 (64 x 91 mm) + + B9 (45 x 64 mm) - B9 (45 x 64 mm) + + C5E (163 x 229 mm) - C5E (163 x 229 mm) + + Comm10E (105 x 241 mm) - Comm10E (105 x 241 mm) + + DLE (110 x 220 mm) - DLE (110 x 220 mm) + + Executive (191 x 254 mm) - Executive (191 x 254 mm) + + Folio (210 x 330 mm) - Folio (210 x 330 mm) + + Ledger (432 x 279 mm) - Ledger (432 x 279 mm) + + Legal (216 x 356 mm) - Legal (216 x 356 mm) + + Letter (216 x 279 mm) - Lettre (216 x 279 mm) + + Tabloid (279 x 432 mm) - Tabloid (279 x 432 mm) + - Code font style - Style de police pour le code SQL + + Custom + Personnalisé - Size: - Taille: + + Unity: + Unité : - pt - pt + + Custom Size: + Taille papier : - Font: - Police: + + Width: + Largeur : - Hide relationship name - Masquer le nom des associations + + Height: + Hauteur : - Hide table extended attributes - Masquer les attributs étendus des tables + + Page Margins: + Marges : - Paper: - Papier: + + Left: + Gauche : - Orientation: - Orientation: + + Left margin + Marge de gauche - Autosave interval: - Interval d'auto-enregistrement: + + Top: + Haut : - Grid size: - Taille de la grille: + + Top margin + Marge du haut - General - Général + + Right: + Droite : - Check for updates at startup - Vérifier MAJ au démarrage + + Right margin + Marge de droite - Operation history: - Historique des opérations: + + Bottom: + Bas : - By default panning mode is triggered with left click and range selection with Shift + left click. - Par défaut : le clic gauche permet de déplacer le canevas (glisser-déplacer), la sélection multiple (rectangle) s'effectue par Shift + clic gauche. + + Bottom margin + Marge du bas - Hide table tags - Masquer le tag des tables + + Landscape + Paysage - Printing - Impression + + Portrait + Portrait - Options: - Options: - + + Print page numbers + Imprimer les numéros de page + - Print grid - Imprimer la grille + + Start move the canvas when the cursor is on the canvas edges + Commencer à déplacer le canevas lorsque le curseur se trouve sur les bords de celui-ci. - Custom - Personalisé + + Move canvas by keep mouse on corners + Déplacer le canevas en gardant la souris sur les coins - Unity: - Unité: + + Disable antialiasing for lines and texts improving performance when handling huge models. + Désactiver l'antialiasing pour les lignes et les textes améliore les performances lors de la manipulation d'énormes modèles. - Custom Size: - Taille papier: + + Triggers a dialog asking the user to validate the model before a save, export or diff operation. + Déclenche une boîte de dialogue demandant à l'utilisateur de valider le modèle avant une opération de sauvegarde, d'export ou de comparaison. - Width: - Largeur: + + When enabled this option creates a placeholder object at the previous table's position when starting to move it. This will cause graphical updates on relationship lines to be performed only when the drag & drop action is done improving the performance. Disabling placeholders will cause those updates to be executed every time the table's position changes a single pixel (classical behavior). + Lorsqu'elle est activée, cette option crée un objet réservé à la position de la table précédente lorsque vous commencez à la déplacer. Afin d'améliorer les performances, la mise à jour graphique sur les lignes associées ne se fera uniquement qu'une fois l'action de glisser-déposer términée. La désactivation des espaces réservés entraîne l'exécution de ces mises à jour chaque fois que la position de la table change d'un seul pixel (comportement classique). - Height: - Hauteur: + + Use placeholders when moving tables + Utiliser des espaces réservés lors du déplacement de tables - Page Margins: - Marges de la page: + + Toggles the code completion in all fields that accepts the input of SQL commands. + (Dés)active l'achèvement du code dans tous les champs qui acceptent les commandes SQL en entrée. - Left: - Gauche: + + Code style + Style du code - Left margin - Marge gauche + + Colors: + Couleurs : - Top: - Haut: + + Display line numbers + Afficher les numéros de ligne - Top margin - Marge haute + + Highlight lines at cursor's position + Surligner les lignes à la position du curseur - Right: - Droite: + + Custom tab width: + Largeur d'onglet personnalisé : - Right margin - Marge droite + + Line numbers' font color + Couleur de la police des numéros de ligne - Bottom: - Bas: + + Line numbers' background color + Couleur d'arrière-plan des numéros de ligne - Bottom margin - Marge basse + + Highlighted line color + Couleur de la ligne en surbrillance - Landscape - Paysage + + The little brown fox jumps over the lazy dog + Le petit renard brun saute par-dessus le chien paresseux - Portrait - Portrait + + System default + Défaillance du système - Print page numbers - Imprimer les numéros de page + + All files (*.*) + Tous les fichiers (*.*) - minute(s) - minute(s) + + Load file + Charger un fichier - items - entrées + + Minimum object opacity (%): + Opacité min. des objets (%) : - pixels - pixels + + Defines the minimum opacity percentage applied to the objects when using the fade out feature. A zero opacity causes the object to be completely hidden not being possible to interact with it in the canvas area. + Définit le pourcentage d'opacité minimum appliqué aux objets lorsqu'ils sont estompés. Une opacité nulle cache complètement l'objet sans qu'il soit possible d'interagir avec lui dans la zone de canevas. - Start move the canvas when the cursor is on the canvas edges - + + Canvas grid size: + Taille de grille du canevas : - Move canvas by keep mouse on corners - + + Defines the vertical and horizontal grid size. This value affects the spacing of objects when using object grid alignment feature. + Définit la taille de la grille verticale et horizontale. Cette valeur affecte l'espacement des objets lors de l'utilisation de la fonction d'alignement des objets sur la grille. - Disable antialiasing for lines and texts improving performance when handling huge models. - + + By default the range selection is triggered with Shift + left click. By checking this option range selection will be activated only with a single click and move. + Par défaut, la sélection de plage est déclenchée avec Maj + clic gauche. En cochant cette option, la sélection de la gamme sera activée qu'en un seul clic et se déplacera. - Triggers a dialog asking the user to validate the model before a save, export or diff operation. - + + Trigger range selection with a single click + Déclenchement de la sélection en un clic - When enabled this option creates a placeholder object at the previous table's position when starting to move it. This will cause graphical updates on relationship lines to be performed only when the drag & drop action is done improving the performance. Disabling placeholders will cause those updates to be executed every time the table's position changes a single pixel (classical behavior). - + + Defines the maximum amount of elements held in the operation history. Once reached the maximum number the history is automatically cleaned. + Définit le nombre maximal d'éléments contenus dans l'historique des opérations. Une fois le nombre maximum atteint, l'historique est automatiquement nettoyé. - Use placeholders when moving tables - + + Defines the period when the opened models will be saved automatically. + Définit la période (en minute) d'enregistrement automatique des modèles ouverts. - Toggles the code completion in all fields that accepts the input of SQL commands. - + + Autosave interval (minutes): + Intervalle sauv. auto : - Code style - + + Replaces any straight line in relationship by curved ones in order to improve the model's visualization. + Remplace les lignes droites des relations par des courbes pour améliorer la lisibilité du modèle. - Colors: - Couleur: + + Use curved lines for relationships + Utiliser des lignes courbes pour les associations - Display line numbers - + + SQL history max. length: + Longueur max. de l'historique SQL : - Highlight lines at cursor's position - + + Souce code editor: + Éditeur de code source : - Custom tab width: - + + lines + lignes - Line numbers' font color - + + Clear the entire SQL comand history. + Nettoyer complètement l'historique des commandes SQL. - Line numbers' background color - + + Clear history + Nettoyer l'historique - Highlighted line color - + + Configurations directory: + Dossier de configuration : - The little brown fox jumps over the lazy dog - + + Browse the source code editor application + Rechercher l'éditeur de code source + + + + Open in file manager + Ouvrir dans le gestionnaire de fichier + + + + Check updates at startup + Vérifier MAJ au démarrage + + + + Souce code editor args: + Arg. pour l'éditeur de code source : + + + + User interface language: + Langue de l'interface graphique : + + + + Overrides the default user interface language defined by the system. Requires restarting the program. <strong>NOTE:</strong> UI translations are third party collaborations thus any typo or mistake should be reported directly to their respective maintainers. + Remplace la langue de l'interface utilisateur définie par défaut par le système. Nécessite de redémarrer le programme. <strong>REMARQUE :</strong> les traductions de l'interface utilisateur sont des collaborations avec des tiers; par conséquent, toute faute de frappe ou erreur doit être signalée directement à leurs responsables respectifs. - GraphicalView + GenericSQLWidget - Connected rels: %1 - Associations : %1 + + SQL code + Code SQL HintTextWidget + Form Formulaire @@ -4911,2857 +6092,3640 @@ Message returned by the DBMS: `%1' IndexWidget - Form - Formulaire - - + Attributes Attributs + Indexing: - Indexation: + Indexation : + Fill Factor: - Taux de remplissage: + Taux de remplissage : + Options: - Options: + Options : + Concurrent Concurrent + Unique Unique + Fast update Mise à jour rapide + Elements - Élements + Éléments + Buffering - + Mémoire tampon + Predicate: - + Prédicat : LanguageWidget - Form - Formulaire - - + Trusted: - De confiance: + De confiance : + The functions to be assigned to the language should have, respectively, the following signatures:<br/><br/> <strong>Handler Function:</strong> <em>language_handler function()</em><br/> <strong>Validator Function:</strong> <em>void function(oid)</em><br/> <strong>Inline Function:</strong> <em>void function(internal)</em> - Les fonctions attribuées au langage doivent avoir espectivement les signatures suivantes:<br/><br/> <strong>Fonction de management:</strong> <em>language_handler fonction()</em><br/> <strong>Fonction de validation:</strong> <em>void fonction(oid)</em><br/> <strong>Fonction Inline:</strong> <em>void fonction(internal)</em> + Les fonctions attribuées au langage doivent avoir respectivement les signatures suivantes :<br/><br/> <strong>Fonction de gestion :</strong> <em>language_handler function()</em><br/> <strong>Fonction de validation :</strong> <em>void function(oid)</em><br/> <strong>Fonction sur une ligne :</strong> <em>void function(internal)</em> + Validator Func.: - + Fonc. de validation : + Handler Func.: - + Fonc. gestionnaire : + Inline Func.: - + Fonc. en ligne : MainWindow + pgModeler - PostgreSQL Database Modeler - pgModeler - PostgreSQL Database Modeler + pgModeler – Modeleur de bases de données PostgreSQL + + + + &Validation + + + + + Alt+V + + + + + Ctrl+F + + + Alt+O + + + + + Alt+B + + + + &File &Fichier + &Edit Édit&ion + &Show &Affichage - &Plugins - E&xtensions - - + Plugins Extensions + New Nouveau + Controls Contrôles + General Général + Ctrl+N Ctrl+N - Save - Enregistrer - - + Ctrl+S Ctrl+S + Zoom in Zoom + + Ctrl+= Ctrl+= + Zoom out Zoom - + Zoom - Zoom - + Ctrl+- Ctrl+- - Load - Ouvrir - - + Ctrl+O Ctrl+O - Next - Suivant - - - Ctrl+Right - Ctrl+Right - - - Previous - Précédent - - - Ctrl+Left - Ctrl+Left - - - Save as - Enregistrer sous - - - Exit - Quitter - - + Ctrl+Q Ctrl+Q - About pgModeler - À propos de pgModeler - - + Export the current opened model in different modes Exporter le modèle courant sous différentes formes - Close - Fermer - - + Close current model Fermer le modèle courant + Ctrl+H Ctrl+H - Settings - Paramètres - - + Edit pgModeler settings Configurer pgModeler + F10 F10 - Wiki - Wiki - - - Access the wiki pages - Visiter le wiki (site) - - - CSS - CSS - - + Access the list of loaded plugins - Accéder a la liste des extensions chargées - - - Recent Models - Modèles récents + Accéder à la liste des extensions chargées + Load recently opened model Charger des modèles ouverts récemment - Import - Importer - - + Import existing database to new model (reverse engineering) Importer une base de données existante vers un modèle (reverse engineering) + Ctrl+Shift+I - Ctrl+Shift+I - - - Restore Session - Restaurer la session - - - Fix a model - Réparer un modèle + Ctrl+Maj+I + New version found! - Nouvelle version disponible! + Nouvelle version disponible ! + Update for the current version is available on project's site Une mise à jour pour votre version est disponible sur le site de pgModeler - Check for update - Vérifier les mises à jour - - + Main menu Menu principal + Show expanded Afficher la barre de menus + Hide main menu Cacher la barre de menus + Hides the main menu bar and put the action on a separated action Masque la barre de menu (le menu reste accessible via un bouton dans la barre d'outils) + Ctrl+Shift+H - Ctrl+Shift+H - - - Diff - Différencier - - - Determine the changes between model and database - Déterminer les modifications apportées entre un modèle et une base existante + Ctrl+Maj+H + Welcome Accueil + Welcome screen Écran d'accueil + Design Modéliser - Design datase models - Modéliser une base de données - - + Manage Administrer + Manage existent databases Administrer des bases existantes - Bug report - Rapporter un bug - - - F1 - F1 - - + O&bjects O&bjets - Alt+B - Alt+B - - - &Validation - &Validation - - - Alt+V - Alt+V - - + &Operations &Opérations - Alt+O - Alt+O - - + Find Object Chercher un objet - Ctrl+F - Ctrl+F - - - msg - message - - - Help - Aide - - - F4 - F4 - - - Print - Imprimer - - - Ctrl+P - Ctrl+P - - - Undo - Annuler - - - Ctrl+Z - Ctrl+Z - - - Redo - Rétablir - - - Ctrl+Y - Ctrl+Y - - - Export - Exporter - - + Ctrl+Shift+S - Ctrl+Shift+S + Ctrl+Maj+S + Show grid Afficher la grille - Ctrl+G - Ctrl+G - - - Ctrl+W - Ctrl+W - - - Normal zoom - Zoom normal - - - Ctrl+0 - Ctrl+0 - - - Align to grid - Aligner sur la grille - - + Align objects position to grid Aligner les objets sur la grille - Show delimiters - Afficher les délimiteurs - - + Show the page delimiters Afficher les délimiteurs de page - Ctrl+L - Ctrl+L - - + Save all Tout enregistrer - Overview - Vue d'ensemble - - + Show the model overview Afficher la vue d'ensemble du modèle - Save all models - Enregistrer tous les modèles - - + Clear Menu - Vider cette liste des modèles récents + Vider le menu + The demonstration version can create only `one' instance of database model! - La version de démonstration ne peut gérer qu'un seul modèle de base à la fois ! + La version de démonstration ne peut gérer qu'une seule instance de modèle de base de données ! + + Save model Enregistrer le modèle + + Warning Avertissement + Save '%1' as... Enregistrer '%1' sous... + + Database model (*.dbm);;All files (*.*) Modèle de base de données (*.dbm);; Tous les fichiers (*.*) + Database model printing Impression du modèle de base de données - Confirmation - Confirmation - - - Some models were modified! Do you really want to quit pgModeler without save them? - Des modifications n'ont pas été enregistrées ! Êtes-vous sûr de vouloir QUITTER pgModeler SANS SAUVEGARDER ? - - - The model was modified! Do you really want to close without save it? - Le modèle a été modifié. -Voulez-vous vraiment le FERMER SANS le SAUVEGARDER? - - + Save anyway Sauvegarder quand même + + + Validate Valider + Changes were detected in the definitions of paper/margin of the model which may cause the incorrect print of the objects. Do you want to continue printing using the new settings? To use the default settings click 'No' or 'Cancel' to abort printing. - Des modifications ont été détectées dans les définitions du papier ou des marges du modèle ce qui pourrait causer une mauvaise impression des objets. Souhaitez vous continuer l'impression avec les nouveaux paramètres? Pour utiliser les paramètres par défaut cliquez sur 'Non' ou 'Annuler' pour interrompre l'impression. + Des modifications ont été détectées dans les définitions du papier ou des marges du modèle ce qui pourrait causer une mauvaise impression des objets. Souhaitez-vous continuer l'impression avec les nouveaux paramètres ? Pour utiliser les paramètres par défaut cliquez sur 'Non' ou sur 'Annuler' pour interrompre l'impression. + Load model Charger un modèle + Could not load the database model file `%1'. Check the error stack to see details. You can try to fix it in order to make it loadable again. - Impossible de charger le modèle `%1'. Consultez la pile d'appel pour plus de détails. Essayez de réparer le modèle pour tenter de l'ouvrir à nouveau. + Impossible de charger le ficher modèle de base de données `%1'. Consultez la pile d'appel pour plus de détails. Essayez de réparer le modèle pour tenter de l'ouvrir à nouveau. + Fix model Réparer un modèle + Cancel Annuler - Open Wiki pages - Accèder au Wiki - - + This action will open a web browser window! Want to proceed? - Cette action ouvrira votre navigateur web! Souhaitez vous continuer? + Cette action ouvrira votre navigateur web ! Souhaitez vous continuer ? + Toggle the model objects widget - + (Dés)activer le widget des objets du modèle + Toogle the model validation widgets - + (Dés)activer le widget de validation du modèle + Toggle the operation history widget - + (Dés)activer le widget de l'historique des opérations + Toggle the object finder - + (Dés)activer le chercheur d'objet + action_main_menu - + action_menu_principal + Expands the main menu bar in classical mode - + Développe la barre de menus principale en mode classique - (Demo) - + + Saving temp. models + Sauvegarde temp. des modèles - Saving temp. models - + + Grid + Grille + + + + Hierarchical + Hiérarchique + + + + Scattered + Dispersé + + + + (Demo) + (Démo) + You're running a demonstration version! The model saving feature is available only in the full version! - + Vous utilisez une version de démonstration ! La fonction d'enregistrement du modèle est uniquement disponible dans la version complète ! + + + + + + Confirmation + + <strong>WARNING:</strong> The model <strong>%1</strong> is invalidated! It's recommended to validate it before save in order to create a consistent model otherwise the generated file will be broken demanding manual fixes to be loadable again! - <strong>AVERTISSEMENT:</strong> Le modèle <strong>%1</strong> n'a pas été validé ! Avant de l'enregistrer il est recommandé de le valider afin de créer un modèle cohérent, sinon il peut en résulter un fichier mal formé nécessitant une édition manuelle pour pouvoir être chargé à nouveau dans l'application par la suite ! + <strong>AVERTISSEMENT :</strong> Le modèle <strong>%1</strong> n'a pas été validé ! Il est recommandé de le valider avant de l'enregistrer afin de créer un modèle cohérent, sinon il peut en résulter un fichier cassé nécessitant une réparation manuelle pour être chargé à nouveau chargeable ! + <strong>WARNING:</strong> The model <strong>%1</strong> is invalidated! Before run the export process it's recommended to validate in order to correctly create the objects on database server! - <strong>AVERTISSEMENT:</strong> Le modèle <strong>%1</strong> n'a pas été validé ! Avant de procéder à un export il est recommandé de valider le modèle afin s'assurer de créer correctement les objets en base ! + <strong>AVERTISSEMENT :</strong> Le modèle <strong>%1</strong> n'a pas été validé ! Avant de procéder à un export il est recommandé de le valider afin de s'assurer de correctement créer les objets sur le serveur de base de données ! + Export anyway Exporter quand même + <strong>WARNING:</strong> The model <strong>%1</strong> is invalidated! Before run the diff process it's recommended to validate in order to correctly analyze and generate the difference between the model and a database! - <strong>AVERTISSEMENT:</strong> Le modèle <strong>%1</strong> n'a pas été validé ! Avant de procéder à un différentiel il est recommandé de valider le modèle afin s'assurer que l'analyse entre celui-ci de la base de donnée se fasse correctement ! + <strong>AVERTISSEMENT :</strong> Le modèle <strong>%1</strong> n'a pas été validé ! Avant de procéder à une comparaison il est recommandé de le valider afin de s'assurer que l'analyse entre celui-ci de la base de donnée se fasse correctement ! + Diff anyway - Différencier quand même + Comparer quand même + (no samples found) - + (aucun exemple trouvé) + save - + sauvegarde + export - + exporter + diff - + comparer + Executing pending <strong>%1</strong> operation... - + Exécution de l'opération <strong>%1</strong> en attente... + + + + Rearrange objects over the canvas is an irreversible operation! Would like to proceed? + Réorganiser les objets sur le canvas est une opération irréversible ! Voulez-vous poursuivre ? + He&lp - + Ai&de + Pl&ugins - + Mod&ules + &New - + &Nouveau + New model - Nouveau modèle + Nouveau modèle + &Save - E&nregistrer + E&nregistrer + &Zoom in - + &Zoomer + Zoo&m out - + Dézoo&mer + &Load - O&uvrir + C&harger + Sa&ve as - + Enre&gistrer sous + E&xit - + Qui&tter + Exit pgModeler - + Quitter pgModeler + &About pgModeler - + &À propos de pgModeler + + + + F4 + + &Print - + Im&primer + Print model - + Imprimer le modèle + + Ctrl+P + + + + &Undo - + Ann&uler + Undo operation - + Annuler l'opération + + + + Ctrl+Z + + &Redo - + &Rétablir + Redo operation - + Rétablir l'opération + + + + Ctrl+Y + + &Export - &Exporter + &Exporter + Ctrl+Shift+E - + Ctrl+Maj+E + &Show grid - + A&fficher la grille + + + + Ctrl+G + + &Close - &Fermer + &Fermer + + + + Ctrl+W + + &Normal zoom - + Zoom &normal + + + + Ctrl+0 + + &Align to grid - + &Aligner sur la grille + Show &delimiters - + Afficher les &délimiteurs + + + + Ctrl+L + + &Settings - + Paramètre&s + F12 - F12 + + &Overview - + &Vue d'ensemble + &Support - + + Access the support page - + Accéder à la page du support + + + + F1 + + New object - + Nouvel objet + &Recent Models - + Modèles &récents + &Import - &Importer + &Importer + Rest&ore Session - + Restaurer la sessi&on + &Fix a model - + Réparer u&n modèle + &Check for update - + Re&chercher une mise à jour + &Diff - + &Comparer + Ctrl+Shift+D - + Ctrl+Maj+D + Shift+W - + Maj+W + Design database models - + Conception de modèles de base de données + Shift+D - + Maj+D + Shift+M - + Maj+M + &Bug report - + Rapport de &bug + Report a bug - + Rapporter un bug + Donate - + Faire un don + Help pgModeler by donating! - + Aider pgModeler en faisant un don ! + Objects me&tadata - + Mé&tadonnées des objets + Objects metadata - + Métadonnées des objets + Save modified model(s) - + Enregistrer le(s) modèle(s) modifié(s) + The following models were modified but not saved: %1. Do you really want to quit pgModeler? - + Les modèles suivants ont été modifiés mais non enregistrés : %1. Voulez-vous vraiment quitter pgModeler ? + The model <strong>%1</strong> was modified! Do you really want to close without save it? - + Le modèle <strong>%1</strong> a été modifié ! Êtes-vous certain de vouloir quitter sans l'enregistrer ? + Access support page - + Accéder à la page de support + You're running a demonstration version! Note that you'll be able to create only <strong>%1</strong> instances of each type of object and some key features will be disabled or limited!<br/><br/>You can purchase a full binary copy or get the source code at <a href='http://pgmodeler.com.br'>pgmodeler.com.br</a>. <strong>NOTE:</strong> pgModeler is an open source software, but purchasing binary copies or providing some donations will support the project and cover all development costs.<br/><br/> <strong>HINT:</strong> in order to test all features it's recommended to use the <strong>demo.dbm</strong> model located in </strong>Sample models</strong> at <strong>Welcome</strong> view.<br/><br/><br/><br/> - + Vous utilisez une version de démonstration ! Notez que vous ne pourrez créer que <strong>%1</strong> instances de chaque type d'objet et que certaines fonctionnalités clés seront désactivées ou limitées !<br/><br/>Vous pouvez acheter une copie binaire complète ou obtenir le code source sur <a href='http://pgmodeler.com.br'> pgmodeler.com.br </a>. <strong> REMARQUE :</strong> pgModeler est un logiciel open source, mais l'achat de copies binaires ou la fourniture de dons soutiendra le projet et couvrira tous les coûts de développement.<br/><br/> <strong>CONSEIL :</strong> Pour tester toutes les fonctionnalités, il est recommandé d'utiliser le modèle <strong>demo.dbm</strong> situé dans <strong>exemples de modèles</strong> dans la vue <strong>Bienvenue</strong>.<br/><br/><br/><br/><br/> + + + + Determine the changes between model/database and another database + Déterminer les changements entre le modèle/la base de données et une autre base de données + + + + Arrange objects + Organiser des objets + + + + Rearrange objects over the canvas + Réorganiser les objets sur le canevas Messagebox + Dialog Boîte de dialogue + msg message + Exceptions Exceptions + Show/hide exceptions stack. - Afficher/cacher la pile d'exceptions. + Afficher/cacher la pile d'exceptions. + ... ... + + &Yes &Oui + + &No &Non + + Information + + + + + Confirmation + + + + Cancel Annuler + Error Erreur + Alert Alerte - Information - Information - - - Confirmation - Confirmation - - + &Ok &Ok + &Cancel A&nnuler + Show raw text errors or information. - + Afficher le texte brute des erreurs ou des informations. MetadataHandlingForm + Handle metadata - + Gérer les métadonnées + &Apply - &Appliquer + &Appliquer + &Cancel - A&nnuler + A&nnuler + Handle objects metadata - + Gérer les métadonnées d'objets + Settings - Paramètres + Paramètres + Extract from: - + Extraction depuis : + Loading a metadata file to the current model is an irreversible operation so be sure to specify a backup file before proceed. - - - - Options - Options + Le chargement d'un fichier de métadonnées dans le modèle actuel est une opération irréversible, assurez-vous de spécifier un fichier de sauvegarde avant de continuer. + Handles the following database model attributes in the metadata file: author, zoom factor, last position and default objects. - + Gère, dans le fichier de métadonnées, les attributs de modèle de base de données suivants : auteur, facteur de zoom, dernière position et objets par défaut. + Database model metadata - + Métadonnées du modèle de base de données + Handles the objects' positioning in the metadata file. - + Gère le positionnement des objets dans le fichier de métadonnées. + + + + Options + + Objects' positioning - + Positionnement des objets + Handles the objects' custom colors in the metadata file. Currently available only for relationships and schemas. - + Gère les couleurs personnalisées des objets dans le fichier de métadonnées. Actuellement disponible uniquement pour les associations et les schémas. + Custom object's colors - + Couleurs de l'objet personnalisé + Handles the objects' protection status in the metadata file. - + Gère l'état de protection des objets dans le fichier de métadonnées. + Objects' protection status - + Statut de protection des objets + Handles the objects' SQL disabled status in the metadata file. - + Gère le statut désactivé du code SQL des objets dans le fichier de métadonnées. + Objects' SQL disabled status - + Statut désactivé du code SQL des objets + Handles the objects' custom SQL commands in the metadata file. - + Gère les commandes SQL personnalisées des objets dans le fichier de métadonnées. + Custom SQL commands - - - - Save textboxes to the output file when extracting metadata. When loading the file textboxes are recreated and duplicated ones are ignored. - + Commandes SQL personnalisées + Textbox objects - - - - Save tags to the output file when extracting metadata. When loading the file tags are recreated and duplicated ones are ignored. - + Objets de zone de texte + Tag objects - + Balises des objets + Backup file: - + Fichier de sauvegarde : + + Select file - - - - ... - ... + Sélectionner un fichier + Apply to: - + Appliquer à : + Operation: - - - - Extracts the objects metadata from one of the loaded models and apply to the current model. - - - - Extract from a &model - - - - Reads the objects metadata from a previously saved backup file and apply to the current model. - - - - Restore a bac&kup file - + Opération : + Output - + Sortie + Progress label... - Indicateur de progression... + Indicateur de progression... + + model not saved yet - + modèle pas encore enregistré + The backup file cannot be the same as the input model! - + Le fichier de sauvegarde ne peut être le même que le modèle d'entrée ! + Extracting metadata to file `%1' - + Extraction des métadonnées vers le fichier `%1' + Saving backup metadata to file `%1' - + Enregistrement des métadonnées de sauvegarde vers le fichier `%1' + Applying metadata from file `%1' - + Application des métadonnées depuis le fichier `%1' + Metadata processing aborted! - + Traitement des métadonnées abandonné ! + Objects metadata file (*.omf);;All files (*.*) - + Fichiers de métadonnées d'objets (*.omf);;Tous les fichiers (*.*) - - - ModelDatabaseDiffForm - Settings - Paramètres + + Handles the objects' fade out status in the metadata file. + Gère l'estompement des objets dans le fichier de métadonnées. - Connection: - Connexion: + + Objects' fade out status + Effet d'estompement des objets - Connect and list available databases - Connecter et lister les bases de données disponibles + + Save tags to the output file when extracting metadata. When loading the file, the tags are recreated and duplicated ones are ignored. + Enregistrer les étiquettes dans le fichier de sortie lors de l'extraction des métadonnées. Lors du chargement du fichier, les balises sont recréées et les doublons ignorés. - ... - ... + + Save textboxes to the output file when extracting metadata. When loading the file, the textboxes are recreated and duplicated ones are ignored. + Enregistrer les zones de texte dans le fichier de sortie lors de l'extraction des métadonnées. Lors du chargement du fichier, les zones de texte sont recréées et les zones dupliquées ignorées. - Ignore import errors - Ignorer les erreurs + + Handles the tables' and views' extended attributes display status in the metadata file. + Gère l'état d'affichage des attributs étendus des tables et des vues dans le fichier de métadonnées. - Import system objects - Importer les objets système + + Tables' extended attributes display + Affichage étendu des attributs des tables - Import extension objects - Importer les objets des extensions + + Save generic SQL objects to the output file when extracting metadata. When loading the file, the objects are recreated and duplicated ones are ignored. + Enregistrer les objets SQL génériques dans le fichier de sortie lors de l'extraction des métadonnées. Lors du chargement du fichier, les objets sont recréés et les doublons ignorés. - File: - Fichier: + + Generic SQL objects + Objets SQL génériques - Select output file - Sélectionner un fichier de sortie + + ... + - Cancel - Annuler + + Extracts the objects' metadata from the loaded models and apply to the current focused model. A backup file can be specified to where the focused model's current metadata will be saved. + Extrait les métadonnées des objets des modèles chargés et s'applique au modèle ciblé actuel. L'emplacement du fichier de sauvegarde dans lequel les métadonnées actuelles du modèle ciblé seront enregistrées peut-être spécifié. - Progress label... - Indicateur de progression... + + &Extract and restore + &Extraction et restauration - 0 - 0 + + Extracts the objects metadata from one of the loaded models saving the info to a backup file. + Extrait les métadonnées d'objets de l'un des modèles chargés et enregistre les informations dans un fichier. - &Close - &Fermer + + Extract &only + Extracti&on seule - Waiting process to start... - En attente... + + Reads the objects' metadata from a previously saved backup file and apply to the current model. + Lit les métadonnées des objets à partir d'un fichier de sauvegarde précédemment enregistré et s'applique au modèle actuel. - Confirmation - Confirmation + + &Restore a backup file + &Restaurer une sauvegarde + + + ModelDatabaseDiffForm - SQL code (*.sql);;All files (*.*) - Code SQL (*.sql);;Tous les fichiers (*.*) + + Settings + Paramètres - Database model diff - + + + Connection: + Connexion : - Generate diff from model - + + Ignore import errors + Ignorer les erreurs d'import - Input database - + + Import system objects + Importer les objets système - Database: - + + Import extension objects + Importer les objets des extensions - Options - + + File: + Fichier : - Trucate tables before alter columns - + + Select output file + Sélectionner un fichier de sortie - For DROP command, the objects that depends on an object to be dropped will be deleted as well. For TRUNCATE command, tables that are linked to a table to be truncated will be truncate too. <strong>NOTE:</strong> this option can affect more objects than listed in the output or diff preview. - + + Cancel + Annuler - Drop or truncate in cascade mode - + + Progress label... + Indicateur de progression... + + &Close + &Fermer + + + + + Waiting process to start... + En attente du démarrage de la tâche... + + + + SQL code (*.sql);;All files (*.*) + Code SQL (*.sql);;Tous les fichiers (*.*) + + + + + + Database: + Base de données : + + + + For DROP command, the objects that depends on an object to be dropped will be deleted as well. For TRUNCATE command, tables that are linked to a table to be truncated will be truncate too. <strong>NOTE:</strong> this option can affect more objects than listed in the output or diff preview. + Pour la commande DROP, les objets qui dépendent d'un objet à supprimer seront également supprimés. Pour la commande TRUNCATE, les tables liées à une table à tronquer seront également tronquées. <strong>REMARQUE :</strong> cette option peut affecter plus d'objets que ceux listés dans l'aperçu de sortie ou de comparaison. + + + + Drop or truncate in cascade mode + Supprimer ou tronquer en mode cascade + + + Permissions already set on database objects will be kept.The ones configured on the model will be applied to the database. - + Les autorisations déjà définies sur les objets de la base de données seront conservées. Les données configurées sur le modèle seront appliquées à la base de données. + Keep object's permissions - + Conserver les permissions des objets + Database cluster level objects like roles and tablespaces will not be dropped. - + Les objets de niveau de cluster de base de données tels que les rôles et les espaces de stockage ne seront pas supprimés. + Keep cluster objects - + Conserver les objets de cluster + Recreate only unmodifiable objects - + Recréer uniquement des objets non modifiables + Force recreation of objects - + Forcer la recréation d'objets + Ignores errors generated by duplicated objects when exporting the diff to database. - + Ignore les erreurs générées par les objets dupliqués lors de l'export de la comparaison vers la base de données. + Ignore duplicity errors - + Ignorer les erreurs de duplicité + Serial columns are converted to integer and having the default value changed to <strong>nextval(sequence)</strong> function call. By default, a new sequence is created for each serial column but checking this option sequences matching the name on column's default value will be reused and will not be dropped. - + Les colonnes de séries sont converties en nombre entier et la valeur par défaut est changée en appel de fonction <strong>nextval(sequence)</strong>. Par défaut, une nouvelle séquence est créée pour chaque colonne série, mais en cochant cette option, les séquences correspondantes au nom de la valeur par défaut de la colonne seront réutilisées et ne seront pas supprimées. + Reuse sequences on serial columns - + Réutiliser des séquences sur des colonnes de séries + Diff mode - + Mode comparaison + Override the PostgreSQL version when generating the diff. The default is to use the same version as the input database. - + Outrepasser la version de PostgreSQL lors de la génération de la comparaison. Par défaut, la valeur est celle de la version de la base de données. + Use PostgreSQL: - + Utiliser PostgreSQL : + Compares the model and the input database storing the diff in a SQL file for later usage. - + Compare le modèle avec la base de données d'entrée et stock le résultat dans un fichier SQL pour une utilisation ultérieure. + + + + ... + + Compares the model and the input database generating a diff and applying it directly to the latter. <strong>WARNING:</strong> this mode causes irreversible changes on the database and in case of failure the original structure is not restored, so make sure to have a backup before proceed. - + Compare le modèle et la base de données d'entrée générant un résultat qui est appliqué directement à cette dernière. <strong>AVERTISSEMENT :</strong> ce mode entraîne des modifications irréversibles sur la base de données et, en cas d'échec, la structure d'origine n'est pas restaurée. Assurez-vous donc d'avoir une sauvegarde avant de continuer. + Output - + Sortie + Changes: - + Modifications : + Step label... - + Étiquette étape... + <html><head/><body><p>Objects marked with an <span style=" font-weight:600;">ALTER</span> may not be effectively changed unless that the differences detected are in attributes that can be modified through ALTER commands otherwise no operationwill be performed or, if the force recreation is checked, the object will be dropped and created again.</p></body></html> - + <html><head/><body><p>Les objets marqués d'un <span style="font-weight : 600;">ALTER</span> ne peuvent être modifiés efficacement que si les différences détectées sont dans les attributs qui peuvent être modifié à l'aide des commandes ALTER. Dans le cas contraire, aucune opération ne sera effectuée ou, si la recréation de force est vérifiée, l'objet sera supprimé et créé à nouveau.</p></body></html> + Objects to be created - + Objets à créer + + + + + + + 0 + + Objects to be dropped - + Objets à supprimer + Possible objects to be changed - + Objets possiblement modifiables + Ignored objects (system ones or with sql disabled) - + Objets ignorés (ceux du système ou avec code SQL désactivé) + Diff Preview - + Aperçu de la comparaison + &Apply diff - + &Appliquer la comparaison + &Generate - + &Générer - Importing database <strong>%1</strong>... - + + <strong>WARNING:</strong> The generated diff is ready to be exported! Once started this process will cause irreversible changes on the database. Do you really want to proceed? + <strong>AVERTISSEMENT :</strong> La comparaison générée est prête à être exportée ! Une fois démarré, ce processus entraînera des changements irréversibles dans la base de données. Voulez-vous vraiment poursuivre ? - Comparing the model <strong>%1</strong> and database <strong>%2</strong>... - + + Apply diff + Appliquer la comparaison - <strong>WARNING:</strong> The generated diff is ready to be exported! Once started this process will cause irreversible changes on the database. Do you really want to proceed? - + + Preview diff + Aperçu de la comparaison - Apply diff - + + model not saved yet + modèle pas encore enregistré - Preview diff - + + (none) + (aucun) - Exporting diff to database <strong>%1</strong>... - + + Step %1/%2: Importing database <strong>%3</strong>... + Étape %1/%2 : Import de la base de données <strong>%3</strong>... + + + + Step %1/%2: Comparing <strong>%3</strong> and <strong>%4</strong>... + Étape %1/%2 : Comparaison de <strong>%3</strong> et de <strong>%4</strong>... + + + + Confirmation + + + + + Step %1/%2: Exporting diff to database <strong>%3</strong>... + Étape %1/%2 : Export de la comparaison de la base de données <strong>%3</strong>... + Diff process paused. Waiting user action... - + Comparaison mise en pause. En attente d'une action utilisateur... + Saving diff to file <strong>%1</strong> - + Enregistrement de la comparaison vers le fichier <strong>%1</strong> + Diff process sucessfully ended! - + Comparaison términée avec succès ! + + No operations left. - + Aucune opération restante. + Operation cancelled by the user. - + Opération annulée par l'utilisateur. + Process aborted due to errors! - + Processus abandonné en raison d'erreurs ! + -- No differences were detected between model and database. -- - + -- Aucune différence détectée entre le modèle et la base de données. -- + Error code <strong>%1</strong> found and ignored. Proceeding with export. - Code erreur <strong>%1</strong> reçu et ignoré. Poursuite de l'export. + Code erreur <strong>%1</strong> reçu et ignoré. Poursuite de l'export. + Save diff as... - + Enregistrer la comparaison sous... + Ignores as many as possible errors on import step. This option generates an incomplete diff. - + Ignore autant d'erreurs que possible sur l'étape de l'import. Cette option génère une comparaison incomplète. + Clears the data of all tables which will have columns modified. This is useful to avoid errors related to type casting. <strong>WARNING:</strong> DO NOT use this option on production servers and always make a backup before use it. - + Efface les données de toutes les tables qui auront des colonnes modifiées. Ceci est utile pour éviter les erreurs liées à la conversion de type. <strong>AVERTISSEMENT :</strong> N'utilisez PAS cette option sur les serveurs de production et faites toujours une sauvegarde avant de l'utiliser. + Import system (built-in) objects. Use this if the import step is returning errors related to missing objects. - + Importer des objets système (intégrés). Utiliser cette option si l'étape d'import renvoie des erreurs liées à des objets manquants. + Import objects created by extensions. Use this if the import step is returning errors even importing built in ones. - + Importer des objets créés par des extensions. Utiliser cette option si l'étape d'import renvoie des erreurs, même si celles-ci sont importées. + Instead of use an ALTER command to modify certain kind of objects a DROP and CREATE will be used in order to do a full modification. This option does not affects the database object. - + Au lieu d'utiliser une commande ALTER pour modifier certains types d'objets, un DROP et un CREATE seront utilisés pour effectuer une modification complète. Cette option n'affecte pas l'objet de base de données. + No command to rename the destination database will be generated even the model's name differ from database name. - + Aucune commande permettant de renommer la base de données de destination ne sera générée même si le nom du modèle diffère du nom de la base de données. + Preserve database name - + Conserver le nom de la base de données + Avoid the generation of DROP commands for objects that exists in database but not in the model. This is useful when diff a partial model against the complete database. - + Éviter la génération de commandes DROP pour les objets qui existent dans la base de données mais pas dans le modèle. Ceci est utile lorsque un modèle partiel a été comparé à la base de données complète. + Do not drop missing objects - + Ne pas supprimer les objets manquants + Store in S&QL file - + Stocker dans un fichier S&QL + Appl&y on server - + Appliquer sur le serveur + -- SQL code purposely truncated at this point in demo version! - + + +-- Le code SQL est volontairement tronqué à ce stade dans la version démo ! + + + + Diff tool + Outil de comparaison + + + + Generate diff code + Générer un code de comparaison + + + + Source database + Base de données source + + + + Current model: + Modèle courant : + + + + (model) + (modèle) + + + + Compare to + Comparer à + + + + Diff + Comparaison + + + + Import && Export + Import && Export + + + + Import + + + + + Export + + + + + This advanced option causes pgModeler to ignore extra errors by their numeric codes. These errors must be informed in the input below and separeted by space. For the complete list of error codes check the PostgreSQL docs, section <strong> Appendix A. PostgreSQL Error Codes</strong>. <strong>WARNING:</strong> use this option with extreme care since it can interfere in final export result. + Cette option avancée oblige pgModeler à ignorer les erreurs supplémentaires par leurs codes numériques. Ces erreurs doivent être renseignées dans l'entrée ci-dessous et séparées par des espaces. Pour la liste complète des codes d'erreur, consulter les documents PostgreSQL, section <strong>Annexe A. Codes d'erreur PostgreSQL</strong>. <strong>AVERTISSEMENT :</strong> utiliser cette option avec un soin extrême, car elle peut interférer dans le résultat de l'export finale. + + + + Ignore error codes + Ignorer les codes d'erreur + + + + Froce the generation of DROP commands for columns and constraints that exist in database but not in the model. This is useful when diff a partial model against the complete database and the user needs to drop columns and constraint but preserve the rest of the objects. + Forcer la génération de commandes DROP pour les colonnes et les contraintes qui existent dans la base de données mais pas dans le modèle. Ceci est utile lorsqu'un modèle partiel est comparé à la base de données complète et que l'utilisateur doit supprimer les colonnes ainsi que les contraintes mais conserver les autres objets. + + + + Drop missing columns and constraints + Supprimer colonnes/contraintes manquantes + + + + Truncate tables before alter columns + Tronquer les tables avant de modifier les colonnes ModelExportForm - Model Export - Export du modèle - - + + File: - Fichier: + Fichier : + + Select target file Sélectionner le fichier cible + + ... ... + Zoom: - Zoom: + Zoom : + + Export model - Exportation d'un modèle + Export d'un modèle + Settings Paramètres + Database server Serveur de base de données + pgModeler ignores errors generated by duplicated objects and creates only that ones which does not exists in the database. This option may be used when an object was created after a previous model export. pgModeler ignorera les erreurs générées en raison d'objets dupliqués et ne créera uniquement ceux qui n'existent pas déjà en base. Cette option peut être utile lorsqu'un objet est créé après un précédent export. + PostgreSQL version in which the SQL code should be generated. It is recommended to select this option only when the version of the DBMS, somehow, is not identifiable or if you need to generate a specific version of SQL code for test purposes. Version de PostgreSQL pour laquelle le code SQL sera généré. Il est recommandé d'activer cette option uniquement si la version du SGBD n'est pas identifiable ou pour une raison spécifique par exemple pour des essais. + If <strong>DB</strong> is checked pgModeler will destroy the database if already exists on the server. When <strong>Objects</strong> is checked pgModeler will execute the DROP command attached to SQL-enabled objects. <strong>WARNING:</strong> this option leads to data loss so make sure to have a backup first. - Si <strong>BDD</strong> est coché pgModeler procèdera à la suppression complète de la base de données si elle existe déjà. Lorsque <strong>Objets</strong> est coché pgModeler effectuera la commande DROP rattachée à l'objet (si la génération du code SQL pour cet objet n'a pas été désactivée dans ses propriétés) <strong>AVERTISSEMENT:</strong> cette option engendre la perte de données, pensez à faire une sauvegarde avant. + Si <strong>BDD</strong> est coché, pgModeler procédera à la suppression complète de la base de données si elle existe déjà. Lorsque <strong>Objets</strong> est coché pgModeler effectuera la commande DROP rattachée à l'objet (si la génération du code SQL pour cet objet n'a pas été désactivée dans ses propriétés). <strong>AVERTISSEMENT :</strong> cette option engendre la perte de données, pensez à faire une sauvegarde avant. + Drop: - Ordre SQL intuitif - Drop: + Suppr. : + DB BDD - Objects - Objets - - - PNG Image - Image PNG - - + Show delimiters Afficher les délimiteurs de page + Exporting the model page by page will generate files with a <strong>_p[n]</strong> suffix where <strong>n</strong> is the page id. Check if the current user has write permission on output folder. - Exporter le modèle page par page génèrera des fichiers avec un suffixe de type <strong>_p[n]</strong> où <strong>n</strong> est le numéro de la page. Vérifiez que vous avez bien le droit d'écriture dans le dossier de sortie. + Exporter le modèle page par page générera des fichiers avec un suffixe de type <strong>_p[n]</strong> où <strong>n</strong> est le numéro de la page. Vérifiez que vous avez bien le droit d'écriture dans le dossier de sortie. + Page by page Une image par page + + PostgreSQL: - PostgreSQL: + PostgreSQL : + PostgreSQL version in which the SQL code should be generated Version de PostgreSQL pour laquelle le code SQL doit être généré + Cancel Annuler + pgModeler will destroy the database if already exists on the server. Make sure to have a backup before use this option because all data will be lost. pgModeler détruira la base de données si elle existe déjà sur le serveur. Assurez-vous d'avoir une sauvegarde si besoin avant car les données seront définitivement perdues. - Image: - Image: - - + Show grid Afficher la grille + Connection: - Connexion: + Connexion : + Ignore object duplicity Ignorer les objets dupliqués + SQL file Fichier texte SQL + + I&mage (PNG) + + + + Output Progression + Progress label... Indicateur de progression... + &Export &Exporter + &Close &Fermer + Initializing model export... - Initialisation de l'exportation du modèle... + Initialisation de l'export du modèle... + Saving file '%1' Enregistrement du fichier '%1' + + Exporting process aborted! - Processus d'exportation terminé en erreur! + Export abandonnée ! + Exporting process canceled by user! - Processus d'exportation annulé par l'utilisateur! + Export annulée par l'utilisateur ! + Exporting process sucessfuly ended! - Processus d'exportation terminé avec succès! + Export terminée avec succès ! + Export model as... Exporter le modèle sous... + Error code <strong>%1</strong> found and ignored. Proceeding with export. Code erreur <strong>%1</strong> reçu et ignoré. Poursuite de l'export. - SQL code (*.sql);;All files (*.*) - Fichiers SQL (*.sql);;Tous les fichiers (*.*) - - - PNG image (*.png);;All files (*.*) - Image PNG (*.png);;Tous les fichiers (*.*) - - + Ob&jects - + Ob&jets + Graphics file - - - - Image (PNG) - + Fichier graphique + Type: - Type: - - - Vectorial (SVG) - + Type : + SQL script (*.sql);;All files (*.*) - + Script SQL (*.sql);;Tous les fichiers (*.*) + Portable Network Graphics (*.png);;All files (*.*) - + Portable Network Graphics (*.png);;Tous les fichiers (*.*) + Scalable Vector Graphics (*.svg);;All files (*.*) - + Scalable Vector Graphics (*.svg);;Tous les fichiers (*.*) + + + + This advanced option causes pgModeler to ignore extra errors by their numeric codes. These errors must be informed in the input below and separeted by space. For the complete list of error codes check the PostgreSQL docs, section <strong> Appendix A. PostgreSQL Error Codes</strong>. <strong>WARNING:</strong> use this option with extreme care since it can interfere in final export result. + Cette option avancée oblige pgModeler à ignorer les erreurs supplémentaires par leurs codes numériques. Ces erreurs doivent être renseignées dans l'entrée ci-dessous et séparées par des espaces. Pour la liste complète des codes d'erreur, consulter les documents PostgreSQL, section <strong>Annexe A. Codes d'erreur PostgreSQL</strong>. <strong>AVERTISSEMENT :</strong> utiliser cette option avec un soin extrême, car elle peut interférer dans le résultat de l'export finale. + + + + Ignore error codes + Ignorer les codes d'erreur + + + + &Vectorial (SVG) + &Vectoriel (SVG) ModelExportHelper + Generating SQL code for PostgreSQL `%1' - + Génération du code SQL pour PostgreSQL `%1' + Output SQL file `%1' successfully written. - + Fichier SQL de sortie `%1' écrit avec succès. + Rendering objects to page %1/%2. - + Rendu des objets de la page %1/%2. + Output image `%1' successfully written. - + Fichier image de sortie `%1' écrit avec succès. + Starting export to DBMS. - + Lancement de l'export vers le SGBD. + PostgreSQL version detection overridden. Using version `%1'. - + Détection de version dépassée de PostgreSQL. Utilisation de la version `%1'. + PostgreSQL `%1' server detected. - + Serveur PostgreSQL `%1' détecté. + Generating temporary names for database, roles and tablespaces. - + Génération de noms, de rôles et d'espace de stockage temporaires pour la base de données. + Enabling the SQL code for database `%1' to avoid errors. - + Activation du code SQL de la base de données `%1' pour éviter les erreurs. + Ignoring object duplication errors. - + Omission des erreurs de duplication d'objet. + Ignoring the following error code(s): `%1'. - + Omission des codes erreur suivants : `%1'. + Trying to drop database `%1'. - + Tentative de suppression de la base de données `%1'. + Simulation mode activated. - + Mode simulation activé. + Generating SQL for `%1' objects... - + Génération de code SQL pour `%1' objets... + Destroying objects created on the server. - + Destruction des objets créés sur le server. + Restoring original names of database, roles and tablespaces. - + Restauration des noms, des rôles et des espaces de stockage originaux de la base de données. + + + Creating object `%1' (%2) - + Création de l'objet `%1' (%2) + + Dropping object `%1' (%2) - + Suppression de l'objet `%1' (%2) + Changing object `%1' (%2) - + Modification de l'objet `%1' (%2) + Running auxiliary command. - + Exécution de la commande auxiliaire. + Exporting model to SVG file. - + Export du modèle vers un fichier SVG. + SVG representation of database model - + Représentation SVG d'un modèle de base de données + SVG file generated by pgModeler - + Fichier SVG généré par pgModeler + Output file `%1' successfully written. - + Fichier de sortie `%1' écrit avec succès. + Creating database `%1' - + Création de la base de données `%1' + Connecting to database `%1' - + Connexion à la base de données `%1' + Renaming `%1' (%2) to `%3' - + Renommage de `%1' (%2) en `%3' ModelFixForm + Model file fix Réparer un fichier modèle + &Fix &Réparer + &Close &Fermer + Fix model file Réparer un modèle + <html><head/><body><p>[pgmodeler-cli not found error]</p></body></html> <html><head/><body><p>[pgmodeler-cli not found error]</p></body></html> + pgmodeler-cli: - pgmodeler-cli: + pgmodeler-cli : + Browse for pgmodeler-cli tool Rechercher l'outil pgmodeler-cli + + + ... ... + The specified file is not the pgModeler command line tool (pgmodeler-cli). Ce fichier n'est pas l'outil en ligne de commande de pgModeler (pgmodeler-cli). + Input file: - Fichier source: + Fichier source : + Output file: - Fichier cible: + Fichier cible : + Fix tries: - Tentatives: - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'Monospace'; font-size:9pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Waiting process to start...</p></body></html> - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'Monospace'; font-size:9pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">En attente...</p></body></html> + Tentatives : + Select input file Sélectionner le modèle à réparer + Select output file Sélectionner un fichier de sortie + Load fixed model when finish Charger le modèle réparé une fois l'opération terminée + In some cases the fix process will fail to restore all objects within the model demanding manual fixes by changing the file on a text editor. <strong>NOTE:</strong> relationships may lost their graphical configuration like custom points and line color. - Dans certains cas, le processus de réparation peut échouer à restaurer et récupérer tous les objets du modèle, ce qui peut réclamer des modifications manuelles dans le fichier à partir d'un éditeur de texte. <strong>REMARQUE:</strong> les associations peuvent perdre leur configuration graphique tels que des points placés manuellement par l'utilisateur ou la couleur. + Dans certains cas, le processus de réparation peut échouer à restaurer et récupérer tous les objets du modèle, ce qui peut réclamer des modifications manuelles dans le fichier à partir d'un éditeur de texte. <strong>REMARQUE :</strong> les associations peuvent perdre leur configuration graphique tels que des points placés manuellement par l'utilisateur ou la couleur. + Waiting process to start... - En attente... + Processus en attente de lancement... + Could not locate <strong>%1</strong> tool on <strong>%2</strong>. The fix process can't continue! Please check pgModeler installation or try to manually specify the command below. - Impossible de localiser l'outil <strong>%1</strong> dans <strong>%2</strong>. Impossible de continuer ! Veuillez vérifier votre installation de pgModeler ou alors spécifiez l'emplacement de l'outil. + Impossible de localiser l'outil <strong>%1</strong> sur <strong>%2</strong>. Le processus de réparation ne peut continuer ! Vérifiez votre installation de pgModeler ou spécifiez manuellement la commande ci-dessous. + pgModeler command line tool (%1) Outil en ligne de commande de pgModeler (%1) + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Monospace'; font-size:10pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:9pt;">Waiting process to start...</span></p></body></html> - + < !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http ://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Monospace'; font-size:10pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:9pt;">En attente du lancement du processus...</span></p></body></html> ModelNavigationWidget + Form Formulaire + Previous model Modèle précédent - Ctrl+Up - Ctrl+Haut + + Alt+C + + Next model Modèle suivant - Ctrl+Down - Ctrl+Bas - - + Close model Fermer + ... ... + (model not saved yet) - (modèle pas encore sauvegardé) + (modèle pas encore enregistré) + Ctrl+Left - Ctrl+Left + Ctrl+Gauche + Ctrl+Right - Ctrl+Right - - - Alt+C - + Ctrl+Droite ModelObjectsWidget + Model Objects Objets du modèle + Hide this widget Cacher ce widget + 1 1 + Object Objet + Type Type + Parent Object Objet parent + Parent Type Type parent - Visible Object Types - Afficher les objets des types suivants - - + Select All - Tout sélect. + Tout sélectionner + Clear All Tout effacer + Select Sélectionner + Return - Retour + Retour + Cancel Annuler + Esc - Échap. + Échap + Objects view configuration Filtres d'affichage des objets + Expands all items Développer tous les éléments + Collapses all items Replier tous les éléments + Filter: - Filtrer: + Filtrer : + + + + + + ... ... + Tree view Vue en arbre + List view Vue en liste + New Nouveau + ID - ID + Identifiant + By ID - + Par identifiant + + + + Visible object types + Types d'objets visibles + + + + Model objects + Objets de modèle ModelOverviewWidget + Model overview Vue générale du modèle + + + Failed to generate the overview image. +The requested size %1 x %2 was too big and there was not enough memory to allocate! + Impossible de générer l'aperçu de l'image. +La taille demandée%1 x%2 était trop grande et il n'y avait pas assez de mémoire à allouer ! + ModelRestorationForm + Model restoration Restauration de modèle + &Restore &Restaurer + &Cancel A&nnuler - Modified: %1 - Modifié: %1 - - + pgModeler was not closed properly in a previous execution and some models were still being edited. Click <strong>Restore</strong> to reopen the models or <strong>Cancel</strong> to abort the restoration. - + pgModeler n'a pas été fermé correctement lors d'une précédente exécution et certains modèles étaient encore en cours d'édition. Cliquez sur <strong>Restaurer</strong> pour rouvrir les modèles ou sur <strong>Annuler</strong> pour abandonner la restauration. + pgModeler will try to recover the selected models but will not destroy them in case of loading failure. This option serves as a last resort in order to try to recover the database model. Temporary models will last until the application is closed so the user must try to manually recover the files before exit pgModeler. - + pgModeler va essayer de récupérer les modèles sélectionnés mais ne les détruira pas en cas d'échec de chargement. Cette option sert de dernier recours pour essayer de récupérer le modèle de base de données. Les modèles temporaires resteront jusqu'à ce que l'application soit fermée. L'utilisateur doit donc essayer de récupérer manuellement les fichiers avant de quitter pgModeler. + Keep temporary models in case of restoration failure - + Conserver les modèles temporaires en cas d'échec de la restauration + Database - Base de données + Base de données + File - + Fichier + Modified - + Modifié + Size - + Taille ModelValidationHelper + There are pending errors! SQL validation will not be executed. - + Il y a des erreurs en attente ! La validation SQL ne sera pas exécutée. + Operation canceled by the user. - + Opération annulée par l'utilisateur. ModelValidationWidget + Form Formulaire + + 0 0 + Try to apply a fix on the selected validation info. Essayer d'appliquer le correctif sur l’élément sélectionné. + Clear validation results Effacer le résultat de la validation + Va&lidate Va&lider + Warnings: does not prevents model to be saved. - Avertissements: n'empêche de pouvoir sauvegarder le modèle. + Avertissements : n'empêche de pouvoir sauvegarder le modèle. + Errors: model will not be saved while there are validation errors. - Erreurs: le modèle ne peut être sauvegardé tant que des erreurs de validation subsistent. - - - Use unique temporary names for database, role and tablespace objects - Utiliser des noms uniques et temporaires pour la base, les rôles et les tablespaces + Erreurs : le modèle ne peut être sauvegardé tant que des erreurs de validation subsistent. + SQL Validation: - Validation SQL: - - - Connection alias - Alias de la connexion + Validation SQL : + PostgreSQL version Version de PostgreSQL - SQL validation, if enabled, will occur only on the last step or when there are no warnings. - Validation SQL, si activée, ne sera déclenchée qu'à la fin ou uniquement s'il n'y a pas d'avertissements. - - - Using temporary names will avoid object duplication errors when running the SQL validation. - Utiliser des noms temporaires évite les erreurs dues aux objets dupliqués lors de la validation SQL. - - + Try to resolve the reported issues. Essayer de résoudre les problèmes rencontrés. + Ctrl+S Ctrl+S + Clear Effacer + Options Options + Cancel the SQL validation in progress. Annuler le processus de validation SQL en cours. + Cancel Annuler + Esc Échap - Change the creation order for two objects by swapping their ids - Modifie l'ordre de création de deux objets en échangeant leurs numéros d'identification - - - Swap Ids - Echanger identifiants + + Apply fixes + - Enable validation of SQL code on DBMS (requires connection) - Activer la validation SQL sur le serveur (requiert une connexion) + + Change the creation order for two objects by swapping their ids + Modifie l'ordre de création de deux objets en échangeant leurs numéros d'identification - Apply Fix - Appliquer le correctif + + Swap ids + Échanger identifiants + Hide this widget Fermer ce widget + ... ... + The object <strong>%1</strong> <em>(%2)</em> [id: %3] is being referenced by <strong>%4</strong> object(s) before its creation. L'objet <strong>%1</strong> <em>(%2)</em> [id: %3] est référencé par <strong>%4</strong> objet(s) avant sa création. + Autodetect Auto détection + The object <strong>%1</strong> <em>(%2)</em> [id: %3]%4 is referencing columns created by <strong>%5</strong> relationship(s) but is created before them. - L'objet <strong>%1</strong> <em>(%2)</em> [id: %3]%4 a pour référence des colonnes créées par <strong>%5</strong> association(s) but is created before them. + L'objet <strong>%1</strong> <em>(%2)</em> [id : %3]%4 référence des colonnes créées par <strong>%5</strong> association(s) mais a été créé avant eux. + The object <strong>%1</strong> <em>(%2)</em> has a name that conflicts with <strong>%3</strong> object's name(s). - Le nom de l'objet <strong>%1</strong> <em>(%2)</em> entre en conflit avec l'objet<strong>%3</strong>. - - - Database model sucessfully validated. - Modèle de données validé avec succès. - - - Running SQL validation... - Validation SQL en cours... + Le nom de l'objet <strong>%1</strong> <em>(%2)</em> entre en conflit avec celui de l'objet<strong>%3</strong>. + Processing object: %1 - Traitement de l'objet: %1 + Traitement de l'objet : %1 + Conflicting object: <strong>%1</strong> <em>(%2)</em>. - Objet en conflit: <strong>%1</strong> <em>(%2)</em>. + Objet en conflit : <strong>%1</strong> <em>(%2)</em>. + Referrer object: <strong>%1</strong> <em>(%2)</em> [id: %3]. - Seconde lecture ? - Objet réferent: <strong>%1</strong> <em>(%2)</em> [id: %3]. + Objet réferent : <strong>%1</strong> <em>(%2)</em> [id: %3]. + SQL validation failed due to error(s) below. <strong>NOTE:</strong><em> These errors does not invalidates the model but may affect operations like <strong>export</strong> and <strong>diff</strong>.</em> - + La validation SQL a échoué en raison des erreurs ci-dessous. <strong>REMARQUE :</strong><em> Ces erreurs n'invalident pas le modèle mais peuvent affecter des opérations telles que <strong>l'export</strong> et <strong>la comparaison</strong>. </em> - <em>The above object was created by a relationship. Change the name pattern on it's generator relationship. Fix will not be applied!</em> + + The column <strong>%1</strong> on <strong>%2</strong> <em>(%3)</em> is referencing the geospatial data type <strong>%4</strong> but the <strong>postgis</strong> extension is not present in the model! - Relationship: <strong>%1</strong> [id: %2]. + + <strong>HINT:</strong> Create the extension in the model or let it be created by applying the needed fixes. + + <em>The above object was created by a relationship. Change the name pattern on it's generator relationship. Fix will not be applied!</em> + <em>L'objet ci-dessus a été créé par une relation. Changer le motif du nom sur sa relation de générateur. La correction ne sera pas appliquée !</Em> + + + + Relationship: <strong>%1</strong> [id: %2]. + Relation : <strong>%1</strong> [id : %2]. + + + Running SQL commands on server... - Execution des commandes SQL sur le serveur... + Exécution des commandes SQL sur le serveur... + Enables the validation of SQL code in DBMS. This process requires the use of a pre-configured connection. SQL validation will occur only in the last step (when all objects were validated) or when there are no warnings. - + Active la validation du code SQL dans la SGBD. Ce processus nécessite l'utilisation d'une connexion pré-configurée. La validation SQL ne se produira qu'à la dernière étape (lorsque tous les objets ont été validés) ou lorsqu'il n'y a pas d'avertissement. + Connection to be used in the SQL validation - + Connexion à utiliser dans la validation SQL + pgModeler will generate unique and temporary names for database, role and tablespace objects. This option avoids object duplication errors when running the SQL validation. - + pgModeler générera des noms uniques et temporaires pour les objets base de données, rôle et espace de stockage. Cette option évite les erreurs de duplication d'objet lors de l'exécution de la validation SQL. + Use unique temporary names for cluster level objects - + Utiliser des noms temporaires uniques pour les objets de niveau cluster + The relationship <strong>%1</strong> [id: %2] is in a permanent invalidation state and needs to be relocated. - + La relation <strong>%1</strong> [id : %2] est dans un état d'invalidation permanent et a besoin d'être déplacé. + <strong>HINT:</strong> try to swap the relationship by another ones that somehow are linked to it through generated columns or constraints to solve this issue. Note that other objects may be lost in the swap process. - + <strong>CONSEIL :</strong> essayer d'échanger la relation par une autre qui est liée à celle-ci via des colonnes générées ou des contraintes pour résoudre ce problème. Noter que d'autres objets peuvent être perdus dans le processus d'échange. + SQL validation not executed! No connection defined. - + La validation SQL n'est pas exécutée ! Aucune connexion définie. + Database model successfully validated. - + Modèle de base de données validé avec succès. ModelWidget + + Copy Copier - Generalization - Généralisation - - + Convert Convertir + New Nouveau + Quick - Act. rapides + Actions rapides + Source code Code source + Show object source code Afficher le code source de l'objet - Source - Source - - + + Properties Propriétés + Space Espace + Edit the object properties - Editer les propriétés de l'objet + Modifier les propriétés de l'objet + + Protect Vérrouiller + + Unprotect Déverrouiller + Protects object(s) from modifications - Empêcher l(es)'objet(s) d'être modifiés + Empêcher la modification du ou des objets + + Delete - Supprimer + Effacer + Shift+Del Shift+Suppr + Select all - Tout sélect. + Tout sélectionner + Selects all the graphical objects in the model Sélectionner tous les objets graphiques du modèle + Paste Coller + Cut Couper + Deps && Referrers - Dép. && Rèf. + Dépendances && Rèférences + Add a new object in the model Ajouter un nouvel objet dans le modèle + Rename Renommer + Quick rename the object Renommage rapide de l'objet + Move to schema Déplacer vers le schema + Edit permissions - Editer les permissions + Modifier les permissions + Change owner Changer le propriétaire + Select children - Sélectionnez les éléments - - - Highlight - Mettre en avant + Sélectionner les enfants + Del Suppr - Ctrl+A - Ctrl+A - - - F2 - F2 - - + Custom SQL - Code SQL Libre - - - Alt+Q - Alt+Q + Code SQL personnalisé + Loading database model Ouverture du modèle de base de données + Saving database model Enregistrement du modèle de base de données + Also copy all dependencies of selected objects? This minimizes the breakdown of references when copied objects are pasted into another model. - Copier également les dépendences des objets sélectionnés? Ceci minimise la perte des références lorsque les objets copiés sont collés dans un autre modèle. + Copier également les dépendences des objets sélectionnés ? Cela minimise la casse des références lorsque les objets copiés sont collés dans un autre modèle. + Pasting objects... Collage des objets... + Not all objects were pasted to the model due to errors returned during the process! Refer to error stack for more details! - Tous les objets n'ont pas été collés dans le modèle à cause d'erreurs retournés durant le processus! Se référer à la pile d'erreurs pour plus de détails! + Tous les objets n'ont pas été collés dans le modèle car des erreurs ont été retournées durant le processus ! Se référer à la pile d'erreurs pour plus de détails ! + Do you really want to delete the selected object? - Souhaitez vous réellement supprimer l'objet sélectionné? + Souhaitez-vous réellement effacer l'objet sélectionné ? + (no objects) (aucun objet) + + None + + + + Constraints Contraintes + One to One (1-1) - + Un à un (1-1) + One to Many (1-n) - + Un à plusieurs (1-n) + Many to Many (n-n) - + Plusieurs à plusieurs (n-n) + <strong>ATTENTION:</strong> The database model is protected! Operations that could modify it are disabled! - + <strong>ATTENTION :</strong> Le modèle de base de données est protégé ! Les opérations qui pourraient le modifier sont désactivées ! + + + + Edit data + Modifier données + + + + Source + + Alt+S - + + + Del. cascade Supprimer en cascade + Ctrl+C - Ctrl+C + + Ctrl+V - Ctrl+V + + Ctrl+X - Ctrl+X + + Quick action for the selected object - Actions rapides sur l'objet sélectionné + Action rapide pour l'objet sélectionné + + + + F2 + + Set tag - Affecter un tag + Affecter une balise + Ctrl+E - Ctrl+E + + + + + Select tagged + Séléction balisée + + + + Select + Sélectionner + Open relationship - + Ouvrir les relations + + Alt+Q + + + + Convert to sequence - + Convertir en séquence + Convert to serial - + Convertir en série + Break line - + Ligne d'interruption + Remove points - + Supprimer des points + Enable SQL - + Activer le code SQL + Disable SQL - + Désactiver le code SQL + + + + Duplicate + Dupliquer + + + + Ctrl+D + + + + + Extended attributes + Attributs étendus + + + + + Show + Afficher + + + + + Hide + Masquer + + + + Jump to table + Sauter à la table + + + + Schemas rectangles + Rectangles de schémas + + + + Fade in/out + Effets de fondu + + + Fade in + Accentuer + + + + + Fade out + Estomper + + + + + + Relationships + Associations + + + + Swap ids + Échanger identifiants + + + + Edit the objects creation order by swapping their ids + Modifier l'ordre de création des objets en échangeant leurs identifiants + + + 90° (vertical) - + + 90° (horizontal) - + + 90° + 90° (vertical) - + + 90° + 90° (horizontal) - + + + + + + + All objects + Tous les objets + + + + + Schemas + Schémas + + + Views + Vues + + + + + Textboxes + Boites de textes + + + + + Tables + + + + + Ctrl+A + + + + Zoom: %1% - + Zoom : %1% + Do you really want to convert the relationship into an intermediate table? - + Voulez-vous vraiment convertir les relations en une table intermédiaire ? + Validating object: `%1' (%2) - + Validation de l'objet : `%1' (%2) + Generating XML for: `%1' (%2) - + Génération du code XML pour : `%1' (%2) + Pasting object: `%1' (%2) - + Collage de l'objet : `%1' (%2) + <strong>CAUTION:</strong> You are about to delete objects in cascade mode which means more objects than the selected will be dropped too. Do you really want to proceed? - + <strong>ATTENTION :</strong> Vous êtes sur le point de supprimer des objets en mode cascade, ce qui signifie que des objets non sélectionnés seront également supprimés. Voulez-vous vraiment poursuivre ? + <strong>CAUTION:</strong> Remove multiple objects at once can cause irreversible invalidations to other objects in the model causing such invalid objects to be deleted too. Do you really want to proceed? - + <strong>ATTENTION :</strong> Supprimer plusieurs objets à la fois peut entraîner des invalidations irréversibles sur d'autres objets du modèle, entraînant également la suppression de ces objets invalides. Voulez-vous vraiment poursuivre ? + <strong>CAUTION:</strong> Remove a relationship can cause irreversible invalidations to other objects in the model causing such invalid objects to be deleted too. Do you really want to proceed? - + <strong>ATTENTION :</strong> Supprimer une relation peut entraîner des invalidations irréversibles d'autres objets dans le modèle, entraînant également la suppression de ces objets invalides. Voulez-vous vraiment poursuivre ? + The cascade deletion found some problems when running! Some objects could not be deleted or registered in the operation's history! Please, refer to error stack for more details. - + La suppression en cascade a rencontré des problèmes lors de son exécution ! Certains objets n'ont pas pu être supprimés ou enregistrés dans l'historique des opérations ! Veuillez vous reporter à la pile d'erreurs pour plus de détails. + Inheritance - + Héritage + Do you want to %1 the selected schema's children too? - + Voulez-vous %1 les enfants du schèma séléctionné aussi ? + protect - + protéger + unprotect - + déprotéger ModelsDiffHelper + Processing object `%1' (%2)... - + Traitement de l'objet `%1' (%2)... + Skipping object `%1' (%2)... - + Omission de l'objet `%1' (%2)... + Processing diff infos... - + Comparaison des informations... + Processing `%1' info for object `%2' (%3)... - + Traitement de l'info `%1' pour l'objet `%2' (%3)... + No differences between the model and database. - + Aucune différence entre le modèle et la base de données. + Preparing diff code... - + Préparation du code de comparaison... NewObjectOverlayWidget + Form - Formulaire + Formulaire + Role Rôle + Tag Tag + Cast - Convertion de type + Conversion de type + Language Langage + Textbox Zone de texte + Event Trigger - Déclencheur sur évènement + Déclencheur sur évènement + Tablespace - Tablespace + Espace de stockage + Schema Schéma + Domain - Domaine + Domaine + Conversion - Convertion + Conversion - Aggregate - Fonction d'agrégat + + Extension + - Collation - Collation + + Type + - Table - Table + + Aggregate + Agrégat - Type - Type + + Collation + + Sequence - Séquence + Séquence - Extension - Extension + + Table + + Function - Fonction + Fonction + View Vue + + Permissions - Permissions + - Rule - Règle + + Index + - Index - Index + + Rule + Règle + Column - Colonne + Colonne + Constraint - Contrainte + Contrainte + Trigger - Déclencheur + Déclencheur + Copy - Copie + Copie - M - M + + + A + - 9 - 9 + + G + - Z - Z + + K + - 1 - 1 + + H + - 2 - 2 + + J + - 3 - 3 + + D + - 5 - 5 + + E + - 4 - 4 + + F + - 0 - 0 + + L + - A - + + O + - Op. Family - + + U + - Op. Class - + + I + - Operator - + + R + - Many-to-many - + + S + - One-to-many - + + Q + - One-to-one - + + T + - Inheritance - + + P + - G - + + M + - K - + + Y + - H - + + W + - J - + + + 9 + - D - + + Z + - E - + + X + - F - + + C + - L - + + V + - O - + + B + + + + + 8 + + + + + 1 + + + + + 2 + + + + + 3 + + + + + 5 + + + + + 4 + + + + + 0 + + + + + Op. Family + Famille d'op. - U - + + Op. Class + Classe d'op. - I - + + Operator + Opérateur - R - + + Many-to-many + Plusieurs-à-plusieurs - S - + + One-to-many + Un-à-plusieurs - Q - + + One-to-one + Un-à-un - T - + + Inheritance + Héritage - P - + + Generic SQL + SQL générique - Y - + + Policy + Politique + + + NumberedTextEditor - W - + + Load + Charger - X - + + Load the object's source code from an external file + Charger le code source de l'objet depuis un fichier externe - C - + + Edit + Modifier - V - + + Edit the source code in the preferred external editor + Modifier le code source avec son éditeur préféré - B - + + Clear + Nettoyer - - - NumberedTextEditor + Upper case - + Majuscule + Lower case - + Minuscule + Ident right - + Ident droit + Ident left - + Ident gauche + + + + SQL file (*.sql);;All files (*.*) + Fichier SQL (*.sql);;Tous les fichiers (*.*) + + + + Load file + Charger un fichier + + + + The source editor `%1' is running on `pid: %2'. + L'éditeur de source `%1' s'exécute sur pid : `%2'. + + + + Could not start the source code editor application `%1'! Make to sure that the source editor path defined in the general settings points to a valid executable and the current user has permission to run the application. Error message returned: `%2' + Impossible de démarrer l'application de l'éditeur de code source `%1' ! Assurez-vous que le chemin de l'éditeur source défini dans les paramètres généraux pointe vers un exécutable valide et que l'utilisateur actuel a l'autorisation d'exécuter l'application. Message d'erreur renvoyé : `%2' ObjectDepsRefsWidget - Form - Formulaire - - + Dependencies Dépendances + + Object Objet + + Type Type + + Parent Object Objet parent + + Parent Type Type parent + References Références + + ID - Intuitif ID + Exclude indirect dependencies Exclure les dépendances indirectes + Include indirect references Inclure les références indirectes + This object does not exists anymore. The dependencies and references listing are disabled. Cet objet n'existe plus. L'affichage de ses dépendances et références est désactivé. + Object's dependencies & references Dépendances et références d'un objet @@ -7769,117 +9733,169 @@ p, li { white-space: pre-wrap; } ObjectFinderWidget + Form Formulaire + Pattern: - Motif: + Motif : + Hide this widget Cacher ce widget + + ... ... - Highlight - Mettre en avant - - + Find Chercher + Clears the search results - Éffacer les résultats + Effacer les résultats + Clear Effacer + + (Un)selects the graphical objects in the results grid + + + + Regular Expression Expression régulières + Exact Match Correspondance exacte + Select All - Tout sélect. + Tout sélectionner + Clear All Tout effacer + Case Sensitive Sensible à la casse + Object Objet + Type Type + Parent Object Objet parent + Parent Type Type parent + + Fades outs all the graphical objects in the results grid (or those not listed). The current fade in/out state of all objects is modified. + + + + Defines the search filter Défini le filtre de recherche + Filter Filtrer + + + Listed + + + + + + Not listed + + + + Found <strong>%1</strong> object(s). <strong>%1</strong> objet(s) trouvé(s). + No objects found. Aucun objet trouvé. - Highlight graphical objects when selecting them or their children on the result list - + + ID + Identifiant - ID - ID + + Select + Sélectionner + + + + Fade out + Estomper ObjectRenameWidget + Form Formulaire + .... .... + to: - en: + en : + + Rename Renommer + Cancel Annuler @@ -7887,279 +9903,338 @@ p, li { white-space: pre-wrap; } ObjectSelectorWidget + Form Formulaire + Clear field - Effeacer le champs + Effacer le champ + Select Object Sélectionner un objet + Select %1 - + Sélectionner %1 - ObjectTableWidget + ObjectsTableWidget + Form Formulaire + Add Item Ajouter un élément + Ins - Ins + Insérer + Remove Item Supprimer un élément + Del - Suppr. + Suppr + Update Item - Actualiser les éléments + Actualiser l'élément + Alt+R - Alt+R + + Remove All Tout supprimer + Shift+Del - Shift+Del + Maj+Suppr. + + Duplicate item + Dupliquer l'élément + + + + Ctrl+D + + + + Edit Item - Editer l'élément + Modifier l'élément + Space - Space + Espace + Move Up Déplacer vers le haut + Ctrl+Up Ctrl+Haut + Move Down Déplacer vers le bas + Ctrl+Down Ctrl+Bas + Move to start Déplacer au début + Ctrl+Home Ctrl+début + Move to end Déplacer à la fin + Ctrl+End, Ctrl+S Ctrl+Fin, Ctrl+S - Confirmação - Confirmation - - + Do you really want to remove the selected item? - Souhaitez vous réellement supprimer l'élément sélectionné? + Souhaitez-vous réellement supprimer l'élément sélectionné ? - Do you really want to remove the all items? - Souhaitez vous réellement supprimer tous les éléments? + + + Confirmation + - Confirmation - Confirmation + + Do you really want to remove all the items? + Souhaitez-vous réellement supprimer tous les éléments ? OperationList + (invalid object) - + (objet invalide) OperationListWidget + + Executed Operations Opérations exécutées + Hide this widget Cacher ce widget + ... ... + 1 1 + Operations: - Opérations: + Opérations : + + 0 0 + Position: - Position: + Position : + Delete operation history Supprimer l'historique des opérations + Undo Annuler + Redo Rétablir + Object: %1 - Objet: %1 + Objet : %1 + Name: %1 - Nom: %1 + Nom : %1 + created créé + removed supprimé + modified modifié + moved déplacé + Operation: %1 - Opération: %1 - - - Undoing operations... - Annulation des opérations... - - - Redoing operations... - Rétablissement des opérations... + Opération : %1 + Operation history exclusion - ?? À controler dans le contexte ?? Exclure l'historique des opérations + Delete the executed operations history is an irreversible action, do you want to continue? - Supprimer l'historique des opérations exécutées est une action irréversible, souhaitez vous continuer? + Effacer l'historique des opérations exécutées est une action irréversible, souhaitez-vous continuer ? OperatorClassWidget - Form - Formulaire - - + Default Class: - Classe par défaut: + Classe par défaut : + Indexing: - Indexation: + Indexation : + Elements - Élements + Éléments + Element Type: - Type d'élement: + Type d'élément : + Operator - Operateur + Opérateur + Function Fonction + Storage Stockage + Function: - Fonction: + Fonction : + Operator: - Opérateur: + Opérateur : + Support/Strategy: - Support/Stratégie: + Support/Stratégie : + + Op. Family: - Famille d'opérateurs: + Famille d'opérateurs : + Storage Type Type de Stockage + Object Objet + Type - Type + + Support/Strategy Support/Stratégie + Operator Family Famille d'opérateurs @@ -8167,96 +10242,103 @@ p, li { white-space: pre-wrap; } OperatorFamilyWidget - Form - Formulaire - - + Indexing: - Indexation: + Indexation : OperatorWidget - Form - Formulaire - - + Options: - Options: + Options : + MERGES MERGES + HASHES HASHES + Arguments Arguments + Advanced Avancé + Restrict: - Restriction: + Restriction : + Commutator: - Commutateur: + Commutateur : + Negator: - Négateur: + Négateur : + Operator Func.: - Fonction de l'opérateur: + Fonction de l'opérateur : + Join: - Jointure: + Jointure : + Right Argument Type - Type argument à droite + Type argument droit + Left Argument Type - Type d'argument à gauche + Type d'argument gauche + To create a unary operator it is necessary to specify as <strong><em>'any'</em></strong> one of its arguments. Additionally, the function that defines the operator must have only one parameter and this, in turn, must have the same data type of the the argument of unary operator. - Pour créer un opérateur unaire il est nécessaire de spécifier <strong><em>'any'</em></strong> comme l'un de ses arguments. De plus, la fonction qui définit l'opérateur doit avoir seulement un paramètre et celui-ci doit avoir le même type de donnée que l'argument de l'opérateur unaire. + Pour créer un opérateur unitaire, il est nécessaire de spécifier <strong><em>'any'</em></strong> comme l'un de ses arguments. De plus, la fonction qui définit l'opérateur doit avoir seulement un paramètre et celui-ci doit avoir le même type de donnée que l'argument de l'opérateur unitaire. ParameterWidget - Form - Formulaire - - + Default Value: - Valeur par défaut: + Valeur par défaut : + Mode: - Mode: + Mode : + IN IN + OUT OUT + VARIADIC VARIADIC @@ -8264,528 +10346,912 @@ p, li { white-space: pre-wrap; } PermissionWidget - Form - Formulaire - - + + Roles Rôles + ID: - Identifiant: + Identifiant : + + Permissions Permissions + Add Permission Ajouter permission + Update Permission Actualiser permission + Cancel Operation Annuler l'opération + + Privileges Privilèges + Disable SQL code Désactiver le code SQL - Grant - Grant + + Cascade + Cascade + + + + Privilege + Privilège + + + + GRANT OPTION + GRANT OPTION + + + + Code Preview + Prévisualisation du code + + + + Name + Nom + + + + Id + + + + + Leave the <em><strong>Roles</strong></em> grid empty in order to create a %1 applicable to <strong><em>PUBLIC</em></strong>. + Laissez la grille <em><strong>Rôles</strong></em> vide afin de créer un %1 applicable à <strong><em>PUBLIC</em></strong>. + + + + -- No permissions defined for the specified object! + -- Aucune permission définie pour cet objet ! + + + + /* Could not generate the SQL code preview for permissions! + /* Impossible de générer la prévisualisation du code SQL pour les permissions ! + + + + Edit permissions + Modifier les permissions + + + + &Grant + Acco&rder + + + + Re&voke + Ré&voquer + + + + PgModelerCLI + + + Unrecognized option '%1'. + Option '%1' non reconnue. + + + + Value not specified for option '%1'. + Valeur pour l'option '%1' manquante. + + + + Option '%1' does not accept values. + L'option '%1' n'accepte pas de valeur. + + + + Usage: pgmodeler-cli [OPTIONS] + Utilisation : pgmodeler-cli [OPTIONS] + + + + + command line interface. + interface en ligne de commande. + + + + General options: + Options générales : + + + + DBMS export options: + Options d'export directe dans un serveur : + + + + Input file must be different from output! + Le fichier source doit être différent du fichier de sortie ! + + + + Incomplete connection information! + Les informations de connexion sont incomplètes ! + + + + Starting model export... + Début de l'export du modèle... + + + + Miscellaneous options: + Options diverses : + + + + There are no connections configured. + Il n'y a aucune connexion configurée. + + + + Invalid zoom specified! + Zoom spécifié invalide ! + + + + Invalid action specified to update mime option! + Action spécifiée invalide pour mettre à jour l'option mime ! + + + + Starting model fixing... + Lancement de la fixation du modèle... + + + + Starting mime update... + Lancement de la mise à jour du mime... + + + + Model successfully fixed! + Modèle fixé avec succès ! + + + + Extracting objects' XML... + Extraction des objets XML... + + + + Connection aliased as '%1' was not found in the configuration file. + + + + + PostgreSQL Database Modeler Project - pgmodeler.io + + + + + Copyright 2006-2018 Raphael A. Silva <raphael@pgmodeler.io> + + + + + This CLI tool provides several operations over models and databases without the need to perform them +in pgModeler's graphical interface. All available options are described below. + + + + + %1, %2 [FILE] Input model file (.dbm). This is mandatory for fix, export operations. + + + + + %1, %2 [DBNAME] Input database name. This is mandatory for import operation. + + + + + %1, %2 [FILE] Output file. This is mandatory for fixing model or exporting to file, png or svg. + + + + + %1, %2 Try to fix the structure of the input model file in order to make it loadable again. + + + + + %1, %2 [NUMBER] Model fix tries. When reaching the maximum count the invalid objects will be discarded. + + + + + %1, %2 Export the input model to a sql script file. + + + + + %1, %2 Export the input model to a png image. + - Revoke - Revoke + + %1, %2 Export the input model to a svg file. + - Cascade - Cascade + + %1, %2 Export the input model directly to a PostgreSQL server. + - Privilege - Privilège + + %1, %2 Import a database to an output file. + - GRANT OPTION - GRANT OPTION + + %1, %2 Compares a model and a database or two databases generating the SQL script to synch the latter in relation to the first. + - Code Preview - Prévisualisation du code + + %1, %2 Force the PostgreSQL version of generated SQL code. + - Type: - Type: + + %1, %2 Silent execution. Only critical messages and errors are shown during process. + - Role - Rôle + + %1, %2 Show this help menu. + - Id - Identifiant + + Connection options: + - Leave the <em><strong>Roles</strong></em> empty to create a permission applicable to <strong><em>PUBLIC</em></strong>. - Laissez le champ <em><strong>Rôles</strong></em> vide pour créer une permission applicable à <strong><em>PUBLIC</em></strong>. + + %1, %2 List available connections in file %3. + - -- No permissions defined for the specified object! - -- Aucune permission définie pour cet objet! + + %1, %2 [ALIAS] Connection configuration alias to be used. + - /* Could not generate the SQL code preview for permissions! - /* Impossible de générer la prévisualisation du code SQL pour les permissions! + + %1, %2 [HOST] PostgreSQL host in which a task will operate. + - Edit permissions - Editer les permissions + + %1, %2 [PORT] PostgreSQL host listening port. + - &Grant + + %1, %2 [USER] PostgreSQL username. - Re&voke + + %1, %2 [PASSWORD] PostgreSQL user password. - - - PgModelerCLI - Unrecognized option '%1'. - Option '%1' non reconnue. + + %1, %2 [DBNAME] Connection's initial database. + - Value not specified for option '%1'. - Valeur pour l'option '%1' manquante. + + %1, %2 Draws the grid in the exported image. + - Option '%1' does not accept values. - L'option '%1' n'accepte pas de valeur. + + %1, %2 Draws the page delimiters in the exported image. + - Connection aliased as '%1' was not found on configuration file. - La connexion nommé '%1' n'existe pas dans le fichier de configuration. + + %1, %2 Each page will be exported in a separated png image. (Only for PNG images) + - Usage: pgmodeler-cli [OPTIONS] - Utilisation: pgmodeler-cli [OPTIONS] + + %1, %2 [FACTOR] Applies a zoom (in percent) before export to png image. Accepted zoom interval: %3-%4 (Only for PNG images) + - command line interface. - interface en ligne de commande + + %1, %2 Ignores errors related to duplicated objects that eventually exist in the server. + - PostgreSQL Database Modeler Project - pgmodeler.com.br - PostgreSQL Database Modeler Project - pgmodeler.com.br + + %1, %2 [CODES] Ignores additional errors by their codes. A comma-separated list of alphanumeric codes should be provided. + %1, %2=[CODES] Ignore les erreurs supplémentaires par leurs codes. Une liste de codes alphanumériques séparés par des virgules doit être fournie. {1,?} {2 ?} - General options: - Options générales: + + %1, %2 Drop the database before execute a export process. + - %1, %2 Export to a sql script file. - %1, %2 Export vers un fichier SQL. + + %1, %2 Runs the DROP commands attached to SQL-enabled objects. + - %1, %2 Export to a png image. - %1, %2 Export en image PNG. + + %1, %2 Simulates an export process by executing all steps but undoing any modification in the end. + - %1, %2 Export directly to a PostgreSQL server. - %1, %2 Exporter directement dans un serveur PostgreSQL. + + %1, %2 Generates temporary names for database, roles and tablespaces when in simulation mode. + - %1, %2 List available connections on %3 file. - %1, %2 Lister les connexions disponnibles dans le fichier %3. + + Database import options: + - %1, %2 Version of generated SQL code. Only for file or dbms export. - %1, %2 Version de PostgreSQL pour laquelle doit être généré l'export. Uniquement pour les exports fichier SQL et en direct dans le serveur. + + %1, %2 Ignore all errors and try to create as many as possible objects. + - %1, %2 Silent execution. Only critical errors are shown during process. - %1, %2 Exécution silencieuse. Seuls les avertissements et erreurs seront affichés pendant le traitement. + + %1, %2 Import system built-in objects. This option causes the model bloating due to the importing of unneeded objects. + - %1, %2 Show this help menu. - %1, %2 Affiche ce menu. + + %1, %2 Import extension objects. This option causes the model bloating due to the importing of unneeded objects. + - PNG export options: - Option d'export PNG: + + %1, %2 Run import in debug mode printing all queries executed in the server. + - %1, %2 Draws the grid on the exported png image. - %1, %2 Dessiner la grille. + + Diff options: + - %1, %2 Draws the page delimiters on the exported png image. - %1, %2 Dessiner les limites de pages. + + %1, %2 [DBNAME] The database used in the comparison. All the SQL code generated is applied to it. + - DBMS export options: - Option d'exportation directe dans un serveur: + + %1, %2 Save the generated diff code to output file. + - %1, %2 Ignores errors related to duplicated objects that eventually exists on server side. - %1, %2 Ignorer les erreurs relatives à d'éventuels objets dupliqués déjà existant sur le serveur. + + %1, %2 Apply the generated diff code on the database server. + - %1, %2=[ALIAS] Connection configuration alias to be used. - %1, %2=[ALIAS] Alias de connexion à utiliser. + + %1, %2 Don't preview the generated diff code when applying it to the server. + - %1, %2=[HOST] PostgreSQL host which export will operate. - %1, %2=[HOST] Hôte du serveur PostgreSQL. + + %1, %2 Drop cluster level objects like roles and tablespaces. + - %1, %2=[PORT] PostgreSQL host listening port. - %1, %2=[PORT] Port du serveur PostgreSQL. + + %1, %2 Revoke permissions already set on the database. New permissions configured in the input model are still applied. + - %1, %2=[USER] PosrgreSQL username. - %1, %2=[USER] Nom d'utilisateur. + + %1, %2 Drop missing objects. Generates DROP commands for objects that are present in the input model but not in the compared database. + - %1, %2=[PASSWORD] PosrgreSQL user password. - %1, %2=[PASSWORD] Mot de passe. + + %1, %2 Force the drop of missing columns and constraints. Causes only columns and constraints to be dropped, other missing objects aren't removed. + - %1, %2=[DBNAME] Connection's initial database. - %1, %2=[DBNAME] Base de données initiale de connexion. + + %1, %2 Rename the destination database when the names of the involved databases are different. + - Available connections (alias : conn. string) - Connexions disponibles (alias : chaîne de conn.) + + %1, %2 Don't drop or truncate objects in cascade mode. + - No export mode specified! - Pas de mode d'export spécifié! + + %1, %2 Truncate tables prior to alter columns. Avoids errors related to type casting when the new type of a column isn't compatible to the old one. + - Multiple export mode especified! - Multiples mode d'exportation spécifiés! + + %1, %2 Don't reuse sequences on serial columns. Drop the old sequence assigned to a serial column and creates a new one. + - No input file specified! - Pas de fichier source! + + %1, %2 Don't force the recreation of objects. Avoids the usage of a DROP and CREATE commands to create a new version of the objects. + - No output file specified! - Pas de fichier de sortie! + + %1, %2 Don't recreate the unmodifiable objects. These objects are the ones which can't be changed via ALTER command. + - Input file must be different from output! - Le fichier source doit être différent du fichier de sortie! + + %1, %2 [ACTION] Handles the file association to .dbm files. The ACTION can be [%3 | %4]. + - Incomplete connection information! - Les information de connexion sont incomplètes! + + ** The diff process allows the usage of the following options related to import and export operations: + - Starting model export... - Début de l'export du modèle... + + * Export: + - Loading input file: - Chargement du fichier source: + + * Import: + - Export to PNG image: - Export en image PNG: + + ** When running the diff using two databases (%1 and %2) there's the need to specify two connections/aliases. + - Export to SQL script file: - Export en fichier SQL: + + If only one connection is set it will be used to import the input database as well to retrieve database used in the comparison. + - Export to DBMS: - Export directement en base: + + A second connection can be specified by appending a 1 on any connection configuration parameter listed above. + - Export successfully ended! - Export complété avec succès! + + Available connections (alias : connection string) + - Copyright 2006-2015 Raphael A. Silva <raphael@pgmodeler.com.br> - + + No operation mode was specified! + - This CLI tool provides the operations to export pgModeler's database models without -the need to load them on graphical interface as well to fix model files to the most recent -accepted structure. All available options are described below. - Cet outil en ligne de commande permet d'exporter des modèles de base pgModeler sans avoir besoin de les ouvrir via l'interface graphique. Il permet aussi de réparer des fichiers de modèle vers un format de structure le plus récent. Toutes les options disponibles sont décrites ci-dessous. + + Export, fix model, import database, diff and update mime operations can't be used at the same time! + - %1, %2=[FILE] Input model file (.dbm). Mandatory use when fixing a model or exporting it. + + Multiple export mode was specified! - %1, %2=[FILE] Output file. Mandatory use when fixing model or export to file or png. + + No input file was specified! - %1, %2 Try to fix the structure of the input model file in order to make it loadable again. + + No input database was specified! - %1, %2 Model fix tries. When reaching the maximum count the invalid objects will be discard. + + No output file was specified! - %1, %2 Drop the database before execute a export process. + + No input file or database was specified! - %1, %2 Runs the DROP commands attached to SQL-enabled objects. + + The input file and database can't be used at the same time! - %1, %2 Simulates a export process. Actually executes all steps but undoing any modification. + + No database to be compared was specified! - %1, %2 Generates temporary names for database, roles and tablespaces when in simulation mode. + + No diff action (save or apply) was specified! - Miscellaneous options: + + No output file for the diff code was specified! - %1, %2=[ACTION] Handles the file association to .dbm files. The ACTION can be [%3 | %4]. + + ** Error code `%1' found and ignored. Proceeding with export. - There are no connections configured. + + ** Command: %1 - Export, fix model and update mime operations can't be used at the same time! + + Invalid input file! It seems that is not a pgModeler generated model or the file is corrupted! + Fichier d'entrée invalide ! Il semble que ce ne soit pas un modèle généré par pgModeler ou que le fichier soit corrompu ! + + + + Recreating objects... + Recréation des objets... + + + + +** Object(s) that couldn't fixed: + +** Ces objets ne peuvent être corrigés : + + + + WARNING: There are objects that maybe can't be fixed. Trying again... (tries %1/%2) + AVERTISSEMENT : Certains objets ne peuvent peut-être pas être corrigés. Nouvel essai... (%1/%2) + + + + + Loading input file: %1 - Invalid zoom specified! + + Fixed model file: %1 - Invalid action specified to update mime option! + + Export to PNG image: %1 - Starting model fixing... + + Export to SVG file: %1 - Starting mime update... + + Export to SQL script file: %1 - Fixed model file: + + Export to DBMS: %1 - Model successfully fixed! + + Export successfully ended! + - Extracting objects' XML... + + Starting database import... - Invalid input file! It seems that is not a pgModeler generated model or the file is corrupted! + + + Input database: %1 - Recreating objects... + + Saving the imported database to file... - -** Object(s) that couldn't fixed: + + Import successfully ended! + - WARNING: There are objects that maybe can't be fixed. Trying again... (tries %1/%2) + + Starting diff process... - Database model files (.dbm) are already associated to pgModeler! + + Input model: %1 - There is no file association related to pgModeler and .dbm files! + + Compare to: %1 - Mime database operation: %1 + + Loading input model... - Can't erase the file %1! Check if the current user has permissions to delete it and if the file exists. + + + Importing the database `%1'... - Running update-mime-database command... + + Comparing the generated models... - This CLI tool provides the operations to export pgModeler's database models without - the need to load them on graphical interface as well to fix model files to the most recent - accepted structure. All available options are described below. + + No differences were detected. - %1, %2 Export to a svg file. + + Saving diff to file `%1' - PNG and SVG export options: + + ** WARNING: You are about to apply the generated diff code to the server. Data can be lost in the process! - %1, %2 Each page will be exported on a separated png image. (Only for PNG) + + ** Proceed with the diff applying? (yes/no) > - %1, %2=[FACTOR] Applies a zoom (in percent) before export to png image. Accepted zoom interval: %3-%4 (Only for PNG) + + yes - %1, %2=[USER] PostgreSQL username. + + + no - %1, %2=[PASSWORD] PostgreSQL user password. + + Diff code not applied to the server. - Multiple export mode specified! + + Applying diff to the database `%1'... - Mime database successfully updated. + + Diff successfully ended! + - Export to SVG file: + + Mime database successfully updated! + + + + Database model files (.dbm) are already associated to pgModeler! + Les fichiers de modèle de bases de données (.dbm) sont déjà associés à pgModeler ! + + + + There is no file association related to pgModeler and .dbm files! + Il n'y a pas d'association entre pgModeler et .les fichiers dbm ! + + + + Mime database operation: %1 + Opération de base de données mime : %1 + + + + Can't erase the file %1! Check if the current user has permissions to delete it and if the file exists. + Impossible d'effacer le fichier %1 ! Vérifiez si l'utilisateur actuel dispose des autorisations pour le supprimer et si le fichier existe. + + + + Running update-mime-database command... + Exécution de la commande update-mime-database... + + + + PNG and SVG export options: + Options d'export en PNG et SVG : + PgModelerPlugin + Plugin Information - Information de l'extension + Information d'extension + Version: %1 - Version: %1 + Version : %1 + Author: %1 - Auteur: %1 + Auteur : %1 PgModelerUiNS + Do you want to apply the <strong>SQL %1 status</strong> to the object's references too? This will avoid problems when exporting or validating the model. - Souhaitez-vous appliquer <strong>SQL %1 status</strong> aux références de l'objet également ? Cela permet d'éviter des porlbèmes lors de l'exportation ou la validation du modèle. + Souhaitez-vous appliquer <strong>statut SQL %1 </strong> aux références de l'objet également ? Cela permet d'éviter des problèmes lors de l'export ou de la validation du modèle. + disabling - + désactivation + enabling - + activation PgSQLTypeWidget + Form Formulaire + Data Type Type de donnée + SRID: - SRID: + SRID : + Variation: - Variation: + Variation : + Z Z + M M + + Precision Précision + Spatial: - Spatial: + Spatial : + + Dimension Dimension + Format: - Format: + Format : + Timezone: - Fuseau horaire: + Fuseau horaire : + Type: - Type: + Type : + P: - P: + P : + + Length - Taille ? Longueur + L: - L: + L : + Interval: - Intervalle: + Intervalle : + [ ]: - [ ]: + [ ] : + NONE AUCUN @@ -8793,667 +11259,888 @@ accepted structure. All available options are described below. PluginsConfigWidget + Form Formulaire + Plug-ins root directory: - Répertoire racine des extentions: + Répertoire racine des extensions : + Open in file manager - Ouvrir dans le getionnaire de fichier + Ouvrir dans le gestionnaire de fichier + Loaded plug-ins Extensions chargées + Plugin Extension + Version - Version + + Library Bibliothèque + + PolicyWidget + + + Basics + Notions de base + + + + Command: + Commande : + + + + Permissive + Permissif + + + + Roles + Rôles + + + + Expressions + + + + + USING: + UTILISANT : + + + + CHECK: + VÉRIFIER : + + + + Name + Nom + + + + Leave the <em><strong>Roles</strong></em> grid empty in order to create a %1 applicable to <strong><em>PUBLIC</em></strong>. + Laissez la grille <em><strong>Rôles</strong></em> vide afin de créer un %1 applicable à <strong><em>PUBLIC</em></strong>. + + QObject + new_database - nouvelle_base + nouvelle_base_de_données + + + + %1 (line: %2) - %1 (ligne: %2) + %1 (ligne : %2) Relationship + %1_has_one_%2 - Traduction approprié ? - %1_has_one_%2 + Faut-il le traduire ? + + %1_has_many_%2 - Traduction approprié ? - %1_has_many_%2 + Faut-il le traduire ? + + many_%1_has_many_%2 - Traduction approprié ? - many_%1_has_many_%2 + Faut-il le traduire ? + + %1_inherits_%2 - Traduction approprié ? - %1_inherits_%2 + Faut-il le traduire ? + + %1_copies_%2 - Traduction approprié ? - %1_copies_%2 + Faut-il le traduire ? + RelationshipConfigWidget + Form Formulaire + Connect FK to PK columns - Relier les associations avec chacune des colonnes des clés étrangères/primaires concernées + Relier les colonnes associant clés étrangères/clés primaires + Connect tables' center points Relier les associations aux tables en un point central + Foreign key settings Clés étrangères + Deferral: - Report: + Report : + Deferrable: - Différable: + Reportable : + ON DELETE: - ON DELETE: + ON DELETE : + ON UPDATE: - ON UPDATE: + ON UPDATE : + Name patterns Règles de nommage + Relationship type: - Type d'association: + Type d'association : + Foreign Key (Target): - Clé étrangère (Cible): + Clé étrangère (Cible) : + Unique Key Name: - Nom contrainte unique: + Nom contrainte unique : + Primary Key Name: - Nom contrainte clé primaire: + Nom contrainte clé primaire : + Primary Key Column: - Nom colonne clé primaire: + Nom colonne clé primaire : + Column (Target): - Colonne (Cible): + Colonne (Cible) : + Foreign Key (Source): - Clé étrangère (Source): + Clé étrangère (Source) : + Column (Source): - Colonne (Source): + Colonne (Source) : + One to one (1:1) - Un à un (1:1) + Un à un (1 :1) + Connection Mode Affichage + FK Settings && Patterns - Clès étrangères && nommage + Clés étrangères && nommage + One to many (1:n) - Un à plusieurs (1:n) + Un à plusieurs (1 :n) + Many to many (n:n) - Plusieurs à plusieurs (n:n) + Plusieurs à plusieurs (n :n) + Generalization Généralisation + Copy Copie + Default Défaut - This mode is available only for <strong>one-to-one</strong>, <strong>one-to-many</strong> and <strong>fk relationships</strong> but provides a better semantics when linking tables by placing the lines on the exact point where the relationship occurs. - Ce mode d'affichage est disponible uniquement pour les associations de type <strong>un à un</strong>, <strong>un à plusieurs</strong> et <strong>les associations à clé étrangère</strong>. Il permet une meilleure sémantique pour relier les tables en traçant les lignes sur chacunes des colonnes concernées par l'assocation. - - - This mode is the classical one. It connects the relationship to tables through their central points. - Ceci est le mode classique. L'association est reliée aux tables en un seul trait central. - - + Pattern for foreign key generated based upon reference table's pk (1-1 and 1-n) or based upon source table's pk (n-n). - Motif pour les noms de clés étrangères générées qui sont basées sur la clé primaire d'une table référencée (1:1 et 1:n) ou sur la clé primaire de la table source (n:n). + Motif pour les noms de clés étrangères générées qui sont basées sur la clé primaire d'une table référencée (1 :1 et 1 :n) ou sur la clé primaire de la table source (n :n). + Pattern for columns generated based upon target table's pk (n-n). - Motif pour les noms de colonnes générées qui sont basées sur la clé primaire de la table cible (n:n). + Motif pour les noms de colonnes générées qui sont basées sur la clé primaire de la table cible (n :n). + Pattern for columns generated based upon reference table's pk (1-1 and 1-n) or based upon source table's pk (n-n). - Motif pour les noms de colonnes générées qui sont basées sur la clé primaire d'une table référencée (1:1 et 1:n) ou sur la clé primaire de la table source (n:n). + Motif pour les noms de colonnes générées qui sont basées sur la clé primaire d'une table référencée (1 :1 et 1 :n) ou sur la clé primaire de la table source (n :n). + Pattern for foreign key generated based upon target table's pk (n-n). - Motif pour les noms de clés étrangères générées qui sont basées sur une clé primaire de la table cible (n:n). + Motif pour les noms de clés étrangères générées qui sont basées sur une clé primaire de la table cible (n :n). + Pattern for unique key generated by the relationship. Motif pour les noms de clés uniques qui sont générées par une association. + + Pattern for primary key generated by identifier relationship. Motif pour les noms de clés primaires qui sont générées par une association. + + + This mode renders the relationships in crow's foot notation which has a better semantics and readability. It also determines the optimal point where the relationship is connected on the tables' edges taking their position into account. + Ce mode affiche les associations en pied d'oiseau ce qui améliore le sémantique et la lisibilité. Il détermine également le point optimal où la relation est connectée sur les bords des tables en tenant compte de leur position. + + + + Crow's foot notation + Affichage en pied d'oiseau + + + + This mode determines the optimal point where the relationship is connected on the tables' edges taking their position into account. It implies the usage of the classical ER notation. + Ce mode détermine le point optimal où la relation est connectée sur les bords des tables en tenant compte de leur position. Cela implique l'utilisation de la notation ER classique. + + + + Connect tables' edges + Connecter les bords des tables + + + + This mode is available only for <strong>one-to-one</strong>, <strong>one-to-many</strong> and <strong>fk relationships</strong> but provides a better semantics when linking tables by placing the lines on the exact point where the relationship occurs. It implies the usage of the classical ER notation. + Ce mode d'affichage est disponible uniquement pour les associations de type <strong>un-à-un</strong>, <strong>un-à-plusieurs</strong> et <strong>les associations aux clés étrangères</strong> mais fournit une meilleure sémantique lors de l'association de tables en plaçant les lignes sur le point exact où l'association se produit. Cela implique l'utilisation de la notation ER classique. + + + + This mode is the classical one. It connects the relationship to tables through their central points. It implies the usage of the classical ER notation. + Ce mode est le classique. Il relie les associations de tables depuis leurs points centraux. Cela implique l'utilisation de la notation ER classique. + RelationshipWidget - Form - Formulaire - - + General Général + One to one relationship Association un à un - 1-1 - 1-1 - - + One to many relationship Association un à plusieurs + 1-n 1-n + Many to many relationship Association plusieurs à plusieurs + n-n n-n + Generalization relationship (inheritance) Association de généralisation (héritage) - gen - gen - - + Dependency / Copy relationship Relation de dépendance / copie + dep dep + Relationship generated via foreign key - Relation générée par une clef étrangère + Relation générée par une clé étrangère + fk fk + Identifier Identifiant + Rel. Type: - Type de relation: + Type de relation : + Table 1: - Table n°1: + Table n°1 : + Table 2: - Table n°2: + Table n°2 : + Foreign key Settings Propriétés par défaut des clés étrangères + + Use the values defined on settings dialogs for the fields below Utiliser les paramètres de pgModeler pour les champs ci-dessous + + Use global settings for these fields Utiliser les paramètres globaux de pgModeler + ON DELETE: - Intuitif - ON DELETE: + ON DELETE : + ON UPDATE: - Intuitif - ON UPDATE: + ON UPDATE : + + + + &1-1 + + + + + &gen + + Name Patterns Règles de nommage + Column (Source): - Colonne (Source): + Colonne (Source) : + Column (Target): - Colonne (Cible): + Colonne (Cible) : + Foreign Key (Source): - Clé étrangère (Source): + Clé étrangère (Source) : + Foreign Key (Target): - Clé étrangère (Cible): + Clé étrangère (Cible) : + Cardinality: - Cardinalité: + Cardinalité : + [SRC] is required [SRC] est requis + [DST] is required [DST] est requis + + Name of the table generated from many to many relationship Nom de la table générée par une relation plusieurs à plusieurs + Deferrable: - Différable: + Reportable : + Deferral: - Report: + Report : + Copy Options Options de copie + INDEXES - INDEXES + INDEX + COMMENTS COMMENTAIRES + INCLUDING INCLURE + DEFAULTS DEFAUTS - EXCLUDING - EXCLURE - - + CONSTRAINTS CONTRAINTES + Use defaults Utiliser les valeurs par défauts + ALL TOUT + STORAGE STOCKAGE + Gen. Table Name: - Nom nouvelle table: + Nom nouvelle table : + Attributes Attributs + Constraints Contraintes + Primary key - Clef primaire + Clé primaire + Advanced Avancé + Attribute Attribut + + + Type - Type + + Constraint Contrainte + Name Nom + This advanced tab shows the objects (columns or table) auto created by the relationship's connection as well the foreign keys that represents the link between the participant tables. - Cet onglet avancé montre les objets (colonnes ou tables) générés automatiquement par la relation ainsi que les clefs étrangères qui forment le(s) lien(s) entre les tables. + Cet onglet avancé montre les objets (colonnes ou tables) générés automatiquement par la relation ainsi que les clés étrangères qui forment le(s) lien(s) entre les tables. + + is required est requis + + + Reference Table: - Table de référence: + Table référente : + Default Défaut + Receiver Table: - Table de destination: + Table de destination : + Pattern for columns generated based upon reference table's pk (1-1 and 1-n) or based upon source table's pk (n-n). - Motif pour les noms de colonnes générées qui sont basées sur la clé primaire d'une table référencée (1:1 et 1:n) ou sur la clé primaire de la table source (n:n). + Motif pour les noms de colonnes générées qui sont basées sur la clé primaire d'une table référencée (1 :1 et 1 :n) ou sur la clé primaire de la table source (n :n). + Pattern for columns generated based upon target table's pk (n-n). - Motif pour les noms de colonnes générées qui sont basées sur la clé primaire de la table cible (n:n). + Motif pour les noms de colonnes générées qui sont basées sur la clé primaire de la table cible (n :n). + Pattern for foreign key generated based upon reference table's pk (1-1 and 1-n) or based upon source table's pk (n-n). - Motif pour les noms de clés étrangères générées qui sont basées sur la clé primaire d'une table référencée (1:1 et 1:n) ou sur la clé primaire de la table source (n:n). + Motif pour les noms de clés étrangères générées qui sont basées sur la clé primaire d'une table référencée (1 :1 et 1 :n) ou sur la clé primaire de la table source (n :n). + Pattern for foreign key generated based upon target table's pk (n-n). - Motif pour les noms de clés étrangères générées qui sont basées sur une clé primaire de la table cible (n:n). + Motif pour les noms de clés étrangères générées qui sont basées sur une clé primaire de la table cible (n :n). + + Pattern for primary key generated by identifier relationship. - Motif pour les noms de clés primaires qui sont générées par une association. + Motif pour les noms de clés primaires qui sont générées par une association. + Primary Key Name: - Nom contrainte clé primaire: + Nom de clé primaire : + Pattern for unique key generated by the relationship. - Motif pour les noms de clés uniques qui sont générées par une association. + Motif pour les noms de clés uniques qui sont générées par une association. + Unique Key Name: - Nom contrainte unique: + Nom clé unique : + Primay Key Column: - + Colonne de clé primaire : + The receiver's primary key will be composed by the generated foreign key columns. - + La clé primaire du destinataire sera composée des colonnes de clé étrangère générées. + Instead of create a multi-valued primary key with the generated foreign keys columns a single column is created and used as primary key. - + Au lieu de créer une clé primaire à valeurs multiples avec les colonnes de clés étrangères générées, une seule colonne est créée et utilisée comme clé primaire. + Single PK column - + Colonne clé primaire simple + Custom Color: - + Couleur personnalisée : + Use the special primary key if you want to include a primary key containing generated columns to the receiver table. <strong>Important:</strong> if this is a new relationship there is a need to finish its creation and reopen this dialog to create the special primary key. - + Utilisez la clé primaire spéciale si vous souhaitez inclure une clé primaire contenant des colonnes générées dans la table de destination. <strong>Important :</strong> s'il s'agit d'une nouvelle relation, il est nécessaire de terminer sa création et de réouvrir cette boîte de dialogue pour créer la clé primaire spéciale. + Referer View: - + Vue référente : + Referer view references one or more columns of a table to construct it's own columns. - + La vue référente référence une ou plusieurs colonnes d'une table pour construire ses propres colonnes. + Referenced table has its columns referenced by a view in order to construct the columns of this latter. - + La table référencée a ses colonnes référencées par une vue afin de construire les colonnes de cette dernière. + Referer Table: - + Table référente : + Referer table references one or more columns of a table through foreign keys. This is the (n) side of relationship. - + La table référente référence une ou plusieurs colonnes d'une table via des clés étrangères. C'est le côté (n) de la relation. + Referenced table has its columns referenced by a table's foreign key. This is the (1) side of relationship. - + La table référencée a ses colonnes référencées par la clé étrangère d'une table. C'est le côté (1) de la relation. + Referenced Table: - + Table référencée : + Reference table has the columns from its primary key will copied to the receiver table in order to represent the linking between them. This is the (1) side of relationship. - + La table de référence a les colonnes de sa clé primaire copiées dans la table de réception afin de représenter la liaison entre elles. C'est le côté (1) de la relation. + Receiver (or referer) table will receive the generated columns and the foreign key in order to represent the linking between them. This is the (n) side of relationship. - + La table référente recevra les colonnes générées et la clé étrangère afin de représenter la liaison entre elles. C'est le côté (n) de la relation. + In many-to-many relationships both tables are used as reference to generate the table that represents the linking. Columns from both tables are copied to the resultant table and two foreign keys are created as well in order to reference each participant table. - - - - &1-1 - - - - &gen - + Dans les relations plusieurs-à-plusieurs, les deux tables sont utilisées comme référence pour générer la table qui représente la liaison. Les colonnes des deux tables sont copiées dans la table résultante et deux clés étrangères sont également créées afin de référencer chaque table participante. + E&XCLUDING - + E&XCLUSION + Available tokens to define name patterns:<br/> <strong>%1</strong> = Reference (source) primary key column name. <em>(Ignored on constraint patterns)</em><br/> <strong>%2</strong> = Reference (source) table name.<br/> <strong>%3</strong> = Receiver (destination) table name.<br/> <strong>%4</strong> = Generated table name. <em>(Only for n:n relationships)</em> - + Formes disponibles pour définir les modèles de noms : <br/> <strong>%1</strong> = Nom de la colonne de clé primaire de référence (source). <em>(Ignoré sur les modèles de contrainte)</em><br/> <strong>%2</strong> = Nom de la table de référence (source).<br/> <strong>%3</strong> = Nom de la table référencée (ou de déstination). <br/> <strong>%4</strong> = Nom de la table générée. <em>(Seulement pour les relations n:n)</em> - RoleWidget + ResultSetModel - Form - Formulaire + + [binary data] + [données binaires] + + + RoleWidget + Password: - Mot de passe: + Mot de passe : + Connections: - Connexions: + Connexions : + Attributes Attributs + Superuser Super utilisateur - Inherit Permissions + + Inherit permissions Hériter des permissions - Can create Database + + Can create database Peut créer des bases de données - Can create Role - Peut créer des rôles + + Can use replication + Peut utiliser la réplication - Can use Replication - Peut utiliser la réplication + + Can login + Peut se loguer + Encrypted Encrypté - Can Login - Peut s'authentifier - - + + Members Membres + + Member of Membre de + + Members (Admin.) - Membres (Admin.) - - - Assigning <strong><em>-1</em></strong> to <strong><em>Connections</em></strong> creates a role without connection limit.<br/> Unchecking <strong><em>Validity</em></strong> creates an role that never expires. - Definir <strong><em>Connexions</em></strong> à <strong><em>-1</em></strong> créé le rôle sans limite de connexion.<br/> Décocher <strong><em>Validité</em></strong> créé un rôle qui n'expire jamais. + Membres (Admin.) + Role Rôle + + Validity Validité + yyyy-MMM-dd hh:mm:ss - + aaaa-MMM-jj hh :mm :ss + Assigning <strong><em>-1</em></strong> to <strong><em>Connections</em></strong> creates a role without connection limit.<br/> Unchecking <strong><em>Validity</em></strong> creates an role that never expires. - + L'affectation de <strong><em>-1</em></strong> à <strong><em>Connexions</em></strong> crée un rôle sans limite de connexion.<br/> Décocher <strong><em>Validité</em></strong> crée un rôle qui n'expire jamais. + + + + Bypass RLS + Contournement RLS + + + + Can create role + Peut créer des rôles RuleWidget - Form - Formulaire - - + Event: - Evènement: + Évènement : + Execution Type: - Type d'exécution: + Type d'exécution : + Conditional Expr.: - Expr. conditionnelle: + Expr. conditionnelle : + Commands Commandes + SQL Command: - Commandes SQL: + Commandes SQL : + SQL command Commande SQL + To create a rule that does not perform any action (<strong>DO NOTHING</strong>) simply do not specify commands in the SQL commands table. Pour créer une règle qui n'éxécute aucune action (<strong>DO NOTHING</strong>), ne spécifiez aucune commandes dans le champs des commandes SQL. @@ -9461,912 +12148,1314 @@ accepted structure. All available options are described below. SQLExecutionWidget + Form Formulaire - Load SQL script - Ouvrir un script SQL - - - &Load - O&uvrir - - + Save SQL commands Sauvegarder commandes SQL - &Save - E&nregistrer - - - &Find - &Rechercher - - + Alt+F Alt+F + Run the specified SQL command - Exécute la commande SQL entrée + Exécuter la commande SQL entrée + Run SQL Exécuter SQL + F6 F6 + Clear sql input field and results Effacer le code SQL et la grille de résultat + Clear All Effacer + + Export results to a CSV file Exporter les résultats dans un fichier CSV + Snippe&ts - Snippe&ts + Extrai&ts + + + + Alt+T + + E&xport E&xporter - Shows the command history - Afficher l'historique des commandes + + ... + ... + + + + SQL file (*.sql);;All files (*.*) + Fichier SQL (*.sql);;Tous les fichiers (*.*) + + + + Load + Charger - &History - &Historique + + Save + Enregistrer - Alt+H - Alt+H + + Save as + Enregistrer sous - Command History - Historique des commandes + + [binary data] + [données binaires] - Clear sql input field and results. - Effacer les résultats et le code SQL saisi. + + + Messages (%1) + - Clear - Effacer + + [%1]: SQL command successfully executed in <em><strong>%2</strong></em>. <em>%3 <strong>%4</strong></em> + - ... - ... + + Save CSV file + Sauvegarder fichier CSV - 0 - 0 + + Comma-separated values file (*.csv);;All files (*.*) + Fichiers CSV avec champs séparés par des virgules (*.csv);;Tous les fichiers (*.*) - Rows returned: - Lignes retournées: + + The SQL input field and the results grid will be cleared! Want to proceed? + Le champ d'entrée SQL ainsi que la grille des résultats vont être purgés ! Voulez-vous poursuivre ? - SQL file (*.sql);;All files (*.*) - Fichier SQL (*.sql);;Tous les fichiers (*.*) + + Save history + Enregistrer l'historique - [binary data] - [données binaires] + + Reload history + Recharger l'historique - Save CSV file - Sauvegarder fichier CSV + + Find in history + Rechercher dans l'historique - Comma-separated values file (*.csv);;All files (*.*) - Fichiers CSV, champs séparés par des points-virgules (*.csv);;Tous les fichiers (*.*) + + Hide find tool + Masquer l'outil de recherche - The SQL input field and the results grid will be cleared! Want to proceed? - Tout le code SQL ainsi que la grille des résultats vont être purgés! Continuer? + + This action will wipe out all the SQL commands history for the current connection! Do you really want to proceed? + Cette action effacera tout l'historique des commandes SQL pour la connexion en cours ! Voulez-vous vraiment poursuivre ? + Load SQL commands - + Charger commandes SQL + Copy selection - + Copier la sélection + Search in SQL code - + Rechercher dans le code SQL + Toggles the output pane - + (Dés)active le volet de sortie + &Output - + S&ortie + Alt+O - Alt+O + Alt+O + + + Results - + Résultats + Messages - + + History - + Historique + No results retrieved or changes done due to the error above. - + Aucun résultat n'a été récupéré ou des modifications ont été effectuées en raison de l'erreur ci-dessus. - Messages (%1) - + + Results (%1) + Resultats (%1) - Results (%1) - + + Rows affected + Lignes affectées - [%1]: SQL command successfully executed. <em>%2 <strong>%3</strong></em> - + + Rows retrieved + Lignes récupérées - Rows affected - + + Plain format + Format simple - Rows retrieved - + + CVS format + Format CVS + + This action will wipe out all the SQL commands history for all connections! Do you really want to proceed? + Cette action effacera tout l'historique des commandes SQL pour toutes les connexions ! Voulez-vous vraiment poursuivre ? + + + Clear history - + Nettoyer l'historique - - - SQLToolWidget - Form - Formulaire + + Close the current SQL script + Fermer le script SQL actuel - Database explorer - Explorateur de bases de données + + SQL script currently handled + Script SQL actuellement géré + + + + (not saved) + (non enregistré) - Connect to server - Démarrer la connexion + + Handle external SQL script + Gérer le script SQL externe - Disconnect from server - Se déconnecter + + &Script + - Browse selected database. - Charger les informations de la base sélectionnée + + Fi&nd + &Rechercher - Drop the selected database - Supprimer la base de données sélectionnée + + Alt+X + - Shift+Del - Shift+Del + + Current working database + Base de données de travail actuelle + + + + SQLToolWidget + + + Form + Formulaire - Update the database list. - Actualiser la liste des bases de données. + + Database explorer + Explorateur de bases de données + SQL execution - Exécuteur SQL + Exécuteur de code SQL + + ... ... + Warning Avertissement - <strong>CAUTION:</strong> You are about to drop the entire database <strong>%1</strong>! All data will be completely wiped out. Do you really want to proceed? - <strong>ATTENTION:</strong> Vous êtes sur le point de supprimer l'intégralité de la base de données <strong>%1</strong>! Toutes les données seront définitivement supprimées. Détruire la base ? - - - You're running a demonstration version! The data manipulation feature is available only in the full version! - Vous utilisez la version de démonstration ! Cette fonctionnalité est disponible uniquement sur la version complète ! - - + Disconnect from all databases - + Se déconnecter de toutes les bases de données + Update the database list - + Mettre à jour la liste des bases de données + Toggle the object's attributes grid - + (Dés)active la grille des attributs de l'objet + Attributes - Attributs + Attributs + Alt+R - Alt+R + Alt+R + Toggle the display of source code pane - + (Dés)active l'affichage du volet du code source + + Source code - Code source + Code source + <strong>ATTENTION:</strong> Disconnect from all databases will close any opened tab in this view! Do you really want to proceed? - + <strong>ATTENTION :</strong> Se déconnecter de toutes les bases de données fermera tout onglet ouvert dans cette vue ! Voulez-vous vraiment poursuivre ? - SchemaWidget + SceneInfoWidget + Form - Formulaire + Formulaire + + + + + Current position of the mouse in the canvas + Position actuelle de la souris dans le canevas + + + + + + + - + + + + + + Current zoom factor + Facteur de zoom actuel + + + Currently selected object(s) + Objet(s) actuellement sélectionné(s) + + + + + Dimensions of the selected object(s) + Dimensions de(s) l'objet(s) sélectionné(s) + + + + No selection + Aucune séléction + + + + N/A + Inconnu + + + + Sel. objects: %1 + Objets select. : %1 + + + + SchemaWidget + + Show rectangle Afficher le rectangle + Fill color: - Couleur de remplissage: + Couleur de remplissage : SequenceWidget - Form - Formulaire - - + Cyclic: - Cyclique: + Cyclique : + Start: - Début: + Début : + Maximum: - Maximum: + Maximum : + Minimum: - Minimum: + Minimum : + + + + Defualt values: + + Increment: - Incrément: + Incrément : + Cache: - Cache: + Cache : + Owner Col.: - Pas mieux - Owner Col.: + Proprio. Col. : + + + + User defined + SnippetsConfigWidget + Form - Formulaire + Formulaire + Create new connection - Créer une nouvelle connexion + Créer une nouvelle connexion + Cancel edition - Annuler l'édition + Annuler l'édition + Edit selected connection - Editer la connexion sélectionnée + Modifier la connexion sélectionnée + Delete selected connection - Supprimer la connexion sélectionnée + Supprimer la connexion sélectionnée + Remove All - Tout supprimer + Tout supprimer + Shift+Del - Shift+Del + Maj+Suppr + Filter: - Filtrer: + Filtrer : + ID: - Identifiant: + Identifiant : + Add - Ajouter + Ajouter + Update - Mettre à jour + Mettre à jour + General - Général + Général + Label: - + Étiquette : + Applies to: - + S'applique à : + Parsable or dynamic snippets are written in the <strong>schema micro language</strong> syntax. When using a parsable snippet the attributes surrounded in <strong>{}</strong> will be replaced by the selected object's matching attributes. - + Les extraits de code analysables ou dynamiques sont écrits dans la syntaxe <strong>schema micro language</strong>. Lorsque vous utilisez un extrait de code analysé, les attributs entourés par des <strong>{}</strong> seront remplacés par les attributs correspondants de l'objet sélectionné. + Parsable - + Analysable + When handling parsable snippets empty attributes will be replaced by a value in the format <strong>{attribute}</strong>. Note that this option can affect the semantics of the resulting snippet. - + Lors de la manipulation d'extraits de code analysables, les attributs vides seront remplacés par une valeur au format <strong>{attribut}</strong>. Noter que cette option peut affecter la sémantique de l'extrait résultant. + Placeholders - + Élément de substitution + Parse the snippet in order to check if there are syntax errors. - + Analyser l'extrait de code afin de vérifier s'il existe des erreurs de syntaxe. + Parse - + Analyser + Snippets: - + Extraits : + General purpose - + Usage général + All snippets - + Tous les extraits + /* Error parsing the snippet '%1': %2 */ - + /* Erreur lors de l'analyse de l'extrait '%1': + + %2 */ + Duplicated snippet id <strong>%1</strong> detected. Please, specify a different one! - + Identifiant <strong>%1</strong> d'extrait dupliqué détécté. Merci d'en choisir un autre ! + Invalid ID pattern detected <strong>%1</strong>. This one must start with at leat one letter and be composed by letters, numbers and/or underscore! - + Motif d'identification <strong>%1</strong> incorrect détecté. Celui-ci doit commencer par au moins une lettre et être composé de lettres, de chiffres et/ou de tirets bas _ ! + Empty label for snippet <strong>%1</strong>. Please, specify a value for it! - + Label vide pour l'extrait <strong>%1</strong>. Merci de lui spécifier une valeur ! + Empty code for snippet <strong>%1</strong>. Please, specify a value for it! - + Code vide pour l'extrait <strong>%1</strong>. Merci de lui spécifier une valeur ! + The dynamic snippet contains syntax error(s). Additional info: <br/><em>%1</em> - + L'extrait dynamique contient des erreurs de syntax. Plus d'informations : <br/><em>%1</em> + Do you really want to remove all snippets? - + Voulez-vous vraiment supprimer tous les extraits ? + No syntax errors found in the snippet. - + Aucune erreur de syntax retrouvée dans l'extrait. SourceCodeWidget - Form - Formulaire - - + Version: - Version: + Version : + PostgreSQL PostgreSQL + iconecodigo - icone + icône + SQL SQL - XML - XML + + Original + - Type: - Type: + + XML + XML + Source code visualization Visualisation du code source + SQL code (*.sql);;All files (*.*) - Code SQL (*.sql);;Tous les fichiers (*.*) + Code SQL (*.sql);;Tous les fichiers (*.*) + Generating source code... Génération du code source... + + -- NOTE: the code below contains the SQL for the selected object +-- as well for its dependencies and children (if applicable). +-- +-- This feature is only a convinience in order to permit you to test +-- the whole object's SQL definition at once. +-- +-- When exporting or generating the SQL for the whole database model +-- all objects will be placed at their original positions. + + + + -- NOTE: le code ci-dessous contient le code SQL de l'objet sélectionné +-- ainsi que de ses dépendances et enfants (le cas échéant). +-- +-- Cette fonctionnalité n'est qu'une commodité vous permettant de tester +-- la définition SQL de l'objet entier. +-- +-- Lors de l'export ou de la génération du code SQL pour l'ensemble du modèle de base de données, +-- tous les objets seront placés à leurs positions d'origine. + + + + + + -- SQL code unavailable for this type of object -- -- Code SQL non disponible pour ce type d'objet. -- + Code display: - - - - Original - + Affichage du code : + Original + depedencies' SQL - + Original + dépendances de SQL + Original + children's SQL - + Original + enfants de SQL + Save the SQL code to a file. - + Enregistrer le code SQL dans un fichier. + Save SQL - + Enregistrer le code SQL + Save SQL code as... - - - - -- NOTE: the code below contains the SQL for the selected object --- as well for its dependencies and children (if applicable). --- --- This feature is only a convinience in order to permit you to test --- the whole object's SQL definition at once. --- --- When exporting or generating the SQL for the whole database model --- all objects will be placed at their original positions. - - - - + Enregistrer le code SQL sous... + <!-- XML code preview disabled in demonstration version --> - + < !-- Aperçu du code XML désactivé dans la version de démonstration --> + <strong>Original:</strong> displays only the original object's SQL code.<br/><br/> <strong>Dependencies:</strong> displays the original code including all dependencies needed to properly create the selected object.<br/><br/> <strong>Children:</strong> displays the original code including all object's children SQL code. This option is used only by schemas, tables and views. - + <strong>Original :</strong> affiche uniquement le code SQL de l'objet d'origine.<br/><br/> <strong>Dépendances :</strong> affiche le code d'origine ainsi que toutes les dépendances nécessaires pour créer correctement l'objet sélectionné.<br/><br/> <strong>Enfants :</strong> affiche le code original ainsi que le code SQL de tous les enfants. Cette option est utilisée uniquement par les schémas, les tables et les vues. + -- SQL code purposely truncated at this point in demo version! - + + +-- Le code SQL est volontairement tronqué à ce stade dans la version démo ! SwapObjectsIdsWidget - Form - Formulaire + + Create: + Créer : + + + + + ID: + Identifiant : + + + + Before: + Avant : + + + + Swap the values of the fields + Procède à l'échange + + + + Swap values + Échanger + + + + Change objects creation order + Changer l'ordre de création des objets + + + + Change the objects creation order is an irreversible operation and cause the operations history to be automatically erased. Note that the creation order configured in this form is not definitive and may change after a model validation. + Modifier l'ordre de création des objets est une opération irréversible qui entraîne l'effacement automatique de l'historique des opérations. Noter que l'ordre de création configuré dans ce formulaire n'est pas définitif et peut changer après la validation d'un modèle. + + + + Swap the object ids changing their creation order + Modifie l'ordre de création de deux objets en échangeant leurs numéros d'identification - Create: - Créer: + + Swap ids + Échanger identifiants - ID: - Identifiant: + + Filter: + Filtrer : - Before: - Avant: + + ID + Identifiant - It's recommended to use this feature only when the SQL validation fails in cases when a object is being referenced in portions where the ordinary validation couldn't reach, e.g., inside of a rule command or check constraint expression. - Il est recommandé d'utiliser cette fonctionnalité seulement lorsque la validation SQL échoue. C'est souvent le cas lorsque des objets possèdent des références vers d'autres objets que vous avez créé ultérieurement dans le modèle . Echanger les ID débloque la situation. + + Object + Objet - Swap the values of the fields - Procède à l'échange + + Type + - Swap values - Échanger + + Parent Object + Objet parent - Change objects creation order - + + Parent Type + Type parent Table + new_table nouvelle_table + In demonstration version tables can have only `%1' instances of each child object type or ancestor tables! You've reach this limit for the type: `%2' - + Dans la version de démonstration, les tables ne peuvent contenir que `%1' instance(s) de chaque type d'objet enfant ou table ancêtre ! Vous avez atteint cette limite pour le type : `%2' TableDataWidget + Edit table data + Modifier les données de la table + + + + Copy items on the grid + Copier les éléments sur la grille + + + + Copy + Add empty rows - + Ajouter des lignes vides - Add - Ajouter + + Add row + + Ins - Ins + Insérer - Some invalid or duplicated columns were detected. In order to solve this issue double-click the header of the highlighted ones in order to define the correct name in which the data belongs to or delete the entire column. Note that these columns are completely igored when generating the <strong>INSERT</strong> commands. - + + Ctrl+D + + Add an empty column - + Ajouter une colonne vide - Remove all rows from the grid preserving columns + + Delete rows - Clear - Effacer + + Remove all rows from the grid preserving columns + Supprimer toutes les lignes des colonnes de préservation de la grille + Shift+Del - + Maj+Suppr + Delete the selected rows - + Supprimer les lignes sélectionnées - Delete - Supprimer + + + Del + Suppr - Del - + + Duplicate the selected rows + Dupliquer les lignes sélectionnées + + + + Delete the selected columns + Supprimer les colonnes sélectionnées - <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in <span style=" font-weight:600;">{}</span>. To use <span style=" font-weight:600;">{</span> or <span style=" font-weight:600;">}</span> as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\{</span> or <span style=" font-weight:600;">\}</span>.</p></body></html> + + Delete column - Duplicate the selected rows + + Paste items on the grid + Copier les éléments sur la grille + + + + Paste + Coller + + + + Ctrl+V - Duplicate + + <html><head/><body><p>Some invalid or duplicated columns were detected. In order to solve this issue double-click the header of the highlighted ones in order to define the correct name in which the data belongs to or delete the entire column. Note that these columns are completely ignored when generating the <span style=" font-weight:600;">INSERT</span> commands.</p></body></html> - Ctrl+D + + Add column - Delete the selected columns + + Duplicate rows + + Change the values of all selected cells at once + Modifier d'un coup les valeurs de toutes les cellules sélectionnées + + + + Bulk data edit + Modification de données en masse + + + + Ctrl+E + Ctrl+E + + + Remove all columns (and rows) from the grid + Supprimer toutes les colonnes (et lignes) de la grille + + + + Delete all columns + Ctrl+Shift+Del + Ctrl+Maj+Suppr + + + + Delete all rows + Delete columns is an irreversible action! Do you really want to proceed? - + Effacer des colonnes est une action irréversible ! Voulez-vous vraiment poursuivre ? + Remove all rows is an irreversible action! Do you really want to proceed? - + Supprimer toutes les lignes est une action irréversible ! Voulez-vous vraiment poursuivre ? + Remove all columns is an irreversible action! Do you really want to proceed? - + Supprimer toutes les colonnes est une action irréversible ! Voulez-vous vraiment poursuivre ? + + Unknown column - + Colonne inconnue + Duplicated column - + Colonne dupliquée - (no columns) - + + Fills the grid using a CSV file + Remplit la grille en utilisant un fichier CSV + + + + <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in two slashes, e.g., <span style=" font-weight:600;">/value/</span>. To use a slash as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\/</span>.</p></body></html> + <html><head/><body><p>Les valeurs vides sont supposées être <span style="font-weight :600;">DEFAULT</span>. Pour utiliser des valeurs spéciales comme <span style="font-weight :600;">NULL</span>, un appel de fonction comme <span style="font-weight :600;">now()</span> ou un échappement des données spécifiques, entourer les valeurs de deux barres obliques, par exemple <span style="font-weight :600;">/valeur/</span>. Pour utiliser une barre oblique dans le cadre de la valeur, ajouter le caractère barre oblique inverse, par exemple <span style="font-weight :600;">/</span>.</p></body></html> TableObjectView + Relationship: %1 - - - - - TableView - - Connected rels: %1 - Associations: %1 + +Relations : %1 TableWidget - Form - Formulaire - - + Options Options + Tag: - Tag: + Balise : + With OID Avec OID + Generate ALTER for columns/constraints Utiliser ALTER pour les colonnes/contraintes + Unlogged Unlogged - Columns - Colonnes - - - Constraints - Contraintes - - - Triggers - Déclencheur - - - Rules - Règles - - - Indexes - Indexes - - - Tables - Tables - - + + + + + + + Name Nom + Schema Schéma + + + Type - Type + + + PK + Faut-il le traduire ? + CP + + + Default Value Valeur par défaut - Attribute - Attribut + + Attribute(s) + Attribut(s) + + It is not possible to mark a column as primary key when the table already has a primary key which was created by a relationship! This action should be done in the section <strong>Primary key</strong> of the relationship's editing form. + Il n'est pas possible de marquer une colonne comme clé primaire quand la table a déjà une clé primaire qui a été créée par une relation ! Cette action doit être effectuée dans la section <strong>Clé primaire</strong> du formulaire d'édition de la relation. + + + + It is not possible to mark a column created by a relationship as primary key! This action should be done in the section <strong>Primary key</strong> of the relationship's editing form. + Il n'est pas possible de marquer une colonne créée par une relation comme clé primaire ! Cette action doit être effectuée dans la section <strong>Clé primaire</strong> du formulaire d'édition de la relation. + + + ON DELETE - ON DELETE + Faut-il le traduire ? + À la suppression + ON UPDATE - ON UPDATE + Faut-il le traduire ? + À la mise à jour + Refer. Table - Table référ. + Table de référ. + Firing Déclencheur + Events Evènements + Execution Exécution + Event Evènement + Indexing Indexation + + Command + Commande + + + + Permissive + Permissif + + + + USING expression + Faut-il le traduire ? + + + + + CHECK expression + Faut-il le traduire ? + + + + + Roles + Rôles + + + Parent - Parent + + Copy Copie + + Yes + Oui + + + + No + Non + + + &Columns - + &Colonnes + Co&nstraints - + Co&ntraintes + Tri&ggers - + Décl&encheurs + &Rules - + &Régles + &Indexes - + &Index + &Tables - + &Tables + Edit data - + Modifier données + Define initial data for the table - + Définir les données initiales de la table + + + + Enable row level security + Activer la sécurité au niveau de la ligne + + + + Force RLS for owner + Forcer RLS pour le propriétaire + + + + &Policies + &Politiques TablespaceWidget + Form Formulaire + Directory: - Dossier: + Dossier : TagWidget - Form - Formulaire - - + Colors Couleurs + Extended body: - Corps étendu: + Corps étendu : + Body: - Corps: + Corps : + Title: - Titre: + Titre : + Schema name: - Nom du schéma: + Nom du schéma : + Table name: - Nom de la table: + Nom de la table : TaskProgressWidget + Executing tasks Exécution des tâches + + Waiting task to start... En attente du démarrage de la tâche ... @@ -10374,633 +13463,727 @@ Relationship: %1 TextboxWidget - Form - Formulaire - - + Font: - Police: + Police : + Text Texte + pt pt + Color: - Couleur: + Couleur : + Bold Gras + Italic Italique + Underline Souligné + Select text color - Sélection de la couleur de texte + Sélection de la couleur du texte TriggerWidget - Form - Formulaire - - + Event: - Evènement: + Évènement : + INSERT INSERT + DELETE DELETE + UPDATE UPDATE + TRUNCATE TRUNCATE + Deferrable: - Différable: + Reportable : + Columns Colonnes + Column: - Colonne: + Colonne : + Arguments Arguments + Constraint Contrainte + FOR EACH ROW Pour chaque ligne + Refer. Table: - Table référ.: + Table référ. : + Condition: - Condition: + Condition : + Argument: - Argument: + Argument : + Function: - Fonction: + Fonction : + Options: - Options: + Options : + Excution: - Excution: + Exécution : + Column Colonne + Type - Type + TypeWidget - Form - Formulaire - - + Configuration: - Configuration: + Configuration : + Base Type Type de base + Enumeration - Enumération - - - Composite - Composite + Énumération + Enumerations Énumérations + Enumeration: - Énumeration: + Énumération : + + + Attributes Attributs + Internal Length: - Long. interne: + Long. interne : + Storage: - Stockage: + Stockage : + Category: - Catégorie: + Catégorie : + Delimiter: - Délimiteur: + Délimiteur : + Alignment: - Alignement: + Alignement : + char char + smallint smallint + integer integer + double precision - double precision + double précision + Default Value: - Valeur par défaut: + Valeur par défaut : + Range - Interval + Intervalle + Options: - Options: + Options : + By value Par valeur + Preferred Préféré + Collatable - Collatable + Assemblable + Functions Fonctions + INPUT: - INPUT: + INPUT : + OUTPUT: - OUTPUT: + OUTPUT : + RECV: - RECV: + RECV : + SEND: - SEND: + SEND : + TPMOD_IN: - TPMOD_IN: + TPMOD_IN : + TPMOD_OUT: - TPMOD_OUT: + TPMOD_OUT : + ANALYZE: - ANALYZE: + ANALYZE : + Name: - Nom: + Nom : + Collation: - Collation: + Collation : + Subtype Diff Func.: - Fonction de différence du sous-type: + Fonction de différence du sous-type : + Operator Class: - Classe d'opérateurs: + Classe d'opérateurs : + Canonical Func.: - Fonction canonique: + Fonction canonique : + Like Type - Type de Like + Type de Like + Element Type Type d'élement + Subtype Sous-type + Name Nom + Type - Type + + Collation - Collation + + The functions to be assigned to a type should be written in C language and possess, respectively, the following signatures:<br/> <table> <tr> <td><strong>INPUT:</strong> <em>any function(cstring, oid, integer)</em></td> <td><strong>OUTPUT:</strong> <em>cstring function(any)</em></td> </tr> <tr> <td><strong>SEND:</strong> <em>byta function(any)</em></td> <td><strong>RECV:</strong> <em>any function(internal, oid, integer)</em></td> </tr> <tr> <td><strong>TPMOD_IN:</strong> <em>integer function(cstring[])</em></td> <td><strong>TPMOD_OUT:</strong> <em>cstring function(integer)</em></td> </tr> <tr> <td><strong>ANALYZE:</strong> <em>boolean function(internal)</em></td> <tr> </table> - La fonction assignée à un type devrait être écrite en langage C et possèder, les signatures respective suivantes:<br/> <table> <tr> <td><strong>INPUT:</strong> <em>any fonction(cstring, oid, integer)</em></td> <td><strong>OUTPUT:</strong> <em>cstring fonction(any)</em></td> </tr> <tr> <td><strong>SEND:</strong> <em>byta fonction(any)</em></td> <td><strong>RECV:</strong> <em>any fonction(internal, oid, integer)</em></td> </tr> <tr> <td><strong>TPMOD_IN:</strong> <em>integer fonction(cstring[])</em></td> <td><strong>TPMOD_OUT:</strong> <em>cstring fonction(integer)</em></td> </tr> <tr> <td><strong>ANALYZE:</strong> <em>boolean fonction(internal)</em></td> <tr> </table> + Les fonctions assignées à un type devraient être écrites en langage C et possèder, les signatures suivantes :<br/> <table> <tr> <td><strong>INPUT:</strong> <em>any function(cstring, oid, integer)</em></td> <td><strong>OUTPUT:</strong> <em>cstring function(any)</em></td> </tr> <tr> <td><strong>SEND:</strong> <em>byta function(any)</em></td> <td><strong>RECV:</strong> <em>any function(internal, oid, integer)</em></td> </tr> <tr> <td><strong>TPMOD_IN:</strong> <em>integer function(cstring[])</em></td> <td><strong>TPMOD_OUT:</strong> <em>cstring function(integer)</em></td> </tr> <tr> <td><strong>ANALYZE:</strong> <em>boolean function(internal)</em></td> <tr> </table> + The functions to be assigned to a range type should have the following signatures:<br/><br/><strong>Canonical:</strong> <em>any function(any)</em> <br/><strong>Subtype Diff:</strong> <em>double precision function(subtype, subtype)</em> - Les fonction assignables au type interval (RANGE) doivent avoir la signature suivante:<br/><br/><strong>Canonique:</strong> <em>any function(any)</em> <br/><strong>Subtype Diff:</strong> <em>double precision function(subtype, subtype)</em> + Les fonction assignables au type plage (RANGE) doivent avoir la signature suivante :<br/><br/><strong>Canonical:</strong> <em>any function(any)</em> <br/><strong>Subtype Diff:</strong> <em>double precision function(subtype, subtype)</em> + Co&mposite - + Co&mposite UpdateNotifierWidget + Update Notifier Vérificateur de mise à jour - New update found! - Nouvelle mise à jour disponible! - - + Hide this widget Cacher ce widget + ... ... + Released in: - Date de sortie: + Date de sortie : + mmm dd, yyyy - dd mmm yyyy - - - Version: - Version: + jj mmm aaaa + 0.0.0 0.0.0 + Changelog Journal des modifications + Redirects to purchase page. Redirige vers la page web pour acheter. + Get binary package Télécharger l'application compilée + Redirects to GitHub source repository. Redirige vers la page web du dépôt GitHub. + Get source code Télécharger le code source - <strong>Note:</strong> Both actions below will open a new web browser window - <strong>Remarque:</strong> Ces boutons entraînent l'ouverture de votre navigateur web - - - Purchase a new package - Acheter un nouveau paquet - - + + Failed to check updates Impossible de vérifier la présence de mise à jour - The update notifier failed to check for new versions! Please, verify your internet connectivity and try again! Connection error returned: <strong>%1</strong>. - Le vérificateur de mise à jour n'a pas pu vérifier la présence de nouvelles versions ! Vérifiez votre connexion à Internet et réessayez ! Code d'erreur retourné : <strong>%1</strong>. + + The update notifier failed to check for new versions! Please, verify your internet connectivity and try again! Connection error returned: <em>%1</em> - <strong>%2</strong>. + Le notificateur de mise à jour n'a pas pu vérifier les nouvelles versions ! Merci de vérifier votre connexion internet et de réessayer ! Erreur de connexion renvoyée : <em>%1</em> - <strong>%2</strong>. + No updates found - Aucune mise à jour disponible + Aucune mise à jour trouvée + You are running the most recent pgModeler version! No update needed. Vous utilisez déjà la version de pgModeler la plus récente ! Aucune mise à jour requise. + The update notifier failed to check for new versions! A HTTP status code was returned: <strong>%1</strong> Le vérificateur de mise à jour n'a pas pu vérifier la présence de nouvelles versions ! Code retour HTTP reçu : <strong>%1</strong> - Recover a package - - - + Update found! - + Mise à jour trouvée ! + New version: - + Nouvelle version : ViewWidget - Form - Formulaire - - + References Références + Column Colonne + Expression Expression + Used in: - Utilisé dans: + Utilisé dans : + Reference Type: - Type de référence: - - - SELECT-FROM - SELECT-FROM - - - FROM-WHERE - FROM-WHERE - - - After WHERE - Après WHERE + Type de référence : + View Definition Définition de la vue + Options Options + Tag: - Tag: + Balise : + Mode: - Mode: + Mode : + Ordinary Ordinaire - Recursive - Récursif - - - Materialized - Matérialisée - - + With no data - With no data + Sans données + Table: - Table: + Table : + Table Alias: - Alias table: + Alias table : + Column: - Colonne: + Colonne : + Column Alias: - Alias colonne: + Alias colonne : + Expression: - Expression: + Expression : + Expression Alias: - Alias expression: + Alias expression : + + + + SELECT ... + Faut-il le traduire ? + + + + + WHERE ... + Faut-il le traduire ? + + + FROM ... + Faut-il le traduire ? + + + + Triggers Déclencheur + Rules Règles + + Indexes + + + + Table Expression CTE + Code Preview Prévisualisation du code + + Alias Col. + Alias col. + + + Col./Expr. - Col./Expr. + + Alias - Alias + - Alias Col. - Alias col. + + Flags: SF FW AW EX VD + Marques : SF FW AW EX VD - Flags: SF FW AW VD - Flags: SF FW AW VD + + To reference all columns in a table (*) just do not fill the field <strong>Column</strong>, this is the same as write <em><strong>[schema].[table].*</strong></em> + Pour référencer toutes les colonnes d'une table (*), ne pas remplir le champ <strong>Colonne</strong> revient à écrire <em><strong>[schema].[table].*</Strong></em> + + + Name Nom + Refer. Table - Table référ. + Table de référ. + Firing Déclenche + Events Evènements + + Indexing + Indexation + + + Execution Exécution + Event Evènement + /* Could not generate the SQL code. Make sure all attributes are correctly filled! - /* Le code SQL ne peut être généré. Vérifiez que les champs sont correctement remplis! - - - To reference all columns in a table (*) just do not fill the field <strong>Column</strong>, this is the same as write <em><strong>[schema].[tablel].*</strong></em> - Pour référencer toutes les colonnes dans une table (*) ne remplissez pas le champs <strong>Colonne</strong>, ceci revient à écrire <em><strong>[schéma].[table].*</strong></em> + /* Le code SQL ne peut être généré. Vérifiez que les champs sont correctement remplis ! + Recursi&ve - + Récursi&f + &Materialized - - - - - WelcomeWidget - - Form - Formulaire + &Matérialiser - New model - Nouveau modèle + + The element will be used as part of the SELECT statement to retrieve columns or expressions that will compose the view's columns + L'élément sera utilisé dans le cadre de l'instruction SELECT pour extraire des colonnes ou des expressions qui composeront les colonnes de la vue. - Open model - Ouvrir modèle + + The element will be used as part of the WHERE clause in form of conditional expression + L'élément sera utilisé dans le cadre de la clause WHERE sous forme d'expression conditionnelle. - Sample models - Modèles de démo + + The element is used in the FROM portion of the command in order to reference tables or construct JOIN statements + L'élément est utilisé dans la partie FROM de la commande afin de référencer des tables ou de construire des instructions JOIN. - Recent models - Modèles récents + + The element's expression is used exclusively as the view's definition + L'expression de l'élément est utilisée exclusivement comme définition de la vue. - Last session - Dernière session + + The element will be appended to the very end of the view's definition. This is useful when using GROUP BY/HAVING statements + L'élément sera ajouté à la fin de la définition de la vue. Ceci est utile lors de l'utilisation des instructions GROUP BY/HAVING. - - - Xml2Object - Xml2Object - Xml2Object + + End expression + Expression finale - Xml2ObjectWidget - - XML2Object - XML2Object - + WelcomeWidget - Load XML - Charger XML + + Form + Formulaire - Clear - Effacer + + New model + Nouveau modèle - Generate - Générer + + Open model + Ouvrir modèle - Close - Fermer + + Sample models + Modèles de démo - Database model (*.dbm);;XML file (*.xml);;All files (*.*) - Modèle de base de données (*.dbm);;Fichier XML (*.xml);;Tous les fichiers (*.*) + + Recent models + Modèles récents - Load file - Charger un fichier + + Last session + Dernière session diff --git a/lang/nl_NL.qm b/lang/nl_NL.qm index 5a3df20d0b..d5035fc200 100644 Binary files a/lang/nl_NL.qm and b/lang/nl_NL.qm differ diff --git a/lang/nl_NL.ts b/lang/nl_NL.ts index 83dfa028b2..0d901913f3 100644 --- a/lang/nl_NL.ts +++ b/lang/nl_NL.ts @@ -9,250 +9,63 @@ Over pgModeler - + + 0.0.0 + 0.0.0 + + + + build: + + + + PostgreSQL Database Modeler PostgreSQL Database Modeler - + Open source data modeling tool designed for PostgreSQL. No more DDL commands written by hand, let pgModeler do the job for you! This software reunites the concepts of entity-relationship diagrams and the features that PostgreSQL implements as extensions of SQL standards. Een Open Source data modeleer tool ontworpen voor PostgreSQL. Met pgModeler hoef je niet langer zelf je DDL commando's schrijven, laat dit over aan pgModeler! Deze software brengt de concepten van Entity-Relationship diagrammen samen met de features die PostgreSQL implementeerd als uitbreidingen van de SQL standaard. - - Design, configure, deploy - Ontwerp, configureer, implementeer - - - - pgModeler is proudly a brazilian software! - pgModeler is trotse braziliaanse software! + + <html><head/><body><p><a href="http://pgmodeler.com.br"><span style=" text-decoration: underline; color:#2980b9;">https://pgmodeler.io</span></a></p></body></html> + - - <a href="http://pgmodeler.com.br">http://pgmodeler.com.br</a> + + <html><head/><body><p>Copyright 2006-2018 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.io</span></a>&gt;</p></body></html> - - <html><head/><body><p>Copyright 2006-2016 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.com.br</span></a>&gt;</p></body></html> - + + pgModeler is proudly a brazilian software! + pgModeler is trotse braziliaanse software! - + Hide this widget Verberg dit widget - + ... - - 0.0.0.0 - - - - - (CODE_NAME) - - - - - Build: - - - - + (BUILD_NUM) - + License Licensie - - - Contributors - Medewerkers - - - - <html><head/><body><p>This page is dedicated to all contributors who gave a bit of their time in make pgModeler a better software somehow. The complete list of people that helped pgModeler can be found at <a href="https://github.com/pgmodeler/pgmodeler/graphs/contributors"><span style=" text-decoration: underline; color:#00a489;">GitHub</span></a>.</p><p>If you have a great idea to improve pgModeler please submit it <a href="http://github.com/pgmodeler/pgmodeler/issues"><span style=" text-decoration: underline; color:#00a489;">here</span></a>. No ideas for now but want to help? Why not donate a few bucks <a href="http://pgmodeler.com.br/#donate"><span style=" text-decoration: underline; color:#00a489;">here</span></a>!?</p></body></html> - <html><head/><body><p>Deze pagina is opgedragen aan alle medewerkers die een beetje van hun tijd opofferden om pgModeler te verbeteren op verschillende manieren. De volledige lijst van individuen die meewerken aan pgModeler is terug te vinden op <a href="https://github.com/pgmodeler/pgmodeler/graphs/contributors"><span style=" text-decoration: underline; color:#00a489;">GitHub</span></a>.</p><p>Indien je een geweldig idee hebt om pgModeler te verbeteren, <a href="http://github.com/pgmodeler/pgmodeler/issues"><span style=" text-decoration: underline; color:#00a489;">aarzel dan niet om het ons te laten weten</span></a>. Geen idee hoe je ons kan helpen? Waarom geen kleine bijdrage <a href="http://pgmodeler.com.br/#donate"><span style=" text-decoration: underline; color:#00a489;">storten</span></a>!?</p></body></html> - - - - 1 - - - - - 2 - - - - - 3 - - - - - 4 - - - - - 5 - - - - - 6 - - - - - 7 - - - - - 8 - - - - - Name - Naam - - - - Country - Land - - - - Contribution - Bijdrage - - - - Damien Degois - - - - - - - France - Frankrijk - - - - French UI translation and several improvements in auxiliary scripts. - Franse vertaling en verschillende verbeteringen in scripts. - - - - Ji Bin - - - - - China - China - - - - Chinese UI translation and small fixes. - Chinese vertaling en kleine verbeteringen. - - - - Pierre-Samuel LE STANG - - - - - - French UI translation. - Franse vertaling. - - - - Lisandro Damián Nicanor - - - - - Argentina - Argentinië - - - - Improvements on build scripts enabling the custom packaging in Linux distros; Per-user settings; pgModeler's package maintainer in Debian Linux. - Aanpassingen aan de build script die aangepaste verpakking for Linux distro's mogelijk maakt; per-user instellingen; Debian Linux package maintainer voor pgModeler. - - - - Pavel Alexeev - - - - - Russia - Rusland - - - - Additional work for packaging in Linux distros; pgModeler's package maintainer in Fedora Linux. - Bijkomend werk voor Linux Distro verpakking; Fedora Linux package maintainer voor pgModeler. - - - - Mariusz Fik - - - - - Poland - Polen - - - - Custom packaging first ideas. Tester of first version of custom packaging patch. - Eerste ideëen betreffende aangepaste verpakkingen. Tester van de eerste versie van de aangepaste verpakkingen patch. - - - - Jonathan DUPRE - - - - - Gilberto Castillo - - - - - Cuba - Cuba - - - - Spanish UI translation. - Spaanse vertaling. - AggregateWidget - - Form - Venster - Final Function: @@ -294,7 +107,7 @@ Status Data Type - + An aggregate function that accepts the types <em><strong>typeA</strong></em> and <em><strong>typeB</strong></em> as input types and which type of state is <em><strong>state_type</strong></em>, must obey the following rules: <br/><br/> <strong> &nbsp;&nbsp;&nbsp;• Final Function:</strong> <em>void final_function(<strong>state_type</strong>)</em><br/> <strong> &nbsp;&nbsp;&nbsp;• Transition Function:</strong> <em><strong>state_type</strong> transition_function(<strong>state_type</strong>, <strong>typeA</strong>, <strong>typeB</strong>)</em> Een aggregatie-funtie die de types <em><strong>typeA</strong></em> en <em><strong>typeB</strong></em> als invoer aanvaardt en waarvan het status-type <em><strong>status_type</strong></em> is. De volgende regels moeten voldaan zijn: <br/><br/> <strong>&nbsp;&nbsp;&nbsp;• Finale Functie:</strong> <em>void finale_functie(<strong>status_type</strong>)</em><br/> <strong>&nbsp;&nbsp;&nbsp;• Overgangsfunctie:</strong> <em><strong>status_type</strong> transitie_functie(<strong>status_type</strong>, <strong>typeA</strong>, <strong>typeB</strong>)</em> @@ -408,181 +221,191 @@ + Constraint: Name + + + + + Constraint: Descriptor + + + + View: Schema name View: Schemanaam - + View: View name View: View-naam - + View: References box View: Referenties box - + View: Extended attributes box View: Uitgebreide attributen box - + View: Title box View: Titel box - + View: Table / columns alias View: Tabel / Kolom alias - + View: Referenced column View: Gerefereerde kolom - + View: Referenced table View: Gerefereerde tabel - + View: Reference descriptor View: Referentiebeschrijving - + Textbox: Body Tekst box: Inhoud - + Column: Column name Kolom: Kolom naam - + Column: Descriptor Kolom: Beschrijving - + Column: Included / Inherited by relationship Kolom: Ingesloten / Overgeërfd via relatie - + Column: Protected Kolom: Beschermd - + Column (pk): Column name Kolom (pk): Kolom naam - + Column (pk): Descriptor Kolom (pk): Beschrijving - + Column (fk): Column name Kolom (fk): Kolom naam - + Column (fk): Descriptor Kolom (fk): Beschrijving - + Column (uq): Column name Kolom (uq): Kolom naam - + Column (uq): Descriptor Kolom (uq): Beschrijving - + Column (nn): Column name Kolom (nn): Kolom naam - + Column (nn): Descriptor Kolom (nn): Beschrijving - + Relationship: Descriptor Relatie: Beschrijving - + Relationship: Label text Relatie: Label tekst - + Relationship: Label box Relatie: Label box - + Relationship: Attribute text Relatie: Attribuut tekst - + Relationship: Attribute descriptor Relatie: Attribuut beschrijving - + Tag: Name Tag: Naam - + Tag: Body Tag: Inhoud - + Placeholder: Body - + Font: Lettertype: - + Colors: Kleuren: - + pt pt - + Underline Onderstrepen - + Italic Cursief - + Bold Vet @@ -590,16 +413,24 @@ Application - + Unknown exception caught! Een onbekende uitzondering trad op! - + Failed to create initial configuration in `%1'! Check if the current user has write permission over that path and at least read permission over `%2'. De initiële configuratie kon niet worden gecreëerd in `%1'! Kijk na of de huidige gebruiker schrijf-machtigingen heeft op dit pad en minstens lees-machtigingen op '%2'. + + BaseConfigWidget + + + A backup of the previous settings was saved into <strong>%1</strong>! + + + BaseForm @@ -624,7 +455,7 @@ &Ok - + %1 properties @@ -632,167 +463,177 @@ BaseObject - + Column Kolom - + Constraint Constraint - + Function Functie - + Trigger Trigger - + Index Index - + Rule Regel - + Table Tabel - + View View - + Domain Domein - + Schema Schema - + Aggregate Aggregator - + Operator Operator - + Sequence Sequentie - + Role Rol - + Conversion Conversie - + Cast Cast - + Language Taal - + Type Type - + Tablespace Tablespace - + Operator Family Operator Familie - + Operator Class Operator Klasse - + Database Database - + Collation Sortering - + Extension Uitbreiding - + Event Trigger Event Trigger - + Relationship Relatie - + + Policy + + + + Textbox Tekst box - + Permission Machtiging - + Parameter Parameter - + Type Attribute Type Attribuut - + Tag Tag - + Basic Relationship Basisrelatie + + + Generic SQL + + - + new_object nieuw_object @@ -803,17 +644,13 @@ BaseObjectView - + SQL off SQL uit BaseObjectWidget - - Form - Venster - Name: @@ -825,114 +662,119 @@ Commentaar: - + Tablespace: Tablespace: - + Schema: Schema: - + Edit object's permissions Machtiginen voor dit object aanpassen - + Edit permissions Machtigingen aanpassen - + This object is protected thus no change in form will be applied to it. Dit object is beschermd en dus worden vorm-aanpassingen niet toegepast. - + Disables the generated SQL code using comment tokens (--). This will disable the code of all child and referrer objects. Maakt de gegenereerde SQL code onuitvoerbaar via comment-tokens (--). Dit zorgt ervoor dat de code voor alle kinder-objecten en refererende objecten wordt uitgeschakeld. - + Disable SQL code Niet-uitvoerbare SQL code - + Collation: Sortering: - + Append or prepend a set of SQL commands to the object's definition. Voeg SQL commando toe voor of na de definitie van het object. - + Custom SQL Aangepaste SQL - + Owner: Eigenaar: - + ID: ID: - + icone icone - Create / Edit: - Creëer / Pas aan: - - - + Required field. Leaving this empty will raise errors! Vereist veld. Dit veld leeglaten leidt tot foutmeldingen! - + Value(s) Waarde(s) - + Version Versie - + The <em style='color: %1'><strong>highlighted</strong></em> fields in the form or one of their values are available only on specific PostgreSQL versions. Generating SQL code for versions other than those specified in the fields' tooltips may create incompatible code. - - The <em style='color: %1'><strong>highlighted</strong></em> fields on the form are available only on specific PostgreSQL versions. When generating SQL code for versions other than those specified on fields' tooltips pgModeler will ignore their values. - De <em style='color: %1'><strong>aangeduidde</strong></em> velden zijn enkel beschikbaar in specifieke versies van PostgreSQL. Wanneer SQL code voor andere versies wordt gegenereerd zal pgModeler deze negeren. - BaseRelationship - + rel_%1_%2 rel_%1_%2 - BugReportForm + BaseTableView - - Bug Report + + Toggles the extended attributes display + + + + + Connected rels: %1 + Verbonden relaties: %1 + + + + BugReportForm + + + Bug Report Bug Rapport @@ -991,10 +833,6 @@ Dit zorgt ervoor dat de code voor alle kinder-objecten en refererende objecten w Database Model Database Model - - In none occasion the models sent within the report will be published. They are kept safe and are used only for debug purpose. - Database modellen die u ons opstuurt worden onder geen enkel beding gepubliceerd. Deze worden op een veilige manier bewaard door de ontwikkelaars en worden enkel geraadpleegd voor debugging doeleinden. - Attach the below database model file to be debugged. @@ -1027,15 +865,15 @@ Dit zorgt ervoor dat de code voor alle kinder-objecten en refererende objecten w - CastWidget - - Form - Venster - + BulkDataEditWidget - Implicit - Impliciet + + Bulk data edit + + + + CastWidget I&mplicit @@ -1066,10 +904,6 @@ Dit zorgt ervoor dat de code voor alle kinder-objecten en refererende objecten w E&xplicit - - Explicit - Expliciet - Source data type @@ -1086,62 +920,31 @@ Dit zorgt ervoor dat de code voor alle kinder-objecten en refererende objecten w De functie die wordt gebruikt bij den cast van <em><strong>typeA</strong></em> naar <em><strong>typeB</strong></em> moet de volgende signature hebben:: <em><strong>typeB</strong> functie(<strong>typeA</strong>, integer, boolean)</em>. - - CentralWidget - - Form - Venster - - - New model - Nieuw model - - - Open model - Open model - - - Sample models - Voorbeeldmodellen - - - Recent models - Recente modellen - - - Last session - Vorige sessie - - CodeCompletionWidget - - Make persistent - Maakt blijvend + + Make &persistent + - + Makes the widget closable only by ESC key or mouse click on other controls. Zorgt ervoor dat widgets enkel kunnen worden gesloten via de ESC toets of via een muisklik op andere controls. - + SQL Keyword SQL Sleutelwoord - + (no items found.) (geen items gevonden.) CollationWidget - - Form - Venster - Locale: @@ -1199,41 +1002,40 @@ Dit zorgt ervoor dat de code voor alle kinder-objecten en refererende objecten w ColumnWidget - - Form - Venster - Default Value: Standaardwaarde: - - E&xpression: + + Edit the underlying sequence's attributes - - &NOT NULL + + Edit sequence - - Se&quence: + + Identity: - Expression: - Expressie: + + E&xpression: + - NOT NULL - NOT NULL + + &NOT NULL + - Sequence: - Sequentie: + + Se&quence: + @@ -1254,42 +1056,52 @@ Dit zorgt ervoor dat de code voor alle kinder-objecten en refererende objecten w Relaties - + Appearance Voorkomen - + Connections Verbindingen - + Snippets Snippets - + Plug-ins Plug-ins - + Defaults Standaard waarden - + &Apply &Toepassen - + &Cancel &Annuleren + In some cases restore the default settings related to it may solve the problem. Would like to do that? + + + + + Restore + + + + Any modification made until now in the current section will be lost! Do you really want to restore default settings? De waarden in de huidige sectie zullen worden overschreven! Bent u er zeker van dat u de standaard waarden wilt instellen? @@ -1297,129 +1109,117 @@ Dit zorgt ervoor dat de code voor alle kinder-objecten en refererende objecten w ConnectionsConfigWidget - Form - Venster - - - + Password: Wachtwoord: - + Connection Alias: Verbindingsalias: - + Connection DB: Verbinding DB: - + Host/Port: Host/Poort: - + User: Gebruiker: - + Timeout: Timeout: - + SSL Mode: SSL Modus: - + Disable Uit - + Diff Diff - + Export Exporteer - + Import Importeren - + Validation - + Security - + Allow Toegelaten - + Require Vereist - + AC verification AC verificatie - + Full verification Volledige verificatie - + Kerberos Server: - + Client Certificate: Client Certificaat: - + Revoked Certs.: Herroepen Certs: - + Client Key: Client Sleutel: - + Root Certificate: Root Certificaat: - Options: - Opties: - - - Kerberus Server: - Kerberos Server: - - - + ~/.postgresql/root.crt @@ -1429,42 +1229,42 @@ Dit zorgt ervoor dat de code voor alle kinder-objecten en refererende objecten w Verbindingen: - + second(s) Second(en) - + Force GSSAPI Forceer GSSAPI - + ~/.postgresql/postgresql.crt - + Add Toevoegen - + Update Updaten - + Test Test - + ~/.postgresql/root.crl - + ~/.postgresql/postgresql.key @@ -1475,7 +1275,7 @@ Dit zorgt ervoor dat de code voor alle kinder-objecten en refererende objecten w - + Edit database connections @@ -1505,27 +1305,27 @@ Dit zorgt ervoor dat de code voor alle kinder-objecten en refererende objecten w Algemeen - + Other params: - + Specify additional connection parameters in the form [param]=[value]. These parameters are described in the <strong>libpq</strong> chapter at PostgreSQL docs. - + Default for: - + Automatically browses the named database when using this connection to manage databases on <strong>Manage</strong> view. Bladert automatisch door de genoemde database wanneer deze verbinding wordt gebruikt om databases te beheren via de <strong>Beheer</strong> view. - + Auto browse @@ -1535,54 +1335,44 @@ Dit zorgt ervoor dat de code voor alle kinder-objecten en refererende objecten w - + Success Success - - Connection successfuly stablished! + + Connection successfully established! Server details: PID: `%1' Protocol: `%2' Version: `%3' - De verebinding werd aangemaakt! - -Details Server: - -PID: `%1' -Protocol: `%2' -Versie: `%3' + - + There is a connection being created or edited! Do you want to save it? Wenst u de nieuwe of aan te passen verbinding op te slaan vooraleer verder te gaan? - + Found %1 connection(s) %1 verbinding(en) gevonden - + No connections found Geen verbindingen gevonden - + Edit connections ConstraintWidget - - Form - Venster - Match: @@ -1665,29 +1455,25 @@ Versie: `%3' Vul-factor: - - + + Column Kolom - - + + Type Type - + Columns which were included by relationship can not be added / removed manually from the primary key. If done such changes they can raise errors. To create primary key using columns included by relationship use the following options: identifier field, attributes & constraints tab or primary key tab on the relationship form. Kolommen die werden ingesloten via relaties kunnen niet manueel worden toegevoegd aan of verwijderd uit de primaire sleutel. Dit soort aanpassingen kan tot fouten leiden. Om een primaire sleutel aan te maken via kolommen die werden ingesloten door relaties, gebruik de volgende opties: identifier veld, attributen & constraints tab-blad of primaire sleutel tab=blad in het relatie-venster. ConversionWidget - - Form - Venster - Source Encoding: @@ -1717,77 +1503,171 @@ Versie: `%3' CrashHandlerForm - + Crash Handler Crash Handler - + Stack trace Stack trace - + Input: Invoer: - + Load report file for analysis Laad rapport bestand voor analyze - + Save the attached model file on the filesystem Bewaar het ingevoegde model bestaand op het bestandssysteem - + pgModeler bug report (*.bug);;All files (*.*) pgModeler bug rapport (*.bug);;Alle bestanden (*.*) - + Load report Laad rapport - + Save model Bewaar model - + Database model (*.dbm);;All files (*.*) Database model (*.dbm);;Alle bestanden (*.*) - + Crash handler Crash Handler - + Bug report analysis mode activated. Bug rapport analyze modus is geactiveerd. - + Oops! pgModeler just crashed! Oeps! pgModeler crashte! - + We apologize for what happened! It is clear that a nasty bug caused that. Please fill out the form below describing your actions before pgModeler quit unexpectedly. This will help on bug extermination and improve the software. We verontschuldigen ons voor wat net gebeurde! Het is overduidelijk dat een ernstige bug dit veroorzaakte. Gelieve het formuleer hieronder in te vullen met een beschrijving van wat u deed vooraleer pgModeler onverwachts afsloot. Dit zal ons helpen om deze bug te corrigeren en de software te verbeteren. - CustomSQLWidget + CsvLoadWidget + Form - Venster + Venster + + + + Load CSV + + + + + CSV File: + + + + + Select output file + Selecteer uitvoerbestand + + + + ... + ... + + + + Separator: + + + + + Use the first row as column names in the CSV file. By unchecking this option the first row is used as data. + + + + + Columns in the first row + + + + + Load + Laden + + + + Semicolon (;) + + + + + Comma (,) + + + + + Space + Spatie + + + + Tabulation + + + + + Other + + + + + ; + + + + + Text delimiter: + + + + + " + + + + + Load CSV file + + + + + Comma-separted values (*.csv);;All files (*.*) + + + + CustomSQLWidget Add custom SQL code @@ -1877,56 +1757,47 @@ Deze optie afvinken zorgt ervoor dat de SQL wordt ingevoegd na het CREATE DATABA <html><head/><body><p>Wees voorzichtig bij het gebruik van aangepaste SQL. Dit kan leiden tot een verandering van de betekenis van het volledige model wanneer SQL validatie wordt uigevoerd of wanneer het model wordt geëxporteerd. Het is ook mogelijk, afhankelijk van de hoeveelheid commando's, dat de prestaties van deze processen voelbaar en negatief kunnen worden beïnvloed.</p></body></html> - Append / Prepend SQL code - Voeg SQL code voor/na - - - - Type: - Type: - - - + Generic INSERT Generische INSERT - + Include serial columns Sluit seriële kolommen in - + Exclude serial columns Sluit seriële kolommen uit - + Generic SELECT Generische SELECT - + Table SELECT Tabel SELECT - + Generic UPDATE Generische UPDATE - + Table UPDATE Tabel UPDATE - + Generic DELETE Generische DELETE - + Table DELETE Tabel DELETE @@ -1944,339 +1815,348 @@ Deze optie afvinken zorgt ervoor dat de SQL wordt ingevoegd na het CREATE DATABA &Sluiten - Rows returned: - Aantal rijen: - - - 0 - 0 - - - Maximum limit of listed rows - Maximum limit van weergegeven rijen - - - (Limit: 0) - (Limiet: 0) - - - Empty values are assumed as <strong>DEFAULT</strong>. To use special values like <strong>NULL</strong>, a function call like <strong>now()</strong> or a specific data escaping, enclose values in <strong>&lt;&gt;</strong>. To use <strong>&lt;</strong> or <strong>&gt;</strong> as part of the value prepend the backslash character, e.g., <strong>\&lt;</strong> or <strong>\&gt;</strong>. - Een lege waarde wordt verondersteld <strong>DEFAULT</strong> te zijn. Om speciale waarden zoals <strong>NULL</strong>, een functie-aanroep zoals <strong>now()</strong> of een specifieke data-escaping te gebruiken, sluit deze waarden in tussen<strong>&lt;&gt;</strong>. Om <strong>&lt;</strong> of <strong>&gt;</strong> te gebruiken als deel van een waarde, voeg een backslash toe voor de waarde, bv., <strong>\&lt;</strong> of <strong>\&gt;</strong>. - - - + Refresh listing De lijst wordt vernieuwd - - Refresh - Vernieuwen - - - + F5 F5 - + Save changes Aanpassingen opslaan - - Save - Opslaan - - - + Ctrl+S Ctrl+S - - Copy the selection as CSV buffer - Kopieer de selectie als CSV buffer - - - - Copy - Kopieer - - - - Ctrl+C - Ctrl+C - - - + Export results to CSV file Exporteer de resultaten naar een CSV bestand - - Export - Exporteer - - - + Ctrl+X Ctrl+X - + Undo modifications Aanpassingen ongedaan maken - - Undo - Ongedaan maken - - - + Ctrl+Z Ctrl+Z - Add data - Data toevoegen - - - - Add - Toevoegen - - - - + + Ins Ins - + Mark the selected rows to be deleted Markeer de geselecteerde rij als 'te verwijderen' - - - Delete - Verwijderen - - - - - - - + + + + + Del Del - + Duplicate the selected rows - - Duplicate + + Ctrl+D - - Ctrl+D + + Add new rows from a CSV file - + Filter the result set Filter de resultaten - + Table: Tabel: - + Schema: Schema: - + in in - + Hide views Verberg views - + Filter expression Filterexpressie - + Order && Limit Sortering && Limiet - + results (Use <strong>0</strong> for no limit) - + Column: Kolom: - - ASC - ASC + + <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in two slashes, e.g., <span style=" font-weight:600;">/value/</span>. To use a slash as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\/</span>.</p></body></html> + - - <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in <span style=" font-weight:600;">{}</span>. To use <span style=" font-weight:600;">{</span> or <span style=" font-weight:600;">}</span> as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\{</span> or <span style=" font-weight:600;">\}</span>.</p></body></html> + + Copy items on the grid - - Add empty rows + + Paste items on the grid - - DESC - DESC + + Ctrl+V + Ctrl+V - - Limit in: - Limiet in: + + Browse referenced tables + + + + + Change the values of all selected cells at once + + + + + Ctrl+E + Ctrl+E + + + + ASC + ASC - 000000 - 000000 + + Add empty rows + - 100 - 100 + + DESC + DESC - results - resultaten + + Limit in: + Limiet in: - + Add Item Item Toevoegen - + Remove Item Item Verwijderen - + Clear the order by columns list Maak de sorterings-kolomlijst leeg - + Move selected item up Verplaats het geselecteerde item naar boven - + Move selected item down Verplaats het geselecteerde item naar beneden - - <strong>WARNING: </strong> There are some changed rows waiting the commit! Do you really want to discard them and retrieve the data now? + + Copy as CSV - - Rows returned: <strong>%1</strong>&nbsp;&nbsp;&nbsp; + + Copy as text - - <em>(Limit: <strong>%1</strong>)</em> - <em>(Limiet: <strong>%1</strong>)</em> + + Copy items + - - none + + Pase items - - No objects found - Geen objecten gevonden + + Browse tables + - - Found %1 object(s) - %1 object(en) gevonden + + Duplicate row(s) + - - Views can't have their data handled through this grid, this way, all operations are disabled. + + Delete row(s) + + + + + Edit cell(s) + + + + + <strong>WARNING: </strong> There are some changed rows waiting the commit! Do you really want to discard them and retrieve the data now? + + + + + Rows returned: <strong>%1</strong>&nbsp;&nbsp;&nbsp; + + + + + <em>(Limit: <strong>%1</strong>)</em> + <em>(Limiet: <strong>%1</strong>)</em> + + + + none + + + + + Column + Kolom + + + + No objects found + Geen objecten gevonden + + + + Found %1 object(s) + %1 object(en) gevonden + + + + Views can't have their data handled through this grid, this way, all operations are disabled. Data van views kan niet worden aangepast via dit raster, alle operaties zijn uitgeschakeld. - + The selected table doesn't owns a primary key! Updates and deletes will be performed by considering all columns as primary key. <strong>WARNING:</strong> those operations can affect more than one row. De geselecteerde tabel bevat geen primary key! Update en delete commando's worden uitgevoerd door alle kolommen als primary key te beschouwen. <strong>OPGEPAST</strong> deze acties kunnen meer dan één rij beïnvloeden. - + + Referenced tables + + + + + + (none) + + + + + Referrer tables + + + + This row is marked to be %1 Deze rij is als %1 gemarkeerd. - + deleted verwijderd - + updated aangepast - + inserted ingevoegd - + [binary data] [binaire data] - + <strong>WARNING:</strong> Once commited its not possible to undo the changes! Proceed with saving? <strong>OPGEPAST: </strong> Eens toegepast is het niet langer mogelijk om aanpassingen ongedaan te maken! Bent u zeker dat u wilt opslaan? - + delete delete - + update update - + insert insert @@ -2289,1030 +2169,1178 @@ Deze optie afvinken zorgt ervoor dat de SQL wordt ingevoegd na het CREATE DATABA Venster - - Toggles the display of system objects. - Schakelt de weergave van systeemobjecten in of uit. - - - - System - Systeem - - - - Toggles the display of extension objects - Schakelt de weergave van uitbreidingsobjecten in of uit - - - - Extension - Uitbreiding - - - Open the grid to visualize or edit data. - Open het raster om data te visualiseren of aan te passen. - - - + + Data &Grid Data &Grid - + + Alt+G Alt+G - Open a new SQL execution pane. - Open een nieuw SQL uitvoerpaneel. - - - - - - - + + + + + ... ... - Ctrl+F5 - Ctrl+F5 - - - Update the objects tree. - Verfrish de objectenstructuur. - - - + Open the grid to visualize or edit data - + Open a new SQL execution pane - + Ctrl+F6 Ctrl+F6 - + Update the objects tree - - Ctrl+S - Ctrl+S + + Toggle the display of filter widget as well the system/extension objects. + - + + Sort items alphabetically. When unchecked, items are sorted by OID. + + + + + Sort alphabetically + + + + Drop this database Verwijder deze database - + Expands all items Alle items uitklappen - + Collapses all items Alle items inklappen - + Filters the currently loaded items in the tree by using a pattern and matching their names. If <strong>By OID</strong> is checked the pattern is interpreted as an integer value that represents the object id (OID). <br><br/><strong>HINT:</strong> if you need to search the entire database use the full refresh (<strong>Ctrl+F5</strong>) prior the filtering. - + Filter: Filter: - + By OID Per OID - - + + Attribute Attribuut - + Value Waarde - + Show raw attributes - Show raw attributes names - Toon onbewerkte attribuutnamen - - - + (not found, OID: %1) (niet gevonden, OID: %1) - + -- Source code not generated! Hit F7 or middle-click the item to load it. -- - + Admin. roles Admin. rollen - + Alignment Uitlijning - + Analyze func. Analyzeer func. - + Arg. count Aantal Argumenten - + Arg. default count Standaard aantal argument - + Arg. defaults Standaardargumenten - + Arg. modes Argumentenmodus - + Arg. names Argumentennamen - + Arg. types Argumententypes - + Behavior type Gedragstype - + By value Per waarde - + Cast type Cast type - + Category Categorie - + Collatable Sorteerbaar - + Collation Sortering - + Comment Commentaar - + Commutator Op. Commutator Op. - + Configuration Configuratie - + Conn. limit Verbindingslimiet - - + + Constraint Constraint - + Create DB Maak DB aan - + Create role Maak rol aan - + Curr. version Huidige versie - + Default Standaard - + Default value Standaardwaarde - + Definition Definitie - + Delimiter Delimiter - + Dest. type Doeltype - + Dimension Dimensie - + Directory Map - + Dest. encoding Doelcodering - + Element Element - + Encoding Codering - + Encrypted Geëncrypteerd - + Enumerations Enumeraties - + Exec. cost Uitvoeringskost - + Expression Expressie - + Op. family Operator Familie - + Final func. Finale functie - + Function Functie - + Func. type Functietype - + Handler func. Behandelende Functie - + Handles type Behandelt type - + Hashes Hashes - + Index type Indextype - + Inherit Erft over - + Ini. condition Initiële Vereiste: - + Inline func. Inline Functie - + Input func. Invoerfunctie - + Internal length Interne lengte - + Interval type Intervalstype - + I/O cast I/O cast - + Join func. Join func. - + Language Taal - + LC COLLATE LC COLLATE - + LC CTYPE LC CTYPE - + Leak proof Lekdicht - + Left type Linkse type - + Length Lengte - + Library Bibliotheek - + Can login Kan inloggen - + Materialized Gematerialiseerd - + Member roles Lid-rollen - + Merges Samenvoegingen - + Name Naam - + Negator op. Negator op. - + Not null Niet null - + Object type Objecttype - + OID OID - + With OIDs Met OIDs - + Old version Oude versie - + Operator Operator - + Operator func. Operator functie - + Output func. Uitvoerfunctie - + Owner Eigenaar - + Owner column Bezittende kolom - + Parents Ouders - + Password Wachtwoord - + Permissions Machtigingen - + Precision Precisie - + Preferred Voorkeur - + Range attributes Omvangsattributen - + Receive func. Ontvangersfunctie - + Ref. roles Ref. rollen - + Replication Replicatie - + Restriction func. Belemmeringsfunctie - + Return type Resultaatstype - + Returns SETOF Geeft SETOF terug - + Right type Rechtse type - + Rows amount Aantal rijen - + Schema Schema - + Security type Beveiligingstype - + Send func. Zendfunctie - + Sort op. Sorteeroperato - + Source type Brontype - + Src. encoding Broncodering - + State type Statustype - + Storage Opslag - + Superuser Superuser - + Tablespace Tablespace - + Type mod. in func. Type mod. in functie - + Type mod. out func. Type mod. buiten functie - + Transition func. Transitiefunctie - + Trusted Vertrouwd - + Type Type - + Type attribute Typeattribuut - + Types Types - + Unlogged Niet gelogged - + Validator func. Validatiefunctie - + Validity Geldigheid - + Windows func. Windowing func. - + false onwaar - + true waar - + Cache value Cachewaarde - + Cycle Cyclus - + Increment Toename - + Max. value Max. waarde - + Min. value Min. waarde - + Start value Startwaarde - + Last value Laatste waarde - + Subtype Subtype - + Op. class Op. klasse - + Canonical func. Canonische func. - + Subtype diff func. Subtype diff func. - + Deferrable Uitstelbaar - + For each row Voor elke rij - + Firing Afvuring - + On insert Bij insert - - + + On delete Bij delete - - + + On update Bij update - + On truncate Bij truncate - + Arguments Argumenten - + Table Tabel - + Trigger func. Trigger func. - - - + + + Columns Kolommen - + Condition Voorwaarde - + Deferment Uitstel - + Event Event - + Execution mode Uitvoeringsmodus - + Commands Commando's - + Position Positie - + Comparison type Vergelijkingstype - + Ref. columns Ref. columns - + Expressions Expressies - + Fill factor Vulfactor - + No inherit Geen overerving - + Op. classes Op. klasses - + Operators Operators - + Ref. table Ref. tabel - + Unique Uniek - + Predicate Predicaat - + Collations Sorteringen - + Inherited Overgeërfd - + + Client encoding + + + + + Configuration file + + + + + Data directory + + + + + Dynamic library path + + + + + Dynamic shared memory + + + + + Hba file + + + + + Listen addresses + + + + + Max. connections + + + + + Listen port + + + + + Server encoding + + + + + SSL + + + + + SSL ca file + + + + + SSL cert file + + + + + SSL crl file + + + + + SSL key file + + + + + Server version + + + + + Ident file + + + + + Password encryption + + + + + Connection ID + + + + + Server PID + + + + + Server protocol + + + + + Referrers + + + + + Identity + + + + + Command + + + + + USING expr. + + + + + CHECK expr. + + + + + Roles + Rollen + + + + RLS enabled + + + + + RLS forced + + + + + Show objects filter + + + + + Show system objects + + + + + Show extension objects + + + + Snippets Snippets - + Drop object Verwijder object - + Drop cascade Verwijder cascade - + Truncate Truncate - + Trunc. cascade Trunc. cascade - + Show data Toon data - + Reload properties Eigenschappen herladen - + Update Updaten - + Rename Hernoem - + Source code Broncode - + Quick refresh - + Full refresh - + + -- Source code unavailable for this kind of object -- + + + + Do you really want to drop the object <strong>%1</strong> <em>(%2)</em>? Bent u zeker dat u het object <strong>%1</strong> <em>%2</em> wilt verwijderen? - + Do you really want to <strong>cascade</strong> drop the object <strong>%1</strong> <em>(%2)</em>? This action will drop all the other objects that depends on it. Bent u er zeker van dat u het object &lt;strong&gt;%1&lt;/strong&gt; &lt;em&gt;(%2)&lt;/em&gt; via &lt;strong&gt;cascade&lt;/strong&gt; wilt verwijderen? Deze actie verwijdert ook alle objecten die afhankelijk zijn van dit object. - + Do you really want to truncate the table <strong>%1</strong>? Bent u zeker dat u de tabel <strong>%1</strong> wil truncaten? - + Do you really want to <strong>cascade</strong> truncate the table <strong>%1</strong>? This action will truncate all the tables that depends on it? Bent u er zeker van dat u de tabel <strong>%1</strong> <em>(%2)</em> via <strong>cascade</strong> wilt verwijderen? Deze actie verwijdert ook alle tabellen die afhankelijk zijn van deze tabel. - + + Also restart sequences + + + + Src. table: %1 Src. column(s): %2 - + Ref. table: %1 Ref. column(s): %2 - + -- Source code genaration for buil-in and base types currently unavailable -- - + -- Source code unavailable for the object %1 (%2). -- - - - DatabaseImportForm - - Database Import - Database Import + + + Warning + Opgepast - - Database import - Database import + + You're running a demonstration version! The data manipulation feature is available only in the full version! + Dit is een demonstratie-versie. De data manipulatie functionaliteit is enkel beschikbaar in de volledige versie! + + + <strong>CAUTION:</strong> You are about to drop the entire database <strong>%1</strong>! All data will be completely wiped out. Do you really want to proceed? + <strong>PAS OP:</strong> U staat op het punt om de volledige database <strong>%1</strong> te verwijderen! Alle data zal verloren gaan. Bent u zeker dat u verder wilt gaan? + + + + DatabaseImportForm Settings @@ -3329,249 +3357,211 @@ Ref. column(s): %2 Verbinding: - - Origin point: - Oorsprongspunt: - - - - Starting point where objects will be put. - Startpunt waar objecten zullen worden neergezet. - - - - Tables per row: - Tabellen per rij: - - - - Tables per row - Tabellen per rij - - - - Spacing: - Spatiëring: - - - - Spacing between objects - Spatiëring tussen objecten - - - - Schemas per row: - Schemas per rij: - - - + Resolve some of the object's dependencies by querying the catalog when a needed object does not exists on the loaded set. In some cases it's necessary to combine this option with others below. This option does not applies to database level objects like role, tablespace and language as well for data types, extensions. - + Automatically resolve dependencies Los afhankelijkheden automatisch op - + Random colors will be assigned to imported relationships facilitating the identification of links between tables mainly in large models. Om de identificatie van de links tussen tabellen in grote modellen makkelijker te maken zullen willekeurige kleuren worden gebruikt om de geïmporteerde relaties aan te duiden. - + Random colors for relationships Willekeurige kleuren voor relaties - + Enables the import of system built-in objects. It's recommend to select only those objects that are directly referenced by the ones to be imported. WARNING: Try to import a huge set of system objects can bloat the resultant model or even crash pgModeler due to memory/cpu overuse. Activeert het importeren van ingebouwde systeemobjecten. Het is aangeraden om enkel objecten te importeren waarnaar onmiddellijk worden gerefereerd. PAS OP: grote hoeveelheden systeemobjecten importeren kan leiden tot een opgezwollen resultaatsmodel of kan zelfs pgModeler tot een crash leiden omwillen van geheugen- of processor-uitputting. - + + + Import database + + + + Import system objects Importeer systeemobjecten - + Enables the import of objects created by extensions. Generally there is no need to check this option but if there are objects in the database that directly references this category of objects this mode must be enabled. Activeert het importeren van objecten die werden aangemaakt door uitbreidingen. Algemeen gezien is er geen nood om deze optie aan te vinken tenzij er objecten in de databse leven die onmiddellijk naar objecten van deze categorie refereren. - + Import extension objects Importeer uitbreidingsobjecten - + pgModeler ignores import errors and will try to create as many as possible objects. By checking this option the import operation will be not aborted but an incomplete model will be constructed. This option generates a log file on pgModeler's temp directory. pgModeler negeert importeerfouten en zal pogen om zoveel mogelijk objecten aan te maken. Door deze optie aan te vinken zal de importeer-taak niet afbreken bij een fout maar zal een onvolledig model worden aangemaakt. Deze optie creëert een log bestand in de tijdelijke map voor pgModeler. - + Ignore import errors Negeer importeerfouten - - Schemas per row - Schemas per rij - - - Resolve some of the object's dependencies by querying the catalog when a needed object does not exists on the loaded set. In some cases it's necessary to combine this option with others below. This option does not applies to database level objects like role, tablespace and language as well for data types and extensions. - Los sommige afhankelijkheden van objecten op door de catalogus raad te plegen wanneer een object niet in de geladen set bestaat. In sommige gevallen is het nodig om deze optie met andere opties te combineren. Deze optie is niet van toepassing op database-niveau objecten zoals rollen, tablespaces en talen alsook data types en uitbreidingen. - - - + All catalog queries as well the created objects' source code are printed to standard output (stdout). Alle catalogusqueries plus the broncode van de aangemaakte objecten wordt naar de standaard output (stdout) geprint. - + Debug mode Debugmodus - + Create all imported objects in the current working model instead of create a new one. Maak alle geïmporteerde objecten aan in het huidige model en maak geen nieuw model aan. - + Import objects to the working model Importeer de objecten in het huidige model - + Database Database - + Filter: Filter: - + Filter object by it's OID Filter objecten per hun OID - + By OID Per OID - + Select all objects Selecteer alle objecten - - - - + + + + ... ... - + Clear object selection Maak de objectselectie ongedaan - + Expands all items Alle items uitklappen - + Collapses all items Alle items inklappen - + Output Uitvoer - + Progress label... Vooruitgangslabel... - + Cancel Annuleren - + &Import - + &Close &Sluiten - + <strong>ATTENTION:</strong> You are about to import objects to the current working model! This action will cause irreversible changes to it even in case of critical errors during the process. Do you want to proceed? <strong>OPGEPAST:</strong> U staat op het punt om objecten te importeren in het huidige model! Deze actie zal onherroepbare verandering teweegbrengen, zelfs wanneer kritische problemen opduiken gedurende dit proces. Bent u zeker dat u verder wilt gaan? - + Importing process aborted! Het import proces werd afgebroken! - + Importing process canceled by user! Het import proces werd geannuleerd door de gebruiker! - + Importing process sucessfuly ended! Het import proces werd succesvol beëindigt! - + No databases found Er werd database gevonden - + Found %1 database(s) Er werd(en) %1 database(s) gevonden - + Retrieving objects from database... De objecten worden van de database opgehaald... - + Retrieving cluster level objects... De objecten op cluster-niveau worden opgehaald... - + Retrieving objects of schema `%1'... De objecten uit schema `%1' worden opgehaald... - - Retrieving objects of table `%1'... - De objecten van tabel `%1' worden opgehaald... + + Retrieving objects of `%1' (%2)... + - + This is a PostgreSQL built-in data type and cannot be imported. Dit is een ingebouwd type van PostgreSQL en kan niet worden geïmporteerd. - + This is a pgModeler's built-in object. It will be ignored if checked by user. Dit is een ingebouwd object van pgModeler. Dit object wordt genegeerd indien aangevinkt door de gebruiker. @@ -3590,58 +3580,62 @@ Ref. column(s): %2 Objecten ophalen... `%1' - - - Creating object `%1' (%2)... - Object aanmaken `%1' (%2)... + + Creating object `%1' (%2), oid `%3'... + - - Trying to recreate object `%1' (%2)... - Object `%1' proberen aan te maken (%2)... + + Trying to recreate object `%1' (%2), oid `%3'... + - + + Creating object `%1' (%2)... + Object aanmaken `%1' (%2)... + + + Import failed to recreate some objects in `%1' tries. Het importeren faalde na `%1' pogingen om sommige objecten te her-creëeren. - + Creating permissions for object `%1' (%2)... Machtigingen aanmaken voor object `%1' (%2)... - + Creating columns permissions... Kolommachtigingen aanmaken... - + Updating relationships of `%1' (%2)... Updaten van de relaties voor `%1' (%2)... - + Validating relationships... - + The database import ended but some errors were generated and saved into the log file `%1'. This file will last until pgModeler quit. Het importeren van de database is voltooid maar er werden enkele fouten gegenereerd, deze werden opgeslagen in het log-bestand `%1'. Dit bestand zal worden verwijderd wanneer u pgModeler afsluit. - + Destroying unused detached columns... De vrijstaande kolommen worden verwijderd... - + Assigning sequences to columns... - + Creating table inheritances... Tabel-overervingen worden aangemaakt... @@ -3649,135 +3643,146 @@ Ref. column(s): %2 DatabaseModel - + The demonstration version can create only `%1' instances of each object type! You've reach this limit for the type: `%2' U kan slechts `%1' instancies per object type aanmaken in demonstratie-versies! U heeft deze limiet bereikt voor het type `%2' - + Loading: `%1' (%2) Bezig met laden: `%1' (%2) - - + + Validating relationships... - - Generating %1 of the object `%2' (%3) - Genereren van %1 van het type `%2' (%3) + + Generating %1 code: `%2' (%3) + - + Saving object `%1' (%2) - + Saving metadata of the object `%1' (%2) - + Metadata file successfully saved! - + Process successfully ended but no metadata was saved! - + Creating object `%1' (%2) Object `%1' (%2) wordt aangemaakt. - + Object `%1' (%2) already exists. Ignoring. - + Loading metadata for object `%1' (%2) - + Object `%1' (%2) not found. Ignoring metadata. - + Metadata file successfully loaded! DatabaseWidget - - Form - Venster - Attributes Attributen - + LC_COLLATE: - + LC_CTYPE: - + Template DB: Sjabloon DB: - + Model Author: Modelauteur: - + Encoding: Codering: - + Connections: Verbindingen: - + + Options: + Opties: + + + + Allow connections + + + + + Is template + + + + Default Objects Standaardobjecten - + Tablespace: Tablespace: - + Schema: Schema: - + Collation: Sortering: - + Owner: Eigenaar: @@ -3794,8 +3799,8 @@ Ref. column(s): %2 - - + + Default Standaard @@ -3803,33 +3808,44 @@ Ref. column(s): %2 DomainWidget - Form - Venster + + Attributes + Attributen - + Default Value: Standaardwaarde: - - Constraint - Constraint + + Not null + Niet null + + + + Check constraints + - + + Expression: + Expressie: + + + Name: Naam: - - Not Null: - Not Null: + + Name + Naam - - Check Expr.: - Check Expressie: + + Expression + Expressie @@ -3860,7 +3876,7 @@ Ref. column(s): %2 <html><head/><body><p>pgModeler komt tot stand dankzij <span style=" font-style:italic;">een grote inzet om een kwaliteitsvol product te bezorgen</span>. Dit project heeft een niveau van volwassenheid bereikt die nooit was voorzien. Dit alles is het resultaat van de samenwerken tussen de auteur(s) en de <span style=" font-weight:600;">Open Source gemeenschap</span>. <br/><br/>Dit product heeft nog een lange weg af te leggen; met uw hulp kunnen we deze uitdaging aan en kunnen we nieuwe verbeteringen en toevoegingen aan dit product blijven publiceren bij elke release. Als u vertrouwd op pgMOdeler en denkt dat u kan bijdragen, gelieve dan een donatie te maken aan pgModeler!</p></body></html> - + I want to help! Ik wil helpen! @@ -3873,47 +3889,47 @@ Ref. column(s): %2 Venster - + Column: Kolom: - + Expression: Expressie: - + Collation: Sortering: - + Operator Class: Operator Klasse: - + Operator: Operator: - + Sorting: Sortering: - + Ascending Stijgend - + Descending Afdalend - + Nulls first Nulls eerst @@ -3943,37 +3959,33 @@ Ref. column(s): %2 Nulls eerst - + Collation Sortering - + Operator Operator - + Expression Expressie - + Yes Ja - + No Nee EventTriggerWidget - - Form - Venster - Event: @@ -4009,725 +4021,791 @@ Ref. column(s): %2 - Zero length assignment! - Toewijzing van een waarde met lengte nul! - - - Assignment of a precision greater than the length of the type! Toewijzing van een waarde met grotere precisie dan de toegewezen locatie! - + Assignment of an invalid precision to type time, timestamp or interval. The precision in this case must be equal to or less than 6! Toewijzing van een ongeldige precisie aan het type time, timestamp of interval. De precisie moet in dit geval kleiner dan of gelijk zijn aan 6! - + Assignment of a not allocated column to object `%1' (%2)! Toewijzing van een niet-gealloceerde kolom aan het object `%1' (%2)! - + Reference to a column which index is out of the capacity of the column list! Referentie naar een kolom wiens index buiten de capaciteit van de kolomlijst ligt! - + Assignment of not allocated object! Toewijzing van een niet-gealloceerd object! - + Assignment of a not allocated schema to object `%1' (%2)! Toewijzing van een niet-gealloceerde schema aan het object `%1' (%2)! - + The object `%1' (%2) has inconsistent SQL or XML definition! het object `%1' (%2) heeft een inconsistente SQL of XML definitie! - + The object `%1' (%2) already exists on `%3' (%4)! Het object `%1' (%2) bestaat reeds op `%3' (%4)! - + The object `%1' (%2) cannot be assigned because there is already exists in the container object `%3'! Het object `%1' (%2) kan niet worden toegewezen omdat het reeds bestaat in het container-object `%3'! - + Assigning object of an invalid type! Toewijzing van een object van een ongeldig type! - + Removing an object of an invalid type! Verwijdering van een object van een ongeldig type! - + Obtaining an object of an invalid type! Het verkregen object is van een ongeldig type! - + Assignment of empty name to table return type! Toewijzing van een lege naam aan een tabel-terugkeertype! - + The insertion of the parameter `%1' will not be possible because there is another parameter with same name in the function `%2'! Het toevoegen van parameter `%1' is niet mogelijk omdat de functie `%2' reeds een parameter met deze naam bevat! - + The insertion of the table return type `%1' will not be possible because there is another return type with the same name in the `%2'! Het invoegen van tabel-terugkeertype `%1' is niet mogelijk omdat er reeds een terugkeer-type met deze naam bestaat in `%2'! - + Reference to a parameter which index is out of the parameter list bounds! Een referentie naar een parameter met een index die buiten de limieten ligt van de parameterlijst! - + Reference to an event which does not belongs to trigger! Een referentie naar een event die niet tot de trigger behoort! - + The column `%1' cannot be assigned to the trigger `%2' because they belongs to different parent tables! De kolom `%1' kan niet toegewezen worden aan de trigger `%2' omdat deze tot verschillende ouder-tabellen behoren! - + Assignment of a not allocated function to object `%1' (%2)! Toewijzing van een niet-gealloceerde functie aan het object `%1' (%2)! - + Assignment of a function which return type is different from `%1'! Toewijzing van een functie waarvan het terugkeertype verschilt van `%1'! - + Assignment of a function which parameter count is invalid to the object `%1' (%2)! Toewijzing van een functie waarvan het aantal parameters ongeldig is voor het object `%1' (%2)! - + Assignment of a function which language is invalid! Toewijzing van een functie waarvan de taal ongeldig is! - + Event trigger function must be coded in any language other than SQL! Event triggerfunctie moet geschreven zijn in een taal die verschilt van SQL! - + Assignment of not allocated table to object `%1' (%2)! Toewijzing van een niet-gealloceerde tabel aan object `%1' (%2)! - + Reference to an argument which index is out of argument list bounds! Referentie naar een argument met een index die buiten de limieten ligt van de argumentenlijst! - + Assignment of empty name to an object! Toewijzing van een lege naam aan een object! - + Assignment of a name which contains invalid characters! Toewijzen van een naam die ongeldige karakters bevat! - + Assignment of a name which length exceeds the maximum of 63 characters! Toewijzing van een naam die de maximumlengte van 63 karakters overtreed! - + Assignment of schema object which type is invalid! Toewijzing van een schemaobject wiens type ongeldig is! - + Assignment of tablespace object with invalid type! Toewijzing van een tablespaceobject met een ongeldig type! - + Assignment of tablespace to an invalid object! Toewijzing van een tablespace aan een ongeldig object! - + Assignment of tablespace to a constraint which type is invalid! To belong to a tablespace the constraint must be a primary key or unique! Toewijzing van een tablespace aan een constraint wiens type ongeldig is! Om tot een tablespace te behoren moet een constraint een primary key of een unieke sleutel zijn! - + Assignment of owner object which type is invalid! Toewijzing van een eigenaarsobject wiens type ongeldig is! - + Assignment of owner to an invalid object! Toewijzing van een eigenaar aan een ongeldig object! - + Assignment of appended or prepended SQL to an invalid object! Toewijzing van toegevoegde of voorgevoegde SQL aan een ongeldig object! - + Reference to a function with invalid type! Referentie naar een functie met een ongeldig type! - + Reference to an argument of the operator with invalid type! Referentie naar een argument van de operator met een ongeldig type! - + Reference to an operator with invalid type! Referentie naar een operator met een ongeldig type! - + Assignment of value to an invalid option type on role! Toewijzing van een waarde aan een ongeldig optietype van een rol! - + Reference to an invalid role type! Referentie naar een ongeldig rol-type! - + The insertion of the role `%1' is not possible because this is already being referenced by role `%2'! Het invoegen van de rol `%1' is onmogelijk omdat deze reeds wordt gerefereerd door rol `%2'! - + Reference redundancy detected by having the role `%1' referencing the role `%2'! Referentieredundantie gedetecteerd doordat de rol `%1' refereert naar rol `%2'! - + The role `%1' can not be listed as a member of itself! De rol `%1' kan geen lid zijn van zichzelf! - + Reference to a role which index is out of role list bounds! Referentie naar een rol wiens index buiten de limieten van de rollelijst ligt! - + Insertion of empty command to the rule! Invoeging van een leeg commando aan de regel! - + Reference to a command which index is out of the command list bounds! Referentie naar een commando wiens index buiten de limieten van de commandolijst ligt! - + Is not possible to create a self generalization/copy relationship! The table can not inherit or copy their own attributes! Het is onmodelijk om een zelf-generalisatie/kopieer-relatie aan te maken! De tabel kan niet van zichzelf erven of zijn eigen attributen kopieren! - + Assignment of an object that already belongs to another table! Toewijzing van een object dat reeds aan een andere tabel toehoort! - + Assignment of a schema to the sequence which differs from the schema of the owner table! Toewijzing van een schema aan de sequentie die verschilt van het schema van de eigenaars-tabel! - + Assignment of an invalid value to one of the sequence attributes! Toewijzing van een ongeldige waarde aan een van de sequentie-attributen! - + Assignment of a minimum value to the sequence which is greater than the maximum value! Toewijzing van een minimumwaarde die groter is dan de maximumwaarde van de sequentie! - + Assignment of a start value to the sequence which is extrapolating the range defined by minimum and maximum values! Toewijzing van een startwaarde aan de sequentie die de omvang extrapoleerd als gedefinieerd door de minimum- en maximumwaarden! - + Assignment of a null increment value to the sequence! Toewijzing van een null-vermeerdering aan de sequentie! - + Assignment of null cache value to the sequence! Toewijzing van null-cachewaarden aan de sequentie! - + Assignment of owner table which is not in the same schema as the sequence `%1'! Toewijzing van een eigenaarstabel die zich niet in hetzelfde schema bevindt als de sequentie `%1'! - + Assignment of owner table which does not belong to the same owner of the sequence `%1'! Toewijzing van een eigenaarstabel die niet tot dezelfde eigenaar behoort als de sequentie `%1'! - + Assignment of a nonexistent owner column to the sequence `%1'! Toewijzing van een niet-bestaande eigenaarskolom aan de sequentie `%1'! - + Assignment of an owner column to the sequence `%1' that is not related to any table! Toewijzing van een eigenaarskolom aan de sequentie `%1' die aan geen enkele tabel gerelateerd is! - + Reference to a label which index is out of labels list bounds! Referentie naar een label wiens index buiten de limieten ligt van de label-lijst! - + Allocation of object with invalid type! Allocatie van een object met ongeldig type! - + Assignment of a function with invalid return type to object `%1' (%2)! Toewijzing van een functie met een ongeldige terugkeerwaarde aan object `%1' (%2)! - + Assignment of a function with invalid parameter(s) type(s) to object `%1' (%2)! Toewijzing van een functie met ongeldige parametertype(s) aan object `%1' (%2)! - + Assignment of not allocated language! Toewijzing van een niet-gealloceerde taal! - + Assignment of language object which type is invalid! Toewijzing van een taalobject wiens type ongeldig is! - + Reference to data type with an index outside the capacity of data types list! Referentie naar een datatype met een index die buiten de capaciteit van de datatype lijst ligt! - + Assignment of a null type to object `%1' (%2)! Toewijzing van een null type aan het object `%1' (%2)! - + Assignment of invalid type to the object! Toewijzing van een ongeldig type aan het object! - + Assignment of an empty directory to object `%1' (%2)! Toewijzing van een lege map aan object `%1' (%2)! - + Obtaining types with invalid quantity! Types met ongeldige hoeveelheid verkregen! - + Insertion of item which already exists in the attributes list of the type! Invoegen van een item dat reeds bestaat in de attributenlijst van het type! - + Insertion of invalid item in the attributes list of the type! Invoegen van een ongeldig item in de attributenlijst van het type! - + Insertion of item which already exists in the enumarations list of the type! Invoegen van een item dat reeds bestaat in de enumeratielijst van het type! - + Insertion of invalid item in the enumerations list of the type! Invoegen van een ongeldig item in de enumeratielijst van het type! - + Reference to an attribute which index is out of the attributes list bounds! Referentie naar een attribuut met een index die buiten de limieten van de attributenlijst ligt! - + Reference to an enumeration which index is out of the enumerations list bounds! Referentie naar een enumeratie met een index buiten de limieten van de enumeratielijst! - + Assignment of invalid configuration to the type! Toewijzing van een ongeldige configuratie aan het type! - The data type `%1' can not be assigned because it already exists in the types list of the aggregate function `%2'! - Het datatype `%1' kan niet worden toegewezen omdat het reeds bestaat in de typelijst van de aggregatiefunctie `%2'! + + There is already a relationship between `%1' (%2) and `%3' (%4) in the model! When using relationships of the type generalization, copy and one-to-one there can't be other relationships linked to the pair of tables. + + + + + Unable to load the configuration file `%1'! Please check if file exists in its folder and/or if it is not corrupted! + - + + Invalid syntax in file `%1', line %2, column %3! + + + + + Invalid instruction `%1' on file `%2', line %3, column %4! + + + + + Unknown attribute `%1' in file `%2', line %3, column %4! + + + + + Invalid metacharacter `%1' in file `%2', line %3, column %4! + + + + + Invalid operator `%1' in comparison expression, file `%2', line %3, column %4! + + + + + Attribute `%1' with an undefined value in file `%2', line %3, column %4! + + + + + Attribute `%1' with an invalid name in file `%2', line %3, column %4! + + + + + Could not access the file or directory `%1'! Make sure that it exists or if the user has access permissions on it! + + + + + Could not load file `%1'. The same appears to be inconsistent or one of its dependencies (DTD files) has errors or is missing! + + + + + Unsupported PostgreSQL version (%1) detected! Valid versions are between %2 and %3. + + + + + Failed to drop the database `%1' because it is defined as the default database for the connection `%2'! + + + + + The column `%1' must be `NOT NULL' because it composes the primary key of the table `%2'. You need to remove the column from the mentioned contraint in order to disable the `NOT NULL' on it! + + + + + The identity column `%1' has an invalid data type! The data type must be `smallint', `integer' or `bigint'. + + + + + Reference to an invalid affected command in policy `%1'! + + + + + Reference to an invalid special role in policy `%1'! + + + + Assignment of an operator which input type count is invalid to aggregate function! Toewijzing van een operatie wiens inputtypehoeveelheid ongeldig is voor een aggregatiefunctie! - + Assignment of an operator which types of arguments is invalid! Toewijzing van een operator wiens argumententypes ongeldig zijn! - + Assignment of system reserved name to the object `%1' (%2)! Toewijzing van een systeem-gereserveerde naam aan het object `%1' (%2)! - + One function with invalid configuration is been used by the object `%1' (%2)! Een functie met ongeldige configuratie wordt gebruikt door het object `%1' (%2)! - + Assignment of an invalid strategy/support number to an operator class element! Toewijzing van een ongeldig strategy- of supportnummer aan een operatorklasse element! - + Insertion of element which already exists in the element list! Invoegen van een element dat reeds bestaat in de elementenlijst! - + Reference to an element which index is out of element list bounds! Referentie naar een element wiens index buiten de limiet van de elementenlijst valt! - + Reference to an object which index is out of object list bounds! Referentie anar een object wiens index buiten de limiet van de objectenlijst valt! - + Removal of an object not allocated! Verwijdering van een niet-gealloceerd object! - + The object `%1' (%2) can not be removed because it is being referenced by object `%3' (%4)! Het object `%1' (%2) kan niet worden verwijderd omdat object `%3' (%4) ernaar verwijst! - + The object `%1' (%2) can not be removed because it is being referenced by object `%3' (%4) that belongs to `%5' (%6)! Het object `%1' (%2) kan niet worden verwijderd omdat object `%3' (%4), dat aan `%5' (%6) toehoort, ernaar verwijst! - + Operation with object(s) which type(s) is invalid! Operatie met object(en) van een ongeldig type! - + Reference to object with invalid type! Verwijzing naar een object van een ongeldig type! - + Operation with object not allocated! Operatie op een niet-gealloceerd object! - + The creation of the relationship `%1' between the table `%2' and `%3' can not be done because one does not have a primary key. If the relationship is of the type n-n both tables must have primary keys! Het aanmaken van de relatie `%1' tussen de tabellen `%2' en `%3' kan niet worden voltooid omdat deze geen primary key bevatten. Indien de relatie van het type n-n is, moeten beide tabellen over een primary key beschikken! - + The relationship of the type 1-1 where both tables are mandatory participation is not implemented because it requires fusion between the tables that breaks the modeling done by the user! De relatie van het type 1-1 waar beide tabellen verplicht meespelen is niet geimplementeerd omdat dit een fusie tussen de tabellen vereist die het design van de gebruiker zou breken! - + Assignment of an invalid expression to the object! Toewijzing van een ongeldige expressie aan het object! - + Assignment of a primary key to a table which already has one! Toewijzing van een primary key aan een tabel die reeds over een primary key beschikt! - + Identifier relationship can not be created for a self relationship, relationships of the type n-n, copy or generalization! De identifier-relatie kan niet worden aangemaakt voor een zelf-relatie, relaties van het type n-n, kopie or generalisatie! - + Unable to create a copy relationship because the column `%1' in table `%2' already exists in table `%3'! De kopie-relatie kon niet worden aangemaakt omdat de kolom `%1' in table `%2' reeds bestaat in tabel `%3'! - + Unable to create the generalization relationship because the column `%1' in table `%2' can not be merged with the column `%3' of table `%4' because they have incompatible types! De generalisatierelatie kan niet worden aangemaakt omdat de kolom `%1' in tabel `%2' niet kan worden samengevoegd met kolom `%3' van tabel `%4', deze kolommen hebben incompatibele types! - + Unable to create the generalization relationship because the constraint `%1' in table `%2' can not be merged with the constraint `%3' of table `%4' due to their incompatible composition! De generalisatierelatie kan niet worden aangemaakt omdat de constraint `%1' in tabel `%2' niet kan worden samengevoegd met constraint `%3' van tabel `%4', deze constraints hebben een incompatibele compositie! - + An attribute can not be added to a copy or generalization relationship! Een attribuut kan niet worden toegevoegd aan een kopie of een generalisatierelatie! - + A foreign key can not be added to a relationship because is created automatically when this is connected! Een foreign key kan niet worden toegevoegd aan een relatie omdat deze automatisch wordt aangemaakt wanneer deze wordt verbonden! - + The object `%1' (%2) is referencing the object `%3' (%4) which was not found in the model! Het object `%1' (%2) refereert naar het object `%3' (%4), dit laatste object kon niet worden gevonden in het model! - + Reference to an user-defined data type that not exists in the model! Referentie naar een gebruikersgedefinieerd type dat niet in het model bestaat! - + Assignment of invalid maximum size to operation list! Toewijzing van een ongeldige maximumwaarde aan de operatielijst! - + Unable to write the file or directory `%1'! Make sure the output directory exists, or if the user has write permissions over it! Het bestand of de map `%1' kon niet worden aangemaakt! Zorg ervoor dat de uitvoermap bestaat en dat de gebruiker er schrijfmachtigingen toe heeft! - + Unable to write the file `%1' due to one or more errors in the definition generation process! Het bestand `%1' kan niet worden geschreven omwille van een of meerdere fouten die optraden tijdens het definitie-generatie proces! - There is already a relationship between `%1' (%2) and `%3' (%4) in the model! - Het model bevat reeds een relatie tussen `%1' (%2) en `%3' (%4)! - - - The configuration of the relationship `%1' generates a redundancy between the relationships `%2'. Redundancy on identifier or generalization/copy relationships are not accepted since they result in incorrect column spreading making the model inconsistent! De configuratie van de relatie `%1' creeert een redundantie tussen de relaties `%2'. Redundanties van identifiers of generalisatie/kopie-relaties zijn niet geldig omdat deze kunnen leiden tot het incorrect verspreiden van kolommen en dit kan het model inconsistent maken! - + One or more objects were invalidated and automatically removed because they were referencing table columns which were included through relationships and which no longer exists due to disconnection of relationships or exclusion of such generated columns! Een of meerdere objecten werden als ongeldig gemarkeerd en werde automatisch verwijderd omdat deze naar kolommen refereerden die werden ingesloten door relaties die niet langer bestaan omwille van het ontkoppelen van de relatie of het uitsluiten van zulke gegenereerde kolommen! - + The primary key `%1' can only be allocated if declared within a block of code that defines a table or relationship! Een foreign key `%1' kan niet worden toegevoegd aan een relatie omdat deze automatisch wordt aangemaakt wanneer deze wordt verbonden! - + Reference to an invalid privilege type! Referentie naar een ongeldig machtigingstype! - + Insertion of a role which already exists in the role list of the permission! Invoegen van een rol die reeds in de rollenlijst van de machtiging aanwezig is! - + Assignment of privilege incompatible with the type of object referenced by permission! Toewijzing van een machtiging die niet compatibel is met het type waarnaar wordt verwezen door de machtiging! - + There is already a permission on object `%1' (%2) which has one or more equal roles from those present on permission to be assigned to the object! Er bestaat reeds een machtiging op object `%1' (%2) die een of meerdere zelfde rollen bevat als deze die onderdeel uitmaken van de nieuwe machtiging die aan het object worden toegewezen! - + A permission is referencing the object `%1' (%2) which was not found in the model! Een machtiging refereert naar object `%1' (%2) dat niet in het model kon worden teruggevonden! - + The object `%1' (%2) can not be created because its not being assigned to any schema! Het object `%1' (%2) kan niet worden aangemaakt omdat het niet aan een schema is toegewezen! - + The tablespace `%1' can not be inserted into the model because it points to the same directory as the tablespace `%2'! De tablespace `%1' kan niet worden ingevoegd in het model omdat het naar dezelfde map verwijst als de tablespace `%2'! - + It is not possible to create arrays of domains or sequences (dimension >= 1)! PostgreSQL does not yet implement this feature! Het is niet mogelijk om arrays van domeinen of sequenties (dimensie >= 1) aan te maken! Dit feature is nog niet aanwezig in PostgreSQL! - + The function `%1' can not get a source code as a definition because its language is set to C. Use the attributes symbol and dynamic library instead! De functie `%1' kan geen broncode bevatten als definitie omdat de taal is ingesteld als 'C'. Gebruik het attributensymbool en dynamische bibliotheek in de plaats! - + The function `%1' can have the attributes symbol and dynamic library configured only if the language is set to C. For all other cases you must specify a source code that defines it in the DBMS! De functie `%1' kan enkel symboolattributen en een dynamische bibliotheek configureren waneer de taal is ingesteld als zijnde 'C'. In alle andere gevallen moet u broncode specifieren die de functie definieert in het DBMS! - + The operator `%1' can not be assigned as a comutator of operator `%2' because it has incompatible settings! De operator `%1' kan niet worden toegewezen als comutator van operator `%2' omdat deze incompatibele instellingen heeft! - + The operator `%1' can not be assigned as negator of operator `%2' because it has incompatible settings! De operator `%1' kan niet worden toegewezen als negator van operator `%2' omdat deze incompatibele instellingen heeft! - + The type `%1' can not self refer in the attributes `element' or `copy type' or be used as a data type of an attribute in the configuration of a composite type! Het type `%1' kan geen zelf-referentie bevatten in de attributen 'element' of 'kopie type' noch kan het worden gebruikt als het data type van een attribuut in de configuratie van een composiet-type! - + Assignment of invalid element to type `%1'! Toewijzing van een ongeldig element aan type `%1'! - + Assignment of invalid alignment to type `%1'! Toewijzing van een ongeldig uitlijning aan type `%1'! - + Assignment of invalid name to the table generated from N-N relationship! Een ongeldige naam werd toegewezen aan de tabel gegenereerd op basis van een N-N relatie! - + The relationship `%1' can not make use of the special primary key because it is marked as identifier or it is a self relationship! De relatie `%1' kan geen gebruik maken van de primary key omdat deze is aangeduid als identifier of omdat het een zelfverwijzende relatie is! - + The object `%1' (%2) can not be edited or deleted because it was automatically included through a relationship! If the object is an attribute or constraint the modifications must be done on the relationship editing form. Het object `%1' (%2) kan niet worden bewerkt of verwijderd omdat het automatisch werd ingesloten via een relatie! Indien het object een attribuut of een constraint is moeten de bewerkingen worden uitgevoerd via het Relatie bewerk-venster. - + The object `%1' (%2) can not be deleted because it is protected! Het object `%1' (%2) kan niet worden verwijderd omdat het beschermd is! - + The group `%1' has already been declared earlier! De groep `%1' werd reeds eerder gedeclareerd! - + The group `%1' can not be built in the groups declaration block (%2)! De groep `%1' kan niet worden opgebouwd in de groependeclaratie-block (%2)! - + The group `%1' was built but not declared in the groups declaration block (%2)! De groep `%1' werd opgebouwd maar is niet gedeclareerd in de groependeclaratie-block (%2)! - + The group `%1' can not be built without possessing child elements! De groep `%1' kan niet worden opgebouwd zonder kind-elementen! - + The group `%1' can not be built once more because this was done in previous blocks! De groep `%1' kan niet worden opgebouwd omdat dit reeds werd uitgevoerd in een vorige block! - + The group `%1' has been declared but not built! De groep `%1' werd gedeclareerd maar niet opgebouwd! - + Reference to a column of the objects table with invalid index! Een referentie naar een kolom in de objectentabel met een ongeldige index! - + Reference to a row of the objects table with invalid index! Een referentie naar een rij in de objectentabel met een ongeldige index! - + The object `%1' (%2) can not be manipulated because it is reserved to PostgreSQL! This object is present in the database model only as a reference! Het object `%1' (%2) kan niet worden gemanipuleerd omdat dit een gereserveerd object is in PostgreSQL! Dit object bestaat enkel als referentie in het databasemodel! - + The new configuration of the function invalidates the object `%1' (%2)! In this case it is needed to undo the relationship between the affected object and function in order to the new configuration to take effect! De nieuwe configuratie van de functie maakt het object `%1' (%2) niet langer gevalideerd! Om de nieuwe configuratie in voege te doen treden moet u de relatie tussen het beinvloedde object en de functie ongedaan maken. - + A view reference must be used in at least one these SQL scopes: View Definition, SELECT-FROM, FROM-WHERE or After WHERE! Een viewreferentie moet minstens in een van de volgende SQL scopes worden gebruikt: View Definitie, SELECT-FROM, FROM_WHERE of Na WHERE! - + Constraints like primary key, foreign key or unique must have at least one column related to them! For foreign keys must be selected, in addition, the referenced columns! Constraints zoals primary key, foreign key of unique key moeten minstens een kolom bevatten! Voor foreign keys moeten ook de gerefereerde kolommen worden geselecteerd! - Unable to load one or more configuration files! Please check if files exists in the configuration folder and if they are not corrupted to preventing this error to occur again on the next startup! - Een of meerdere configuratiebestanden kunnen niet worden geladen! Om ervoor te zorgen dat deze fout zich niet voordoet de volgende maal u het programma opstart, gelieve na te kijken of deze bestanden in de configuratie-map bestaan en dat deze niet gecorrupteerd zijn. - - - Could not find the default settings file `%1'! To restore default settings check the existence of the file and try again! Het standaardinstellingsbestand `%1' kon niet worden gevonden. Kijk na of dit bestand bestaat om de standaardinstellingen terug te zetten en probeer opnieuw! - + The export process failed due to an error triggered by the PostgreSQL server in an attempt to execute a SQL command. For more details about the error check the exception stack! ** Executed SQL command: ** @@ -4740,413 +4818,355 @@ Ref. column(s): %2 %1 - + Could not load the plugin `%1' from the library `%2'! Message returned by plugin manager: `%3' De plugin `%1' kon niet worden geladen van de bibliotheek `%2'! De plugin manager antwoordde met: `%3' - + One or more plugins were not activated due to errors during the loading process! Check the exception stack for more details. Een of meerdere plugin werden niet geactiveerd omwille van fouten gedurende het laadproces! Kijk de exception stack na voor meer details. - - - Invalid syntax in file %1, line %2, column %3! - Het bestand %1 bevat ongeldige syntax op lijn %2, kolom %3! - - - - Invalid instruction `%1' on file %2, line %3, column %4! - De instructie `%1' in bestand %2 op lijn %3, kolom %4 is ongeldig! - - - - Unknown attribute `%1' in file %2, line %3, column %4! - De attribuut `%1' in bestand %2 op lijn %3, kolom %4 is ongeldig! - - - - Invalid metacharacter `%1' in file %2, line %3, column %4! - Het metakarakter `%1' in bestand %2 op lijn %3, kolom %4 is ongeldig! - - - - Invalid operator `%1' in comparison expression, file %2, line %3, column %4! - De operator `%1' binnen de vergelijkingsexpressie in bestand %2 op lijn %3, kolom %4 is ongeldig! - - - - Attribute `%1' with an undefined value in file %2, line %3, column %4! - Een attribuut `%1' met een ongedefinieerde waarde in bestand %2 op lijn %3, kolom %4! - - Attribute `%1' with an invalid name in file %2, line %3, column %4! - Een attribuut `%1' met een ongeldige naam in bestand %2 op lijn %3, kolom %4! - - - Assignment of empty XML buffer to parser! Toewijzingen van een lege XML buffer aan de parser! - Could not access the file or directory %1! Make sure that it exists or if the user has access permissions on it! - Het bestand of de map %1 is niet toegankelijk! Zorg ervoor dat het pad bestaat en dat de gebuiker toegangsmachtigingen tot dit pad heeft! - - - Assignment of empty DTD file name! Toewijzing van een lege DTD bestandsnaam! - + Assignment of empty name to the DTD declaration! Toewijzing van een lege naam aan de DTD declaratie! - + Error while interpreting XML buffer at line %1 column %2. Message generated by the parser: %3. %4 Er trad een fout op tijdens het interpreteren van de XML buffer op lijn %1, kolom %2. De parser antwoordde met: %3. %4 - + Operation on unallocated element tree! It is necessary to load the XML parser buffer and interpret it so that the tree is generated! Een operatie werd uitgevoerd op een niet-gealloceerd element in de boomstructuur! De XML parser buffer moet eerst worden geladen en geinterpreteerd zodat deze boomstructuur kan worden gegenereerd! - Could not load file %1. The same appears to be inconsistent or one of its dependencies (DTD files) has errors or is missing! - Het bestand %1 kon niet worden geladen. Ditzelfde lijkt inconsistent te zijn of een van zijn dependencies (DTD bestanden) heeft ofwel fouten of ontbreekt! - - - Operation with unallocated tree element! Operatie met een niet-gealloceerd object! - + Operation with element which does not exists in the element tree currently loaded! Er werd een operatie uitgevoerd op een element dat niet bestaat in de huidig geladen elementen-boomstructuur! - + Assignment of a value to an invalid connection parameter! Toewijzing van een waarde aan een ongeldige verbindingsparameter! - + Operation on connection not established! Er werd een operatie uitgevoerd op een niet-verbonden verbinding! - + Attempt to connect without define configuration parameters! Poging tot verbinden zonder dat de configuratieparameters zijn gedefinieerd! - + Attempt to start a connection already stablished! Poging tot het starten van een verbinding die reeds verbonden is! - + Could not connect to the database. Message returned: `%1' Er kon geen verbinding worden gemaakt met de database. Het bericht is: `%1' - + Assignment of not allocated SQL command result! Toewijzing van een niet-gealloceerde SQL commandoresultaat! - + Unable to allocate the result of the SQL command because the response from the DBMS was not understood by the client! Het is niet mogelijk om het resultaat van het SQL commando te allocaren omdat de client het antwoord van de DBMS niet verstond! - + Unable to allocate command result for the SQL because the server has generated a fatal error! Message returned by the DBMS: `%1' Het commandoresultaat voor de SQL code kan niet worden gealloceerd omdat de server een fatale fout genereerde! Het bericht dat terugkwam van de DBMS is: `%1' - + Reference to a column of tuple with invalid index! Referentie naar een kolom van een tuple met een ongeldige index! - + Reference to a column of tuple with invalid name! Referentie naar een kolom van een tuple met een ongeldige naam! - + Reference to a tuple with an invalid index or the result is empty (no tuples)! Referentie naar een tuple met een ongeldige index of het resultaat is leeg (geen tuples)! - + Reference to a column of a tuple which was not yet initialized (tuple navigation not started)! Referentie naar een kolom van een tuple dat nog niet werd geinitializeerd (tuple-navigatie nog niet gestart)! - + Could not execute the SQL command. Message returned: `%1' Het SQL commando kon niet worden uitgevoerd. Het teruggekeerde bericht is: `%1' - + Invalid use of a view reference as whole SQL definition! The assigned reference must be an expression! Ongeldig gebruik van een view-referentie als volledige SQL definitie! De toegewezen referentie moet een expressie zijn! - + Assignment of a second definition expression to the view! Toewijzing van een tweede definitie-expressie aan de view! - + It is not possible mix ordinary references (SELECT-FROM, FROM-WHERE, After WHERE) with references used as view SQL definition! Gewone referenties (SELECT-FROM, FROM-WHERE, Na WHERE) kunnen niet worden gemixt met referenties die gebruikt worden als SQL definitie! - + Assignment of collation object which type is invalid! Toewijzing van een sorteringsobject wiens type ongeldig is! - + At the moment pgModeler does not support the creation of primary keys which some columns were generated by relationship connection. To create primary keys with this feature you can use the field `Identifier' or the tab `Primary key' on relationship editing form! Op dit moment ondersteunt pgModeler de aanmaak van primary keys waarvan sommige kolomen door relatie-verbindingen worden gegenereerd nog niet. Om primary keys met dit feature aan te maken kan u gebruik maken van het veld 'Identifier' of het 'Primary key' tab-blad in het relatie-bewerkingsvenster! - + Collations must be created at least with attributes LC_COLLATE and LC_CTYPE defined! Sorteringsmethodes moeten worden aangemaakt en minstens LC_COLLATE en LC_CTYPE gedefinieerd hebben! - + The object `%1' (%2) cannot reference itself! This operation is not permitted for this kind of object! Het object `%1' (%2) kan niet naar zichzelf verwijzen! Deze operatie is niet toegelaten voor dit type object! - + Only operator families which uses `btree' as indexing method are accepted by operator class elements! Enkel operator-families die gebruik maken van `btree' als indexeringsmethod kunnen worden aanvaard als operatorklasse element! - + Reference to an invalid copy table option! Referentie naar een ongeldige kopie-tabel optie! - + Copy relationship between tables `%1' and `%2' cannot be done because the first one already copies attributes from `%3'! Tables can have only one copy table! De kopie-relatie tussen tabellen `%1' en `%2' kan niet worden aangemaakt omdat de eerste reeds attributen kopieert van `%3'! Tabellen kunnen over slechts een kopie-tabel beschikken! - + The INSTEAD OF mode cannot be used on triggers that belongs to tables! This is available only for view triggers! De INSTEAD OF modus kan niet worden gebruikt voor triggers die aan tabellen toehoren! Dit is enkel beschikbaar voor triggers die aan views toehoren! - + The TRUNCATE event can only be used when the trigger executes for each statement and belongs to a table! Het TRUNCATE event kan enkel worden gebruikt wanneer de trigger uitvoert voor elk statement en aan een tabel toebehoort! - + The INSTEAD OF mode cannot be used on view triggers that executes for each statement! De INSTEAD OF modus kan niet worden gebruikt voor view triggers die voor elk statement worden uitgevoerd! - + Constraint triggers can only be executed on AFTER events and for each row! Constraint triggers kunnen enkel worden uitgevoerd NA events en voor elke rij! - + A view trigger cannot be AFTER/BEFORE when it executes for each row! Een view trigger kan niet AFTER/BEFORE zijn wanneer deze voor elke rij wordt uitgevoerd! - + A trigger cannot make reference to columns when using INSTEAD OF mode and UPDATE event! Een trigger kan niet naar kolommen refereren wanneer deze gebruikt maakt van de INSTEAD OF modus binnen een UPDATE event! - + Assignment of a column which has no parent table to the object `%1' (%2)! Toewijzing van een kolom aan object `%1' (%2) die geen ouder-tabel heeft! - + Only constraint triggers can be deferrable or reference another table! Enkel constraint triggers kunnen uitstelbaar zijn of naar andere tabellen refereren! - + Reference to a function id which is incompatible with the user define type configuration! Een referentie naar een functie id die niet compatibel is met de configuratie van het gebruiker gedefinieerde type! - + The operator class assigned to the object `%1' (%2) must use `btree' as indexing method! De operatorklasse die is toegewezen aan het object `%1' (%2) moet 'btree' als indexeringsmethod gebruiken! - Unsupported PostgreSQL version (%1) detected! Valid versions are: %2 - Er werd een niet-ondersteunde versie van PostgreSQL gedetecteerd (%1)! Geldige versies zijn: %2 - - - The validation process failed due to an error triggered by the validation helper. For more details about the error check the exception stack! Het validatieproces faalde omwille van een fout in de validatie-helper. Kijk voor meer details over de fout de exception stack na! - + The extension `%1' is registered as a data type and cannot have the attribute `handles datatype' modified! De uitbreiding `%1' is geregistreerd als een data type, het 'behandeld data type' attribuut kan niet worden aangepast! - + The fk relationship `%1' cannot be created because the foreign-key that represents it was not created on table `%2'! De fk relatie `%1' kan niet worden aangemaakt omdat de foreign key die deze relatie weergeeft niet werd aangemaakt op tabel `%2'! - + Assignement of an invalid object name pattern to the relationship `%1'! Toewijzijng van een ongeldig objectnaamspatroon aan de relatie `%1'! - + Reference to an invalid object name pattern id on the relationship `%1'! Referentie naar een ongeldige id van objectnaamspatronen voor de relatie `%1'! - + Invalid use of variadic parameter mode! This mode can be used only with an array or "any" data type! - + + The object `%1' (%2), oid `%3', could not be imported due to one or more errors! Check the exception stack for more details. `HINT:' if the object somehow references objects in `pg_catalog' or `information_schema' consider enable the importing of system objects. + + + + It's not possible convert the type of the column `%1' to serial! It must have an `integer' based type and its default value must be a call to `nextval(seq_name::regclass)' function or a sequence object must be directly assigned to the column! - + A parent table of `%1' which OID is `%2' was not found in the set of imported objects! - + The enumeration `%1' can't be assigned to the type `%2' because contains invalid characters! - + The enumeration `%1' can't be assigned to the type `%2' because is too long! - + The connection was idle for too long and was automatically closed! - + The connection was unexpectedly closed by the database server `%1' at port `%2'! - Invalid use of variadic parameter mode! This mode can be used only with array data types! - Ongeldig gebruik van varierende-parametermodus! Deze modus kan enkel worden gebruikt bij array types! - - - + Mixing incompatibles DBMS export modes: `ignore object duplications', `drop database' or `drop objects' cannot be used with `simulate export'! Mixen van niet-compatibele DBMS export-modussen: `negeer object duplicaten', `verwijder database' of `verwijder objecten' kan niet samen worden gebruikt met `simuleer export'! - + Mixing incompatibles DROP options: `drop database' and `drop objects' cannot be used at the same time! Mixen van niet-compatibele DROP opties: `verwijder database' en `verwijder objecten' kunnen niet samen worden gebruikt! - + Invalid object id swapping operation! The objects involved are the same! Ongeldige object id wissel-operatie! De betrokken objecten zijn dezelfde! - + Invalid object id swapping operation! The database itself, tablespaces or roles cannot have the ids swapped! Ongeldige object id wissel-operatie! De database zelf, tablespaces en rollen kunnen geen ids omwisselen! - + The widget already has a parent and cannot be assigned to a different object! Het widget heeft reeds een ouder en kan niet aan een ander object worden toegewezen! - The object `%1' (%2) could not be imported due to one or more errors! Check the exception stack for more details. - Het object `%1' (%2) kon niet worden geïmporteerd omwille van een of meer fouten! Kijk de exception stack na voor meer details. - - - Could not load the database model file `%1'. Check the error stack to see details. Try to run `pgmodeler-cli --fix-model' in order to correct the structure of the file if that is the case. Het datababase modelbestand `%1' kon niet worden geladen. Kijk de foutenstack na voor meer details. Probeer `pgmodeler-cli --fix-model' uit te voeren op het model om de bestandsstructuur te corigeren indien dit nodig zou zijn. - + The column `%1' cannot reference it's parent table `%2' as data type! De kolom `%1' kan niet naar de oudertabel `%2' als data type verwijzen! - + Operation with an invalid element id `%1'! Operatie met een ongeldige olement id `%1'! - + Reference to an invalid color id `%1' for element `%2'! Referentie naar een ongeldige kleuren-id `%1' voor element `%2'! - + Assignment of an invalid object to `%1' (%2)! The assigned object must be of type `%3'. Toewijzing van een ongeldig object aan `%1' (%2)! Het toegewezen object moet van het type `%3' zijn. - + The sequence `%1' can't be assigned to the column `%2' because the data type of the latter is incompatible. The type used must be an integer one! De sequentie `%1' kan niet aan de kolom `%2' worden toegewezen omdat het data type van de kolom niet compatibel is. Het gebruikte type moet een integer type zijn! - + The option to generate temporary object names can only be used in simulation mode! De optie om tijdelijke objectnamen te genereren kan enkel worden gebruikt in simulatie-modus! - It's not possible convert the type of the column `%1' to serial! It must have an `integer' based type and its default value must be a call to `nextval(seq_name::regclass)' function! - Het is niet mogelijk om het type van kolom `%1' naar serial om te vormen! Het type van de kolom moet een `integer'-gebaseerd type zijn en de standaardwaarde moet een aanroep van de `nextval(seq_name::regclass)' functie zijn! - - - + Could not assign the variable `%1' to event trigger's filter. Currently, PostgreSQL supports only the `TAG' variable! De variabele `%1' kon niet worden toegewezen aan de filter van de event trigger! Op dit moment ondersteunt PostgreSQL enkel de `TAG' variabele! - + Could not perform the `%1' operation on `%2' using the data on row `%3'! All changes were rolled back. ** Returned error ** @@ -5159,32 +5179,28 @@ Het bericht dat terugkwam van de DBMS is: `%1' %4 - + Malformed unescaped value on row `%1' column `%2'! Incorrect gevormde un-escape waarde op rij `%1', kolom `%2'! - + Trying to undo/redo an invalid operation over an object that does not exists anymore or can't be handled! The operation history will be cleaned up. Poging tot het ongedaan maken of opnieuw uitvoeren van een ongeldige operatie op een object dat niet langer bestaat of niet kan worden behandeld! De taakgeschiedenis zal worden leeggemaakt. - + The object `%1' (%2) can't be handled because some needed fields are not set! Please, make sure to fill at least the requires fields in order to properly create or update the object. Het object `%1' (%2) kan niet worden behandeld omdat sommige nodige velden niet werden ingesteld! Gelieve de verplichte velden in te voeren om het object correct aan te kunnen maken of passen. - + A relationship can only be swapped by other object of the same kind! De relatie kan enkel worden omgewisseld door een ander object van dezelfde soort! ExtensionWidget - - Form - Venster - Version: @@ -5214,87 +5230,93 @@ Het bericht dat terugkwam van de DBMS is: `%1' Venster - + + Hide this widget + Verberg dit widget + + + + ... + ... + + + Replace one occurrence Vervang één voorkomen - + Replace Vervangen - + Replace all occurrences Vervang alle voorkomens - + Replace All Vervang Allen - + Replace the selection and find the next one Vervang in de selectie en vindt de volgende - + Replace && Find Vervang && Zoek - + Replace: Vervang: - + Find: Zoek: - + Find previous Zoek vorige - + Shift+F3 - + Find next Zoek volgende - + F3 - + Case sensitive Hoofdlettergevoelig - + Regular expression Regular expression - + Whole words Volledig woord - FunctionWidget - - Form - Venster - + FunctionWidget Attributes @@ -5316,90 +5338,82 @@ Het bericht dat terugkwam van de DBMS is: `%1' Aantal rijen - - Langague: - Taal: - - - + Return Method: Terugkeermethode: - + Behavior: Gedrag: - Simple - Simpel - - - + Set Set - Table - Tabel + + Language: + - + Si&mple - + Tab&le - + Return Table Terugkeertabel - + Execution Cost: Uitvoeringskost: - + Windown Func. Windowing Functie - + Leakproof Lekdicht - + Parameters Parameters - + Definition Definitie - + Dynamic Library: Dynamische Bibliotheek - + Symbol: Symbool: - + Library: Bibliotheek: - + Source code: Broncode: @@ -5443,532 +5457,609 @@ Het bericht dat terugkwam van de DBMS is: `%1' Algemeen && Design - + General Algemeen - - The opened models will be saved periodically - De geopende modellen worden periodiek opgeslagen - - - - Autosave interval: - Automatische opslaginterval: - - - + Operation history: Taakgeschiedenis: - - minute(s) - minuten - - - - items - items - - - + Check if there is a new version on server Vink dit aan om na te kijken of een nieuwe versie beschikbaar is op de server - - Check for updates at startup - Zoek naar updates bij het opstarten - - - - pixels - pixels - - - - Grid size: - Rastergrootte: - - - + Design Design - + Graphical objects (table, views and textboxes) will be created in a single step without the need to click on canvas Grafische objecten (tabellen, views en tekstvakken) worden in een enkele stap aangemaakt zonder op het canvas te hoeven klikken - + Simplify creation of graphical objects Should be 'Vereenvoudig de aanmaak van grafische objecten' but that's way too long for the space Versimpel creatie van grafische objecten - + After loading the model the last zoom and position on canvas will be restored Nadat het model geladen is wordt de laatste zoomwaarde en positie op het canvas hersteld - + Save and restore last position and zoom Behoud de laatste positie en zoom - Disable antialiasing for lines and texts improving performance on huge models (requires restart) - Schakel anti-aliassing uit voor lijnen en tekst, dit verbetert de performantie bij grote modellen (vereist opnieuw opstarten van de applicatie) - - - + Disable render smoothness Schakel vlakke rendering uit - + Hide the object that represents the relationship name Verberg het object dat de relatienaam voorstelt - + Hide relationship name Verberg relatienaam - Operations like save, export and diff will be executed without asking user to validate the model - Operaties zoals opslaan, exporteren en diff worden uitgevoerd zonder dat de gebruiker gevraagd wordt om het model te valideren - - - + Validate before save, export or diff Valideer voor opslaan, exporteren of diff - + Hide the object which represents the tag assigned to the table Verberg het tag object dat is toegekend aan de tabel - + Hide table tags Verberg tabel-tags - + Start move the canvas when the cursor is on the canvas edges Verplaatst het canvas wanneer de cursor zich op de rand van het canvas bevindt - + Move canvas by keep mouse on corners Verplaats canvas bij muis in de hoeken - + Hide the portion of table which represent triggers, indexes and rules Verberg het tabel-gedeelte dat triggers, indexes en regels voorstelt - + Hide table extended attributes Verberg uitgebreide attributen - - By default panning mode is triggered with left click and range selection with Shift + left click. - De standaard panning modus wordt geactiveerd met linkermuisknop en een gebied-selectie via Shift+Linkermuisknop. - - - + Disable antialiasing for lines and texts improving performance when handling huge models. - + Triggers a dialog asking the user to validate the model before a save, export or diff operation. - - Swap panning and range selection triggers - Wissel panning- && gebiedsselectietriggers - - - + When enabled this option creates a placeholder object at the previous table's position when starting to move it. This will cause graphical updates on relationship lines to be performed only when the drag & drop action is done improving the performance. Disabling placeholders will cause those updates to be executed every time the table's position changes a single pixel (classical behavior). - + Use placeholders when moving tables - + Toggles the code completion in all fields that accepts the input of SQL commands. Schakelt codevervollediging aan of af in alle velden die SQL commando's aanvaarden. - + + Minimum object opacity (%): + + + + + Defines the minimum opacity percentage applied to the objects when using the fade out feature. A zero opacity causes the object to be completely hidden not being possible to interact with it in the canvas area. + + + + + Canvas grid size: + + + + + Defines the vertical and horizontal grid size. This value affects the spacing of objects when using object grid alignment feature. + + + + + By default the range selection is triggered with Shift + left click. By checking this option range selection will be activated only with a single click and move. + + + + + Trigger range selection with a single click + + + + + Defines the maximum amount of elements held in the operation history. Once reached the maximum number the history is automatically cleaned. + + + + + Defines the period when the opened models will be saved automatically. + + + + + Autosave interval (minutes): + + + + Enable SQL code completion Schakel SQL codevervollediging in - + + Replaces any straight line in relationship by curved ones in order to improve the model's visualization. + + + + + Use curved lines for relationships + + + + + Souce code editor args: + + + + + lines + + + + + Clear the entire SQL comand history. + + + + + Clear history + + + + + Open in file manager + Open in bestandsbeheer + + + + Overrides the default user interface language defined by the system. Requires restarting the program. <strong>NOTE:</strong> UI translations are third party collaborations thus any typo or mistake should be reported directly to their respective maintainers. + + + + + SQL history max. length: + + + + + Check updates at startup + + + + + User interface language: + + + + + Browse the source code editor application + + + + + Souce code editor: + + + + + Configurations directory: + + + + Printing && Code Printen && Code - + Code style Codestijl - + Size: Grootte: - + Font: Lettertype: - + Colors: Kleuren: - - + + Options: Opties: - + Display line numbers Geef lijnnummers weer - + Highlight lines at cursor's position Licht de huidige lijn onder de cursor op - + pt pt - + Custom tab width: - + Printing Printen - + Print grid Print raster - + Print page numbers Print paginanummers - + Paper: Papier: - + A0 (841 x 1189 mm) - + A1 (594 x 841 mm) - + A2 (420 x 594 mm) - + A3 (297 x 420 mm) - + A4 (210 x 297 mm) - + A5 (148 x 210 mm) - + A6 (105 x 148 mm) - + A7 (74 x 105 mm) - + A8 (52 x 74 mm) - + A9 (37 x 52 mm) - + B0 (1030 x 1456 mm) - + B1 (728 x 1030 mm) - + B10 (32 x 45 mm) - + B2 (515 x 728 mm) - + B3 (364 x 515 mm) - + B4 (257 x 364 mm) - + B5 (182 x 257 mm) - + B6 (128 x 182 mm) - + B7 (91 x 128 mm) - + B8 (64 x 91 mm) - + B9 (45 x 64 mm) - + C5E (163 x 229 mm) - + Comm10E (105 x 241 mm) - + DLE (110 x 220 mm) - + Executive (191 x 254 mm) - + Folio (210 x 330 mm) - + Ledger (432 x 279 mm) - + Legal (216 x 356 mm) - + Letter (216 x 279 mm) - + Tabloid (279 x 432 mm) - + Custom Aangepast - + Orientation: Oriëntatie: - + Landscape Landschap - + Portrait Portret - + Unity: Eenheid: - + Custom Size: Aangepaste Grootte: - + Width: Breedte: - + Height: Hoogte: - + Page Margins: Paginamarges: - + Left: Links: - + Left margin Linkermarge - + Top: Kop: - + Top margin Kopmarge - + Right: Rechts: - + Right margin Rechtermarge - + Bottom: Voet: - + Bottom margin Voetmarge - + Milimeters Milimeters - + Pixels Pixels - + Inches Inches - + Centimeter Centimeter - + Line numbers' font color Lettertypekleur van lijnnummers - + Line numbers' background color Achtergrondkleur van lijnnummers - + Highlighted line color Uitlichtkleur - + The little brown fox jumps over the lazy dog The little brown fox jumps over the lazy dog + + + System default + + + + + All files (*.*) + + + + + Load file + + - GraphicalView + GenericSQLWidget - - Connected rels: %1 - Verbonden relaties: %1 + + SQL code + SQL code @@ -5981,10 +6072,6 @@ Het bericht dat terugkwam van de DBMS is: `%1' IndexWidget - - Form - Venster - Attributes @@ -6038,10 +6125,6 @@ Het bericht dat terugkwam van de DBMS is: `%1' LanguageWidget - - Form - Venster - Trusted: @@ -6136,839 +6219,725 @@ Het bericht dat terugkwam van de DBMS is: `%1' Ctrl+F - msg - msg - - - + &File &Bestand - + &Edit &Bewerken - Help - Help - - - + &Show &Weergave - &Plugins - &Plugins - - - + General Algemeen - + Controls Controls - + &Load &Laden - + Sa&ve as - + E&xit - + Exit pgModeler - + &About pgModeler - + &Print - + Print model - + &Undo - + Undo operation - + &Redo - + Redo operation - + &Export &Exporteer - + Ctrl+Shift+E - + &Show grid - + &Close &Sluiten - + &Normal zoom - + &Align to grid - + Show &delimiters - + &Settings - + F12 F12 - + &Overview - + &Support - + Access the support page - + New Nieuw - + &Diff - + + Determine the changes between model/database and another database + + + + Shift+M - + &Bug report - + Objects me&tadata - + Objects metadata - - Ctrl+N - + + Arrange objects + - Save - Opslaan + + Rearrange objects over the canvas + + + + + Ctrl+N + - + Ctrl+S Ctrl+S - + Zoom in Inzoomen - + Ctrl+= Ctrl+= - + Zoom out Uitzoomen - + Zoom - Zoom - - + He&lp - + Pl&ugins - + &New - + New model Nieuw model - + &Save Op&slaan - + &Zoom in - + Zoo&m out - + Ctrl+- Ctrl+- - Load - Laden - - - + Ctrl+O Ctrl+O - Save as - Opslaan als - - - Exit - Afsluiten - - - + Ctrl+Q Ctrl+Q - About pgModeler - Over pgModeler - - - + F4 F4 - Print - Printen - - - + Ctrl+P Ctrl+P - Undo - Ongedaan maken - - - + Ctrl+Z Ctrl+Z - Redo - Opnieuw doen - - - + Ctrl+Y Ctrl+Y - Export - Exporteer - - - + Export the current opened model in different modes Exporteer het huidig geopende model in verschillende modussen - + &Recent Models - + &Import - + Rest&ore Session - + &Fix a model - + &Check for update - + Ctrl+Shift+S Ctrl+Shift+S - + Show grid Raster tonen - + Ctrl+G Ctrl+G - Close - Sluiten - - - + Close current model Sluit dit model - + Ctrl+W Ctrl+W - Normal zoom - Normale zoom - - - + Ctrl+0 Ctrl+0 - Align to grid - Uitlijnen op raster - - - + Align objects position to grid Lijn objecten uit op het raster - + Ctrl+H Ctrl+H - Show delimiters - Delimiters tonen - - - + Show the page delimiters Toon pagina-delimiters - + Ctrl+L Ctrl+L - Settings - Instellingen - - - + Edit pgModeler settings Bewerk de pgModeler instellingen - + Save all Alles opslaan - Overview - Overzicht - - - + Show the model overview Toon modeloverzicht - + F10 F10 - Wiki - Wiki - - - Access the wiki pages - Ga naar de wiki paginas - - - + F1 F1 - + New object - + Plugins Plugins - + Access the list of loaded plugins Bekijk de lijst van geladen plugins - Recent Models - Recente Modellen - - - + Load recently opened model Laad recent geopend model - Import - Importeren - - - + Import existing database to new model (reverse engineering) Importeert een bestaande database in een nieuw model (Reverse Engineering) - + Ctrl+Shift+I Ctrl+Shift+I - Restore Session - Sessie Herstellen - - - Fix a model - Corrigeer een model - - - + New version found! Er is een nieuwe versie beschikbaar! - + Update for the current version is available on project's site Er is een update beschikbaar voor de huidige versie op de website van het project - Check for update - Zoek naar updates - - - + action_main_menu - + Main menu Hoofdmenu - + Show expanded Toon uitgeklapt - + Expands the main menu bar in classical mode Klapt het hoofdmenu uit in klassieke modus - + Hide main menu Verberg hoofdmenu - + Hides the main menu bar and put the action on a separated action This looks like something that could use revisiting (the original EN text that is) Verbergt de hoofdmenu en verplaats de actie naar een afgescheiden actie - + Ctrl+Shift+H Ctrl+Shift+H - Diff - Diff - - - - Determine the changes between model and database - Bepaal de verschillen tussen het model en een database - - - + Ctrl+Shift+D - + Welcome Welkom - + Welcome screen Welkomstscherm - + Shift+W - + Design Design - + Design database models Design databasemodellen - + Shift+D - + Manage Beheer - + Manage existent databases Beheer bestaande databases - Bug report - Bug rapport - - - + Report a bug Rapporteer een bug - + Donate Doneer - + Help pgModeler by donating! Help pgModeler via donering! - + (Demo) (Demo) - - Save all models - Sla alle modellen op - - - Some models were modified! Do you really want to quit pgModeler without save them? - Sommige modellen werden aangepast! Bent u er zeker van dat u pgModeler wilt sluiten zonder deze op te slaan? - Saving temp. models Tijdelijke modellen opslaan - + Clear Menu Menu leegmaken - + The demonstration version can create only `one' instance of database model! De demonstratieversie kan slechts één databasemodel instantie aanmaken! - - + + Save model Model opslaan - The model was modified! Do you really want to close without save it? - Het model werd aangepast! Bent u er zeker van dat u het wilt sluiten zonder het op te slaan? + + Grid + + + + + Hierarchical + - + + Scattered + + + + Save modified model(s) - + The following models were modified but not saved: %1. Do you really want to quit pgModeler? - + The model <strong>%1</strong> was modified! Do you really want to close without save it? - - + + Warning Opgepast - + You're running a demonstration version! The model saving feature is available only in the full version! Dit is een demonstratie-versie! Het opslaan van modellen is enkel beschikbaar in de volledige versie! - - - + + + Confirmation Bevestiging - + <strong>WARNING:</strong> The model <strong>%1</strong> is invalidated! It's recommended to validate it before save in order to create a consistent model otherwise the generated file will be broken demanding manual fixes to be loadable again! <strong>PAS OP: </strong> Het model <strong>%1</strong> is niet gevalideerd! Het is aangeraden om het model te valideren vooraleer dit op te slaan om ervoor te zorgen dat u een consistent model behoudt, anders is het modelijk dat het gegenereerde bestand onvolledig is en manuele correcties zal vereissen om het opnieuw te kunnen laden! - + Save anyway Toch opslaan - - - + + + Validate Valideer - + Save '%1' as... Sla '%1' op als... - - + + Database model (*.dbm);;All files (*.*) Database model (*.dbm);;Alle bestanden (*.*) - + Access support page - + You're running a demonstration version! Note that you'll be able to create only <strong>%1</strong> instances of each type of object and some key features will be disabled or limited!<br/><br/>You can purchase a full binary copy or get the source code at <a href='http://pgmodeler.com.br'>pgmodeler.com.br</a>. <strong>NOTE:</strong> pgModeler is an open source software, but purchasing binary copies or providing some donations will support the project and cover all development costs.<br/><br/> <strong>HINT:</strong> in order to test all features it's recommended to use the <strong>demo.dbm</strong> model located in </strong>Sample models</strong> at <strong>Welcome</strong> view.<br/><br/><br/><br/> - You're running a demonstration version! The model export feature can be tested twice per pgModeler execution! - Dit is een demonstratie-versie. De model-export functionaliteit kan slechts twee maal per pgModeler uitvoering worden getest! + + Rearrange objects over the canvas is an irreversible operation! Would like to proceed? + - + <strong>WARNING:</strong> The model <strong>%1</strong> is invalidated! Before run the export process it's recommended to validate in order to correctly create the objects on database server! <strong>PAS OP:</strong> Het model <strong>%1</strong> is niet gevalideerd! Vooraleer u het export proces start is het aangeraden om de validatie uit te voeren. Dit zorgt ervoor dat de objecten correct op de database server kunnen worden aangemaakt! - + Export anyway Toch exporteren - You're running a demonstration version! The database import (reverse engineering) feature is available only in the full version! - Dit is een demonstratie-versie! De database-import functie (reverse engineering) is enkel beschikbaar in de volledige versie! - - - You're running a demonstration version! The model-database diff feature is available only in the full version! - Dit is een demonstratie-versie! De databasemodel diff functie is enkel beschikbaar in de volledige versie! - - - + <strong>WARNING:</strong> The model <strong>%1</strong> is invalidated! Before run the diff process it's recommended to validate in order to correctly analyze and generate the difference between the model and a database! <strong>PAS OP:</strong> Het model <strong>%1</strong> is niet gevalideerd! Het is aangeradem om het model te valideren vooraleer u het diff process start. Dit zorgt voor een correcte analyse en het correct genereren van de diff tussen het model en de database! - + Diff anyway Voer diff toch uit - + Database model printing Databasemodel printen - + Changes were detected in the definitions of paper/margin of the model which may cause the incorrect print of the objects. Do you want to continue printing using the new settings? To use the default settings click 'No' or 'Cancel' to abort printing. Er werden veranderingen gedetecteerd tussen de papier- en margedefinities van het model die ertoe kunnen leiden dat de objectenn foutief worden geprint. Wenst u te printen met deze nieuwe instellingen? Om de standaardinstellingen te gebruiken, klik op 'Nee' of klik 'Annuleren' om het printen af te breken. - + Load model Laad model - + Could not load the database model file `%1'. Check the error stack to see details. You can try to fix it in order to make it loadable again. Het database modelbestand `%1' kon niet worden geladen. Kijk de error stack na voor details. U kan proberen het probleem te corrigeren om het bestand weer laadbaar te maken. - + Fix model Corrigeer model - + Cancel Annuleren - Open Wiki pages - Open Wiki paginas - - - + This action will open a web browser window! Want to proceed? Deze actie opent een browservenster! Wilt u verdergaan? - + (no samples found) (geen voorbeelden gevonden) - You're running a demonstration version! Note that you'll be able to create only <strong>%1</strong> instances of each type of object and some key features will be disabled!<br/><br/>You can purchase a full binary copy or get the source code at <a href='http://pgmodeler.com.br'>pgmodeler.com.br</a>. <strong>NOTE:</strong> pgModeler is an open source software, but purchasing binary copies or providing some donations will support the project and cover all development costs.<br/><br/><br/><br/> - Dit is een demonstratieversie! Houdt er rekening mee dat u slechts <strong>%1</strong> instantie van elk type object aan zal kunnen maken en dat sommige features uitgeschakeld zijn!<br/><br/>U kan de volledige versie aankopen of de broncode raadplegen via <a href='http://pgmodeler.com.br'>pgmodeler.com.br</a>. <strong>LET OP:</strong> pgModeler is open source software maar volledige versies aakopen of doneren aan het project ondersteunen het project en de ontwikkelingskosten hiervan.<br/><br/><br/><br/> - - - The execution of demonstration version has finished! Did you like pgModeler and want to purchase it? Use the following promocodes and receive good discounts:<br/><br/> <strong>D3M02BR0NZ3</strong> (Discount on bronze package)<br/> <strong>D3M02S1LV3R</strong> (Discount on silver package)<br/> <strong>D3M02G0LD</strong> (Discount on gold package)<br/> <strong>D3M02PL4T1NUM</strong> (Discount on platinum package)<br/> <strong>D3M02D14M0ND</strong> (Discount on diamond package)<br/> <br/>Thank you for testing pgModeler! - De uitvoer van de demonstratieversie is voltooid! Vindt u pgModeler een goed product en wenst u het aan te schaffen? Gebruik de volgende promocodes en krijg een aangename korting:<br/><br/> <strong>D3M02BR0NZ3</strong> (Korting voor brons-pakket)<br/> <strong>D3M02S1LV3R</strong> (Korting voor zilver pakket)<br/> <strong>D3M02G0LD</strong> (Korting voor gouden pakket)<br/> <strong>D3M02PL4T1NUM</strong> (Korting voor platinum pakket)<br/> <strong>D3M02D14M0ND</strong> (Korting voor diamanten pakket)<br/> <br/>Hartelijk dank om pgModeler te testen! - - - + save opslaan - + export exporteer - + diff diff - + Executing pending <strong>%1</strong> operation... De uitvoer wacht op <strong>%1</strong> taak... @@ -6981,74 +6950,74 @@ Het bericht dat terugkwam van de DBMS is: `%1' Dialoogvenster - + msg - + Exceptions Uitzonderingen - + Show raw text errors or information. Toon technische error-tekst en -informatie. - + Show/hide exceptions stack. Toon/verberg uitzonderingsstack. - + ... - - + + &Yes &Ja - - + + &No &Nee - + Cancel Annuleren - + &Ok &OK - + &Cancel &Annuleren - + Error Fout - + Alert Waarschuwing - + Information Informatie - + Confirmation Bevestiging @@ -7096,592 +7065,667 @@ Het bericht dat terugkwam van de DBMS is: `%1' Opties - + Handles the following database model attributes in the metadata file: author, zoom factor, last position and default objects. - + Database model metadata - + Handles the objects' positioning in the metadata file. - + Objects' positioning - + Handles the objects' custom colors in the metadata file. Currently available only for relationships and schemas. - + Custom object's colors - - Handles the objects' protection status in the metadata file. + + Handles the objects' protection status in the metadata file. + + + + + Objects' protection status + + + + + Handles the objects' SQL disabled status in the metadata file. + + + + + Objects' SQL disabled status + + + + + Handles the objects' fade out status in the metadata file. - - Objects' protection status + + Objects' fade out status - - Handles the objects' SQL disabled status in the metadata file. + + Save tags to the output file when extracting metadata. When loading the file, the tags are recreated and duplicated ones are ignored. - - Objects' SQL disabled status + + Save textboxes to the output file when extracting metadata. When loading the file, the textboxes are recreated and duplicated ones are ignored. - + Handles the objects' custom SQL commands in the metadata file. - + Custom SQL commands - - Save textboxes to the output file when extracting metadata. When loading the file textboxes are recreated and duplicated ones are ignored. + + Textbox objects - Textbox objects + Tag objects - - Save tags to the output file when extracting metadata. When loading the file tags are recreated and duplicated ones are ignored. + + Handles the tables' and views' extended attributes display status in the metadata file. - - Tag objects + + Tables' extended attributes display + + + + + Save generic SQL objects to the output file when extracting metadata. When loading the file, the objects are recreated and duplicated ones are ignored. + + + + + Generic SQL objects - + Backup file: - - + + Select file - + ... ... - - Apply to: + + Extracts the objects' metadata from the loaded models and apply to the current focused model. A backup file can be specified to where the focused model's current metadata will be saved. - - Operation: + + &Extract and restore + + + + + Extracts the objects metadata from one of the loaded models saving the info to a backup file. + + + + + Extract &only - - Extracts the objects metadata from one of the loaded models and apply to the current model. + + Reads the objects' metadata from a previously saved backup file and apply to the current model. - - Extract from a &model + + &Restore a backup file - - Reads the objects metadata from a previously saved backup file and apply to the current model. + + Apply to: - - Restore a bac&kup file + + Operation: - + Output Uitvoer - + Progress label... Vooruitgangslabel... - - + + model not saved yet - + The backup file cannot be the same as the input model! - + Extracting metadata to file `%1' - + Saving backup metadata to file `%1' - + Applying metadata from file `%1' - + Metadata processing aborted! - + Objects metadata file (*.omf);;All files (*.*) ModelDatabaseDiffForm - - - Database model diff - Databasemodel verschillen - - - - Generate diff from model - Genereer een diff op basis van het model - Settings Instellingen - - Input database - Invoerdatabase - - - + + Connection: Verbinding: - + + + Database: Database: - - Options - Opties - - - Ignores as many as possible errors on import step. This option generates a incomplete diff. - Negeer zoveel mogelijk fouten gedurende de invoer-stap. Deze optie genereerd een onvolledige diff. - - - + Ignore import errors Negeer importeerfouten - Clears the data of all tables which will have columns modified. This is useful to avoid errors related to type casting. <strong>WARNING:</strong> DO NOT use this option on production server and always make a backup before use this options. - Maak de data van alle tabellen waarvan kolommen werden aangepast leeg. Dit kan nuttig zijn om fouten te vermijden die worden veroorzaakt door type-casting. <strong>PAS OP</strong> gebruik deze optie NIET op een productie-server en maak altijd een backup vooraleer deze opties te gebruiken. - - - - Trucate tables before alter columns - Trunceer de tabellen vooraleer de kolommen aan te passen - - - Import system (built in) objects. Use this if the import step is returning errors. - Importeer systeem- /ingebouwde objecten. Gebruik deze optie indien de importeer-stap fouten genereert. - - - + Import system objects Importeer systeemobjecten - Import extension objects. Use this if the import step is returning errors even importing built in ones. - Importeer uitbreidingsobjecten. Gebruik deze optie indien de importeer-stap fouten genereert. - - - + Import extension objects Importeer uitbreidingsobjecten - + For DROP command, the objects that depends on an object to be dropped will be deleted as well. For TRUNCATE command, tables that are linked to a table to be truncated will be truncate too. <strong>NOTE:</strong> this option can affect more objects than listed in the output or diff preview. Voor DROP commando's worden objecten die afhankelijk zijn van het object dat verwijderd wordt, ook verwijderd. Voor het TRUNCATE commando worden tabellen die gelinkt zijn aan de te trunceren tabel ook getrunceerd. <strong>LET OP:</strong> deze optie kan objecten beïnvloeden die niet in het uitvoer- of diff-voorbeeld opgenomen zijn. - + Drop or truncate in cascade mode Drop of trunceer in cascade modus - + Permissions already set on database objects will be kept.The ones configured on the model will be applied to the database. Machtigingen die reeds op databaseobjecten zijn toegepast zullen behouden blijven. De machtigingen die door het model worden gespecifieerd zullen worden toegepast op de database. - + Keep object's permissions Behoudt de machtigingen van het object - + Database cluster level objects like roles and tablespaces will not be dropped. Database cluster-niveau objecten zoals rollen en tablespaces zullen niet worden verwijderd. - + Keep cluster objects Behoudt clusterobjecten - + Recreate only unmodifiable objects Hercreeer enkel niet-aanpasbare objecten - Instead of use an ALTER command to modify certain kind of objects a DROP and CREATE will be used in order to do a full modification. This option does not affects database objects. - In plaats van een ALTER commando om een bepaald soort object aan te passen, wordt eerst een DROP en dan een CREATE gebruikt. Deze optie beïnvloedt geen database objecten. - - - + Force recreation of objects Forceer het heraanmaken van objecten - + Ignores errors generated by duplicated objects when exporting the diff to database. Negeer fouten die worden gegenereerd door duplicate objecten gedurende het exporteren van de diff naar de database. - + Ignore duplicity errors Negeer fouten omwille van duplicaten - + Serial columns are converted to integer and having the default value changed to <strong>nextval(sequence)</strong> function call. By default, a new sequence is created for each serial column but checking this option sequences matching the name on column's default value will be reused and will not be dropped. Seriële kolommen worden geconverteerd naar integers en hun standaardwaarde wordt ingesteld als een functieaanroep naar <strong>nextval(sequentie)</strong>. Normaal gezien wordt een nieuwe sequentie aangemaakt voor elke seriële kolom maar deze optie aanvinken zorgt ervoor dat sequenties die de naam van de kolom gebruiken worden hergebruikt in plaats van verwijderd. - + Reuse sequences on serial columns Hergebruik sequenties op seriële kolommen - + No command to rename the destination database will be generated even the model's name differ from database name. Behoudt de naam van de doeldatabase wanneer deze verschilt van de databasenaam in het model. - + Preserve database name Behoudt databasenaam - + Diff mode Diff modus - + Override the PostgreSQL version when generating the diff. The default is to use the same version as the input database. Zet de versie waarvoor de diff wordt gegenereerd expliciet zelf. Standaard wordt dezelfde versie gebruikt als de invoerdatabase. - + Use PostgreSQL: Gebruikt PostgreSQL: - + Compares the model and the input database storing the diff in a SQL file for later usage. Vergelijkt het model en de invoerdatabase en slaat het verschil op in een SQL bestand voor later gebruik. - Store in SQL file - Sla op in SQL bestand - - - + File: Bestand: - + Select output file Selecteer uitvoerbestand - + ... ... - + Compares the model and the input database generating a diff and applying it directly to the latter. <strong>WARNING:</strong> this mode causes irreversible changes on the database and in case of failure the original structure is not restored, so make sure to have a backup before proceed. Vergelijkt het model met de invoerdatabase en genereerd een diff die op die laatste wordt toegepast. <strong>PAS OP:</strong> deze modus veroorzaakt onherroepelijke veranderingen in de database en in geval van falen wordt de originele structuur niet hersteld, zorg ervoor dat u een backup hebt vooraleer u verdergaat. - Apply on server - Toepassen op de server - - - + Ignores as many as possible errors on import step. This option generates an incomplete diff. - + Clears the data of all tables which will have columns modified. This is useful to avoid errors related to type casting. <strong>WARNING:</strong> DO NOT use this option on production servers and always make a backup before use it. - + Import system (built-in) objects. Use this if the import step is returning errors related to missing objects. - + Import objects created by extensions. Use this if the import step is returning errors even importing built in ones. - + Instead of use an ALTER command to modify certain kind of objects a DROP and CREATE will be used in order to do a full modification. This option does not affects the database object. - + Avoid the generation of DROP commands for objects that exists in database but not in the model. This is useful when diff a partial model against the complete database. - + Do not drop missing objects - + Store in S&QL file - + + Diff tool + + + + + Generate diff code + + + + + Source database + + + + + Current model: + + + + + (model) + + + + + Compare to + + + + Appl&y on server - + + Diff + Diff + + + + Froce the generation of DROP commands for columns and constraints that exist in database but not in the model. This is useful when diff a partial model against the complete database and the user needs to drop columns and constraint but preserve the rest of the objects. + + + + + Drop missing columns and constraints + + + + + Truncate tables before alter columns + + + + + Import && Export + + + + + Import + Importeren + + + + Export + Exporteer + + + + This advanced option causes pgModeler to ignore extra errors by their numeric codes. These errors must be informed in the input below and separeted by space. For the complete list of error codes check the PostgreSQL docs, section <strong> Appendix A. PostgreSQL Error Codes</strong>. <strong>WARNING:</strong> use this option with extreme care since it can interfere in final export result. + + + + + Ignore error codes + + + + Output Uitvoer - + Changes: Aanpassingen: - + Cancel Annuleren - + Progress label... Vooruitgangslabel... - + Step label... Staplabel... - + <html><head/><body><p>Objects marked with an <span style=" font-weight:600;">ALTER</span> may not be effectively changed unless that the differences detected are in attributes that can be modified through ALTER commands otherwise no operationwill be performed or, if the force recreation is checked, the object will be dropped and created again.</p></body></html> <html><head/><body><p>Objecten die zijn aangeduid met <span style=" font-weight:600;">ALTER</span> kunnen mogelijkerwijs niet worden aangepast tenzij de gedetecteerde verschillen in de attribute liggen die kunnen worden aangepast via een ALTER commando; in alle andere gevallen zal geen actie worden ondernomen of, indien 'Forceer het heraanmaken van objecten' is aangevinkt, zal het object worden verwijderd en heraangemaakt.</p></body></html> - + Objects to be created Objecten die aangemaakt moeten worden - - - - + + + + 0 0 - + Objects to be dropped Objecten die verwijderd moeten worden - + Possible objects to be changed Objecten die mogelijkerwijs aangepast moeten worden - + Ignored objects (system ones or with sql disabled) Genegeerde objecten (systeemobjecten of objecten waarvan SQL is uitgeschakeld) - + Diff Preview Diff voorbeeld - + &Apply diff Diff &Toepassen - + &Generate &Genereer - + &Close &Sluiten - - + + Waiting process to start... Wachten op het starten van de taak... - - Importing database <strong>%1</strong>... - Bezig met het importeren van database <strong>%1</strong>... - - - - Comparing the model <strong>%1</strong> and database <strong>%2</strong>... - Bezig met het vergelijken van model <strong>%1</strong> en database <strong>%2</strong>... - - - + Confirmation Bevestiging - + <strong>WARNING:</strong> The generated diff is ready to be exported! Once started this process will cause irreversible changes on the database. Do you really want to proceed? <strong>PAS OP:</strong> De gegenereerde diff is klaar om geëxporteerd te worden! Eens gestart zal dit proces onherroepelijke veranderingen aanbrengen aan de database. Bent u zeker dat u wilt verdergaan? - + Apply diff Diff toepassen - + Preview diff Diff belijken - - Exporting diff to database <strong>%1</strong>... - Diff exporteren naar database <strong>%1</strong>... + + model not saved yet + + + + + (none) + + + + + Step %1/%2: Importing database <strong>%3</strong>... + + + + + Step %1/%2: Comparing <strong>%3</strong> and <strong>%4</strong>... + + + + + Step %1/%2: Exporting diff to database <strong>%3</strong>... + - + Diff process paused. Waiting user action... Het diff proces is gepauzeerd. Wachten op een actie van de gebruiker... - + Saving diff to file <strong>%1</strong> De diff wordt opgeslagen in het bestand <strong>%1</strong> - + Diff process sucessfully ended! Het diff proces werd succesvol beëindigd! - - + + No operations left. Er zijn geen operaties meer. - + Operation cancelled by the user. De operatie werd geannulleerd door de gebruiker. - + Process aborted due to errors! Het proces werd afgebroken omwille van fouten! - + -- SQL code purposely truncated at this point in demo version! - + -- No differences were detected between model and database. -- -- Er werden geen verschillen gedetecteerd tussen het model en de database. -- - + Error code <strong>%1</strong> found and ignored. Proceeding with export. Foutencode <strong>%1</strong> trad op en werd genegeerd. De export gaat voort. - + Save diff as... Sla diff op als... - + SQL code (*.sql);;All files (*.*) SQL Code (*.sql);;Alle bestanden (*.*) @@ -7690,10 +7734,6 @@ Het bericht dat terugkwam van de DBMS is: `%1' ModelExportForm - Model Export - Modelexport - - Export model Exporteer model @@ -7704,227 +7744,217 @@ Het bericht dat terugkwam van de DBMS is: `%1' Instellingen - + Database server Database server - + pgModeler ignores errors generated by duplicated objects and creates only that ones which does not exists in the database. This option may be used when an object was created after a previous model export. pgModeler negeert fouten die worden gegenereerd door duplicate objecten en creëert objecten die nog niet in de database bestaan. Deze optie kan worden gebruikt wanneer een object werd gecreëerd door een eerdere model export. - + Ignore object duplicity Negeer object-duplicaten - + Connection: Verbinding: - + PostgreSQL version in which the SQL code should be generated. It is recommended to select this option only when the version of the DBMS, somehow, is not identifiable or if you need to generate a specific version of SQL code for test purposes. De PostgreSQL versie waarvoor SQL code moet worden gegenereerd. Het is aangeraden om deze optie enkel in te stellen wanneer de versie niet automatisch kan worden bepaald of wanneer u een specifieke versie nodig hebt voor bijvoorbeeld test-doeleinden. - - + + PostgreSQL: PostgreSQL: - + + This advanced option causes pgModeler to ignore extra errors by their numeric codes. These errors must be informed in the input below and separeted by space. For the complete list of error codes check the PostgreSQL docs, section <strong> Appendix A. PostgreSQL Error Codes</strong>. <strong>WARNING:</strong> use this option with extreme care since it can interfere in final export result. + + + + + Ignore error codes + + + + If <strong>DB</strong> is checked pgModeler will destroy the database if already exists on the server. When <strong>Objects</strong> is checked pgModeler will execute the DROP command attached to SQL-enabled objects. <strong>WARNING:</strong> this option leads to data loss so make sure to have a backup first. Indien <strong>DB</strong> aangevinkt is, zal pgModeler de database verwijderen indien deze reeds in de server bestaat. Indien <strong>Objecten</string> is aangevinkt zal pgModeler DROP commando's toevoegen aan de objecten waarvoor SQL is ingeschakeld. <strong>PAS OP:</strong> deze optie kan tot dataverlies leiden, zorg ervoor dat u een recente backup kan terugplaatsen. - + Drop: Verwijder: - + DB DB - Objects - Objecten - - - + pgModeler will destroy the database if already exists on the server. Make sure to have a backup before use this option because all data will be lost. pgModeler zal de database verwijderen indien deze reeds in de server aanwezig is. Zorg ervoor dat u een recente backup kan terugplaatsen indien nodig want alle data zal verloren gaan. - PNG Image - PNG Afbeelding - - - + Zoom: Zoom: - + Show grid Raster tonen - + Show delimiters Delimiters tonen - + Exporting the model page by page will generate files with a <strong>_p[n]</strong> suffix where <strong>n</strong> is the page id. Check if the current user has write permission on output folder. Het model pagina per pagina exportern genereert bestanden met de suffix <strong>_p[n]</strong> waarbij <strong>n</strong> de pagina id is. Zorg ervoor dat de huidige gebruiker schrijf-machtiging heeft in de uitvoermap. - + Page by page Pagina per pagina - - + + Select target file Selecteer doelbestand - - + + ... ... - Image: - Afbeelding: - - - + SQL file SQL bestand - - + + File: Bestand: - + Ob&jects - + Graphics file - - Image (PNG) - - - - + Type: Type: - - Vectorial (SVG) + + PostgreSQL version in which the SQL code should be generated + De PostgreSQL versie waarvoor SQL code moet worden gegenereerd + + + + I&mage (PNG) - - PostgreSQL version in which the SQL code should be generated - De PostgreSQL versie waarvoor SQL code moet worden gegenereerd + + &Vectorial (SVG) + - + Output Uitvoer - + Cancel Annuleren - + Progress label... Vooruitgangslabel... - + &Export &Exporteer - + &Close &Sluiten - + Error code <strong>%1</strong> found and ignored. Proceeding with export. Foutencode <strong>%1</strong> trad op en werd genegeerd. De export gaat voort. - + Initializing model export... Model export wordt geïnitialiseerd... - + Saving file '%1' Bestand `%1' wordt opgeslagen - - + + Exporting process aborted! Het export proces werd afgebroken! - + Export model as... Exporteer model als... - + SQL script (*.sql);;All files (*.*) - + Portable Network Graphics (*.png);;All files (*.*) - + Scalable Vector Graphics (*.svg);;All files (*.*) - SQL code (*.sql);;All files (*.*) - SQL Code (*.sql);;Alle bestanden (*.*) - - - PNG image (*.png);;All files (*.*) - PNG Afbeelding (*.png);;Alle bestanden (*.*) - - - + Exporting process canceled by user! Het export proces werd geannuleerd door de gebruiker! - + Exporting process sucessfuly ended! Het export proces werd succesvol beëindigt! @@ -7932,156 +7962,140 @@ Het bericht dat terugkwam van de DBMS is: `%1' ModelExportHelper - + Generating SQL code for PostgreSQL `%1' Bezig met het genereren van SQL code voor PostgreSQL `%1' - + Output SQL file `%1' successfully written. Het uitvoer-SQL bestand `%1' werd succesvol opgeslagen. - + Rendering objects to page %1/%2. Objecten worden gerendered naar pagina %1/%2. - + Output image `%1' successfully written. Uitvoerafbeelding `%1' werd succesvol opgeslagen. - + Exporting model to SVG file. - + SVG representation of database model - + SVG file generated by pgModeler - + Output file `%1' successfully written. - + Starting export to DBMS. De export naar het DBMS begint. - + PostgreSQL version detection overridden. Using version `%1'. PostgreSQL versie-detectie werd overschreven. Versie `%1' wordt gebruikt. - + PostgreSQL `%1' server detected. PostgreSQL `%1' server ontdekt. - + Generating temporary names for database, roles and tablespaces. De tijdelijke namen voor de database, rollen en tablespaces worden gegenereerd. - + Enabling the SQL code for database `%1' to avoid errors. SQL code voor de database `%1' wordt geactiveerd om fouten te vermijden. - + Ignoring object duplication errors. Duplicaten-fouten worden genegeerd. - + Ignoring the following error code(s): `%1'. De volgende foutencode(s) worden genegeerd: `%1' - + Trying to drop database `%1'. Proberen om database `%1' te verwijderen. - + Simulation mode activated. Simulatiemodus geactiveerd. - Creating object `%1' (%2). - Creëer object `%1' (%2). - - - Creating database `%1'. - Creëer database `%1'. - - - Connecting to database `%1'. - Verbinden met database `%1'. - - - + Generating SQL for `%1' objects... Genereren van SQL voor `%1' objecten... - + Destroying objects created on the server. Objecten aangemaakt op de server worden verwijderd. - + Restoring original names of database, roles and tablespaces. De originele namen van de database, rollen en tablespaces worden teruggezet. - Dropping object `%1' (%2). - Object `%1' (%2) wordt verwijderd. - - - - - + + + Creating object `%1' (%2) Object `%1' (%2) wordt aangemaakt. - + Creating database `%1' - + Connecting to database `%1' - + Renaming `%1' (%2) to `%3' - - + + Dropping object `%1' (%2) Object `%1' (%2) wordt verwijderd - + Changing object `%1' (%2) Object `%1' (%2) wordt aangepast. - + Running auxiliary command. Een hulpcommando wordt uitgevoerd. @@ -8159,18 +8173,6 @@ p, li { white-space: pre-wrap; } Fix tries: Correctiepogingen: - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'Monospace'; font-size:9pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Waiting process to start...</p></body></html> - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'Monospace'; font-size:9pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Wachten op het starten van het process...</p></body></html> - Select input file @@ -8230,30 +8232,22 @@ p, li { white-space: pre-wrap; } - + Alt+C - - Ctrl+Up - Ctrl+Op - Next model Volgende model - Ctrl+Down - Ctrl+Neer - - - + Close model Sluit model - + ... ... @@ -8267,127 +8261,131 @@ p, li { white-space: pre-wrap; } ModelObjectsWidget - Model Objects Modelobjecten - + + Visible object types + + + + Hide this widget Verberg dit widget - - - - - - + + + + + + ... ... - + 1 1 - + ID ID - + Object Object - + Type Type - + Parent Object Ouder Object - + Parent Type Ouder Type - - Visible Object Types - Zichtbare Object Types - - - + Select All Selecteer Alles - + Clear All Alles Wissen - + + Model objects + + + + Select Selecteer - + Return Keer terug - + Cancel Annuleren - + Esc Esc - + Tree view Boomstructuur - + List view Lijst - + Objects view configuration Object-overzichtsconfiguratie - + Expands all items Alle items uitklappen - + Collapses all items Alle items inklappen - + Filter: Filter: - + By ID Volgens ID - + New Nieuw @@ -8399,6 +8397,12 @@ p, li { white-space: pre-wrap; } Model overview Modeloverzicht + + + Failed to generate the overview image. +The requested size %1 x %2 was too big and there was not enough memory to allocate! + + ModelRestorationForm @@ -8452,20 +8456,16 @@ p, li { white-space: pre-wrap; } &Restore &Herstel - - Modified: %1 - Aangepast: %1 - ModelValidationHelper - + There are pending errors! SQL validation will not be executed. Er zijn fouten! SQL validatie zal niet worden uitgevoerd. - + Operation canceled by the user. De operatie werd geannuleerd door de gebruiker. @@ -8478,143 +8478,123 @@ p, li { white-space: pre-wrap; } Venster - + Enables the validation of SQL code in DBMS. This process requires the use of a pre-configured connection. SQL validation will occur only in the last step (when all objects were validated) or when there are no warnings. - + Connection to be used in the SQL validation - + pgModeler will generate unique and temporary names for database, role and tablespace objects. This option avoids object duplication errors when running the SQL validation. - + Use unique temporary names for cluster level objects - + Warnings: does not prevents model to be saved. Let op: dit voorkomt niet dat het model kan worden opgeslagen. - - + + 0 0 - + Errors: model will not be saved while there are validation errors. Fouten: het model zal niet worden opgeslagen zolang er validatiefouten zijn. - + Hide this widget Verberg dit widget - + ... ... - Use unique temporary names for database, role and tablespace objects - Gebruik unieke namen voor de database, rollen en tablespace objecten - - - Enable validation of SQL code on DBMS (requires connection) - Activeer validatie van SQL code op het DBMS (vereist een verbinding) + + Swap ids + - + SQL Validation: SQL Validatie: - Connection alias - Verbindingsalias - - - + PostgreSQL version PostgreSQL versie - SQL validation, if enabled, will occur only on the last step or when there are no warnings. - Wanneer SQL validatie is geactiveerd, zal deze enkel worden uitgevoerd als laatste stap of wanneer er geen waarschuwingen zijn. - - - Using temporary names will avoid object duplication errors when running the SQL validation. - Tijdelijke namen gebruiken vermijdt object-duplicatiefouten wanneer SQL validatie wordt uitgevoerd. - - - + Try to resolve the reported issues. Probeer om de gerapporteerde problemen te verhelpen. - - Apply Fix - Verhelp - - - + Ctrl+S Ctrl+S - + Clear validation results Validatieresultaten leegmaken - + Clear Leegmaken - + Try to apply a fix on the selected validation info. Probeer de validatieinformatie te verhelpen. - + Options Opties - + Cancel the SQL validation in progress. Annuleer de lopende SQL validatie. - + Cancel Annuleren - + Esc Esc - - Change the creation order for two objects by swapping their ids - Wijzig de aanmaak-volgorde voor twee objecten door hun ids om te wisselen + + Apply fixes + - - Swap Ids - Wissel Ids om + + Change the creation order for two objects by swapping their ids + Wijzig de aanmaak-volgorde voor twee objecten door hun ids om te wisselen - + Va&lidate Va&lideer @@ -8624,76 +8604,82 @@ p, li { white-space: pre-wrap; } Autodetecteer - + The object <strong>%1</strong> <em>(%2)</em> [id: %3] is being referenced by <strong>%4</strong> object(s) before its creation. Het object <strong>%1</strong> <em>(%2)</em> [id: %3] wordt door <strong>%4</strong> object(en) gerefereerd vóór zijn aanmaak. - + The object <strong>%1</strong> <em>(%2)</em> [id: %3]%4 is referencing columns created by <strong>%5</strong> relationship(s) but is created before them. Het object <strong>%1</strong> <em>(%2)</em> [id: %3]%4 refereerd naar kolommen aangemaakt door <strong>%5</strong> relatie(s) maar wordt vóór deze aangemaakt. - + The object <strong>%1</strong> <em>(%2)</em> has a name that conflicts with <strong>%3</strong> object's name(s). Het object <strong>%1</strong> <em>(%2)</em> heeft een naam die conflicteerd met de naam van <strong>%3</strong> andere objecten. - + The relationship <strong>%1</strong> [id: %2] is in a permanent invalidation state and needs to be relocated. De relatie <strong>%1</strong> [id: %2] is in een permanente ongeldige staat en moet worden herplaats. - + SQL validation failed due to error(s) below. <strong>NOTE:</strong><em> These errors does not invalidates the model but may affect operations like <strong>export</strong> and <strong>diff</strong>.</em> SQL validatie faalde omwille van de volgende fouten. <strong>LET OP:</strong><em> Deze fouten ontkrachten het model niet maar kunnen <strong>export</strong> en <strong>diff</strong> beïnvloeden.</em> - <strong>HINT:</strong> try to swap the mentioned relationship by another one in order to solve this situation. Note that other objects may be lost in this process. - <strong>HINT:</strong> probeer om de vermeldde relatie om te wisselen met een andere relatie om dit probleem trachten te verhelpen maar wees ervan bewust dat dit ervoor kan zorgen dat bepaalde andere objecten verloren gaan in het process. + + The column <strong>%1</strong> on <strong>%2</strong> <em>(%3)</em> is referencing the geospatial data type <strong>%4</strong> but the <strong>postgis</strong> extension is not present in the model! + - + <strong>HINT:</strong> try to swap the relationship by another ones that somehow are linked to it through generated columns or constraints to solve this issue. Note that other objects may be lost in the swap process. - + + <strong>HINT:</strong> Create the extension in the model or let it be created by applying the needed fixes. + + + + <em>The above object was created by a relationship. Change the name pattern on it's generator relationship. Fix will not be applied!</em> <em>Het hierboven vermeldde object werd aangemaakt door een relatie. Verander het naamspatroon van de genererende relatie. Dit probleem kan niet automatisch worden verholpen!</em> - + Conflicting object: <strong>%1</strong> <em>(%2)</em>. Conflicterende object: <strong>%1</strong> <em>(%2)</em>. - + Relationship: <strong>%1</strong> [id: %2]. Relatie: <strong>%1</strong> [id: %2]. - + Referrer object: <strong>%1</strong> <em>(%2)</em> [id: %3]. Refererende object: <strong>%1</strong> <em>(%2)</em> [id: %3]. - + SQL validation not executed! No connection defined. - + Database model successfully validated. Het database model werd succesvol gevalideerd. - + Running SQL commands on server... De SQL commando's worden uitgevoerd op de server... - + Processing object: %1 Bezig met het verwerken van object: %1 @@ -8701,397 +8687,510 @@ p, li { white-space: pre-wrap; } ModelWidget - + One to One (1-1) Een-op-een (1-1) - + One to Many (1-n) Een op meer (1-n) - + Many to Many (n-n) Meer op meer (n-n) - - + + Copy Kopieer - Generalization - Generalisatie - - - + Inheritance Overerving - + <strong>ATTENTION:</strong> The database model is protected! Operations that could modify it are disabled! <strong>OPGELET:</strong> Het databasemodel is beschermd! Operaties die het zouden kunnen aanpassen zijn uitgeschakeld! - + Source Bron - + Alt+S Alt+S - + Show object source code Toon object broncode - - + + Properties Eigenschappen - + Space Spatie - + Edit the object properties Bewerk de eigenschappen van het object - - + + Protect Bescherm - - + + Unprotect Bescherming af - + Protects object(s) from modifications Beschermt object(en) tegen aanpassingen - - + + Delete Verwijderen - + Del Del - - + + Del. cascade Verwijder cascade - + Shift+Del Shift+Del - + Select all Selecteer Alles - + + Select tagged + + + + + Select + Selecteer + + + Ctrl+A Ctrl+A - + Selects all the graphical objects in the model Selecteert alle grafische objecten in het model - + + Edit data + + + + Convert Converteer - + Ctrl+C Ctrl+C - + Paste Plakken - + Ctrl+V Ctrl+V - + Cut Knippen - + Ctrl+X Ctrl+X - + Deps && Referrers Afhankelijkheden && Verwijzers - + New Nieuw - + Add a new object in the model Voeg een nieuw object toe aan het model - + Quick Snel - + Quick action for the selected object Snelle actie voor het geselecteerde object - + Rename Hernoem - + F2 F2 - + Quick rename the object Snelle hernoeming van het object - + Move to schema Verplaats naar schema - + Set tag Zet tag - + Edit permissions Machtigingen aanpassen - + Ctrl+E Ctrl+E - + Change owner Eigenaar veranderen - + Select children Selecteer kinderen - - Highlight - Licht op - - - + Open relationship Open relatie - + Custom SQL Aangepaste SQL - + Alt+Q Alt+Q - + Convert to sequence Converteer naar sequentie - + Convert to serial Converteer naar serieel - + Break line Nieuw lijn - + Remove points Verwijder punten - + Enable SQL Schakel SQL in - + Disable SQL Schakel SQL uit - + + Duplicate + + + + + Ctrl+D + + + + + Extended attributes + + + + + + Show + + + + + + Hide + + + + + Jump to table + + + + + Schemas rectangles + + + + + Fade in/out + + + + + + Fade in + + + + + + Fade out + + + + + + + Relationships + Relaties + + + + Swap ids + + + + + Edit the objects creation order by swapping their ids + + + + 90° (vertical) 90° (vertikaal) - + 90° (horizontal) 90° (horizontaal) - + 90° + 90° (vertical) 90° + 90° (vertikaal) - + 90° + 90° (horizontal) 90° + 90° (horizontaal) - + + + + All objects + + + + + + Schemas + + + + + + Tables + Tabellen + + + + + Views + + + + + + Textboxes + + + + Zoom: %1% Zoom: %1% - + Do you really want to convert the relationship into an intermediate table? Bent u zeker dat u de relatie wilt converteren naar een intermediaire tabel? - + Loading database model Het databasemodel wordt geladen - + Saving database model Het databasemodel wordt opgeslagen - + Do you want to %1 the selected schema's children too? - + protect - + unprotect - + Also copy all dependencies of selected objects? This minimizes the breakdown of references when copied objects are pasted into another model. Wenst u alle afhankelijken van de geselecteerde objecten ook te kopiëren? Dit minimalizeert het verbreken van referenties wanneer gekopieerde objecten in een ander model worden geplakt. - + Pasting objects... Bezig met het plakken van objecten... - + Validating object: `%1' (%2) Bezig met het valideren van object: `%1' (%2) - + Generating XML for: `%1' (%2) Bezig met het genereren van XML voor: `%1' (%2) - + Pasting object: `%1' (%2) Bezig met het plakken van object: `%1' (%2) - + Not all objects were pasted to the model due to errors returned during the process! Refer to error stack for more details! Niet alle objecten werden in het model geplakt omwille van fouten die werden gegenereerd gedurende dit proces. Kijk de error-stack na voor meer details! - + <strong>CAUTION:</strong> You are about to delete objects in cascade mode which means more objects than the selected will be dropped too. Do you really want to proceed? <strong>PAS OP:<strong> U staat op het punt om objecten te verwijderen in cascade modus, dit betekent dat ook objecten die niet geselecteerd zijn verwijderd kunnen worden. Bent u zeker dat u wilt verdergaan? - + <strong>CAUTION:</strong> Remove multiple objects at once can cause irreversible invalidations to other objects in the model causing such invalid objects to be deleted too. Do you really want to proceed? <strong>PAS OP:</strong> Meerdere objecten in één keer verwijderen kan onherroepbare ongeldigheden veroorzaken in andere objecten binnen het model en ervoor zorgen dat deze objecten ook worden verwijderd. Bent u zeker dat u verder wenst te gaan? - + <strong>CAUTION:</strong> Remove a relationship can cause irreversible invalidations to other objects in the model causing such invalid objects to be deleted too. Do you really want to proceed? <strong>PAS OP:</strong> Een relatie verwijderen kan onherroepbare ongeldigheden veroorzaken in andere objecten en ervoor zorgen dat deze objecten ook worden verwijderd. Bent u er zeker van dat u wenst verder te gaan? - + Do you really want to delete the selected object? Bent u er zeker van dat u het geselecteerde object wenst te verwijderen? - + The cascade deletion found some problems when running! Some objects could not be deleted or registered in the operation's history! Please, refer to error stack for more details. Het cascade verwijderen kwam enkele problemenen tegen tijdens het uitvoeren! Sommige objecten konden niet worden verwijderd of geregistreerd in de actie-geschiedenis! Gelieve de error-stack na te kijken voor meer details. - + (no objects) (geen objecten) - + + None + + + + Source code Broncode - + Constraints Constraints @@ -9099,39 +9198,35 @@ p, li { white-space: pre-wrap; } ModelsDiffHelper - + Processing object `%1' (%2)... Object `%1' wordt behandeld (%2)... - + Skipping object `%1' (%2)... Object `%1' wordt overgeslagen (%2)... - + Processing diff infos... Diff informatie wordt verwerkt... - + Processing `%1' info for object `%2' (%3)... `%1' informatie voor object `%2' wordt verwerkt (%3)... - + No differences between the model and database. - + Preparing diff code... - - Comparison between model and database finished. - De vergelijking tussen het model en de database is voltooid. - NewObjectOverlayWidget @@ -9141,119 +9236,119 @@ p, li { white-space: pre-wrap; } Venster - + Role Rol - + Tag Tag - + Cast Cast - - + + A A - + Language Taal - + Textbox Tekst box - + Event Trigger Event Trigger - + Tablespace Tablespace - + Schema Schema - + Domain Domein - + Conversion Conversie - + Aggregate Aggregator - + Collation Sortering - + Table Tabel - + Type Type - + Op. Family Op. Familie - + Sequence Sequentie - + Extension Uitbreiding - + Function Functie - + Op. Class Op. Klasse - + Operator Operator - + View View - - + + Permissions Machtigingen @@ -9263,202 +9358,218 @@ p, li { white-space: pre-wrap; } Regel - + Index Index - + Column Kolom - + Constraint Constraint - + + Generic SQL + + + + Trigger Trigger - + + Policy + + + + Many-to-many Meer-op-meer - + One-to-many Een-op-meer - + One-to-one Een-op-een - + Inheritance Overerving - + Copy Kopieer - + G G - + K K - + H H - + J J - + D D - + E E - + F F - + L L - + O O - + U U - + I I - + R R - + S S - + Q Q - + T T - + P P - + M M - + Y Y - + W W - + + 9 9 - + Z Z - + X X - + C C - + V V - + B B - + + 8 + 8 + + + 1 1 - + 2 2 - + 3 3 - + 5 5 - + 4 4 - + 0 0 @@ -9466,84 +9577,125 @@ p, li { white-space: pre-wrap; } NumberedTextEditor - + + Load + Laden + + + + Load the object's source code from an external file + + + + + Edit + + + + + Edit the source code in the preferred external editor + + + + + Clear + Leegmaken + + + Upper case - + Lower case - + Ident right - + Ident left + + + SQL file (*.sql);;All files (*.*) + SQL Code (*.sql);;Alle bestanden (*.*) + + + + Load file + + + + + The source editor `%1' is running on `pid: %2'. + + + + + Could not start the source code editor application `%1'! Make to sure that the source editor path defined in the general settings points to a valid executable and the current user has permission to run the application. Error message returned: `%2' + + ObjectDepsRefsWidget - - Form - Venster - Dependencies Afhankelijken - - + + ID ID - - + + Object Object - - + + Type Type - - + + Parent Object Ouder Object - - + + Parent Type Ouder Type - + Exclude indirect dependencies Sluit indirecte afhankelijken uit - + References Referenties - + Include indirect references Neem indirecte afhankele op - + This object does not exists anymore. The dependencies and references listing are disabled. Dit object bestaat niet langer. Het lijsten van afhankelijken en referenties is uitgeschakeld. @@ -9561,113 +9713,135 @@ p, li { white-space: pre-wrap; } Venster - + Pattern: Patroon: - + Find Zoek - + Defines the search filter Definieert de zoekfilter - + Filter Filter - + Clears the search results Maakt de zoekresultaten leeg - + Clear Leegmaken - - Highlight graphical objects when selecting them or their children on the result list - Licht grafische objecten op wanneer deze of hun kinderen geselecteerd worden in de resultatenlijst - - - - Highlight - Licht op - - - - + + ... ... - + Hide this widget Verberg dit widget - + + (Un)selects the graphical objects in the results grid + + + + + Select + Selecteer + + + Regular Expression Regular expression - + Exact Match Exacte Overeenkomst - + Select All Selecteer Alles - + Clear All Alles Wissen - + Case Sensitive Hoofdlettergevoelig - + ID ID - + Object Object - + Type Type - + Parent Object Ouder Object - + Parent Type Ouder Type - + + Fades outs all the graphical objects in the results grid (or those not listed). The current fade in/out state of all objects is modified. + + + + + Fade out + + + + + + Listed + + + + + + Not listed + + + + Found <strong>%1</strong> object(s). <strong>%1</strong> object(en) gevonden. - + No objects found. Geen objecten gevonden. @@ -9719,144 +9893,142 @@ p, li { white-space: pre-wrap; } Selecteer Object - + Select %1 - ObjectTableWidget + ObjectsTableWidget - + Form - Venster + Venster - + Add Item - Item Toevoegen + Item Toevoegen - + Ins - Ins + Ins - + Remove Item - Item Verwijderen + Item Verwijderen - + Del - Del + Del - + Update Item - Item Updaten + Item Updaten - + Alt+R - Alt+R + Alt+R - + Remove All - Alles Verwijderen + Alles Verwijderen - + Shift+Del - Shift+Del + Shift+Del + + + + Duplicate item + + + + + Ctrl+D + - + Edit Item - Item Aanpassen + Item Aanpassen - + Space - Spatie + Spatie - + Move Up - Naar Boven + Naar Boven - + Ctrl+Up - Ctrl+Up + - + Move Down - Naar Beneden + Naar Beneden - + Ctrl+Down - Ctrl+Down + - + Move to start - Naar de eerste plaats + Naar de eerste plaats - + Ctrl+Home - Ctrl+Home + Ctrl+Home - + Move to end - Naar de laatste plaats + Naar de laatste plaats - + Ctrl+End, Ctrl+S - Ctrl+End, Ctrl+S + Ctrl+End, Ctrl+S - Confirmação - Bevestiging + + + Confirmation + Bevestiging - + Do you really want to remove the selected item? - Bent u zeker dat u het geselecteerde item wilt verwijderen? - - - - - Confirmation - Bevestiging + Bent u zeker dat u het geselecteerde item wilt verwijderen? - - Do you really want to remove the all items? - Bent u zeker dat u alle items wilt verwijderen? + + Do you really want to remove all the items? + OperationList - + (invalid object) (ongeldig object) - - Undoing change on object `%1' (%2). - Aanpassingen op object `%1' ongedaan maken (%2). - - - Redoing change on object `%1' (%2). - Aanpassingen op object `%1' opnieuw topassen (%2). - OperationListWidget @@ -9913,65 +10085,53 @@ p, li { white-space: pre-wrap; } Opnieuw doen - + Object: %1 Object: %1 - + Name: %1 Naam: %1 - + created aangemaakt - + removed verwijderd - + modified aangepast - + moved verplaatst - + Operation: %1 Actie: %1 - Undoing operations... - Acties ongedaan maken... - - - Redoing operations... - Acties opnieuw uitvoeren... - - - + Operation history exclusion Actiegeschiedenisuitsluiting - + Delete the executed operations history is an irreversible action, do you want to continue? Het verwijderen van de geschiedenis van de uitgevoerde acties kan niet worden ongedaan gemaakt, bent u zeker dat u wilt verdergaan? OperatorClassWidget - - Form - Venster - Default Class: @@ -10056,10 +10216,6 @@ p, li { white-space: pre-wrap; } OperatorFamilyWidget - - Form - Venster - Indexing: @@ -10068,10 +10224,6 @@ p, li { white-space: pre-wrap; } OperatorWidget - - Form - Venster - MERGES @@ -10140,10 +10292,6 @@ p, li { white-space: pre-wrap; } ParameterWidget - - Form - Venster - Default Value: @@ -10172,10 +10320,6 @@ p, li { white-space: pre-wrap; } PermissionWidget - - Form - Venster - @@ -10193,499 +10337,763 @@ p, li { white-space: pre-wrap; } Niet-uitvoerbare SQL code - - - Roles - Rollen + + + Roles + Rollen + + + + + Privileges + Machtiginen + + + + Edit permissions + Machtigingen aanpassen + + + + &Grant + + + + + Re&voke + + + + + Cascade + Cascade + + + + Privilege + Machtiging + + + + GRANT OPTION + GRANT OPTION + + + + Add Permission + Machtiging toekennen + + + + Update Permission + Machtiging aanpassen + + + + Cancel Operation + Actie annuleren + + + + Code Preview + Codevoorbeeld + + + + Id + Id + + + + Name + Naam + + + + Leave the <em><strong>Roles</strong></em> grid empty in order to create a %1 applicable to <strong><em>PUBLIC</em></strong>. + + + + + -- No permissions defined for the specified object! + -- Er zijn geen machtigingen gedefinieerd voor het gespecifieerde object! + + + + /* Could not generate the SQL code preview for permissions! + /* Er kon geen SQL Codevoorbeeld worden gegenereerd voor de machtigingen! + + + + PgModelerCLI + + + Unrecognized option '%1'. + Niet-herkende optie '%1'. + + + + Value not specified for option '%1'. + Er is geen waarde gespecifieerd voor optie '%1'. + + + + Option '%1' does not accept values. + Optie '%1' aanvaardt geen waardes. + + + + Usage: pgmodeler-cli [OPTIONS] + Gebruik: pgmodeler-cli [OPTIES] + + + + + command line interface. + commandolijn interface. + + + + General options: + Algemene opties: + + + + PNG and SVG export options: + + + + + DBMS export options: + DBMS exporteringsopties: + + + + Miscellaneous options: + Andere opties: + + + + There are no connections configured. + Er zijn geen verbindingen geconfigureerd. + + + + Input file must be different from output! + Het invoerbestand mag niet hetzelfde zijn als het uitvoerbestand! + + + + Incomplete connection information! + Onvolledige verbindingsinformatie! + + + + Invalid zoom specified! + Een ongeldige zoom gespecifieerd! + + + + Invalid action specified to update mime option! + The actie om de mime optie the updaten is ongeldig! + + + + Starting model fixing... + Modelcorrectie begint... + + + + Starting mime update... + Mime update begint... + + + + Starting model export... + Model export begint... + + + + Model successfully fixed! + Het model werd succesvol gecorrigeerd! + + + + Connection aliased as '%1' was not found in the configuration file. + + + + + PostgreSQL Database Modeler Project - pgmodeler.io + + + + + Copyright 2006-2018 Raphael A. Silva <raphael@pgmodeler.io> + + + + + This CLI tool provides several operations over models and databases without the need to perform them +in pgModeler's graphical interface. All available options are described below. + + + + + %1, %2 [FILE] Input model file (.dbm). This is mandatory for fix, export operations. + + + + + %1, %2 [DBNAME] Input database name. This is mandatory for import operation. + + + + + %1, %2 [FILE] Output file. This is mandatory for fixing model or exporting to file, png or svg. + + + + + %1, %2 Try to fix the structure of the input model file in order to make it loadable again. + + + + + %1, %2 [NUMBER] Model fix tries. When reaching the maximum count the invalid objects will be discarded. + + + + + %1, %2 Export the input model to a sql script file. + + + + + %1, %2 Export the input model to a png image. + + + + + %1, %2 Export the input model to a svg file. + + + + + %1, %2 Export the input model directly to a PostgreSQL server. + + + + + %1, %2 Import a database to an output file. + + + + + %1, %2 Compares a model and a database or two databases generating the SQL script to synch the latter in relation to the first. + + + + + %1, %2 Force the PostgreSQL version of generated SQL code. + - - - Privileges - Machtiginen + + %1, %2 Silent execution. Only critical messages and errors are shown during process. + - Grant - GRANT + + %1, %2 Show this help menu. + - Revoke - REVOKE + + Connection options: + - - Edit permissions - Machtigingen aanpassen + + %1, %2 List available connections in file %3. + - - &Grant + + %1, %2 [ALIAS] Connection configuration alias to be used. - - Re&voke + + %1, %2 [HOST] PostgreSQL host in which a task will operate. - - Cascade - Cascade + + %1, %2 [PORT] PostgreSQL host listening port. + - - Privilege - Machtiging + + %1, %2 [USER] PostgreSQL username. + - - GRANT OPTION - GRANT OPTION + + %1, %2 [PASSWORD] PostgreSQL user password. + - - Add Permission - Machtiging toekennen + + %1, %2 [DBNAME] Connection's initial database. + - - Update Permission - Machtiging aanpassen + + %1, %2 Draws the grid in the exported image. + - - Cancel Operation - Actie annuleren + + %1, %2 Draws the page delimiters in the exported image. + - - Code Preview - Codevoorbeeld + + %1, %2 Each page will be exported in a separated png image. (Only for PNG images) + - - Type: - Type: + + %1, %2 [FACTOR] Applies a zoom (in percent) before export to png image. Accepted zoom interval: %3-%4 (Only for PNG images) + - - Role - Rol + + %1, %2 Ignores errors related to duplicated objects that eventually exist in the server. + - - Id - Id + + %1, %2 [CODES] Ignores additional errors by their codes. A comma-separated list of alphanumeric codes should be provided. + - - Leave the <em><strong>Roles</strong></em> empty to create a permission applicable to <strong><em>PUBLIC</em></strong>. - Laat de <em><strong>Rollen</strong></em> leeg om een machtiging aan te maken die op <strong><em>PUBLIC</em></strong> van toepassing is. + + %1, %2 Drop the database before execute a export process. + - - -- No permissions defined for the specified object! - -- Er zijn geen machtigingen gedefinieerd voor het gespecifieerde object! + + %1, %2 Runs the DROP commands attached to SQL-enabled objects. + - - /* Could not generate the SQL code preview for permissions! - /* Er kon geen SQL Codevoorbeeld worden gegenereerd voor de machtigingen! + + %1, %2 Simulates an export process by executing all steps but undoing any modification in the end. + - - - PgModelerCLI - - Unrecognized option '%1'. - Niet-herkende optie '%1'. + + %1, %2 Generates temporary names for database, roles and tablespaces when in simulation mode. + - - Value not specified for option '%1'. - Er is geen waarde gespecifieerd voor optie '%1'. + + Database import options: + - - Option '%1' does not accept values. - Optie '%1' aanvaardt geen waardes. + + %1, %2 Ignore all errors and try to create as many as possible objects. + - - Connection aliased as '%1' was not found on configuration file. - De verbindingsalias '%1' werd niet teruggevonden in het configuratiebestand. + + %1, %2 Import system built-in objects. This option causes the model bloating due to the importing of unneeded objects. + - - Usage: pgmodeler-cli [OPTIONS] - Gebruik: pgmodeler-cli [OPTIES] + + %1, %2 Import extension objects. This option causes the model bloating due to the importing of unneeded objects. + - - - command line interface. - commandolijn interface. + + %1, %2 Run import in debug mode printing all queries executed in the server. + - - PostgreSQL Database Modeler Project - pgmodeler.com.br - PostgreSQL Database Modelling Project - pgmodeler.com.br + + Diff options: + - - Copyright 2006-2015 Raphael A. Silva <raphael@pgmodeler.com.br> - Copyright 2006-2015 Raphael A. Silva <raphael@pgmodeler.com.br> + + %1, %2 [DBNAME] The database used in the comparison. All the SQL code generated is applied to it. + - This CLI tool provides the operations to export pgModeler's database models without -the need to load them on graphical interface as well to fix model files to the most recent -accepted structure. All available options are described below. - Dit CLI tool maakt het mogelijk om pgModeler database modellen te exporteren zonder -deze in de grafische interface te hoeven laden alsook om modellen te herstellen naar de -laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschreven. + + %1, %2 Save the generated diff code to output file. + - - General options: - Algemene opties: + + %1, %2 Apply the generated diff code on the database server. + - - %1, %2=[FILE] Input model file (.dbm). Mandatory use when fixing a model or exporting it. - %1, %2=[BESTAND] Input model bestand (.dbm). Verplicht wanneer een model wordt geïmporteerd or hersteld. + + %1, %2 Don't preview the generated diff code when applying it to the server. + - - %1, %2=[FILE] Output file. Mandatory use when fixing model or export to file or png. - %1, %2=[BESTAND] Uitvoerbestand. Verplicht wanneer een model wordt hersteld of geexporteerd naar een bestand of PNG. + + %1, %2 Drop cluster level objects like roles and tablespaces. + - - %1, %2 Try to fix the structure of the input model file in order to make it loadable again. - %1, %2 Probeer de structuur van het invoerbestand te herstellen zodat het opnieuw kan worden geladen. + + %1, %2 Revoke permissions already set on the database. New permissions configured in the input model are still applied. + - - %1, %2 Model fix tries. When reaching the maximum count the invalid objects will be discard. - %1, %2 Aantel herstelpogingen. Na het bereiken van deze limiet worden ongeldige objecten verwijderd. + + %1, %2 Drop missing objects. Generates DROP commands for objects that are present in the input model but not in the compared database. + - - %1, %2 Export to a sql script file. - %1, %2 Exporteer naar een sql script bestand. + + %1, %2 Force the drop of missing columns and constraints. Causes only columns and constraints to be dropped, other missing objects aren't removed. + - - %1, %2 Export to a png image. - %1, %2 Exporteer naar een PNG afbeelding. + + %1, %2 Rename the destination database when the names of the involved databases are different. + - - %1, %2 Export directly to a PostgreSQL server. - %1, %2 Exporteer direct naar een PostgreSQL server. + + %1, %2 Don't drop or truncate objects in cascade mode. + - - %1, %2 List available connections on %3 file. - %1, %2 Toon de beschikbare verbindingen in bestand %3. + + %1, %2 Truncate tables prior to alter columns. Avoids errors related to type casting when the new type of a column isn't compatible to the old one. + - - %1, %2 Version of generated SQL code. Only for file or dbms export. - %1, %2 Versie voor de gegenereerde SQL code. ENkel geldig bij bestands- of DBMS export. + + %1, %2 Don't reuse sequences on serial columns. Drop the old sequence assigned to a serial column and creates a new one. + - - %1, %2 Silent execution. Only critical errors are shown during process. - %1, %2 Stille uitvoer. Enkel kritische fouten worden getoond tijdens het proces. + + %1, %2 Don't force the recreation of objects. Avoids the usage of a DROP and CREATE commands to create a new version of the objects. + - - %1, %2 Show this help menu. - %1, %2 Toon deze helpmenu. + + %1, %2 Don't recreate the unmodifiable objects. These objects are the ones which can't be changed via ALTER command. + - PNG export options: - PNG exporteeringsopties: + + %1, %2 [ACTION] Handles the file association to .dbm files. The ACTION can be [%3 | %4]. + - - %1, %2 Draws the grid on the exported png image. - %1, %2 Tekent het raster in de geexporteerde PNG afbeelding. + + ** The diff process allows the usage of the following options related to import and export operations: + - - %1, %2 Draws the page delimiters on the exported png image. - %1, %2 Tekent de paginamarkering op de geexporteerde PNG afbeelding. + + * Export: + - %1, %2 Each page will be exported on a separated png image. - %1, %2 Elke pagina wordt als apparte PNG afbeelding geexporteerd. + + * Import: + - %1, %2=[FACTOR] Applies a zoom (in percent) before export to png image. Accepted zoom interval: %3-%4 - %1, %2=[FACTOR] Past een zoom (in procent) toe vooraleer te exporteren naar PNG afbeelding. Geaccepteerde zoomintervals: %3-%4 + + ** When running the diff using two databases (%1 and %2) there's the need to specify two connections/aliases. + - - This CLI tool provides the operations to export pgModeler's database models without - the need to load them on graphical interface as well to fix model files to the most recent - accepted structure. All available options are described below. + + If only one connection is set it will be used to import the input database as well to retrieve database used in the comparison. - - %1, %2 Export to a svg file. + + A second connection can be specified by appending a 1 on any connection configuration parameter listed above. - - PNG and SVG export options: + + Available connections (alias : connection string) - - %1, %2 Each page will be exported on a separated png image. (Only for PNG) + + No operation mode was specified! - - %1, %2=[FACTOR] Applies a zoom (in percent) before export to png image. Accepted zoom interval: %3-%4 (Only for PNG) + + Export, fix model, import database, diff and update mime operations can't be used at the same time! - - DBMS export options: - DBMS exporteringsopties: + + Multiple export mode was specified! + - - %1, %2 Ignores errors related to duplicated objects that eventually exists on server side. - %1, %2 Negeert fouten omwille van duplicate objecten die uiteindelijk op de server zullen bestaan. + + No input file was specified! + - - %1, %2 Drop the database before execute a export process. - %1, %2 Verwijder de database vooraleer het exporteringsprocess te starten. + + No input database was specified! + - - %1, %2 Runs the DROP commands attached to SQL-enabled objects. - %1, %2 Voert de DROP commando's uit die geassocieerd zijn met SQL-ingeschakelde objecten. + + No output file was specified! + - - %1, %2 Simulates a export process. Actually executes all steps but undoing any modification. - %1, %2 Simuleert het exporteringsprocess. Alle stappen worden uitgevoerd maar aanpassingen worden ongedaan gemaakt. + + No input file or database was specified! + - - %1, %2 Generates temporary names for database, roles and tablespaces when in simulation mode. - %1, %2 Genereert tijdelijke namen voor databases, rollen en tablespaces wanneer simulatiemodus is gespecifieerd. + + The input file and database can't be used at the same time! + - - %1, %2=[ALIAS] Connection configuration alias to be used. - %1, %2=[ALIAS] Verbindingsconfiguratiealias diemoet worden gebruikt. + + No database to be compared was specified! + - - %1, %2=[HOST] PostgreSQL host which export will operate. - %1, %2=[HOST] PostgreSQL host waarnaar te exporteren. + + No diff action (save or apply) was specified! + - - %1, %2=[PORT] PostgreSQL host listening port. - %1, %2=[POORT] De poort waarop de PostgreSQL host luistert. + + No output file for the diff code was specified! + - - %1, %2=[USER] PostgreSQL username. - %1, %2=[GEBRUIKER] PostgreSQL gebruikersnaam. + + ** Error code `%1' found and ignored. Proceeding with export. + - - %1, %2=[PASSWORD] PostgreSQL user password. - %1, %2=[WACHTWOORD] PostgreSQL wachtwoord. + + ** Command: %1 + - - %1, %2=[DBNAME] Connection's initial database. - %1, %2=[DBNAAM] De verbinding's initiele database. + + Extracting objects' XML... + De XML van de objecten word geextraheerd... - - Miscellaneous options: - Andere opties: + + Invalid input file! It seems that is not a pgModeler generated model or the file is corrupted! + Het invoerbestand is ongeldig! Kijk na of dit bestand door pgModeler werd gegenereerd ofdat het bestand gecorrupteerd raakte! - - %1, %2=[ACTION] Handles the file association to .dbm files. The ACTION can be [%3 | %4]. - %1, %2=[ACTIE] Behandelt de bestandsassociatie met .dbm bestanden. De ACTIE kan [%3 | %4] zijn. + + Recreating objects... + De objecten worden heraangemaakt... - - There are no connections configured. - Er zijn geen verbindingen geconfigureerd. + + +** Object(s) that couldn't fixed: + ** Object(en) die niet kon(den) worden gecorrigeerd: - - Available connections (alias : conn. string) - Beschikbare verbindingen (alias: conn. string) + + WARNING: There are objects that maybe can't be fixed. Trying again... (tries %1/%2) + OPGEPAST: Er zijn objecten die niet konden worden gecorrigeerd. We proberen opnieuw... (poging %1 van %2) - - No export mode specified! - Er is geen exportmodus gespecifieerd! + + + Loading input file: %1 + - - Export, fix model and update mime operations can't be used at the same time! - 'Exporteer en corrigeer model' kan niet samen worden gebruikt met 'update the mime operaties'! + + Fixed model file: %1 + - - Multiple export mode specified! - Meerdere exportmodussen gespecifieerd! + + Export to PNG image: %1 + - - No input file specified! - Er werd geen invoerbestand gespecifieerd! + + Export to SVG file: %1 + - - No output file specified! - Er werd geen uitvoerbestand gespecifieerd! + + Export to SQL script file: %1 + - - Input file must be different from output! - Het invoerbestand mag niet hetzelfde zijn als het uitvoerbestand! + + Export to DBMS: %1 + - - Incomplete connection information! - Onvolledige verbindingsinformatie! + + Export successfully ended! + + - - Invalid zoom specified! - Een ongeldige zoom gespecifieerd! + + Starting database import... + - - Invalid action specified to update mime option! - The actie om de mime optie the updaten is ongeldig! + + + Input database: %1 + - - Starting model fixing... - Modelcorrectie begint... + + Saving the imported database to file... + - - Starting mime update... - Mime update begint... + + Import successfully ended! + + - - Starting model export... - Model export begint... + + Starting diff process... + - - Loading input file: - Bezig met het laden van invoerbestand: + + Input model: %1 + - - Fixed model file: - Het modelbestand werd gecorrigeerd: + + Compare to: %1 + - - Model successfully fixed! - Het model werd succesvol gecorrigeerd! + + Loading input model... + - - Mime database successfully updated. - De mime database werd succesvol geupdate. + + + Importing the database `%1'... + - - Export to PNG image: - Exporteren naar PNG afbeelding: + + Comparing the generated models... + - - Export to SVG file: + + No differences were detected. - - Export to SQL script file: - Exporteren naar SQL script bestand: + + Saving diff to file `%1' + - - Export to DBMS: - Exporteren naar DBMS: + + ** WARNING: You are about to apply the generated diff code to the server. Data can be lost in the process! + - - Export successfully ended! - De export is succesvol beëindigd! + + ** Proceed with the diff applying? (yes/no) > + - - Extracting objects' XML... - De XML van de objecten word geextraheerd... + + yes + - - Invalid input file! It seems that is not a pgModeler generated model or the file is corrupted! - Het invoerbestand is ongeldig! Kijk na of dit bestand door pgModeler werd gegenereerd ofdat het bestand gecorrupteerd raakte! + + + no + - - Recreating objects... - De objecten worden heraangemaakt... + + Diff code not applied to the server. + - - -** Object(s) that couldn't fixed: - ** Object(en) die niet kon(den) worden gecorrigeerd: + + Applying diff to the database `%1'... + - - WARNING: There are objects that maybe can't be fixed. Trying again... (tries %1/%2) - OPGEPAST: Er zijn objecten die niet konden worden gecorrigeerd. We proberen opnieuw... (poging %1 van %2) + + Diff successfully ended! + + + + + + Mime database successfully updated! + + - + Database model files (.dbm) are already associated to pgModeler! Database modelbestanden (.dbm) zijn reeds geassocieerd met pgModeler! - + There is no file association related to pgModeler and .dbm files! Er is geen bestandsassociatie tussen pgModeler and .dbm bestanden! - + Mime database operation: %1 Mime databaseoperatie: %1 - + Can't erase the file %1! Check if the current user has permissions to delete it and if the file exists. Het bestand %1 kan niet worden verwijderd! Kijk na of de huidige gebruiker voldoende machtigingen heeft om het bestand te verwijderen en of het bestand bestaat. - + Running update-mime-database command... Het update-mime-database commando wordt uitgevoerd... @@ -10711,17 +11119,17 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr PgModelerUiNS - + Do you want to apply the <strong>SQL %1 status</strong> to the object's references too? This will avoid problems when exporting or validating the model. Wenst u de <strong> SQL %1 status</strong> ook toe te passen op de referenties van het object? Dit vermijdt problemen bij het exporteren of valideren van het model. - + disabling uitschakelen - + enabling inschakelen @@ -10817,7 +11225,7 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr [ ]: - + NONE GEEN @@ -10860,18 +11268,66 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr Bibliotheek + + PolicyWidget + + + Basics + + + + + Command: + + + + + Permissive + + + + + Roles + Rollen + + + + Expressions + Expressies + + + + USING: + + + + + CHECK: + + + + + Name + Naam + + + + Leave the <em><strong>Roles</strong></em> grid empty in order to create a %1 applicable to <strong><em>PUBLIC</em></strong>. + + + QObject - + new_database nieuwe_database - - - - + + + + %1 (line: %2) %1 (lijn %2) @@ -10917,158 +11373,178 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr Verbindingsmodus - - This mode is available only for <strong>one-to-one</strong>, <strong>one-to-many</strong> and <strong>fk relationships</strong> but provides a better semantics when linking tables by placing the lines on the exact point where the relationship occurs. - Deze modus is enkel beschikbaar voor <strong>one-to-one</strong>, <strong>one-to-many</strong> en <strong>fk relaties</strong> maar voorziet in betere semantiek bij het linken van tabellen door de lijnen te plaatsen op de exacte locatie waar de relatie zich bevindt. - - - + Connect FK to PK columns Verbindt FK naar PK kolommen - - This mode is the classical one. It connects the relationship to tables through their central points. - Dit is de klassieke modus. Deze verbindt de relaties tussen tabellen via hun centrale punt. + + This mode renders the relationships in crow's foot notation which has a better semantics and readability. It also determines the optimal point where the relationship is connected on the tables' edges taking their position into account. + + + + + Crow's foot notation + + + + + This mode determines the optimal point where the relationship is connected on the tables' edges taking their position into account. It implies the usage of the classical ER notation. + + + + + Connect tables' edges + + + + + This mode is available only for <strong>one-to-one</strong>, <strong>one-to-many</strong> and <strong>fk relationships</strong> but provides a better semantics when linking tables by placing the lines on the exact point where the relationship occurs. It implies the usage of the classical ER notation. + + + + + This mode is the classical one. It connects the relationship to tables through their central points. It implies the usage of the classical ER notation. + - + Connect tables' center points Verbindt de centrale punten van de tabellen - + FK Settings && Patterns FK instellingen && Patronen - + Foreign key settings Foreign key instellingen - + Deferral: Uitstel: - + Deferrable: Uitstelbaar: - + ON DELETE: ON DELETE: - + ON UPDATE: ON UPDATE: - + Name patterns Naamspatronen - + Pattern for foreign key generated based upon reference table's pk (1-1 and 1-n) or based upon source table's pk (n-n). Het patroon voor de foreign key wordt gegenereerd op basis van de pk van de gerefereerde tabel (1-1 en 1-n) of op basis van de pk van de brontabel (n-n). - + Foreign Key (Source): Foreign Key (Bron): - + Relationship type: Relatietype: - + Pattern for columns generated based upon target table's pk (n-n). Het patroon voor kolommen die worden gegenereerd op basis van de pk van de doeltabel (n-n). - + Column (Target): Kolom (Doel): - + One to one (1:1) Een-op-een (1:1) - + One to many (1:n) Een op meerdere (1:n) - + Many to many (n:n) Meerdere op meerdere (n:n) - + Generalization Generalisatie - + Copy Kopieer - + Pattern for columns generated based upon reference table's pk (1-1 and 1-n) or based upon source table's pk (n-n). Het patroon voor de kolommen wordt gegenereerd op basis van de pk van de gerefereerde tabel (1-1 en 1-n) of op basis van de pk van de brontabel (n-n). - + Column (Source): Kolom (Bron): - + Pattern for foreign key generated based upon target table's pk (n-n). Het patroon voor de foreign key wordt gegenereerd op basis van de pk van de doeltabel (n-n). - + Foreign Key (Target): Foreign Key (Doel): - + Pattern for unique key generated by the relationship. Het patroon voor de unieke sleutel wordt gegenereerd op basis van de relatie. - + Unique Key Name: Naam van de unieke sleutel: - - + + Pattern for primary key generated by identifier relationship. Het patroon voor de primary key wordt gegenereerd op basis van de relatie met de identifier. - + Primary Key Name: Naam van de Primary Key: - + Primary Key Column: Primary Key Kolom: - + Default Standaard @@ -11076,327 +11552,311 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr RelationshipWidget - Form - Venster - - - + General Algemeen - + Table 1: Tabel 1: - + Name Patterns Naamspatronen - - + + Use the values defined on settings dialogs for the fields below Gebruik de waarden ingesteld in het instellingsvenster voor de velden hieronder - - + + Use global settings for these fields Gebruik globale instellingen voor deze velden - + Pattern for columns generated based upon reference table's pk (1-1 and 1-n) or based upon source table's pk (n-n). Het patroon voor de kolommen wordt gegenereerd op basis van de pk van de gerefereerde tabel (1-1 en 1-n) of op basis van de pk van de brontabel (n-n). - + Column (Source): Kolom (Bron): - + Pattern for columns generated based upon target table's pk (n-n). Het patroon voor kolommen die worden gegenereerd op basis van de pk van de doeltabel (n-n). - + Column (Target): Kolom (Doel): - + Pattern for foreign key generated based upon reference table's pk (1-1 and 1-n) or based upon source table's pk (n-n). Het patroon voor de foreign key wordt gegenereerd op basis van de pk van de gerefereerde tabel (1-1 en 1-n) of op basis van de pk van de brontabel (n-n). - + Foreign Key (Source): Foreign Key (Bron): - + Pattern for foreign key generated based upon target table's pk (n-n). Het patroon voor de foreign key wordt gegenereerd op basis van de pk van de doeltabel (n-n). - + Foreign Key (Target): Foreign Key (Doel): - - + + Pattern for primary key generated by identifier relationship. Het patroon voor de primary key wordt gegenereerd op basis van de relatie met de identifier. - + Primary Key Name: Naam van de Primary Key: - + Pattern for unique key generated by the relationship. Het patroon voor de unieke sleutel wordt gegenereerd op basis van de relatie. - + Unique Key Name: Naam van de unieke sleutel: - + Primay Key Column: Primary Key Kolom: - + Cardinality: Cardinaliteit: - - + + Name of the table generated from many to many relationship De naam van de tabel die is gegenereerd op basis van de meer-op-meer relatie - + Gen. Table Name: Algemene Tabelnaam: - + Rel. Type: Relatietype: - + Table 2: Tabel 2: - + [SRC] is required [BRON] is vereist - + [DST] is required [DOEL] is vereist - + Foreign key Settings Foreign key instellingen - + Deferrable: Uitstelbaar: - + Deferral: Uitstel: - + ON DELETE: ON DELETE: - + ON UPDATE: ON UPDATE: - + One to one relationship Een-op-een relatie - + &1-1 - + &gen - + E&XCLUDING - 1-1 - 1-1 - - - + One to many relationship Een-op-meer relatie - + 1-n 1-n - + Many to many relationship Meer-op-meer relatie - + n-n n-n - + Generalization relationship (inheritance) Generalisatierelatie (overerving) - gen - gen - - - + Dependency / Copy relationship Afhankelijkheid / Kopieer de relatie - + dep dep - + Relationship generated via foreign key Relatie gegenereerd via foreign key - + fk fk - + The receiver's primary key will be composed by the generated foreign key columns. De ontvanger's primary key wordt samengesteld door de gegenereerde foreign key kolommen. - + Identifier Identifier - + Instead of create a multi-valued primary key with the generated foreign keys columns a single column is created and used as primary key. In plaats van een multi-kolom primary key te creeren op basis van de foreign key kolommen, wordt een enkele kolom aangemaakt en gebruikt als primary key. - + Single PK column Enkele PK kolom - + Custom Color: Aangepaste kleur: - + Copy Options Kopieeropties - + INDEXES INDEXES - + COMMENTS COMMENTS - + INCLUDING INCLUDING - + DEFAULTS DEFAULTS - EXCLUDING - EXCLUDING - - - + CONSTRAINTS CONSTRAINTS - + Use defaults Gebruik standaardwaarden - + ALL ALL - + STORAGE STORAGE - + Attributes Attributen - + Constraints Constraints - + Primary key Primary key - + Advanced Geavanceerd @@ -11432,10 +11892,6 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr This advanced tab shows the objects (columns or table) auto created by the relationship's connection as well the foreign keys that represents the link between the participant tables. Dit geavanceerde tab-blad toont de objecten (kolommen of tabellen) die automatisch worden aangemaakt door de verbindingen van de relatie alsook de foreign keys die de link tussen de deelnemende tabellen voorstelt. - - Available tokens to define name patterns:<br/> <strong>%1</strong> = Reference (source) primary key column name. <em>(Ignored on constraint patterns)</em><br/> <strong>%2</strong> = Reference (source) table name.<br/> <strong>%3</strong> = Receiver (destination) table name.<br/> <strong>%4</strong> = Generated table name. <em>(Only for n:n relationships)</em> - Beschikbare tokens om naamspatronen te definieren:<br/> <strong>%1</strong> = (Bron)referentie primary key kolom naam. <em>(Genegeerd bij constraint-patronen)</em><br/> <strong>%2</strong> = (Bron)referentie tabelnaam.<br/> <strong>%3</strong> = Receiver (doel) tabelnaam.<br/> <strong>%4</strong> = Gegenereerde tabelnaam. <em>(Enkel voor n:n relaties)</em> - Available tokens to define name patterns:<br/> <strong>%1</strong> = Reference (source) primary key column name. <em>(Ignored on constraint patterns)</em><br/> <strong>%2</strong> = Reference (source) table name.<br/> <strong>%3</strong> = Receiver (destination) table name.<br/> <strong>%4</strong> = Generated table name. <em>(Only for n:n relationships)</em> @@ -11447,80 +11903,84 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr Standaard - + Referer View: Refererende View: - + Referer view references one or more columns of a table to construct it's own columns. De refererende view refereert naar een of meerdere kolommen van een tabel om zijn eigen kolommen aan te maken. - + Referenced table has its columns referenced by a view in order to construct the columns of this latter. De gerefereerde tabel heeft kolommen waarnaar wordt gerefereerd door een view die deze kolommen gebruikt om zijn eigen kolommen aan te maken. - + Referer Table: Refererende Tabel: - + Referer table references one or more columns of a table through foreign keys. This is the (n) side of relationship. De refererende tabel refereert naar een of meerdere kolommen in een andere tabel via foreign keys. Dit is the (n)-zijde van de relatie. - + Referenced table has its columns referenced by a table's foreign key. This is the (1) side of relationship. De gerefereerde tabel heeft kolommen waarnaar wordt gerefereerd door een foreign key in een andere tabel. Dit is de (1) zijde van de relatie. - + Referenced Table: Gerefereerde Tabel: - - - + + + Reference Table: Referentietabel: - + Reference table has the columns from its primary key will copied to the receiver table in order to represent the linking between them. This is the (1) side of relationship. De referentietabel heeft kolommen in zijn primary key die gekopieerd zullen worden naar de ontvangende tabel om de link tussen deze te bewerkstelligen. Dit is de (1) zijde van de relatie. - + Receiver Table: Ontvangende Tabel: - + Receiver (or referer) table will receive the generated columns and the foreign key in order to represent the linking between them. This is the (n) side of relationship. De ontvanger (of gerefereerde) tabel zal de gegenereerde kolommen en de foreign key ontvangen om de link tussen beiden te bewerkstelligen. Dit is de (n) zijde van de relatie. - + In many-to-many relationships both tables are used as reference to generate the table that represents the linking. Columns from both tables are copied to the resultant table and two foreign keys are created as well in order to reference each participant table. In meer-op-meer relaties worden beide tabellen als referentie gebruikt om de link-tabel te representeren. Kolommen van beide tabellen worden gekopieerd naar de resulterende link-tabel en foreign keys naar elke deelnemende tabel worden aangemaakt. - - + + is required is vereist - RoleWidget + ResultSetModel - Form - Venster + + [binary data] + [binaire data] + + + RoleWidget yyyy-MMM-dd hh:mm:ss @@ -11528,7 +11988,7 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr - + Validity Geldigheid @@ -11549,78 +12009,75 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr - Inherit Permissions - Erf Machtigingen Over + Inherit permissions + - Can create Database - Kan Database Aanmaken + Can create database + - Can Login - Kan Inloggen + Bypass RLS + - Can create Role - Kan Rol Aanmaken + Can use replication + - Can use Replication - Kan Replicatie Gebruiken + Can login + Kan inloggen - - + + Can create role + + + + + Members Leden - - + + Member of Lid van - - + + Members (Admin.) Leden (Admin.) - + Password: Wachtwoord: - + Encrypted Geëncrypteerd - - Assigning <strong><em>-1</em></strong> to <strong><em>Connections</em></strong> creates a role without connection limit.<br/> Unchecking <strong><em>Validity</em></strong> creates an role that never expires. - <strong><em>-1</em></strong> toewijzen aan <strong><em>Verbindingen</em></strong> maakt een rol aan zonder verbindingslimiet.<br/> Vink <strong><em>Geldigheid</em></strong> af om een rol aan te maken die nooit vervalt. - Assigning <strong><em>-1</em></strong> to <strong><em>Connections</em></strong> creates a role without connection limit.<br/> Unchecking <strong><em>Validity</em></strong> creates an role that never expires. - + Role Rol RuleWidget - - Form - Venster - Event: @@ -11665,227 +12122,269 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr Venster - - Load SQL script - Laad SQL script + + Save SQL commands + Sla SQL commando's op - - &Load - &Laden + + Search in SQL code + - - - Save SQL commands - Sla SQL commando's op + + Close the current SQL script + - - &Save - Op&slaan + + SQL script currently handled + - - Search in SQL code + + (not saved) + + + + + Handle external SQL script - - &Find - &Zoeken + + &Script + - + Alt+F Alt+Z - + + Fi&nd + + + + Run the specified SQL command Voer het commando uit - + Run SQL Uitvoeren - + F6 F6 - + Clear sql input field and results Wis SQL invoerveld en resultaten - + Clear All Alles Wissen - - + + Export results to a CSV file Exporteer de resultaten naar CSV bestand - + Snippe&ts Snippe&ts - + + Alt+T + + + + E&xport E&xporteren - + + Alt+X + + + + Toggles the output pane - + &Output - + Alt+O Alt+O - - - + + Current working database + + + + + + Results - + Messages - + History - Shows the command history - Toon de commandogeschiedenis - - - &History - &Geschiedenis - - - Alt+H - Alt+G - - - Command History - Commandogeschiedenis - - - Clear sql input field and results. - Wis SQL invoerveld en resultaten - - - Clear - Leegmaken - - - - + ... ... - 0 - 0 + + SQL file (*.sql);;All files (*.*) + SQL Code (*.sql);;Alle bestanden (*.*) + + + + Load + Laden - Rows returned: - Aantal rijen: + + Save + Opslaan - - SQL file (*.sql);;All files (*.*) - SQL Code (*.sql);;Alle bestanden (*.*) + + Save as + Opslaan als - + [binary data] [binaire data] - [<strong>%1</strong>] SQL command successfully executed. <em>Rows affected <strong>%2</strong></em> - [<strong>%1</strong>] SQL command werd succesvol uitgevoerd. <em><strong>%2</strong> rijen werden beïnvloed</em> - - - + No results retrieved or changes done due to the error above. - - + + Messages (%1) - + Results (%1) - - [%1]: SQL command successfully executed. <em>%2 <strong>%3</strong></em> + + [%1]: SQL command successfully executed in <em><strong>%2</strong></em>. <em>%3 <strong>%4</strong></em> - + Rows affected - + Rows retrieved - + Load SQL commands Laad SQL commando's - + Save CSV file Sla CSV bestand op - + Comma-separated values file (*.csv);;All files (*.*) Bestand met komma-gesepareerde waarden (*.csv);;Alle bestanden (*.*) - + The SQL input field and the results grid will be cleared! Want to proceed? Het SQL invoerveld en de resultaten-lijst zullen worden leeggemaakt! Wenst u verder te gaan? - + Copy selection Kopiëer de selectie - + + Plain format + + + + + CVS format + + + + + This action will wipe out all the SQL commands history for all connections! Do you really want to proceed? + + + + Clear history + + + Save history + + + + + Reload history + + + + + Find in history + + + + + Hide find tool + + + + + This action will wipe out all the SQL commands history for the current connection! Do you really want to proceed? + + SQLToolWidget @@ -11895,90 +12394,125 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr Venster - + Database explorer Databaseverkenner - + Disconnect from all databases Van alle databases ontkoppelen - - + + ... - + Update the database list - + Toggle the object's attributes grid - + Attributes Attributen - + Alt+R Alt+R - + Toggle the display of source code pane - - + + Source code Broncode - Update the database list. - Update de database lijst. - - - + SQL execution SQL uitvoering - - - + Warning Opgepast - + <strong>ATTENTION:</strong> Disconnect from all databases will close any opened tab in this view! Do you really want to proceed? <strong>LET OP:</strong> Van alle databases ontkoppelen sluit alle tab-bladen in dit venster! Bent u zeker dat u verder wilt gaan? + + + SceneInfoWidget - - <strong>CAUTION:</strong> You are about to drop the entire database <strong>%1</strong>! All data will be completely wiped out. Do you really want to proceed? - <strong>PAS OP:</strong> U staat op het punt om de volledige database <strong>%1</strong> te verwijderen! Alle data zal verloren gaan. Bent u zeker dat u verder wilt gaan? + + Form + Venster - - You're running a demonstration version! The data manipulation feature is available only in the full version! - Dit is een demonstratie-versie. De data manipulatie functionaliteit is enkel beschikbaar in de volledige versie! + + + Current position of the mouse in the canvas + + + + + + + + - + + + + + + Current zoom factor + + + + + + Currently selected object(s) + + + + + + Dimensions of the selected object(s) + + + + + No selection + + + + + N/A + + + + + Sel. objects: %1 + SchemaWidget - - Form - Venster - Fill color: @@ -11993,44 +12527,50 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr SequenceWidget - Form - Venster - - - + Cyclic: Cyclisch: - + Start: Start: - + Maximum: Maximum: - + Minimum: - + + Defualt values: + + + + Increment: Toename: - + Cache: Cache: - + Owner Col.: Bezittende kolom: + + + User defined + + SnippetsConfigWidget @@ -12194,65 +12734,8 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr Algemeen - - SourceCodeEditorForm - - Form - Venster - - - Load SQL script - Laad SQL script - - - &Load - &Laden - - - Save SQL commands - Bewaar SQL commando's - - - &Save - Op&slaan - - - &Find - &Zoek - - - Alt+F - Z is accelarator for Find - Alt+Z - - - Clear sql input field and results - Wis SQL invoerveld en resultaten - - - Clear All - Alles Wissen - - - Export results to a CSV file - Exporteer de resultaten naar CSV bestand - - - &Apply - Not sure p is a good accellerator here (t would be better but that is used for snippets) - Toe&passen - - - &Cancel - &Annuleren - - SourceCodeWidget - - Form - Venster - Version: @@ -12308,42 +12791,33 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr XML XML - - - Type: - Type: - Source code visualization Broncodevisualisatie - <strong>Original:</strong> displays only the original object's SQL code.<br/><br/><strong>Dependencies:</strong> display the original code including all dependencies needed to properly create the selected object.<br/><br/><strong>Children:</strong> display the original code including all children's SQL code. This option is used only by schemas, tables and views. - <strong>Origineel:</strong> toon enkel de originele SQL code van het object.<br/><br/><strong>Afhankelijken:</strong> toon de originele code inclusief alle afhankelijken die nodig zijn om het geselecteerde object correct aan te maken.<br/><br/><strong>Kinderen:</strong> toon de originele code inclusief de code voor alle kinderen. Deze optie wordt enkel gebruikt door schema's, tabellen en views. - - - + <strong>Original:</strong> displays only the original object's SQL code.<br/><br/> <strong>Dependencies:</strong> displays the original code including all dependencies needed to properly create the selected object.<br/><br/> <strong>Children:</strong> displays the original code including all object's children SQL code. This option is used only by schemas, tables and views. - + Save SQL code as... Sla SQL code op als... - + SQL code (*.sql);;All files (*.*) SQL Code (*.sql);;Alle bestanden (*.*) - + Generating source code... De broncode wordt gegeneerd... - + -- NOTE: the code below contains the SQL for the selected object -- as well for its dependencies and children (if applicable). -- @@ -12368,68 +12842,98 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr - + -- SQL code purposely truncated at this point in demo version! - - --- SQL code purposely truncated at this point on demo version! - -- In de demo-versie wordt de SQL code hier moedwillig afgekort! - - - + -- SQL code unavailable for this type of object -- -- Er is geen SQL code beschikbaar voor dit type object -- - + <!-- XML code preview disabled in demonstration version --> <!-- XML codevoorbeelden zijn niet beschikbaar in de demo-versie --> SwapObjectsIdsWidget - - Form - Venster - Change objects creation order - - Create: - Aanmaken: + + Create: + Aanmaken: + + + + + ID: + ID: + + + + Before: + Voor: + + + + Change the objects creation order is an irreversible operation and cause the operations history to be automatically erased. Note that the creation order configured in this form is not definitive and may change after a model validation. + + + + + Swap the object ids changing their creation order + + + + + Swap ids + + + + + Filter: + Filter: + + + + ID + ID + + + + Object + Object - - - ID: - ID: + + Type + Type - - Before: - Voor: + + Parent Object + Ouder Object - - It's recommended to use this feature only when the SQL validation fails in cases when a object is being referenced in portions where the ordinary validation couldn't reach, e.g., inside of a rule command or check constraint expression. - Het is aangeraden om dit feature enkel te gebruiken wanneer SQL validatie faalt in gevallen waarin naar een object wordt verwezen in delen waar de gewone validitie niet inkijkt, bijvoorbeeld binnen een regel-commando or check-constraint expressie. + + Parent Type + Ouder Type - + Swap the values of the fields Wissel de veldwaarden om - + Swap values Wissel de waarden om @@ -12437,12 +12941,12 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr Table - + new_table nieuwe_tabel - + In demonstration version tables can have only `%1' instances of each child object type or ancestor tables! You've reach this limit for the type: `%2' Tabellen kunnen slechts `%1' instancies per kind-object type of voorouder-tabellen hebben in demonstratie-versies! U heeft deze limiet bereikt voor het type `%2' @@ -12455,324 +12959,407 @@ laatste geaccepteerde structuur. Alle beschikbare opties worden hieronder beschr - + Add empty rows - - - Add - Toevoegen - - - + Ins Ins - - Some invalid or duplicated columns were detected. In order to solve this issue double-click the header of the highlighted ones in order to define the correct name in which the data belongs to or delete the entire column. Note that these columns are completely igored when generating the <strong>INSERT</strong> commands. + + Add an empty column - - Add an empty column + + Delete rows - - Remove all rows from the grid preserving columns + + <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in two slashes, e.g., <span style=" font-weight:600;">/value/</span>. To use a slash as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\/</span>.</p></body></html> - - - Clear - Leegmaken + + Remove all rows from the grid preserving columns + - + Shift+Del Shift+Del - + Delete the selected rows - - - Delete - Verwijderen - - - - + + Del Del - - <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in <span style=" font-weight:600;">{}</span>. To use <span style=" font-weight:600;">{</span> or <span style=" font-weight:600;">}</span> as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\{</span> or <span style=" font-weight:600;">\}</span>.</p></body></html> + + Duplicate the selected rows - - Duplicate the selected rows + + Ctrl+D + + + + + Delete the selected columns + + + + + Copy items on the grid + + + + + Copy + + + + + Add row + + + + + Delete column + + + + + Paste items on the grid + + + + + Paste + Plakken + + + + Ctrl+V + Ctrl+V + + + + Fills the grid using a CSV file + + + + + <html><head/><body><p>Some invalid or duplicated columns were detected. In order to solve this issue double-click the header of the highlighted ones in order to define the correct name in which the data belongs to or delete the entire column. Note that these columns are completely ignored when generating the <span style=" font-weight:600;">INSERT</span> commands.</p></body></html> + + + + + Add column - Duplicate + Duplicate rows - - Ctrl+D + + Change the values of all selected cells at once - - Delete the selected columns + + Bulk data edit - + + Ctrl+E + Ctrl+E + + + Remove all columns (and rows) from the grid - + + Delete all columns + + + + Ctrl+Shift+Del - + + Delete all rows + + + + Delete columns is an irreversible action! Do you really want to proceed? - + Remove all rows is an irreversible action! Do you really want to proceed? - + Remove all columns is an irreversible action! Do you really want to proceed? - + + Unknown column - + Duplicated column - - - (no columns) - - TableObjectView - + Relationship: %1 Relatie: %1 - - TableView - - - Connected rels: %1 - Verbonden relaties: %1 - - TableWidget - - Form - Venster - Options Opties - + Tag: Tag: - + With OID Met OID - + Generate ALTER for columns/constraints Genereer ALTER voor kolommen/constraints - + Unlogged Niet gelogged - + + Enable row level security + + + + + Force RLS for owner + + + + &Columns - + Co&nstraints - + Tri&ggers - + &Rules - + &Indexes - - &Tables + + &Policies - Columns - Kolommen - - - Constraints - Constraints - - - Triggers - Triggers - - - Rules - Regels - - - Indexes - Indexen - - - Tables - Tabellen + + &Tables + - + Edit data - + Define initial data for the table - - - - - - + + + + + + + Name Naam - + Schema Schema - - - + + + Type Type - + + PK + + + + Default Value Standaardwaarde - - Attribute - Attribuut + + Attribute(s) + + + + + It is not possible to mark a column as primary key when the table already has a primary key which was created by a relationship! This action should be done in the section <strong>Primary key</strong> of the relationship's editing form. + - + + It is not possible to mark a column created by a relationship as primary key! This action should be done in the section <strong>Primary key</strong> of the relationship's editing form. + + + + ON DELETE ON DELETE - + ON UPDATE ON UPDATE - + Refer. Table Refer. Tabel - + Firing Afvuring - + Events Events - + Execution Uitvoering - + Event Event - + Indexing Indexering - + + Command + + + + + Permissive + + + + + USING expression + + + + + CHECK expression + + + + + Roles + Rollen + + + Parent Ouder - + Copy Kopie + + + Yes + Ja + + + + No + Nee + TablespaceWidget @@ -12789,10 +13376,6 @@ Relationship: %1 TagWidget - - Form - Venster - Colors @@ -12827,23 +13410,19 @@ Relationship: %1 TaskProgressWidget - + Executing tasks Taken uitvoeren - - + + Waiting task to start... Wachten op het starten van de taak... TextboxWidget - - Form - Venster - Font: @@ -12880,17 +13459,13 @@ Relationship: %1 Onderstrepen - + Select text color Selecteer tekstkleur TriggerWidget - - Form - Venster - Constraint @@ -12977,22 +13552,18 @@ Relationship: %1 Uitvoer: - + Column Kolom - + Type Type TypeWidget - - Form - Venster - Range @@ -13135,10 +13706,6 @@ Relationship: %1 Co&mposite - - Composite - Composite - Enumerations @@ -13222,10 +13789,6 @@ Relationship: %1 Update Notifier Update Aankondiging - - New update found! - Er is een nieuwe update! - Hide this widget @@ -13246,10 +13809,6 @@ Relationship: %1 mmm dd, yyyy mmm dd, yyyy - - Version: - Versie: - Update found! @@ -13291,248 +13850,263 @@ Relationship: %1 Verkrijg de broncode - <strong>Note:</strong> Both actions below will open a new web browser window - <strong>Let op:</strong> Beide acties zullen in een browservenster openen - - - - Recover a package - Herstel een pakket - - - - Purchase a new package - Koop een nieuw pakket aan - - - - + + Failed to check updates Het ophalen van update informatie faalde - - The update notifier failed to check for new versions! Please, verify your internet connectivity and try again! Connection error returned: <strong>%1</strong>. - Het ophalen van nieuwe versie informatie faalde! Gelieve uw internetverbinding na te kijken en opnieuw te proberen! De verbindingsfout die werd gegenereerd is <strong>%1</strong>. + + The update notifier failed to check for new versions! Please, verify your internet connectivity and try again! Connection error returned: <em>%1</em> - <strong>%2</strong>. + - + No updates found Geen nieuwe updates - + You are running the most recent pgModeler version! No update needed. Dit is de meest recente versie van pgModeler! - + The update notifier failed to check for new versions! A HTTP status code was returned: <strong>%1</strong> Het ophalen van nieuwe versie informatie faalde! De volgende HTTP status code werd gegenereerd: <strong>%1</strong> ViewWidget - - Form - Venster - References Referenties - + Expression Alias: Expressiealias: - + Column: Kolom: - + Table: Tabel: - + Table Alias: Tabelalias: - + Used in: Gebruikt in: - + Column Kolom - + Expression Expressie - + Reference Type: Referentietype: - - SELECT-FROM - SELECT-FROM + + View Definition + Viewdefinitie + + + + Expression: + Expressie: + + + + Column Alias: + Kolomalias: + + + + The element will be used as part of the SELECT statement to retrieve columns or expressions that will compose the view's columns + - - FROM-WHERE - FROM-WHERE + + SELECT ... + - - After WHERE - Na WHERE + + The element will be used as part of the WHERE clause in form of conditional expression + - View Definition - Viewdefinitie + WHERE ... + - - Expression: - Expressie: + + The element is used in the FROM portion of the command in order to reference tables or construct JOIN statements + - Column Alias: - Kolomalias: + FROM ... + + + + + The element's expression is used exclusively as the view's definition + + + + + The element will be appended to the very end of the view's definition. This is useful when using GROUP BY/HAVING statements + + + + + End expression + - + Triggers Triggers - + Rules Regels - + + Indexes + Indexen + + + Table Expression Tabelexpressie - + Code Preview Codevoorbeeld - + Options Opties - + Tag: Tag: - + Mode: Modus: - + Ordinary Gewoon - + Recursi&ve - + &Materialized - Recursive - Recursief - - - Materialized - Gematerialiseerd - - - + With no data Zonder data - + Col./Expr. Kol./Expr. - + Alias Alias - + Alias Col. Alias Kol. - - Flags: SF FW AW VD - Vlaggen: SF FW AW VD + + Flags: SF FW AW EX VD + - - To reference all columns in a table (*) just do not fill the field <strong>Column</strong>, this is the same as write <em><strong>[schema].[tablel].*</strong></em> - Om naar alle kolommen in een tabel te refereren (*), laat het veld <strong>Kolom</strong> leeg, dit is equivalent aan <em><strong>[schema].[tabel].*</strong></em> + + To reference all columns in a table (*) just do not fill the field <strong>Column</strong>, this is the same as write <em><strong>[schema].[table].*</strong></em> + - - + + + Name Naam - + Refer. Table Refer. Tabel - + Firing Afvuring - + Events Events - + + Indexing + Indexering + + + Execution Uitvoering - + Event Event - + /* Could not generate the SQL code. Make sure all attributes are correctly filled! /* De SQL code kon niet worden gegenereerd. Kijk na of alle attributen correct zijn ingevuld! diff --git a/lang/pt_BR.qm b/lang/pt_BR.qm index 9060df3e01..b3cecf0428 100644 Binary files a/lang/pt_BR.qm and b/lang/pt_BR.qm differ diff --git a/lang/pt_BR.ts b/lang/pt_BR.ts index caf91dac77..5147272158 100644 --- a/lang/pt_BR.ts +++ b/lang/pt_BR.ts @@ -1,62 +1,6 @@ - - AboutForm - - About pgModeler - Sobre o pgModeler - - - Close - Fechar - - - PostgreSQL Database Modeler - Modelador de Banco de Dados PostgreSQL - - - Design, configure, deploy - Desenhe, configure, implante - - - Copyright 2006-2013 - Raphael Araújo e Silva <rkhaotix@gmail.com> - -The pgModeler project is a CASE tool for modeling relational databases for PostgreSQL DBMS through the use of modeling techniques from entity-relationship diagrams as well merging concepts that PostgreSQL implements. - -Special thanks to friends of the software development team of the Legislative Assembly, Tocantins, Brazil: Michel de Almeida, Felipe Santana, Jonas Nepomuceno, Ricardo Ishibashi and Álvaro Nunes. - Copyright 2006-2012 - Raphael Araújo e Silva <rkhaotix@gmail.com> - -O projeto pgModeler trata de uma ferramenta CASE para a criação de modelos de bancos de dados relacionais para o SGDB PostgreSQL através do uso de técnicas de modelagem de diagramas entidade-relacionamento, como também mesclando conceitos implementados pelo próprio PostgreSQL. - -Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Assembleia Legislativa, Tocantins, Brasil: Michel de Almeida, Felipe Santana, Jonas Nepomuceno, Ricardo Ishibashi and Álvaro Nunes. {2006-2013 ?} - - - This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 3. - -This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - -The complete text of GPLv3 is at LICENSE file on source code root directory. Also, you can get the complete GNU General Public License at <http://www.gnu.org/licenses/> - Este programa é software livre: você pode redistribuí-lo e/ou modificá-lo sob os termos da Licença Pública Geral da GNU como publicada pela Free Software Foundation versão 3. - -Este programa é distribuído na esperança de que seja útil, mas SEM QUALQUER GARANTIA; inclusive sem a garantia implícita de COMERCIABILIDADE ou ADEQUAÇÃO À UM PROPÓSITO ESPECÍFICO. Leia a Licença Pública Geral da GNU para mais detalhes. - -O texto completo da GPLv3 está no arquivo LICENSE no diretório raiz do código fonte. Você também pode obter a Licença Pública Geral da GNU completa em <http://www.gnu.org/licenses/> - - - Version %1 - Versão %1 - - - Copyright 2006-2013 - Raphael Araújo e Silva <rkhaotix@gmail.com> - -The pgModeler project is a CASE tool for modeling relational databases for PostgreSQL DBMS through the use of modeling techniques from entity-relationship diagrams as well merging concepts that PostgreSQL implements. - Em dúvida sobre "bem como mesclando". - Copyright 2006-2013 - Raphael Araújo e Silva <rkhaotix@gmail.com> - -O projeto pgModeler trata de uma ferramenta CASE para a criação de modelos de bancos de dados relacionais para o SGDB PostgreSQL através do uso de técnicas de modelagem de diagramas entidade-relacionamento, como também mesclando conceitos implementados pelo próprio PostgreSQL. - - AboutWidget @@ -71,22 +15,10 @@ O projeto pgModeler trata de uma ferramenta CASE para a criação de modelos de Open source data modeling tool designed for PostgreSQL. No more DDL commands written by hand, let pgModeler do the job for you! This software reunites the concepts of entity-relationship diagrams and the features that PostgreSQL implements as extensions of SQL standards. - - Design, configure, deploy - Desenhe, configure, implante - - - <a href="http://pgmodeler.com.br">http://pgmodeler.com.br</a> - - pgModeler is proudly a brazilian software! - - <html><head/><body><p>Copyright 2006-2016 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.com.br</span></a>&gt;</p></body></html> - - Hide this widget @@ -95,18 +27,6 @@ O projeto pgModeler trata de uma ferramenta CASE para a criação de modelos de ... - - 0.0.0.0 - - - - (CODE_NAME) - - - - Build: - - (BUILD_NUM) @@ -116,156 +36,28 @@ O projeto pgModeler trata de uma ferramenta CASE para a criação de modelos de - Contributors - - - - <html><head/><body><p>This page is dedicated to all contributors who gave a bit of their time in make pgModeler a better software somehow. The complete list of people that helped pgModeler can be found at <a href="https://github.com/pgmodeler/pgmodeler/graphs/contributors"><span style=" text-decoration: underline; color:#00a489;">GitHub</span></a>.</p><p>If you have a great idea to improve pgModeler please submit it <a href="http://github.com/pgmodeler/pgmodeler/issues"><span style=" text-decoration: underline; color:#00a489;">here</span></a>. No ideas for now but want to help? Why not donate a few bucks <a href="http://pgmodeler.com.br/#donate"><span style=" text-decoration: underline; color:#00a489;">here</span></a>!?</p></body></html> - - - - 1 - - - - 2 - - - - 3 - - - - 4 - - - - 5 - - - - 6 - - - - 7 - - - - 8 - - - - Name - Nome - - - Country - - - - Contribution - - - - Damien Degois - - - - France - - - - French UI translation and several improvements in auxiliary scripts. - - - - Ji Bin - - - - China - - - - Chinese UI translation and small fixes. - - - - Pierre-Samuel LE STANG - - - - French UI translation. - - - - Lisandro Damián Nicanor - - - - Argentina - - - - Improvements on build scripts enabling the custom packaging in Linux distros; Per-user settings; pgModeler's package maintainer in Debian Linux. - - - - Pavel Alexeev - - - - Russia - - - - Additional work for packaging in Linux distros; pgModeler's package maintainer in Fedora Linux. - - - - Mariusz Fik - - - - Poland - - - - Custom packaging first ideas. Tester of first version of custom packaging patch. - - - - Jonathan DUPRE + 0.0.0 - Gilberto Castillo + build: - Cuba + <html><head/><body><p><a href="http://pgmodeler.com.br"><span style=" text-decoration: underline; color:#2980b9;">https://pgmodeler.io</span></a></p></body></html> - Spanish UI translation. + <html><head/><body><p>Copyright 2006-2018 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.io</span></a>&gt;</p></body></html> AggregateWidget - - Form - Formulário - Final Function: Função Final: - - Transition Function: - Função de Transição: - Sort Operator: Operador de Ordenação: @@ -299,17 +91,6 @@ O projeto pgModeler trata de uma ferramenta CASE para a criação de modelos de - - Aplicacao - - Error - Erro - - - Unknown exception caught! - Exceção desconhecida capturada! - - AppearanceConfigWidget @@ -520,18 +301,6 @@ O projeto pgModeler trata de uma ferramenta CASE para a criação de modelos de Colors: Cores: - - Font color / Fill color 1 - Cor da fonte / Cor do preenchimento 1 - - - Fill color 2 - Cor do preenchimento 2 - - - Border color - Cor da borda - Underline Sublinhado @@ -552,13 +321,17 @@ O projeto pgModeler trata de uma ferramenta CASE para a criação de modelos de Placeholder: Body + + Constraint: Name + + + + Constraint: Descriptor + + Application - - Error - Erro - Unknown exception caught! Exceção desconhecida capturada! @@ -569,26 +342,10 @@ O projeto pgModeler trata de uma ferramenta CASE para a criação de modelos de - BancoDadosWidget - - Model Author: - Autor do Modelo: - + BaseConfigWidget - Encoding: - Codificação: - - - Connections: - Conexões: - - - Default - Padrão - - - Template DB: - DB Modelo: + A backup of the previous settings was saved into <strong>%1</strong>! + @@ -751,6 +508,14 @@ O projeto pgModeler trata de uma ferramenta CASE para a criação de modelos de Basic Relationship + + Policy + + + + Generic SQL + + BaseObjectView @@ -761,10 +526,6 @@ O projeto pgModeler trata de uma ferramenta CASE para a criação de modelos de BaseObjectWidget - - Form - Formulário - Name: Nome: @@ -790,22 +551,10 @@ O projeto pgModeler trata de uma ferramenta CASE para a criação de modelos de Schema: Esquema: - - Permissions: - Permissões: - - - Edit Permissions - Editar Permissões - This object is protected thus no change in form will be applied to it. Este objeto está protegido, assim nenhuma alteração no formulário será aplicada ao mesmo. - - Create / Edit: - Criar / Editar: - Value(s) Valor(es) @@ -814,18 +563,10 @@ O projeto pgModeler trata de uma ferramenta CASE para a criação de modelos de Version Versão - - The field(s) or value(s) highlighted on the form is(are) for the exclusive use and/or mandatory in specific versions of PostgreSQL. Failure to complete that may cause errors in the generation of SQL code for each version shown in tool tips of the highlighted fields. - O(s) campo(s) ou valor(es) destacado(s) no formulário é(são) de uso exclusivo e/ou obrigatório em versões específicas do PostgreSQL. O não preenchimento do(s) mesmo(s) pode ocasionar erros na geração de código SQL de cada versão indicada nas dicas de ferramenta dos campos destacados. - Edit permissions Editar permissões - - Disables the generated SQL code using comment tokens (--) - Desabilitar o código SQL gerado usando símbolos de comentário (--) - Disable SQL code Desabilitar código SQL @@ -838,10 +579,6 @@ O projeto pgModeler trata de uma ferramenta CASE para a criação de modelos de Required field. Leaving this empty will raise errors! Campo requerido. Deixá-lo em branco gerará erros! - - The <em style='color: %1'><strong>highlighted</strong></em> fields on the form are available only on specific PostgreSQL versions. When generating SQL code for versions other than those specified on field's tooltips pgModeler will ignore it's values. - Os campos <em style='color: %1'><strong>destacados</strong></em> no formulário estão disponíveis apenas em versões específicas do PostgreSQL. Ao gerar código SQL para versões diferentes daquelas especificadas nas dicas de campo, o pgModeler ignorará estes valores. - Edit object's permissions Editar permissões do objeto @@ -875,6 +612,17 @@ This will disable the code of all child and referrer objects. + + BaseTableView + + Toggles the extended attributes display + + + + Connected rels: %1 + + + BugReportForm @@ -951,5729 +699,3554 @@ This will disable the code of all child and referrer objects. - CaixaMensagem + BulkDataEditWidget - Show/hide exceptions stack. - Exibir/Esconder pilha de exceções. + Bulk data edit + + + + CastWidget - &Yes - &Sim + Cast Type: + Molde de Tipo: - &No - &Não + Assignment + Atribuição - Cancel - Cancelar + Input / Output + Entrada / Saída - Error - Erro + Source data type + Tipo dado origem - Alert - Alerta + Target data type + Tipo dado destino - Information - Informação + The function to be assigned to a cast from <em><strong>typeA</strong></em> to <em><strong>typeB</strong></em> must have the following signature: <em><strong>typeB</strong> function(<strong>typeA</strong>, integer, boolean)</em>. + A função a ser atribuída à uma moldagem do <em><strong>tipoA</strong></em> para o <em><strong>tipoB</strong></em> deve possuir a seguinte assinatura: <em><strong>tipoB</strong> funcao(<strong>tipoA</strong>, integer, boolean)</em>. - &Cancel - &Cancelar + I&mplicit + - Exceptions - Exceções + Conversion Func.: + Função de Conv.: - Show excpetion stack in text format (useful to report errors). - Exibe a pilha de exceções em formato texto (útil para se reportar erros). + E&xplicit + - CaixaTextoWidget + CodeCompletionWidget - Bold - Negrito + Makes the widget closable only by ESC key or mouse click on other controls. + - Italic - Itálico + SQL Keyword + - Select text color - Selecionar cor de texto + (no items found.) + - Underline - Sublinhado + Make &persistent + - CastWidget - - Form - Formulário - - - Cast Type: - Molde de Tipo: - + CollationWidget - Implicit - Implícita + Locale: + Localidade: - Assignment - Atribuição + Encoding: + Codificação: - Input / Output - Entrada / Saída + LC_COLLATE: + - Conversion Function: - Função de Conversão: + LC_CTYPE: + - Source data type - Tipo dado origem + The fields <strong><em>Collation</em></strong>, <strong><em>Locale</em></strong>, <strong><em>LC_COLLATE & LC_CTYPE</em></strong> are mutually exclusive, so you have to set only one of them in order to properly handle a collation. + Os campos <strong><em>Intercalação</em></strong>, <strong><em>Localidade</em></strong>, <strong><em>LC_COLLATE & LC_CTYPE</em></strong> são mutuamente exclusivos, então você tem que definir apenas um deles a fim de manipular corretamente a intercalação. - Target data type - Tipo dado destino + Not defined + Não definido + + + ColorPickerWidget - The function to be assigned to a cast from <em><strong>typeA</strong></em> to <em><strong>typeB</strong></em> must have the following signature: <em><strong>typeB</strong> function(<strong>typeA</strong>, integer, boolean)</em>. - A função a ser atribuída à uma moldagem do <em><strong>tipoA</strong></em> para o <em><strong>tipoB</strong></em> deve possuir a seguinte assinatura: <em><strong>tipoB</strong> funcao(<strong>tipoA</strong>, integer, boolean)</em>. + Form + Formulário - I&mplicit + Generate random color(s) - Conversion Func.: - Função de Conv.: + Alt+R + - E&xplicit + Select color - ClasseOperadoresWidget - - Default Class: - Classe Padrão: - - - Indexing: - Indexação: - + ColumnWidget - Elements - Elementos + Default Value: + Valor Padrão: - Elemente Type: - Tipo de Elemento: + E&xpression: + - Operator - Operador + &NOT NULL + - Function - Função + Se&quence: + - Storage - Armazenamento + Edit the underlying sequence's attributes + - Function: - Função: + Edit sequence + - Operator: - Operador: + Identity: + + + + ConfigurationForm - Support/Strategy: - Suporte/Estratégia: + pgModeler Configuration + Configuração do pgModeler - Recheck - Rechecar + &Apply + &Aplicar - Family: - Família: + &Cancel + &Cancelar - Storage Type - Tipo de Armazenamento + Defaults + Padrões - Object - Objeto + General + Geral - Type - Tipo + Plug-ins + Plugins - Support/Strategy - Suporte/Estratégia + Any modification made until now in the current section will be lost! Do you really want to restore default settings? + Qualquer modificação feita até agora na seção atual será perdida! Deseja realmente restaurar as configurações padrão? - Yes - Sim + Relationships + - No - Não + Appearance + - - - CodeCompletionWidget - Make persistent + Connections - Makes the widget closable only by ESC key or mouse click on other controls. + Snippets - SQL Keyword + In some cases restore the default settings related to it may solve the problem. Would like to do that? - (no items found.) + Restore - CodigoFonteWidget + ConnectionsConfigWidget - Version: - Versão: + Connections: + Conexões: - Type: - Tipo: + Create new connection + Criar nova conexão - Source code visualization - Visualização de Código-Fonte + Cancel edition + Cancelar edição - Generating source code... - Gerando código-fonte... + Edit selected connection + Editar conexão selecionada - -- SQL code unavailable for this type of object -- - -- Código SQL não disponível para este tipo de objeto. -- + Delete selected connection + Apagar conexão selecionada - - - CollationWidget - Form - Formulário + Connection Alias: + Apelido da Conexão: - Locale: - Localidade: + Connection DB: + BD Conexão: - Encoding: - Codificação: + Host/Port: + Servidor/Porta: - LC_COLLATE: - + User: + Usuário: - LC_CTYPE: - + Password: + Senha: - The fields <strong><em>Collation</em></strong>, <strong><em>Locale</em></strong>, <strong><em>LC_COLLATE & LC_CTYPE</em></strong> are mutually exclusive, so you have to set only one of them in order to properly handle a collation. - Os campos <strong><em>Intercalação</em></strong>, <strong><em>Localidade</em></strong>, <strong><em>LC_COLLATE & LC_CTYPE</em></strong> são mutuamente exclusivos, então você tem que definir apenas um deles a fim de manipular corretamente a intercalação. + Timeout: + Tempo limite: - Not defined - Não definido + second(s) + segundo(s) - - - ColorPickerWidget - Form - Formulário + SSL Mode: + Modo SSL: - Generate random color(s) - + Disable + Desabilitar - Alt+R - + Allow + Permitir - Select color - + Require + Requerir - - - ColumnWidget - Form - Formulário + AC verification + Verificação de AC - Default Value: - Valor Padrão: + Full verification + Verificação Completa - Not Null: - Não Nulo: + Client Certificate: + Certificado Cliente: - E&xpression: - + ~/.postgresql/postgresql.crt + - &NOT NULL - + Client Key: + Chave Cliente: - Se&quence: - + ~/.postgresql/postgresql.key + - - - ColunaWidget - Default Value: - Valor Padrão: + Root Certificate: + Certificado Raiz: - Not Null: - Não Nulo: + ~/.postgresql/root.crt + - - - ConfAparenciaWidget - Element: - Elemento: + Revoked Certs.: + Cert. Revogados: - Global: Font style - Global: Estilo de fonte + ~/.postgresql/root.crl + - Global: Constraints descriptor - Global: Descritor de restrições + Force GSSAPI + Forçar GSSAPI - Global: Object selection - Global: Seleção de objetos + Add + Adicionar - Global: Position hint text - Global: Texto informativo de posição + Update + Atualizar - Global: Position hint box - Global: Caixa do informativo de posição + Test + Testar - Global: Objects type - Global: Tipo de objetos + Success + Sucesso - Global: Lock arc - Global: Arco de cadeado + Edit database connections + - Global: Lock body - Global: Corpo do cadeado + Duplicate the selected connection + - Table: Schema name - Tabela: Nome de esquema + General + Geral - Table: Table name - Tabela: Nome de tabela + Other params: + - Table: Columns box - Tabela: Caixa de colunas + Specify additional connection parameters in the form [param]=[value]. These parameters are described in the <strong>libpq</strong> chapter at PostgreSQL docs. + - Table: Extended attributes box - Tabela: Caixa de atributos extendidos + Default for: + - Table: Title box - Tabela: Caixa de título + Automatically browses the named database when using this connection to manage databases on <strong>Manage</strong> view. + - Index: Descriptor - Índice: Descritor + Auto browse + - Trigger: Descriptor - Gatilho: Descritor + Diff + - View: Schema name - Visão: Nome de esquema - - - View: View name - Visão: Nome de visão + Export + Exportar - View: References box - Visão: Caixa de referências + Import + - View: Title box - Visão: Caixa de título + Validation + - View: Table / columns alias - Visão: Alias de tabela / coluna + Security + - View: Referenced column - Visão: Coluna referenciada + Kerberos Server: + - View: Referenced table - Visão: Tabela referenciada + Indicates in which operations (diff, export, import or validation) the connection is used if none is explicitly specified by the user. + - View: Reference descriptor - Visão: Descritor de referência + There is a connection being created or edited! Do you want to save it? + - Textbox: Body - Caixa de Texto: Corpo + Found %1 connection(s) + - Column: Column name - Coluna: Nome de coluna + No connections found + - Column: Descriptor - Coluna: Descritor + Edit connections + - Column: Included / Inherited by relationship - Coluna: Incluída / Herdada por relacionamento + Connection successfully established! + +Server details: + +PID: `%1' +Protocol: `%2' +Version: `%3' + + + + ConstraintWidget - Column: Protected - Coluna: Protegida + Constraint Type: + Tipo de Restrição: - Column (pk): Column name - Coluna (pk): Nome de coluna + Fill Factor: + Fator Preenc.: - Column (pk): Descriptor - Coluna (pk): Descritor + Match: + Confrontar: - Column (fk): Column name - Coluna (fk): Nome de coluna + Deferrable: + Postergável: - Column (fk): Descriptor - Coluna (fk): Descritor + Deferral: + Postergação: - Column (uq): Column name - Coluna (uq): Nome de coluna + ON DELETE: + - Column (uq): Descriptor - Coluna (uq): Descritor + ON UPDATE: + - Column (nn): Column name - Coluna (nn): Nome de coluna + Columns + Colunas - Column (nn): Descriptor - Coluna (nn): Descritor + Column: + Coluna: - Relationship: Descriptor - Relacionamento: Descritor + Referenced Columns + Colunas Referenciadas - Relationship: Label text - Relacionamento: Texto do rótulo + Table: + Tabela: - Relationship: Label box - Relacionamento: Caixa do rótulo + Column + Coluna - Relationship: Attribute text - Relacionamento: Texto do atributo + Type + Tipo - Relationship: Attribute descriptor - Relacionamento: Descritor do atributo + No inherit: + Sem herança: - Bold - Negrito + Exclude Elements + Excluir Elementos - Italic - Itálico + Columns which were included by relationship can not be added / removed manually from the primary key. If done such changes they can raise errors. To create primary key using columns included by relationship use the following options: identifier field, attributes & constraints tab or primary key tab on the relationship form. + Colunas que foram incluídas por relacionamento não podem ser adicionadas / removidas manualmente da chave primária. Se tais alterações forem feitas elas podem gerar erros. Para criar chaves primárias usando colunas incluídas por relacionamentos use as seguintes opções: campo identificador, aba atributos & restrições ou aba chave primária no formulário de relacionamento. - Colors: - Cores: + This attribute cannot be changed once the object is created. + - Font color / Fill color 1 - Cor da fonte / preenchimento 1 + Expression: + Expressão: - Fill color 2 - Cor de preenchimento 2 + Indexing: + Indexação: + + + ConversionWidget - Border color - Cor da borda + Source Encoding: + Codificação Origem: - Underline - Sublinhado + Target Encoding: + Codificação Destino: - Rule: Name - Regra: Nome + Default Conversion: + Conversão Padrão: - Rule: Descriptor - Regra: Descritor + The function to be assigned to an encoding conversion must have the following signature: <em>void function(integer, integer, cstring, internal, integer)</em>. + A função a ser atribuída a uma conversão de codificação deve possuir a seguinte assinatura: <em>void funcao(integer, integer, cstring, internal, integer)</em>. - Index: Name - Índice: Nome + Conversion Func.: + Função de Conv.: + + + CrashHandlerForm - Trigger: Name - Gatilho: Nome + Crash Handler + - Font: - Fonte: + Stack trace + Rastreamento de pilha - - - ConfConexoesWidget - Connections: - Conexões: + Input: + - Create new connection - Criar nova conexão + Load report file for analysis + - Cancel edition - Cancelar edição + Save the attached model file on the filesystem + - Edit selected connection - Editar conexão selecionada + pgModeler bug report (*.bug);;All files (*.*) + - Connection Alias: - Alias Conexão: + Load report + - Connection DB: - BD Conexão: + Save model + Salvar modelo - Host/Port: - Host/Porta: + Database model (*.dbm);;All files (*.*) + Modelo de banco de dados (*.dbm);; Todos os arquivos (*.*) - User: - Usuário: + Crash handler + - Password: - Senha: + Bug report analysis mode activated. + - Timeout: - Timeout: + Oops! pgModeler just crashed! + Oopa! O pgModeler acaba de travar! - second(s) - segundo(s) + We apologize for what happened! It is clear that a nasty bug caused that. Please fill out the form below describing your actions before pgModeler quit unexpectedly. This will help on bug extermination and improve the software. + + + + CsvLoadWidget - SSL Mode: - Modo SSL: + Form + Formulário - Disable - Desativado + Load CSV + - Allow - Permitir + CSV File: + - Require - Requerido + Select output file + - AC verification - Verificação de AC + ... + - Full verification - Verificação Completa + Separator: + - Client Key: - Chave Cliente: + Use the first row as column names in the CSV file. By unchecking this option the first row is used as data. + - Revoked Certs.: - Cert. Revogados: + Columns in the first row + - Kerberus Server: - Servidor Kerberus: + Load + Carregar - Force GSSAPI - Forçar GSSAPI + Semicolon (;) + - Options: - Opções: + Comma (,) + - Add - Adicionar + Space + - Update - Atualizar + Tabulation + - Test - Testar + Other + - Delete selected connection - Excluir conexão selecionada + ; + - Client Certificate: - Certificado Cliente: + Text delimiter: + - Root Certificate: - Certificado Raiz: + " + - Success - Sucesso + Load CSV file + - Connection successfuly stablished! - Conexão efetuada com sucesso! + Comma-separted values (*.csv);;All files (*.*) + - ConfGeralWidget + CustomSQLWidget - Grid size: - Tamanho da grade: + Add custom SQL code + - Operation history: - Histórico de operações: + SQL code + - items - itens + Puts an SELECT command template at current cursor position. + - Save model every: - Salvar modelo a cada: + &SELECT + - minute(s) - minuto(s) + Puts an INSERT command template at current cursor position. + - Save widgets position - Salvar posição de widgets + &INSERT + - Save current session - Salvar sessão atual + Puts an UPDATE command template at current cursor position. + - Paper: - Papel: + &UPDATE + - Custom (Based on margins) - Personalizado (Baseado nas margens) + Puts an DELETE command template at current cursor position. + - Orientation: - Orientação: + &DELETE + - Portrait - Retrato + &Clear + - Landscape - Paisagem + Append SQL + - Margins: - Margens: + Append the SQL code at the very end of model definition. +Unchecking this will cause the SQL to be appended at the end of CREATE DATABASE command. + - Milimeters - Milímetros + Append at end of model definition. + - Inches - Polegadas + Prepend SQL + - Centimeter - Centímetros + Prepend at beginning of model definition. + - Left: - Esq.: + <html><head/><body><p>Use custom commands with extreme caution because you can change the semantics of the entire model when running SQL validation or export processes. Additionally, depending on the amount of commands, those processes can have their performance sensibly degradated.</p></body></html> + - Left margin - Margem esquerda + Generic INSERT + - Top: - Topo: + Include serial columns + - Top margin - Margem topo + Exclude serial columns + - Right: - Dir.: - + Generic SELECT + + - Right margin - Margem direita + Table SELECT + - Bottom: - Base: + Generic UPDATE + - Bottom margin - Margem base + Table UPDATE + + + + Generic DELETE + + + + Table DELETE + - ConfigurationForm + DataManipulationForm - pgModeler Configuration - Configuração do pgModeler + Data Manipulation + - &Apply - &Aplicar + &Close + &Fechar - &Cancel - &Cancelar + Refresh listing + - Defaults - Padrões + F5 + - General - Geral + Save changes + - Style - Estilo + Ctrl+S + - Connetions - Conexões + Export results to CSV file + - Plug-ins - Plugins + Ctrl+X + - Confirmation - Confirmação + Undo modifications + - Any modification made until now in the current section will be lost! Do you really want to restore default settings? - Qualquer modificação feita até agora na seção atual será perdida! Deseja realmente restaurar as configurações padrão? + Ctrl+Z + - Relationships + Add empty rows - Appearance + Ins - Connections + Mark the selected rows to be deleted - Snippets + Del - - - ConnectionsConfigWidget - Form - Formulário + Duplicate the selected rows + - Connections: - Conexões: + Ctrl+D + - Create new connection - Criar nova conexão + Filter the result set + - Cancel edition - Cancelar edição + Table: + Tabela: - Edit selected connection - Editar conexão selecionada + Schema: + Esquema: - Delete selected connection - Apagar conexão selecionada + in + - Connection Alias: - Apelido da Conexão: + Hide views + - Connection DB: - BD Conexão: + Filter expression + - Host/Port: - Servidor/Porta: + Order && Limit + - User: - Usuário: + results (Use <strong>0</strong> for no limit) + - Password: - Senha: + Limit in: + - Timeout: - Tempo limite: + Add Item + Adicionar Item - second(s) - segundo(s) + Remove Item + Remover Item - SSL Mode: - Modo SSL: + Clear the order by columns list + - Disable - Desabilitar + Move selected item up + - Allow - Permitir + Move selected item down + - Require - Requerir + ASC + - AC verification - Verificação de AC + DESC + - Full verification - Verificação Completa + Column: + Coluna: - Client Certificate: - Certificado Cliente: + <strong>WARNING: </strong> There are some changed rows waiting the commit! Do you really want to discard them and retrieve the data now? + - ~/.postgresql/postgresql.crt - + Rows returned: <strong>%1</strong>&nbsp;&nbsp;&nbsp; + - Client Key: - Chave Cliente: + <em>(Limit: <strong>%1</strong>)</em> + - ~/.postgresql/postgresql.key - + none + - Root Certificate: - Certificado Raiz: + No objects found + - ~/.postgresql/root.crt - + Found %1 object(s) + - Revoked Certs.: - Cert. Revogados: + Views can't have their data handled through this grid, this way, all operations are disabled. + - ~/.postgresql/root.crl - + The selected table doesn't owns a primary key! Updates and deletes will be performed by considering all columns as primary key. <strong>WARNING:</strong> those operations can affect more than one row. + - Kerberus Server: - Servidor Kerberus: + This row is marked to be %1 + - Force GSSAPI - Forçar GSSAPI + deleted + - Options: - Opções: + updated + - Add - Adicionar + inserted + - Update - Atualizar + [binary data] + - Test - Testar + <strong>WARNING:</strong> Once commited its not possible to undo the changes! Proceed with saving? + - Success - Sucesso + delete + - Connection successfuly stablished! - Conexão estabelecida com sucesso! + update + - Edit database connections + insert - Duplicate the selected connection + <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in two slashes, e.g., <span style=" font-weight:600;">/value/</span>. To use a slash as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\/</span>.</p></body></html> - General - Geral + Copy items on the grid + - Other params: + Paste items on the grid - Specify additional connection parameters in the form [param]=[value]. These parameters are described in the <strong>libpq</strong> chapter at PostgreSQL docs. + Ctrl+V - Default for: + Browse referenced tables - Automatically browses the named database when using this connection to manage databases on <strong>Manage</strong> view. + Change the values of all selected cells at once - Auto browse + Ctrl+E - Diff + Add new rows from a CSV file - Export - Exportar + Copy as CSV + - Import + Copy as text - Validation + Copy items - Security + Pase items - Kerberos Server: + Browse tables - Indicates in which operations (diff, export, import or validation) the connection is used if none is explicitly specified by the user. + Duplicate row(s) - Connection successfuly stablished! - -Server details: - -PID: `%1' -Protocol: `%2' -Version: `%3' + Delete row(s) - There is a connection being created or edited! Do you want to save it? + Edit cell(s) - Found %1 connection(s) + Column + Coluna + + + Referenced tables - No connections found + (none) - Edit connections + Referrer tables - ConstraintWidget + DatabaseExplorerWidget Form - Formulário + Formulário - Constraint Type: - Tipo de Restrição: + Open the grid to visualize or edit data + - Check Expr.: - Expr.Checagem: + Data &Grid + - Fill Factor: - Fator Preenc.: + Alt+G + - Match: - Confrontar: + Open a new SQL execution pane + - Deferrable: - Postergável: + ... + - Deferral: - Postergação: + Ctrl+F6 + - ON DELETE: - + Update the objects tree + - ON UPDATE: - + Drop this database + - Columns - Colunas + Expands all items + Expandir todos os itens - Column: - Coluna: + Collapses all items + Recolher todos os itens - Referenced Columns - Colunas Referenciadas + Filters the currently loaded items in the tree by using a pattern and matching their names. If <strong>By OID</strong> is checked the pattern is interpreted as an integer value that represents the object id (OID). <br><br/><strong>HINT:</strong> if you need to search the entire database use the full refresh (<strong>Ctrl+F5</strong>) prior the filtering. + - Table: - Tabela: + Filter: + - Column - Coluna + By OID + - Type - Tipo + Attribute + Atributo - Columns which were included by relationship can not be added / removed manually from the primary key. If done such changes they will be ignored. To create primary key using columns included by relationship use the feature attributes, constraints and primary key on the relationship form. - Colunas as quais foram incluídas por relacionamento não podem ser adicionadas/removidas manualmente das chaves-primárias. Caso isso ocorra tais alterações serão ignoradas. Para criar chaves-primárias usando colunas incluídas por relacionamentos utilize o recurso de atributos, restrições e chave-primária no formulário de edição relacionamentos. + Value + - No inherit: - Sem herança: + Show raw attributes + - Exclude Elements - Excluir Elementos + (not found, OID: %1) + - Columns which were included by relationship can not be added / removed manually from the primary key. If done such changes they can raise errors. To create primary key using columns included by relationship use the following options: identifier field, attributes & constraints tab or primary key tab on the relationship form. - Colunas que foram incluídas por relacionamento não podem ser adicionadas / removidas manualmente da chave primária. Se tais alterações forem feitas elas podem gerar erros. Para criar chaves primárias usando colunas incluídas por relacionamentos use as seguintes opções: campo identificador, aba atributos & restrições ou aba chave primária no formulário de relacionamento. + -- Source code not generated! Hit F7 or middle-click the item to load it. -- + - This attribute cannot be changed once the object is created. + Admin. roles - Expression: - Expressão: + Alignment + - Indexing: - Indexação: + Analyze func. + - - - ConversaoCodificacaoWidget - Source Encoding: - Codificação Origem: + Arg. count + - Target Encoding: - Codificação Destino: + Arg. default count + - Convertion Function: - Função de Conversão: + Arg. defaults + - Default Conversion: - Conversão Padrão: + Arg. modes + - The function to be assigned to an encoding conversion must have the following signature: <em>void function(integer, integer, cstring, internal, integer)</em>. - A função a ser atribuída a uma conversão de codificação deve possuir a seguinte assinatura: <em>void funcao(integer, integer, cstring, internal, integer)</em>. + Arg. names + - - - ConversaoTipoWidget - Conversion Type: - Tipo da Conversão: + Arg. types + - Implicit - Implícita + Behavior type + - Assignment - Atribuição + By value + Por valor - Input / Output - Entrada / Saída + Cast type + - Convertion Function: - Função de Conversão: + Category + - The function to be assigned to a cast from <em><strong>typeA</strong></em> to <em><strong>typeB</strong></em> must have the following signature: <em><strong>typeB</strong> function(<strong>typeA</strong>, integer, boolean)</em>. - A função a ser atribuída a uma conversão do <em><strong>tipoA</strong></em> para o <em><strong>tipoB</strong></em> deve possuir a seguinte assinatura: <em><strong>tipoB</strong> funcao(<strong>tipoA</strong>, integer, boolean)</em>. + Collatable + Intercalável - Source data type - Tipo dado origem + Collation + Intercalação - Target data type - Tipo dado destino + Comment + - - - ConversionWidget - Form - Formulário + Commutator Op. + - Source Encoding: - Codificação Origem: + Configuration + - Target Encoding: - Codificação Destino: + Conn. limit + - Default Conversion: - Conversão Padrão: + Constraint + Restrição - The function to be assigned to an encoding conversion must have the following signature: <em>void function(integer, integer, cstring, internal, integer)</em>. - A função a ser atribuída a uma conversão de codificação deve possuir a seguinte assinatura: <em>void funcao(integer, integer, cstring, internal, integer)</em>. + Create DB + - Conversion Func.: - Função de Conv.: + Create role + - - - CrashHandler - pgModeler Crash Handler - Gerenciador de erros do pgModeler + Curr. version + - Oops! pgModeler just crashed! - Oopa! O pgModeler acaba de travar! + Default + Padrão - Create - Criar + Default value + - &Cancel - &Cancelar + Definition + Definição - We apologize for what happened! It is clear that a nasty bug caused it. Please fill out the form below describing your actions before pgModeler quit unexpectedly. This will help on bug extermination and improve the software. - Pedimos desculpas pelo ocorrido! Está claro que um bug desagradável causou isso. Por favor, preencha o formulário abaixo descrevendo suas ações antes do pgModeler fechar inesperadamente. Isso ajudará na eliminação do bug e melhoria do software. + Delimiter + - Report - Relatório + Dest. type + - Actions made before the crash: - Ações feitas antes do travamento: + Dimension + Dimensão - Loaded Model - Modelo Carregado + Directory + - Attach the below database model file that possibly generates the crash. - Anexar abaixo o modelo de banco de dados que possivelmente gera o travamento. + Dest. encoding + - Stack trace - Rastreamento de pilha + Element + Elemento - pgModeler crash file analysis - Análise de arquivo de travamento do pgModeler + Encoding + - Error - Erro + Encrypted + Encriptado - File: %1 -Size: %2 bytes - - - Arquivo: %1 -Tamanho: %2 bytes - - + Enumerations + Enumerações - Information - Informação + Exec. cost + - Crash report successfuly generated! Please send the file '%1' to %2 in order be debugged. Thank you for the collaboration! - Relatório de travamento gerado com sucesso! Por favor, envie o arquivo '%1' para %2 a fim de que possa ser depurado. Obrigado pela colaboração! + Expression + Expressão - - - CrashHandlerForm - Crash Handler + Op. family - Stack trace - Rastreamento de pilha + Final func. + - Input: - + Function + Função - Load report file for analysis + Func. type - Save the attached model file on the filesystem + Handler func. - pgModeler bug report (*.bug);;All files (*.*) + Handles type - Load report + Hashes - Save model - Salvar modelo + Index type + - Database model (*.dbm);;All files (*.*) - Modelo de banco de dados (*.dbm);; Todos os arquivos (*.*) + Inherit + - Crash handler + Ini. condition - Bug report analysis mode activated. + Inline func. - Oops! pgModeler just crashed! - Oopa! O pgModeler acaba de travar! + Input func. + - We apologize for what happened! It is clear that a nasty bug caused that. Please fill out the form below describing your actions before pgModeler quit unexpectedly. This will help on bug extermination and improve the software. + Internal length - - - CustomSQLWidget - Add custom SQL code + Interval type - SQL code + I/O cast - Puts an SELECT command template at current cursor position. + Join func. - &SELECT - + Language + Linguagem - Puts an INSERT command template at current cursor position. + LC COLLATE - &INSERT + LC CTYPE - Puts an UPDATE command template at current cursor position. + Leak proof - &UPDATE + Left type - Puts an DELETE command template at current cursor position. - + Length + Comprimento - &DELETE - + Library + Biblioteca - &Clear + Can login - Append SQL + Materialized - Append the SQL code at the very end of model definition. -Unchecking this will cause the SQL to be appended at the end of CREATE DATABASE command. + Member roles - Append at end of model definition. + Merges - Prepend SQL - + Name + Nome - Prepend at beginning of model definition. + Negator op. - <html><head/><body><p>Use custom commands with extreme caution because you can change the semantics of the entire model when running SQL validation or export processes. Additionally, depending on the amount of commands, those processes can have their performance sensibly degradated.</p></body></html> + Not null - Type: - Tipo: + Object type + - Generic INSERT + OID - Include serial columns + With OIDs - Exclude serial columns + Old version - Generic SELECT - + Operator + Operador - Table SELECT + Operator func. - Generic UPDATE + Output func. - Table UPDATE + Owner - Generic DELETE + Owner column - Table DELETE + Parents - - - DataManipulationForm - Data Manipulation + Password - &Close - &Fechar + Permissions + Permissões - <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in <span style=" font-weight:600;">{}</span>. To use <span style=" font-weight:600;">{</span> or <span style=" font-weight:600;">}</span> as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\{</span> or <span style=" font-weight:600;">\}</span>.</p></body></html> - + Precision + Precisão - Refresh listing - + Preferred + Preferido - Refresh + Range attributes - F5 + Receive func. - Save changes + Ref. roles - Save - Salvar - - - Ctrl+S + Replication - Copy the selection as CSV buffer + Restriction func. - Copy - Copiar - - - Ctrl+C + Return type - Export results to CSV file + Returns SETOF - Export - Exportar - - - Ctrl+X + Right type - Undo modifications + Rows amount - Undo - Desfazer + Schema + Esquema - Ctrl+Z + Security type - Add empty rows + Send func. - Add - Adicionar - - - Ins + Sort op. - Mark the selected rows to be deleted + Source type - Delete + Src. encoding - Del + State type - Duplicate the selected rows - + Storage + Armazenamento - Duplicate - + Superuser + Superusuário - Ctrl+D - + Tablespace + Espaço de Tabela - Filter the result set + Type mod. in func. - Table: - Tabela: - - - Schema: - Esquema: + Type mod. out func. + - in + Transition func. - Hide views + Trusted - Filter expression - + Type + Tipo - Order && Limit + Type attribute - results (Use <strong>0</strong> for no limit) + Types - Limit in: + Unlogged - Add Item - Adicionar Item + Validator func. + - Remove Item - Remover Item + Validity + Validade - Clear the order by columns list + Windows func. - Move selected item up + false - Move selected item down + true - ASC + Cache value - DESC + Cycle - Column: - Coluna: - - - <strong>WARNING: </strong> There are some changed rows waiting the commit! Do you really want to discard them and retrieve the data now? + Increment - Rows returned: <strong>%1</strong>&nbsp;&nbsp;&nbsp; + Max. value - <em>(Limit: <strong>%1</strong>)</em> + Min. value - none + Start value - No objects found + Last value - Found %1 object(s) - + Subtype + Subtipo - Views can't have their data handled through this grid, this way, all operations are disabled. + Op. class - The selected table doesn't owns a primary key! Updates and deletes will be performed by considering all columns as primary key. <strong>WARNING:</strong> those operations can affect more than one row. + Canonical func. - This row is marked to be %1 + Subtype diff func. - deleted + Deferrable - updated + For each row - inserted - + Firing + Disparo - [binary data] + On insert - <strong>WARNING:</strong> Once commited its not possible to undo the changes! Proceed with saving? + On delete - delete + On update - update + On truncate - insert - + Arguments + Argumentos - - - DatabaseExplorerWidget - Form - Formulário + Table + Tabela - Toggles the display of system objects. + Trigger func. - System - + Columns + Colunas - Toggles the display of extension objects + Condition - Extension + Deferment - Open the grid to visualize or edit data - + Event + Evento - Data &Grid + Execution mode - Alt+G + Commands - Open a new SQL execution pane + Position - ... + Comparison type - Ctrl+F6 + Ref. columns - Update the objects tree + Expressions - Ctrl+S + Fill factor - Drop this database + No inherit - Expands all items - Expandir todos os itens + Op. classes + - Collapses all items - Recolher todos os itens + Operators + Operadores - Filters the currently loaded items in the tree by using a pattern and matching their names. If <strong>By OID</strong> is checked the pattern is interpreted as an integer value that represents the object id (OID). <br><br/><strong>HINT:</strong> if you need to search the entire database use the full refresh (<strong>Ctrl+F5</strong>) prior the filtering. + Ref. table - Filter: - + Unique + Único - By OID + Predicate - Attribute - Atributo - - - Value + Collations - Show raw attributes + Inherited - (not found, OID: %1) + Snippets - -- Source code not generated! Hit F7 or middle-click the item to load it. -- + Drop object - Admin. roles + Drop cascade - Alignment + Truncate - Analyze func. + Trunc. cascade - Arg. count + Show data - Arg. default count + Reload properties - Arg. defaults - + Update + Atualizar - Arg. modes + Rename + Renomear + + + Source code - Arg. names + Quick refresh - Arg. types + Full refresh - Behavior type + Do you really want to drop the object <strong>%1</strong> <em>(%2)</em>? - By value - Por valor + Do you really want to <strong>cascade</strong> drop the object <strong>%1</strong> <em>(%2)</em>? This action will drop all the other objects that depends on it. + - Cast type + Do you really want to truncate the table <strong>%1</strong>? - Category + Do you really want to <strong>cascade</strong> truncate the table <strong>%1</strong>? This action will truncate all the tables that depends on it? - Collatable - Intercalável + Src. table: %1 +Src. column(s): %2 + - Collation - Intercalação + Ref. table: %1 +Ref. column(s): %2 + - Comment + -- Source code genaration for buil-in and base types currently unavailable -- - Commutator Op. + -- Source code unavailable for the object %1 (%2). -- - Configuration + Toggle the display of filter widget as well the system/extension objects. - Conn. limit + Sort items alphabetically. When unchecked, items are sorted by OID. - Constraint - Restrição + Sort alphabetically + - Create DB + Client encoding - Create role + Configuration file - Curr. version + Data directory - Default - Padrão + Dynamic library path + - Default value + Dynamic shared memory - Definition - Definição + Hba file + - Delimiter + Listen addresses - Dest. type + Max. connections - Dimension - Dimensão + Listen port + - Directory + Server encoding - Dest. encoding + SSL - Element - Elemento + SSL ca file + - Encoding + SSL cert file - Encrypted - Encriptado + SSL crl file + - Enumerations - Enumerações + SSL key file + - Exec. cost + Server version - Expression - Expressão + Ident file + - Op. family + Password encryption - Final func. + Connection ID - Function - Função + Server PID + - Func. type + Server protocol - Handler func. + Referrers - Handles type + Identity - Hashes + Command - Index type + USING expr. - Inherit + CHECK expr. - Ini. condition + Roles + Papéis + + + RLS enabled - Inline func. + RLS forced - Input func. + Show objects filter - Internal length + Show system objects - Interval type + Show extension objects - I/O cast + -- Source code unavailable for this kind of object -- - Join func. + Also restart sequences - Language - Linguagem + Warning + - LC COLLATE + You're running a demonstration version! The data manipulation feature is available only in the full version! - LC CTYPE + <strong>CAUTION:</strong> You are about to drop the entire database <strong>%1</strong>! All data will be completely wiped out. Do you really want to proceed? + + + DatabaseImportForm - Leak proof + Settings - Left type + Options - Length - Comprimento + Connection: + Conexão: - Library - Biblioteca + Resolve some of the object's dependencies by querying the catalog when a needed object does not exists on the loaded set. In some cases it's necessary to combine this option with others below. This option does not applies to database level objects like role, tablespace and language as well for data types, extensions. + - Can login + Automatically resolve dependencies - Materialized + Random colors will be assigned to imported relationships facilitating the identification of links between tables mainly in large models. - Member roles + Random colors for relationships - Merges + Enables the import of system built-in objects. It's recommend to select only those objects that are directly referenced by the ones to be imported. WARNING: Try to import a huge set of system objects can bloat the resultant model or even crash pgModeler due to memory/cpu overuse. - Name - Nome + Import system objects + - Negator op. + Enables the import of objects created by extensions. Generally there is no need to check this option but if there are objects in the database that directly references this category of objects this mode must be enabled. - Not null + Import extension objects - Object type + pgModeler ignores import errors and will try to create as many as possible objects. By checking this option the import operation will be not aborted but an incomplete model will be constructed. This option generates a log file on pgModeler's temp directory. - OID + Ignore import errors - With OIDs + All catalog queries as well the created objects' source code are printed to standard output (stdout). - Old version + Debug mode - Operator - Operador + Create all imported objects in the current working model instead of create a new one. + - Operator func. + Import objects to the working model - Output func. + Database + Banco de Dados + + + Filter: - Owner + Filter object by it's OID - Owner column + By OID - Parents + Select all objects - Password + ... - Permissions - Permissões + Clear object selection + - Precision - Precisão + Expands all items + Expandir todos os itens - Preferred - Preferido + Collapses all items + Recolher todos os itens - Range attributes + Output - Receive func. - + Progress label... + Rótulo de progresso... - Ref. roles - + Cancel + Cancelar - Replication + &Import - Restriction func. - + &Close + &Fechar - Return type + <strong>ATTENTION:</strong> You are about to import objects to the current working model! This action will cause irreversible changes to it even in case of critical errors during the process. Do you want to proceed? - Returns SETOF + Importing process aborted! - Right type + Importing process canceled by user! - Rows amount + Importing process sucessfuly ended! - Schema - Esquema + No databases found + - Security type + Found %1 database(s) - Send func. + Retrieving objects from database... - Sort op. + Retrieving cluster level objects... - Source type + Retrieving objects of schema `%1'... - Src. encoding + This is a PostgreSQL built-in data type and cannot be imported. - State type + This is a pgModeler's built-in object. It will be ignored if checked by user. - Storage - Armazenamento + Import database + - Superuser - Superusuário + Retrieving objects of `%1' (%2)... + + + + DatabaseImportHelper - Tablespace - Espaço de Tabela + Retrieving system objects... `%1' + - Type mod. in func. + Retrieving objects... `%1' - Type mod. out func. + Creating object `%1' (%2)... - Transition func. + Import failed to recreate some objects in `%1' tries. - Trusted + Creating permissions for object `%1' (%2)... - Type - Tipo + Creating columns permissions... + - Type attribute + Updating relationships of `%1' (%2)... - Types + Validating relationships... - Unlogged + The database import ended but some errors were generated and saved into the log file `%1'. This file will last until pgModeler quit. - Validator func. + Creating table inheritances... - Validity - Validade + Destroying unused detached columns... + - Windows func. + Assigning sequences to columns... - false + Creating object `%1' (%2), oid `%3'... - true - - - - Cache value + Trying to recreate object `%1' (%2), oid `%3'... + + + DatabaseModel - Cycle + The demonstration version can create only `%1' instances of each object type! You've reach this limit for the type: `%2' - Increment + Loading: `%1' (%2) - Max. value + Validating relationships... - Min. value + Saving object `%1' (%2) - Start value + Saving metadata of the object `%1' (%2) - Last value + Metadata file successfully saved! - Subtype - Subtipo + Process successfully ended but no metadata was saved! + - Op. class + Creating object `%1' (%2) - Canonical func. + Object `%1' (%2) already exists. Ignoring. - Subtype diff func. + Loading metadata for object `%1' (%2) - Deferrable + Object `%1' (%2) not found. Ignoring metadata. - For each row + Metadata file successfully loaded! - Firing - Disparo + Generating %1 code: `%2' (%3) + + + + DatabaseWidget - On insert - + Template DB: + DB Modelo: - On delete - + Model Author: + Autor do Modelo: - On update - + Encoding: + Codificação: - On truncate - + LC_COLLATE: + - Arguments - Argumentos + Connections: + Conexões: - Table - Tabela + LC_CTYPE: + - Trigger func. - + Default + Padrão - Columns - Colunas + Attributes + Atributos - Condition + Default Objects - Deferment - + Tablespace: + Esp. de Tabela: - Event - Evento + Schema: + Esquema: - Execution mode - + Collation: + Intercalação: - Commands + Owner: - Position + The fields <strong>LC_COLLATE</strong> and <strong>LC_CTYPE</strong> have pre-configured values based upon the running system. You can freely modify those values if you intend to export the model to another host. - Comparison type + Use the above fields to specify the default attributes assigned to new objects created on the database model. Leaving a field empty will cause PostgreSQL to use the default values when exporting the model. - Ref. columns - + Options: + Opções: - Expressions + Allow connections - Fill factor + Is template + + + DomainWidget - No inherit - + Default Value: + Valor Padrão: - Op. classes - + Name: + Nome: - Operators - Operadores + Attributes + Atributos - Ref. table + Not null - Unique - Único + Check constraints + - Predicate - + Expression: + Expressão: - Collations - + Name + Nome - Inherited - + Expression + Expressão + + + DonateWidget - Snippets - + Form + Formulário - Drop object + Donate to pgModeler - Drop cascade + Hide this widget - Truncate + ... - Trunc. cascade + <html><head/><body><p>pgModeler is brought to you thanks to a <span style=" font-style:italic;">great effort to create and distribute a quality product</span>. This project is reaching out levels of maturity never imagined. All this is the result of a joint work between its author and the <span style=" font-weight:600;">Open Source community</span>. <br/><br/>This software has a long way to go yet and with your help we'll keep maintaining the good job and bringing new improvements on each release. If you did like pgModeler and thinks it deserves a contribution please make a donation!</p></body></html> - Show data + I want to help! + + + ElementsWidget - Reload properties - + Form + Formulário - Update - Atualizar + Column: + Coluna: - Rename - Renomear + Expression: + Expressão: - Source code - + Collation: + Intercalação: - Quick refresh - + Operator Class: + Classe de Operadores: - Full refresh - + Operator: + Operador: - Do you really want to drop the object <strong>%1</strong> <em>(%2)</em>? - + Sorting: + Ordenação: - Do you really want to <strong>cascade</strong> drop the object <strong>%1</strong> <em>(%2)</em>? This action will drop all the other objects that depends on it. - + Ascending + Ascendente - Do you really want to truncate the table <strong>%1</strong>? - + Descending + Descendente - Do you really want to <strong>cascade</strong> truncate the table <strong>%1</strong>? This action will truncate all the tables that depends on it? - + Nulls first + Nulos primeiro - Src. table: %1 -Src. column(s): %2 - + Element + Elemento - Ref. table: %1 -Ref. column(s): %2 - + Type + Tipo - -- Source code genaration for buil-in and base types currently unavailable -- - + Operator Class + Classe de Operadores - -- Source code unavailable for the object %1 (%2). -- - + Sorting + Ordenação - - - DatabaseImportForm - Database Import - + Nulls First + Nulos Primeiro - Database import - + Collation + Intercalação - Settings - + Operator + Operador - Options - + Expression + Expressão - Connection: - Conexão: + Yes + Sim - Origin point: - + No + Não + + + EventTriggerWidget - Starting point where objects will be put. - + Event: + Evento: - Tables per row: - + Function: + Função: - Tables per row + Filter - Spacing: + Tag: - Schemas per row + Tag command + + + Exception - Spacing between objects - + Assignment of a pseudo-type to the type of the column! + Atribuição de um pseudo-tipo ao tipo da coluna! - Schemas per row: - + Assignment of a precision greater than the length of the type! + Atribuição de precisão maior do que o comprimento do tipo! - Resolve some of the object's dependencies by querying the catalog when a needed object does not exists on the loaded set. In some cases it's necessary to combine this option with others below. This option does not applies to database level objects like role, tablespace and language as well for data types, extensions. - + Assignment of an invalid precision to type time, timestamp or interval. The precision in this case must be equal to or less than 6! + Atribuição de precisão inválida a um tipo time, timestamp ou interval. A precisão neste caso deve ser igual ou inferior a 6! - Automatically resolve dependencies - - - - Random colors will be assigned to imported relationships facilitating the identification of links between tables mainly in large models. - - - - Random colors for relationships - - - - Enables the import of system built-in objects. It's recommend to select only those objects that are directly referenced by the ones to be imported. WARNING: Try to import a huge set of system objects can bloat the resultant model or even crash pgModeler due to memory/cpu overuse. - - - - Import system objects - - - - Enables the import of objects created by extensions. Generally there is no need to check this option but if there are objects in the database that directly references this category of objects this mode must be enabled. - - - - Import extension objects - - - - pgModeler ignores import errors and will try to create as many as possible objects. By checking this option the import operation will be not aborted but an incomplete model will be constructed. This option generates a log file on pgModeler's temp directory. - - - - Ignore import errors - - - - All catalog queries as well the created objects' source code are printed to standard output (stdout). - - - - Debug mode - - - - Create all imported objects in the current working model instead of create a new one. - - - - Import objects to the working model - - - - Database - Banco de Dados - - - Filter: - - - - Filter object by it's OID - - - - By OID - - - - Select all objects - - - - ... - - - - Clear object selection - - - - Expands all items - Expandir todos os itens - - - Collapses all items - Recolher todos os itens - - - Output - - - - Progress label... - Rótulo de progresso... - - - Cancel - Cancelar - - - &Import - - - - &Close - &Fechar - - - <strong>ATTENTION:</strong> You are about to import objects to the current working model! This action will cause irreversible changes to it even in case of critical errors during the process. Do you want to proceed? - - - - Importing process aborted! - - - - Importing process canceled by user! - - - - Importing process sucessfuly ended! - - - - No databases found - - - - Found %1 database(s) - - - - Retrieving objects from database... - - - - Retrieving cluster level objects... - - - - Retrieving objects of schema `%1'... - - - - Retrieving objects of table `%1'... - - - - This is a PostgreSQL built-in data type and cannot be imported. - - - - This is a pgModeler's built-in object. It will be ignored if checked by user. - - - - - DatabaseImportHelper - - Retrieving system objects... `%1' - - - - Retrieving objects... `%1' - - - - Creating object `%1' (%2)... - - - - Trying to recreate object `%1' (%2)... - - - - Import failed to recreate some objects in `%1' tries. - - - - Creating permissions for object `%1' (%2)... - - - - Creating columns permissions... - - - - Updating relationships of `%1' (%2)... - - - - Validating relationships... - - - - The database import ended but some errors were generated and saved into the log file `%1'. This file will last until pgModeler quit. - - - - Creating table inheritances... - - - - Destroying unused detached columns... - - - - Assigning sequences to columns... - - - - - DatabaseModel - - Loading object: %1 (%2) - Carregando objeto: %1 (%2) - - - Generating %1 of the object: %2 (%3) - Gerando %1 do objeto: %2 (%3) - - - The demonstration version can create only `%1' instances of each object type! You've reach this limit for the type: `%2' - - - - Loading: `%1' (%2) - - - - Validating relationships... - - - - Generating %1 of the object `%2' (%3) - - - - Saving object `%1' (%2) - - - - Saving metadata of the object `%1' (%2) - - - - Metadata file successfully saved! - - - - Process successfully ended but no metadata was saved! - - - - Creating object `%1' (%2) - - - - Object `%1' (%2) already exists. Ignoring. - - - - Loading metadata for object `%1' (%2) - - - - Object `%1' (%2) not found. Ignoring metadata. - - - - Metadata file successfully loaded! - - - - - DatabaseWidget - - Form - Formulário - - - Template DB: - DB Modelo: - - - Model Author: - Autor do Modelo: - - - Encoding: - Codificação: - - - LC_COLLATE: - - - - Connections: - Conexões: - - - LC_CTYPE: - - - - Default - Padrão - - - Attributes - Atributos - - - Default Objects - - - - Tablespace: - Esp. de Tabela: - - - Schema: - Esquema: - - - Collation: - Intercalação: - - - Owner: - - - - The fields <strong>LC_COLLATE</strong> and <strong>LC_CTYPE</strong> have pre-configured values based upon the running system. You can freely modify those values if you intend to export the model to another host. - - - - Use the above fields to specify the default attributes assigned to new objects created on the database model. Leaving a field empty will cause PostgreSQL to use the default values when exporting the model. - - - - - DomainWidget - - Form - Formulário - - - Default Value: - Valor Padrão: - - - Constraint - Restrição - - - Name: - Nome: - - - Not Null: - Não Nulo: - - - Check Expr.: - Expr.Checagem: - - - - DominioWidget - - Default Value: - Valor Padrão: - - - Constraint Name: - Nome da Restrição: - - - Check Expression: - Expressão de Checagem: - - - Not Null: - Não Nulo: - - - - DonateWidget - - Form - Formulário - - - Donate to pgModeler - - - - Hide this widget - - - - ... - - - - <html><head/><body><p>pgModeler is brought to you thanks to a <span style=" font-style:italic;">great effort to create and distribute a quality product</span>. This project is reaching out levels of maturity never imagined. All this is the result of a joint work between its author and the <span style=" font-weight:600;">Open Source community</span>. <br/><br/>This software has a long way to go yet and with your help we'll keep maintaining the good job and bringing new improvements on each release. If you did like pgModeler and thinks it deserves a contribution please make a donation!</p></body></html> - - - - I want to help! - - - - - ElementsWidget - - Form - Formulário - - - Column: - Coluna: - - - Expression: - Expressão: - - - Collation: - Intercalação: - - - Operator Class: - Classe de Operadores: - - - Operator: - Operador: - - - Sorting: - Ordenação: - - - Ascending - Ascendente - - - Descending - Descendente - - - Nulls first - Nulos primeiro - - - Element - Elemento - - - Type - Tipo - - - Operator Class - Classe de Operadores - - - Sorting - Ordenação - - - Nulls First - Nulos Primeiro - - - Collation - Intercalação - - - Operator - Operador - - - Expression - Expressão - - - Yes - Sim - - - No - Não - - - - EspacoTabelaWidget - - Directory: - Diretório: - - - - EventTriggerWidget - - Event: - Evento: - - - Function: - Função: - - - Filter - - - - Tag: - - - - Tag command - - - - - Excecao - - Insufficient memory space to allocate the object! - Espaço em memória insuficiente para alocar o objeto! - - - Assignment of a pseudo-type to the type of the column! - Atribuição de um pseudo-tipo ao tipo da coluna! - - - Zero length assignment! - Atribuição de comprimento igual a zero! - - - Assignment of a precision greater than the length of the type! - Atribuição de precisão maior do que o comprimento do tipo! - - - Assignment of an invalid precision to type time, timestamp or interval. The precision in this case must be equal to or less than 6! - Atribuição de precisão inválida a um tipo time, timestamp ou interval. A precisão neste caso deve ser igual ou inferior a 6! - - - Assignment of a not allocated column to object '%1' (%2)! - Atribuição de coluna não alocada ao objeto '%1' (%2)! - - - Reference to a column which index is out of the capacity of the column list! - Referência a uma coluna com índice fora da capacidade da lista de colunas! - - - Assignment of not allocated object! - Atribuição de um objeto não alocado! - - - Assignment of a not allocated schema to object '%1' (%2)! - Atribuição de um esquema não alocado ao objeto '%1' (%2)! - - - The object '%1' (%2) has inconsistent configuration (invalid SQL/XML definition)! - O objeto '%1' (%2) possui configuração inconsistente (definição SQL/XML inválida)! - - - The object '%1' (%2) already exists in the list of elements of the same type in the object '%3' (%4)! - O objeto '%1' (%2) já existente na lista de elementos desse mesmo tipo no objeto '%3' (%4)! - - - The object '%1' (%2) can't be assigned because there is already exists in the container object '%3'! - O objeto '%1' (%2) não pode ser atribuído pois já existe no container de objetos '%3'! - - - Assignment of object of an invalid type! - Atribuição de objeto de tipo inválido! - - - Removing an object of an invalid type! - Remoção de objeto de tipo inválido! - - - Obtaining an object of an invalid type! - Obtenção de um objeto com tipo inválido! - - - Assignment of empty name to table return type! - Atribuição de nome vazio ao tipo de retorno de tabela! - - - The insertion of the parameter '%1' will not be possible because there is another parameter with same name in the function '%2'! - A inserção do parâmetro '%1' não será possível pois já existe outro parâmetro com mesmo nome na função '%2'! - - - The insertion of the table return type '%1' will not be possible because there is another return type with the same name in the '%2'! - A inserção do tipo de retorno de tabela '%1' não será possível pois já existe outro tipo de retorno com mesmo nome na função '%2'! - - - Reference to a parameter which index is out of the parameter list capacity! - Referência a um parâmetro com índice fora da capacidade da lista de parâmetros! - - - Reference to an event which does not belongs to trigger! - Referência a um evento não pertecente ao gatilho! - - - The column '%1' can't be assigned to the trigger '%2' because does not belongs to the trigger parent table! - A coluna '%1' não pode ser atribuída ao gatilho '%2' pois a mesma não pertence à tabela pai do gatilho! - - - Assignment of a not allocated function to object '%1' (%2)! - Atribuição de função não alocada ao objeto '%1' (%2)! - - - Assignment of a function which return type is different from 'trigger'! - Atribuição de função com tipo de retorno diferente de 'trigger'! - - - Assignment of a function which parameter count is invalid to the object '%1' (%2)! - Atribuição de função com número de parâmetros inválido ao objeto '%1' (%2)! - - - Assignment of a function which language is invalid! - Atribuição de função com linguagem inválida! - - - Assignment of not allocated table to object '%1' (%2)! - Atribuição de tabela não alocada ao objeto '%1' (%2)! - - - Reference to an argument which index is out of argument list capacity! - Referência a um argumento com índice fora da capacidade da lista de argumentos! - - - Insertion of a column which name is already registered to another column of the object! - Inserção de coluna com nome já registrado em outra coluna do objeto! - - - Assignment of empty name to an object! - Atribuição de nome vazio a um objeto! - - - Assignment of invalid name to an object! - Atribuição de nome inválido a um objeto! - - - Assignment of schema object which type is invalid! - Atribuição de um objeto esquema com tipo inválido! - - - Assignment of tablespace object with invalid type! - Atribuição de objeto espaço de tabela com tipo inválido! - - - Assignment of tablespace to an invalid object! - Atribuição de um espaço de tabela a um objeto de tipo inválido! - - - Assignment of tablespace to a constraint which type is invalid! To belong to a tablespace the constraint must be a primary key or unique! - Atribuição de um objeto espaço de tabela a uma restrição de tipo inválido! A restrição deve ser uma chave-primária ou única para pode pertencer a um espaço de tabela! - - - Assignment of owner object which type is invalid! - Atribuição de um objeto papel com tipo inválido! - - - Assignment of owner to an invalid object! - Atribuição de um dono a um objeto de tipo inválido! - - - Reference to a function with invalid type! - Referência a uma função com tipo inválido! - - - Reference to an argument of the operator with invalid type! - Referência a um argumento do operador com tipo inválido! - - - Reference to an operator with invalid type! - Referência a um operador com tipo inválido! - - - Assigment of value to an invalid option type on role! - Atribuição de valor a uma opção de tipo inválido no papel! - - - Reference to an invalid role type! - Referência a um tipo de papel inválido! - - - The insertion of the role '%1' is not possible because this is already being referenced by role '%2'! - A inserção do papel '%1' não será possível pois este já está sendo referenciado pelo papel '%2'! - - - Reference redundance detected by having the role '%1' referencing the role '%2'! - Referência redundante detectada ao fazer com que o papel '%1' referencie o papel '%2'! - - - The role '%1' can not be listed as a member of itself! - O papel '%1' não pode ser relacionado com um membro dele mesmo! - - - Reference to a paper which index is out of paper list capacity! - Referência a um papel com índice fora da capacidade da lista de papéis! - - - Insertion of null command to the rule! - Inserção de comando nulo à regra! - - - Reference to a command which index is out of the command list capacity! - Referência a um comando com índice fora da capacidade da lista de comandos! - - - Is not possible to create a self generalization/dependecy relationship! The table can not inherit or copy their own attributes! - Não é possível criar um auto-relacionamento de generalização ou dependência! A tabela não pode herdar ou copiar seus próprios atributos! - - - Assignment of an object that already belongs to another table! - Atribuição de um objeto o qual já pertence a outra tabela! - - - Assignment of a schema to the sequence which differs from the schema of the owner table! - Atribuição de esquema à seqüência o qual difere do esquema da tabela possuidora! - - - Assignment of an invalid value to one of the sequence attributes! - Atribuição de valor inválido a um dos atributos da seqüência! - - - Assignment of a minimum value to the sequence which is greater than the maximum value! - Atribuição de valor mínimo da seqüência maior do que o valor máximo! - - - Assignment of a start value to the sequence which is extrapolating the range defined by minimum and maximum values​​! - Atribuição de valor de início da seqüência extrapolando o intervalo definido pelos valores mínimo e máximo! - - - Assignment of a null increment value to the sequence! - Atribuição de incremento de seqüência com valor nulo! - - - Assignment of null cache value to the sequence! - Atribuição de cache de seqüência com valor nulo! - - - Assignment of owner table which is not in the same schema as the sequence '%1'! - Atribuição de tabela possuidora a qual não faz parte do mesmo esquema da seqüência '%1'! - - - Assignment of owner table which does not belong to the same owner of the sequence '%1'! - Atribuição de tabela possuidora a qual não pertence ao mesmo dono da seqüência '%1'! - - - Assignment of a nonexistent owner column to the sequence '%1'! - Atribuição de coluna possuidora inexistente à seqüência '%1'! - - - Assignment of an owner column to the sequence '%1' that is not related to any table! - Atribuição de uma coluna possuidora a sequencia '%1' a qual não está relacionada a nenhuma tabela! - - - Reference to a label which index is out of labels list capacity! - Referência a um rótulo com índice fora da capacidade da lista de rótulos! - - - Allocation of object with invalid type! - Alocação de objeto com tipo inválido! - - - Assignment of a function with invalid return type to object '%1' (%2)! - Atribuição de função com tipo de retorno inválido ao objeto '%1' (%2)! - - - Assignment of a function with invalid parameter(s) type(s) to object '%1' (%2)! - Atribuição de função com tipo de parâmetro(s) inválido(s) ao objeto '%1' (%2)! - - - Assignment of not allocated language! - Atribuição de linguagem não alocada! - - - Assignment of language object which type is invalid! - Atribuição de linguagem com tipo inválido! - - - Reference to data type with an index outside the capacity of data types list! - Referência a tipo de dado com índice fora da capacidade da lista de tipos de dados! - - - Assignment of a null type to to object '%1' (%2)! - Atribuição de tipo nulo ao objeto '%1' (%2)! - - - Assignment of invalid type to the object! - Atribuição de um tipo inválido ao objeto! - - - Assignment of an empty directory to object '%1' (%2)! - Atribuição de um diretório vazio ao objeto: '%1' (%2)! - - - Obtaining types with invalid quantity! - Obtenção de tipos com quantidade inválida! - - - Insertion of item which already exists in the attributes list of the type! - Inserção de item já existente na lista de atibutos do tipo! - - - Insertion of invalid item in the attributes list of the type! - Inserção de item inválido na lista de atibutos do tipo! - - - Insertion of item which already exists in the enumarations list of the type! - Inserção de item já existente na lista de enumerações do tipo! - - - Insertion of invalid item in the enumerations list of the type! - Inserção de item inválido na lista de emumerações do tipo! - - - Reference to an attribute which index is out of the attributes list capacity! - Referência a um atributo com índice fora da capacidade da lista de atributos! - - - Reference to an enumeration which index is out of the enumerations list capacity! - Referência a uma enumeração com índice fora da capacidade da lista de enumerações! - - - Assignment of invalid configuration to the type! - Atribuição de configuração inválida ao tipo! - - - The data type '%1' can not be assigned because it already exists in the types list of the aggregate function '%2'! - O tipo de dado '%1' não pode ser atribuído pois o mesmo já existente na lista de tipos da função de agregação '%2'! - - - Assignment of an operator which input type count is invalid to aggregate function! - Atribuição de operador a uma função de agregação com quantidade de tipos de entrada inválida! - - - Assigment of an operator which types of arguments is invalid! - Atribuição de operador com argumentos de tipos inválidos! - - - Assignment of system reserved name to the object '%1' (%2)! - Atribuição de nome reservado pelo sistema ao objeto '%1' (%2)! - - - One function with invalid configuration is been used by the object '%1' (%2)! - Uma função de configuração inválida está sendo usada pelo objeto '%1' (%2)! - - - Assignment of invalid id to the user! - Atribuição de id de usuário inválido! - - - Assignment of an invalid strategy/support number to an operator class element! - Atribuição de valor inválido ao número de estratégia/suporte do elemento de classe de operadores! - - - Insertion of element which already exists in the element list! - Inserção de elemento já existente na lista de elementos! - - - Reference to an element which index is out of element list capacity! - Referência a um elemento com índice fora da capacidade da lista de elementos! - - - Reference to an object which index is out of object list capacity! - Referência a um objeto com índice fora da capacidade da lista de objetos! - - - Removal of an object not allocated! - Remoção de objeto não alocado! - - - The object '%1' (%2) can not be removed because it is being referenced by object '%3' (%4)! - O objeto '%1' (%2) não pode ser removido pois está sendo referenciado pelo objeto '%3' (%4)! - - - The object '%1' (%2) can not be removed because it is being referenced by object '%3' (%4) that belongs to '%5' (%6)! - O objeto '%1' (%2) não pode ser removido pois está sendo referenciado pelo objeto '%3' (%4) pertecente à '%5' (%6)! - - - Operation with object(s) which type(s) is invalid! - Operação com objeto(s) de tipo(s) inválido(s)! - - - Reference to object with invalid type! - Referência a um objeto com tipo inválido! - - - Operation with object not allocated! - Operação com objeto não alocado! - - - The creation of the relationship '%1' between the table '%2' and '%3' can not be done because one does not have a primary key. If the relationship is of the type n-n both tables must have primary keys! - A criação do relacionamento '%1' entre as tabela '%2' e '%3' não pode ser feito pois uma delas não possui uma chave primária. Caso o relacionamento seja do tipo n-n ambas as tabelas devem possuir chaves primárias! - - - The relationship of the type 1-1 where both tables are mandatory participation is not implemented because it requires fusion between the tables that breaks the modeling done by the user! - O relacionamento do tipo 1-1 onde ambas as tabelas são de participação obrigatória não é implementado por necessitar de fusão entre tabelas o que quebra a modelagem feita pelo usuário! - - - Assignment of an invalid expression to the object! - Atribuição de expressão inválida ao objeto! - - - Assignment of a primary key to a table which already has one! - Atribuição de chave primária à uma tabela a qual já possui uma! - - - Identifier relationship can not be created for a self relationship, relationships of the type n-n, dependency or generalization! - Relacionamento identificador não pode ser criado para um autorelacionamentos, relacionamentos do tipo n-n, dependência ou generalização! - - - Unable to create a dependency relationship because the column '%1' in table '%2' already exists in table '%3'! - Impossível criar o relacionamento de dependência pois a coluna '%1' da tabela '%2' já existe na tabela '%3'! - - - Unable to create the generalization relationship because the column '%1' in table '%2' can not be merged with the column '%3' of table '%4' because they have incompatible types! - Impossível criar o relacionamento de generalização pois a coluna '%1' da tabela '%2' não pode ser fundida com a coluna '%3' da tabela '%4' por serem de tipos incompatíveis! - - - An attribute can not be added to a dependence or generalization relationship! - Um atributo não pode ser adicionado a um relacionamento de generalização ou dependência! - - - A foreign key can not be added to a relationship because is created automatically when this is connected! - Uma chave estrangeira não pode ser adicionado a um relacionamento pois esta é criada automaticamente no momento da ligação do mesmo! - - - The object '%1' (%2) is referencing the object '%3' (%4) which was not found in the list of objects of the same type in the model! - O objeto '%1' (%2) está referenciando o objeto '%3' (%4) o qual não foi encontrado na lista de objetos de mesmo tipo no modelo! - - - Reference to an user-defined data type that not exists in the model! - Referência a tipo de dado definido pelo usuário o qual não existe no modelo! - - - Assignment of invalid maximum size to operation list! - Atribuição de tamanho máximo inválido à lista de operações! - - - Unable to write the file %1! Make sure the directory exists, or if the user has access permissions on it! - Não foi possível salvar o arquivo %1! Certifique-se de que o diretório existe ou se o usuário tem permissão de acesso ao mesmo! - - - Unable to write the model in the file %1 due to one or more errors in the definition generation process! - Não foi possível gravar o modelo no arquivo %1 devido a um ou mais erros no processo de geração da definição do mesmo! - - - There is already a relationship between '%1' (%2) and '%3' (%4) in the model! - Já existe um relacionamento entre '%1' (%2) and '%3' (%4) no modelo! - - - The configuration of the relationship '%1' generates a redundancy between the relationships '%2'. Redundancy on identifier or generalization/dependency relationships are not accepted since they result in incorrect column spreading making the model inconsistent! - A configuração do relacionamento '%1' gera uma redundância entre os relacionamentos '%2'. Redundância de relacionamentos identificadores ou de generalização/dependência não são aceitos pois resultam em propagação incorreta de colunas tornando o modelo inconsiste! - - - One or more objects were invalidated and automatically removed because they were referencing table columns which were included through relationships and which no longer exists due to disconnection of relationships or exclusion of such generated columns! - Um ou mais objetos foram invalidados e automaticamente removidos pois os mesmos referenciavam colunas de tabelas as quais foram incluídas através de relacionamentos e que deixaram de existir devido a desconexão ou exclusão dos relacionamentos geradores de tais colunas! - - - The primary key '%1' can only be allocated if declared within a block of code that defines a table or relationship! - A chave-primária '%1' só pode ser alocada caso a mesma esteja declarada dentro de um bloco de código que define uma tabela ou relacionamento! - - - Reference to an invalid privilege type! - Referência a um tipo de privilégio inválido! - - - Insertion of an role which already exists in the role list of the permission! - Inserção de um papel já existente na lista de papéis da permissão! - - - Assignment of privilege incompatible with the type of object referenced by permission! - Atribuição de privilégio incompatível com o tipo do objeto referenciado pela permissão! - - - There is already a permission on object '%1' (%2) which has one or more equal roles from those present on permission to be assigned to the object! - Já existe uma permissão sobre o objeto '%1' (%2) a qual possui um ou mais papéis iguais aos presentes na permissão a ser atribuída ao objeto! - - - A permission is referencing the object '%1' (%2) which was not found in the model! - Uma permissão está referenciando o objeto '%1' (%2) o qual não foi encontrado no modelo! - - - The object '%1' (%2) can not be created by not being assigned to any schema! - O objeto '%1' (%2) não pode ser criado por não estar atribuído a nenhum esquema! - - - The tablespace '%1' can not be inserted into the model because it points to the same directory as the tablespace '%2'! - O espaço de tabela '%1' não pode ser inserido no modelo pois o mesmo aponta para o mesmo diretório que o espaço de tabela '%2'! - - - It is not possible to create arrays of domains or sequences (dimension >= 1)! PostgreSQL does not yet implement this feature! - Não é possível criar arrays de domínios ou sequências (dimensão >= 1)! O PostgreSQL ainda não implementa esta funcionalidade! - - - The function '%1' can not get a source code as a definition because its language is set to C. Use the attributes symbol and dynamic library instead! - A função '%1' não pode receber um código-fonte como definição pois sua linguagem está definida como C. Os atributos símbolo e biblioteca dinâmica é que devem ser utilizados! - - - The function '%1' can have the attributes symbol and dynamic library configured only if the language is set to C. For all other cases you must specify a source code that defines it in the DBMS! - A função '%1' só pode ter os atributos de símbolo e biblioteca configurados caso sua linguagem esteja definida como C. Para os demais casos é necessário especificar um código-fonte que a define o SGBD! - - - The operator '%1' can not be assigned as a comutator of operator '%2' because it has incompatible settings! - O operador '%1' não pode ser atribuído como comutador do operador '%2' pois possui configuração incompatível! - - - The operator '%1' can not be assigned as negator of operator '%2' because it has incompatible settings! - O operador '%1' não pode ser atribuído como negador do operador '%2' pois possui configuração incompatível! - - - The type '%1' can not self refer in the attributes 'element' or 'copy type' or be used as a data type of an attribute in the configuration of a composite type! - O tipo '%1' não pode se referenciar nos atributos 'elemento' ou 'tipo cópia' ou ser usado como tipo de dado de um atributo na configuração de tipo composto! - - - Assignment of invalid element to type '%1'! - Atribuição de elemento inválido ao tipo '%1'! - - - Assignment of invalid alignment to type '%1'! - Atribuição de alinhamento inválido ao tipo '%1'! - - - Assignment of invalid name to the table generated from N-N relationship! - Atribuição de nome inválido à tabela gerada por relacionamento N-N! - - - The relationship '%1' can not make use of the special primary key. Only generalization/dependency relationships have access to this resource! - O relacionamento '%1' não pode fazer uso da chave-primária especial. Apenas relacionamentos de generalização/dependência têm acesso a este recurso! - - - Assignment of invalid suffix to the relationship '%1'! - Atribuição de sufixo inválido ao relacionamento '%1'! - - - The object '%1' (%2) can not be edited or deleted because it was automatically included through a relationship! To manipulate the object is necessary to make it from the edit form of the relationship that holds it. - O objeto '%1' (%2) não pode ser editado ou excluído por ter sido incluído automaticamente através de relacionamento! Para manipular o objeto é necessário fazê-lo a partir do formulário de edição do relacionamento que o detém. - - - The object '%1' (%2) can not be deleted because it is protected! - O objeto '%1' (%2) não pode ser excluído por estar protegido! - - - The group '%1' has already been declared earlier! - O grupo '%1' já foi declarado anteriormente! - - - The group '%1' can not be built in the groups declaration block ('%2')! - O grupo '%1' não pode ser construído no bloco de declaração de grupos ('%2')! - - - The group '%1' was built but not declared in the groups declaration block ('%2')! - O grupo '%1' foi construído porém não declarado no bloco de declaração de grupos ('%2')! - - - The group '%1' can not be built without possessing child elements! - O grupo '%1' não pode ser construído sem possuir elementos filhos! - - - The group '%1' can not be built once more because this was done in previous blocks! - O grupo '%1' não pode ser construído novamente pois já foi construído em blocos anteriores! - - - The group '%1' has been declared but not built! - O grupo '%1' foi declarado porém não construído! - - - Reference to a column of objects table with invalid index! - Referência a uma coluna da tabela de objetos com índice inválido! - - - Reference to a row of objects table with invalid index! - Referência a uma linha da tabela de objetos com índice inválido! - - - The schema public and the languages plpgsql, c and sql can not be manipulated because they are reserved to PostgreSQL! They are present in the model database only as a reference! - O esquema 'public' e as linguagens 'plpgsql', 'c' e 'sql' não podem ser manipuladas por serem reservados ao PostgreSQL! Os mesmos estão presentes no modelo de banco de dados apenas como referência! - - - The new configuration function invalidates the object '%1' (%2)! In this case it is needed to undo the relationship between the affected object and function so that the new configuration of the latter to take effect! - A nova configuração da função invalida o objeto '%1' (%2) o qual a referencia! Neste caso é necessário desfazer a relação entre o objeto afetado e a função para que a nova configuração desta última seja efetivada! - - - A vision reference must have at least one SQL application : SELECT, FROM, FROM-WHERE or After WHERE! - Uma referência de visão deve possuir pelo menos uma aplicação SQL: SELECT-FROM, FROM-WHERE ou Após WHERE! - - - Constraints like primary key, foreign key or unique must have at least one column related to them! For foreign keys must be selected, in addition, the referenced columns! - Restrições do tipo chave-primária, chave-estrangeira ou única devem possuir pelo menos uma coluna relacionada às mesmas! Para chaves-estrangeira devem ser selecionadas, adicionalmente, as colunas referenciadas! - - - Unable to load one or more configuration files! Please check if files exists in the configuration folder and if they are not corrupted to preventing this error to occur again on the next startup! - Não foi possível carregar um ou mais arquivos de configuração! Por favor, cheque se os arquivos existem na pasta de configurações e se o mesmos não estão corrompidos para que este erro não se repita na próxima inicialização! - - - Could not find the default settings file '%1'! To restore default settings check the existence of the file and try again! - Não foi possível encontrar o arquivo de configurações padrão '%1'! Para restaurar as configurações padrão cheque a existência do referido arquivo e tente novamente! - - - The export process failed due to an error triggered by the PostgreSQL server in an attempt to execute a SQL command. For more details about the error check the exception stack! - -** Executed SQL command: ** - -%1 - O processo de exportação falhou devido a um erro disparado pelo servidor PostgreSQL na tentativa de execução de um comando SQL. Para obter mais detalhes sobre erro cheque a pilha de exceções! - -** Comando SQL executado: ** - -%1 - - - Could not load the plugin '%1' from the library '%2'! Message returned by plugin manager: '%3' - Não foi possível carregar o plugin '%1' a partir da biblioteca '%2'! Mensagem retornada pelo gerenciador de plugins: '%3' - - - One or more plugins were not activated due to errors during the loading process! Check the exception stack for more details. - Um ou mais plugins não foram ativados devido a erros no processo de carregamento! Verifique a pilha de exceções para mais detalhes. - - - Invalid syntax in file %1, line %2, column %3! - Sintaxe inválida no arquivo %1, linha %2, coluna %3! - - - Invalid conditional instruction '%1' on file %2, line %3, column %4! - Instrução condicional '%1' inválida no arquivo %2, linha %3, coluna %4! - - - Unknown attribute '%1' in file %2, line %3, column %4! - Atributo '%1' desconhecido no arquivo %2, linha %3, coluna %4! - - - Invalid metacharacter '%1' in file %2, line %3, column %4! - Metacaractere '%1' inválido no arquivo %2, linha %3, coluna %4! - - - Attribute '%1' with an undefined value in file %2, line %3, column %4! - Atributo '%1' com valor indefinido no arquivo %2, linha %3, coluna %4! - - - Assignment of empty XML buffer to parser! - Atribuição de buffer de código XML vazio ao parser! - - - Could not access the file or directory %1! Make sure that it exists or if the user has access permissions on it! - Não foi possível acessar o arquivo ou diretório %1! Certifique-se de que o mesmo existe e o usuário possui permissões de acesso a ele! - - - Assignment of empty DTD file name! - Atribuição de nome de arquivo DTD vazio! - - - Assignment of empty name to the DTD declaration! - Atribuição de nome vazio à declaração DTD! - - - Error while interpreting XML buffer at line %1 column %2. -Message generated by the parser: '%3'. %4 - Erro ao interpretar buffer XML na linha %1 coluna %2. - Mensagem gerada pelo parser: '%3'. %4 - - - Operation on unallocated element tree! It is necessary to load the XML parser buffer and interpret it so that the tree is generated! - Operação sobre árvore de elementos não alocada! É necessário carregar o buffer XML do parser e interpretá-lo para que a árvore seja gerada! - - - Could not load file %1. The same appears to be inconsistent or one of its dependencies (DTD files) has errors or is missing! - Não foi possível carregar o arquivo %1. O mesmo parece estar inconsistente ou uma de suas dependências (arquivos DTD) possui erros ou está ausente! - - - Operation with unallocated tree element! - Operação com elemento de árvore de elementos não alocado! - - - Operation with element which does not exists in the element tree currently loaded! - Operação com elemento o qual não faz parte da árvore de elementos carregada atualmente! - - - Assignment of a value to an invalid connection parameter! - Atribuição de valor a um parâmetro de conexão inválido! - - - Operation on connection not established! - Operação sobre conexão não estabelecida! - - - Attempt to connect without define configuration parameters! - Tentativa de conexão sem parâmetros de configuração definidos! - - - Could not connect to the database. -Message returned: '%1' - Não foi possível estabelecer conexão com o banco de dados. -Mensagem retornada: '%1' - - - Assignment of not allocated SQL command result! - Atribuição de resultado de comando SQL não alocado! - - - Unable to allocate the result of the SQL command because the response from the DBMS was not understood by the client! - Não foi possível alocar o resultado do comando SQL pois a resposta do SGBD não foi compreendida pelo cliente! - - - Unable to allocate command result for the SQL because the server has generated a fatal error! -Message returned by the DBMS: %1 - Não foi possível alocar o resultado do comando SQL pois o servidor gerou um erro fatal! -Mensagem retornada pelo SGBD: %1 - - - Unable to allocate the result of the SQL command because the command passed was an empty SQL! - Não foi possível alocar o resultado do comando SQL pois o comando passado foi uma SQL vazia! - - - Reference to a column of tuple with invalid index! - Referência à uma coluna da tupla com índice inválido! - - - Reference to a column of tuple with invalid name! - Referência à uma coluna da tupla com nome inválido! - - - Reference to a tuple with index invalid or the result is empty (no tuples)! - Referência à uma tupla com índice inválido ou o resultado está vazio (sem tuplas)! - - - Could not execute the SQL command. - Message returned: %1 - Não foi possível executar o comando SQL. - Mensagem retornada: %1 - - - - Exception - - Insufficient memory space to allocate the object! - Espaço em memória insuficiente para alocar o objeto! - - - Assignment of a pseudo-type to the type of the column! - Atribuição de um pseudo-tipo ao tipo da coluna! - - - Zero length assignment! - Atribuição de comprimento igual a zero! - - - Assignment of a precision greater than the length of the type! - Atribuição de precisão maior do que o comprimento do tipo! - - - Assignment of an invalid precision to type time, timestamp or interval. The precision in this case must be equal to or less than 6! - Atribuição de precisão inválida a um tipo time, timestamp ou interval. A precisão neste caso deve ser igual ou inferior a 6! - - - Assignment of a not allocated column to object '%1' (%2)! - Atribuição de coluna não alocada ao objeto '%1' (%2)! - - - Reference to a column which index is out of the capacity of the column list! - Referência a uma coluna com índice fora da capacidade da lista de colunas! - - - Assignment of not allocated object! - Atribuição de um objeto não alocado! - - - Assignment of a not allocated schema to object '%1' (%2)! - Atribuição de um esquema não alocado ao objeto '%1' (%2)! - - - The object '%1' (%2) has inconsistent configuration (invalid SQL/XML definition)! - O objeto '%1' (%2) possui configuração inconsistente (definição SQL/XML inválida)! - - - The object '%1' (%2) already exists in the list of elements of the same type in the object '%3' (%4)! - O objeto '%1' (%2) já existente na lista de elementos desse mesmo tipo no objeto '%3' (%4)! - - - The object '%1' (%2) can't be assigned because there is already exists in the container object '%3'! - O objeto '%1' (%2) não pode ser atribuído pois já existe no container de objetos '%3'! - - - Removing an object of an invalid type! - Remoção de objeto de tipo inválido! - - - Obtaining an object of an invalid type! - Obtenção de um objeto com tipo inválido! - - - Assignment of empty name to table return type! - Atribuição de nome vazio ao tipo de retorno de tabela! - - - The insertion of the parameter '%1' will not be possible because there is another parameter with same name in the function '%2'! - A inserção do parâmetro '%1' não será possível pois já existe outro parâmetro com mesmo nome na função '%2'! - - - The insertion of the table return type '%1' will not be possible because there is another return type with the same name in the '%2'! - A inserção do tipo de retorno de tabela '%1' não será possível pois já existe outro tipo de retorno com mesmo nome na função '%2'! - - - Reference to an event which does not belongs to trigger! - Referência a um evento não pertecente ao gatilho! - - - Assignment of a not allocated function to object '%1' (%2)! - Atribuição de função não alocada ao objeto '%1' (%2)! - - - Assignment of a function which return type is different from 'trigger'! - Atribuição de função com tipo de retorno diferente de 'trigger'! - - - Assignment of a function which parameter count is invalid to the object '%1' (%2)! - Atribuição de função com número de parâmetros inválido ao objeto '%1' (%2)! - - - Assignment of a function which language is invalid! - Atribuição de função com linguagem inválida! - - - Assignment of not allocated table to object '%1' (%2)! - Atribuição de tabela não alocada ao objeto '%1' (%2)! - - - Insertion of a column which name is already registered to another column of the object! - Inserção de coluna com nome já registrado em outra coluna do objeto! - - - Assignment of empty name to an object! - Atribuição de nome vazio a um objeto! - - - Assignment of invalid name to an object! - Atribuição de nome inválido a um objeto! - - - Assignment of schema object which type is invalid! - Atribuição de um objeto esquema com tipo inválido! - - - Assignment of tablespace object with invalid type! - Atribuição de objeto espaço de tabela com tipo inválido! - - - Assignment of tablespace to an invalid object! - Atribuição de um espaço de tabela a um objeto de tipo inválido! - - - Assignment of tablespace to a constraint which type is invalid! To belong to a tablespace the constraint must be a primary key or unique! - Atribuição de um objeto espaço de tabela a uma restrição de tipo inválido! A restrição deve ser uma chave-primária ou única para pode pertencer a um espaço de tabela! - - - Assignment of owner object which type is invalid! - Atribuição de um objeto papel com tipo inválido! - - - Assignment of owner to an invalid object! - Atribuição de um dono a um objeto de tipo inválido! - - - Reference to a function with invalid type! - Referência a uma função com tipo inválido! - - - Reference to an argument of the operator with invalid type! - Referência a um argumento do operador com tipo inválido! - - - Reference to an operator with invalid type! - Referência a um operador com tipo inválido! - - - Reference to an invalid role type! - Referência a um tipo de papel inválido! - - - The insertion of the role '%1' is not possible because this is already being referenced by role '%2'! - A inserção do papel '%1' não será possível pois este já está sendo referenciado pelo papel '%2'! - - - The role '%1' can not be listed as a member of itself! - O papel '%1' não pode ser relacionado com um membro dele mesmo! - - - Assignment of an object that already belongs to another table! - Atribuição de um objeto o qual já pertence a outra tabela! - - - Assignment of a schema to the sequence which differs from the schema of the owner table! - Atribuição de esquema à seqüência o qual difere do esquema da tabela possuidora! - - - Assignment of an invalid value to one of the sequence attributes! - Atribuição de valor inválido a um dos atributos da seqüência! - - - Assignment of a minimum value to the sequence which is greater than the maximum value! - Atribuição de valor mínimo da seqüência maior do que o valor máximo! - - - Assignment of a null increment value to the sequence! - Atribuição de incremento de seqüência com valor nulo! - - - Assignment of null cache value to the sequence! - Atribuição de cache de seqüência com valor nulo! - - - Assignment of owner table which is not in the same schema as the sequence '%1'! - Atribuição de tabela possuidora a qual não faz parte do mesmo esquema da seqüência '%1'! - - - Assignment of owner table which does not belong to the same owner of the sequence '%1'! - Atribuição de tabela possuidora a qual não pertence ao mesmo dono da seqüência '%1'! - - - Assignment of a nonexistent owner column to the sequence '%1'! - Atribuição de coluna possuidora inexistente à seqüência '%1'! - - - Assignment of an owner column to the sequence '%1' that is not related to any table! - Atribuição de uma coluna possuidora a sequencia '%1' a qual não está relacionada a nenhuma tabela! - - - Allocation of object with invalid type! - Alocação de objeto com tipo inválido! - - - Assignment of a function with invalid return type to object '%1' (%2)! - Atribuição de função com tipo de retorno inválido ao objeto '%1' (%2)! - - - Assignment of a function with invalid parameter(s) type(s) to object '%1' (%2)! - Atribuição de função com tipo de parâmetro(s) inválido(s) ao objeto '%1' (%2)! - - - Assignment of not allocated language! - Atribuição de linguagem não alocada! - - - Assignment of language object which type is invalid! - Atribuição de linguagem com tipo inválido! - - - Reference to data type with an index outside the capacity of data types list! - Referência a tipo de dado com índice fora da capacidade da lista de tipos de dados! - - - Assignment of a null type to to object '%1' (%2)! - Atribuição de tipo nulo ao objeto '%1' (%2)! - - - Assignment of invalid type to the object! - Atribuição de um tipo inválido ao objeto! - - - Assignment of an empty directory to object '%1' (%2)! - Atribuição de um diretório vazio ao objeto: '%1' (%2)! - - - Obtaining types with invalid quantity! - Obtenção de tipos com quantidade inválida! - - - Insertion of item which already exists in the attributes list of the type! - Inserção de item já existente na lista de atibutos do tipo! - - - Insertion of invalid item in the attributes list of the type! - Inserção de item inválido na lista de atibutos do tipo! - - - Insertion of item which already exists in the enumarations list of the type! - Inserção de item já existente na lista de enumerações do tipo! - - - Insertion of invalid item in the enumerations list of the type! - Inserção de item inválido na lista de emumerações do tipo! - - - Assignment of invalid configuration to the type! - Atribuição de configuração inválida ao tipo! - - - The data type '%1' can not be assigned because it already exists in the types list of the aggregate function '%2'! - O tipo de dado '%1' não pode ser atribuído pois o mesmo já existente na lista de tipos da função de agregação '%2'! - - - Assignment of system reserved name to the object '%1' (%2)! - Atribuição de nome reservado pelo sistema ao objeto '%1' (%2)! - - - One function with invalid configuration is been used by the object '%1' (%2)! - Uma função de configuração inválida está sendo usada pelo objeto '%1' (%2)! - - - Assignment of invalid id to the user! - Atribuição de id de usuário inválido! - - - Assignment of an invalid strategy/support number to an operator class element! - Atribuição de valor inválido ao número de estratégia/suporte do elemento de classe de operadores! - - - Insertion of element which already exists in the element list! - Inserção de elemento já existente na lista de elementos! - - - Removal of an object not allocated! - Remoção de objeto não alocado! - - - The object '%1' (%2) can not be removed because it is being referenced by object '%3' (%4)! - O objeto '%1' (%2) não pode ser removido pois está sendo referenciado pelo objeto '%3' (%4)! - - - The object '%1' (%2) can not be removed because it is being referenced by object '%3' (%4) that belongs to '%5' (%6)! - O objeto '%1' (%2) não pode ser removido pois está sendo referenciado pelo objeto '%3' (%4) pertecente à '%5' (%6)! - - - Operation with object(s) which type(s) is invalid! - Operação com objeto(s) de tipo(s) inválido(s)! - - - Reference to object with invalid type! - Referência a um objeto com tipo inválido! - - - Operation with object not allocated! - Operação com objeto não alocado! - - - The creation of the relationship '%1' between the table '%2' and '%3' can not be done because one does not have a primary key. If the relationship is of the type n-n both tables must have primary keys! - A criação do relacionamento '%1' entre as tabela '%2' e '%3' não pode ser feito pois uma delas não possui uma chave primária. Caso o relacionamento seja do tipo n-n ambas as tabelas devem possuir chaves primárias! - - - The relationship of the type 1-1 where both tables are mandatory participation is not implemented because it requires fusion between the tables that breaks the modeling done by the user! - O relacionamento do tipo 1-1 onde ambas as tabelas são de participação obrigatória não é implementado por necessitar de fusão entre tabelas o que quebra a modelagem feita pelo usuário! - - - Assignment of an invalid expression to the object! - Atribuição de expressão inválida ao objeto! - - - Assignment of a primary key to a table which already has one! - Atribuição de chave primária à uma tabela a qual já possui uma! - - - Unable to create the generalization relationship because the column '%1' in table '%2' can not be merged with the column '%3' of table '%4' because they have incompatible types! - Impossível criar o relacionamento de generalização pois a coluna '%1' da tabela '%2' não pode ser fundida com a coluna '%3' da tabela '%4' por serem de tipos incompatíveis! - - - A foreign key can not be added to a relationship because is created automatically when this is connected! - Uma chave estrangeira não pode ser adicionado a um relacionamento pois esta é criada automaticamente no momento da ligação do mesmo! - - - The object '%1' (%2) is referencing the object '%3' (%4) which was not found in the list of objects of the same type in the model! - O objeto '%1' (%2) está referenciando o objeto '%3' (%4) o qual não foi encontrado na lista de objetos de mesmo tipo no modelo! - - - Reference to an user-defined data type that not exists in the model! - Referência a tipo de dado definido pelo usuário o qual não existe no modelo! - - - Assignment of invalid maximum size to operation list! - Atribuição de tamanho máximo inválido à lista de operações! - - - Unable to write the file %1! Make sure the directory exists, or if the user has access permissions on it! - Não foi possível salvar o arquivo %1! Certifique-se de que o diretório existe ou se o usuário tem permissão de acesso ao mesmo! - - - Unable to write the model in the file %1 due to one or more errors in the definition generation process! - Não foi possível gravar o modelo no arquivo %1 devido a um ou mais erros no processo de geração da definição do mesmo! - - - There is already a relationship between '%1' (%2) and '%3' (%4) in the model! - Já existe um relacionamento entre '%1' (%2) and '%3' (%4) no modelo! - - - One or more objects were invalidated and automatically removed because they were referencing table columns which were included through relationships and which no longer exists due to disconnection of relationships or exclusion of such generated columns! - Um ou mais objetos foram invalidados e automaticamente removidos pois os mesmos referenciavam colunas de tabelas as quais foram incluídas através de relacionamentos e que deixaram de existir devido a desconexão ou exclusão dos relacionamentos geradores de tais colunas! - - - The primary key '%1' can only be allocated if declared within a block of code that defines a table or relationship! - A chave-primária '%1' só pode ser alocada caso a mesma esteja declarada dentro de um bloco de código que define uma tabela ou relacionamento! - - - Reference to an invalid privilege type! - Referência a um tipo de privilégio inválido! - - - Assignment of privilege incompatible with the type of object referenced by permission! - Atribuição de privilégio incompatível com o tipo do objeto referenciado pela permissão! - - - There is already a permission on object '%1' (%2) which has one or more equal roles from those present on permission to be assigned to the object! - Já existe uma permissão sobre o objeto '%1' (%2) a qual possui um ou mais papéis iguais aos presentes na permissão a ser atribuída ao objeto! - - - A permission is referencing the object '%1' (%2) which was not found in the model! - Uma permissão está referenciando o objeto '%1' (%2) o qual não foi encontrado no modelo! - - - The tablespace '%1' can not be inserted into the model because it points to the same directory as the tablespace '%2'! - O espaço de tabela '%1' não pode ser inserido no modelo pois o mesmo aponta para o mesmo diretório que o espaço de tabela '%2'! - - - It is not possible to create arrays of domains or sequences (dimension >= 1)! PostgreSQL does not yet implement this feature! - Não é possível criar arrays de domínios ou sequências (dimensão >= 1)! O PostgreSQL ainda não implementa esta funcionalidade! - - - The function '%1' can not get a source code as a definition because its language is set to C. Use the attributes symbol and dynamic library instead! - A função '%1' não pode receber um código-fonte como definição pois sua linguagem está definida como C. Os atributos símbolo e biblioteca dinâmica é que devem ser utilizados! - - - The function '%1' can have the attributes symbol and dynamic library configured only if the language is set to C. For all other cases you must specify a source code that defines it in the DBMS! - A função '%1' só pode ter os atributos de símbolo e biblioteca configurados caso sua linguagem esteja definida como C. Para os demais casos é necessário especificar um código-fonte que a define o SGBD! - - - The operator '%1' can not be assigned as a comutator of operator '%2' because it has incompatible settings! - O operador '%1' não pode ser atribuído como comutador do operador '%2' pois possui configuração incompatível! - - - The operator '%1' can not be assigned as negator of operator '%2' because it has incompatible settings! - O operador '%1' não pode ser atribuído como negador do operador '%2' pois possui configuração incompatível! - - - The type '%1' can not self refer in the attributes 'element' or 'copy type' or be used as a data type of an attribute in the configuration of a composite type! - O tipo '%1' não pode se referenciar nos atributos 'elemento' ou 'tipo cópia' ou ser usado como tipo de dado de um atributo na configuração de tipo composto! - - - Assignment of invalid element to type '%1'! - Atribuição de elemento inválido ao tipo '%1'! - - - Assignment of invalid alignment to type '%1'! - Atribuição de alinhamento inválido ao tipo '%1'! - - - Assignment of invalid name to the table generated from N-N relationship! - Atribuição de nome inválido à tabela gerada por relacionamento N-N! - - - Assignment of invalid suffix to the relationship '%1'! - Atribuição de sufixo inválido ao relacionamento '%1'! - - - The object '%1' (%2) can not be edited or deleted because it was automatically included through a relationship! To manipulate the object is necessary to make it from the edit form of the relationship that holds it. - O objeto '%1' (%2) não pode ser editado ou excluído por ter sido incluído automaticamente através de relacionamento! Para manipular o objeto é necessário fazê-lo a partir do formulário de edição do relacionamento que o detém. - - - The object '%1' (%2) can not be deleted because it is protected! - O objeto '%1' (%2) não pode ser excluído por estar protegido! - - - The group '%1' has already been declared earlier! - O grupo '%1' já foi declarado anteriormente! - - - The group '%1' can not be built in the groups declaration block ('%2')! - O grupo '%1' não pode ser construído no bloco de declaração de grupos ('%2')! - - - The group '%1' was built but not declared in the groups declaration block ('%2')! - O grupo '%1' foi construído porém não declarado no bloco de declaração de grupos ('%2')! - - - The group '%1' can not be built without possessing child elements! - O grupo '%1' não pode ser construído sem possuir elementos filhos! - - - The group '%1' can not be built once more because this was done in previous blocks! - O grupo '%1' não pode ser construído novamente pois já foi construído em blocos anteriores! - - - The group '%1' has been declared but not built! - O grupo '%1' foi declarado porém não construído! - - - The schema public and the languages plpgsql, c and sql can not be manipulated because they are reserved to PostgreSQL! They are present in the model database only as a reference! - O esquema 'public' e as linguagens 'plpgsql', 'c' e 'sql' não podem ser manipuladas por serem reservados ao PostgreSQL! Os mesmos estão presentes no modelo de banco de dados apenas como referência! - - - The new configuration function invalidates the object '%1' (%2)! In this case it is needed to undo the relationship between the affected object and function so that the new configuration of the latter to take effect! - A nova configuração da função invalida o objeto '%1' (%2) o qual a referencia! Neste caso é necessário desfazer a relação entre o objeto afetado e a função para que a nova configuração desta última seja efetivada! - - - Constraints like primary key, foreign key or unique must have at least one column related to them! For foreign keys must be selected, in addition, the referenced columns! - Restrições do tipo chave-primária, chave-estrangeira ou única devem possuir pelo menos uma coluna relacionada às mesmas! Para chaves-estrangeira devem ser selecionadas, adicionalmente, as colunas referenciadas! - - - Unable to load one or more configuration files! Please check if files exists in the configuration folder and if they are not corrupted to preventing this error to occur again on the next startup! - Não foi possível carregar um ou mais arquivos de configuração! Por favor, cheque se os arquivos existem na pasta de configurações e se o mesmos não estão corrompidos para que este erro não se repita na próxima inicialização! - - - Could not find the default settings file '%1'! To restore default settings check the existence of the file and try again! - Não foi possível encontrar o arquivo de configurações padrão '%1'! Para restaurar as configurações padrão cheque a existência do referido arquivo e tente novamente! - - - The export process failed due to an error triggered by the PostgreSQL server in an attempt to execute a SQL command. For more details about the error check the exception stack! - -** Executed SQL command: ** - -%1 - O processo de exportação falhou devido a um erro disparado pelo servidor PostgreSQL na tentativa de execução de um comando SQL. Para obter mais detalhes sobre erro cheque a pilha de exceções! - -** Comando SQL executado: ** - -%1 - - - Could not load the plugin '%1' from the library '%2'! Message returned by plugin manager: '%3' - Não foi possível carregar o plugin '%1' a partir da biblioteca '%2'! Mensagem retornada pelo gerenciador de plugins: '%3' - - - One or more plugins were not activated due to errors during the loading process! Check the exception stack for more details. - Um ou mais plugins não foram ativados devido a erros no processo de carregamento! Verifique a pilha de exceções para mais detalhes. - - - Invalid syntax in file %1, line %2, column %3! - Sintaxe inválida no arquivo %1, linha %2, coluna %3! - - - Invalid conditional instruction '%1' on file %2, line %3, column %4! - Instrução condicional '%1' inválida no arquivo %2, linha %3, coluna %4! - - - Unknown attribute '%1' in file %2, line %3, column %4! - Atributo '%1' desconhecido no arquivo %2, linha %3, coluna %4! - - - Invalid metacharacter '%1' in file %2, line %3, column %4! - Metacaractere '%1' inválido no arquivo %2, linha %3, coluna %4! - - - Attribute '%1' with an undefined value in file %2, line %3, column %4! - Atributo '%1' com valor indefinido no arquivo %2, linha %3, coluna %4! - - - Assignment of empty XML buffer to parser! - Atribuição de buffer de código XML vazio ao parser! - - - Could not access the file or directory %1! Make sure that it exists or if the user has access permissions on it! - Não foi possível acessar o arquivo ou diretório %1! Certifique-se de que o mesmo existe e o usuário possui permissões de acesso a ele! - - - Assignment of empty DTD file name! - Atribuição de nome de arquivo DTD vazio! - - - Assignment of empty name to the DTD declaration! - Atribuição de nome vazio à declaração DTD! - - - Error while interpreting XML buffer at line %1 column %2. -Message generated by the parser: '%3'. %4 - Erro ao interpretar buffer XML na linha %1 coluna %2. - Mensagem gerada pelo parser: '%3'. %4 - - - Operation on unallocated element tree! It is necessary to load the XML parser buffer and interpret it so that the tree is generated! - Operação sobre árvore de elementos não alocada! É necessário carregar o buffer XML do parser e interpretá-lo para que a árvore seja gerada! - - - Could not load file %1. The same appears to be inconsistent or one of its dependencies (DTD files) has errors or is missing! - Não foi possível carregar o arquivo %1. O mesmo parece estar inconsistente ou uma de suas dependências (arquivos DTD) possui erros ou está ausente! - - - Operation with unallocated tree element! - Operação com elemento de árvore de elementos não alocado! - - - Operation with element which does not exists in the element tree currently loaded! - Operação com elemento o qual não faz parte da árvore de elementos carregada atualmente! - - - Assignment of a value to an invalid connection parameter! - Atribuição de valor a um parâmetro de conexão inválido! - - - Operation on connection not established! - Operação sobre conexão não estabelecida! - - - Attempt to connect without define configuration parameters! - Tentativa de conexão sem parâmetros de configuração definidos! - - - Could not connect to the database. -Message returned: '%1' - Não foi possível estabelecer conexão com o banco de dados. -Mensagem retornada: '%1' - - - Assignment of not allocated SQL command result! - Atribuição de resultado de comando SQL não alocado! - - - Unable to allocate the result of the SQL command because the response from the DBMS was not understood by the client! - Não foi possível alocar o resultado do comando SQL pois a resposta do SGBD não foi compreendida pelo cliente! - - - Unable to allocate command result for the SQL because the server has generated a fatal error! -Message returned by the DBMS: %1 - Não foi possível alocar o resultado do comando SQL pois o servidor gerou um erro fatal! -Mensagem retornada pelo SGBD: %1 - - - Unable to allocate the result of the SQL command because the command passed was an empty SQL! - Não foi possível alocar o resultado do comando SQL pois o comando passado foi uma SQL vazia! - - - Reference to a column of tuple with invalid index! - Referência à uma coluna da tupla com índice inválido! - - - Reference to a column of tuple with invalid name! - Referência à uma coluna da tupla com nome inválido! - - - Reference to a tuple with index invalid or the result is empty (no tuples)! - Referência à uma tupla com índice inválido ou o resultado está vazio (sem tuplas)! - - - Could not execute the SQL command. - Message returned: %1 - Não foi possível executar o comando SQL. - Mensagem retornada: %1 - - - Assignment of a not allocated column to object `%1' (%2)! - - - - Assignment of a not allocated schema to object `%1' (%2)! - - - - The object `%1' (%2) has inconsistent SQL or XML definition! - - - - The object `%1' (%2) already exists on `%3' (%4)! - - - - The object `%1' (%2) cannot be assigned because there is already exists in the container object `%3'! - - - - Assigning object of an invalid type! - - - - The insertion of the parameter `%1' will not be possible because there is another parameter with same name in the function `%2'! - - - - The insertion of the table return type `%1' will not be possible because there is another return type with the same name in the `%2'! - - - - Reference to a parameter which index is out of the parameter list bounds! - - - - The column `%1' cannot be assigned to the trigger `%2' because they belongs to different parent tables! - - - - Assignment of a not allocated function to object `%1' (%2)! - - - - Assignment of a function which return type is different from `%1'! - - - - Assignment of a function which parameter count is invalid to the object `%1' (%2)! - - - - Event trigger function must be coded in any language other than SQL! - - - - Assignment of not allocated table to object `%1' (%2)! - - - - Reference to an argument which index is out of argument list bounds! - - - - Assignment of a name which contains invalid characters! - - - - Assignment of a name which length exceeds the maximum of 63 characters! - - - - Assignment of appended or prepended SQL to an invalid object! - - - - Assignment of value to an invalid option type on role! - - - - The insertion of the role `%1' is not possible because this is already being referenced by role `%2'! - - - - Reference redundancy detected by having the role `%1' referencing the role `%2'! - - - - The role `%1' can not be listed as a member of itself! - - - - Reference to a role which index is out of role list bounds! - - - - Insertion of empty command to the rule! - - - - Reference to a command which index is out of the command list bounds! - - - - Is not possible to create a self generalization/copy relationship! The table can not inherit or copy their own attributes! - - - - Assignment of a start value to the sequence which is extrapolating the range defined by minimum and maximum values! - - - - Assignment of owner table which is not in the same schema as the sequence `%1'! - - - - Assignment of owner table which does not belong to the same owner of the sequence `%1'! - - - - Assignment of a nonexistent owner column to the sequence `%1'! - - - - Assignment of an owner column to the sequence `%1' that is not related to any table! - - - - Reference to a label which index is out of labels list bounds! - - - - Assignment of a function with invalid return type to object `%1' (%2)! - - - - Assignment of a function with invalid parameter(s) type(s) to object `%1' (%2)! - - - - Assignment of a null type to object `%1' (%2)! - - - - Assignment of an empty directory to object `%1' (%2)! - - - - Reference to an attribute which index is out of the attributes list bounds! - - - - Reference to an enumeration which index is out of the enumerations list bounds! - - - - Assignment of an operator which input type count is invalid to aggregate function! - - - - Assignment of an operator which types of arguments is invalid! - - - - Assignment of system reserved name to the object `%1' (%2)! - - - - One function with invalid configuration is been used by the object `%1' (%2)! - - - - Reference to an element which index is out of element list bounds! - - - - Reference to an object which index is out of object list bounds! - - - - The object `%1' (%2) can not be removed because it is being referenced by object `%3' (%4)! - - - - The object `%1' (%2) can not be removed because it is being referenced by object `%3' (%4) that belongs to `%5' (%6)! - - - - The creation of the relationship `%1' between the table `%2' and `%3' can not be done because one does not have a primary key. If the relationship is of the type n-n both tables must have primary keys! - - - - Identifier relationship can not be created for a self relationship, relationships of the type n-n, copy or generalization! - - - - Unable to create a copy relationship because the column `%1' in table `%2' already exists in table `%3'! - - - - Unable to create the generalization relationship because the column `%1' in table `%2' can not be merged with the column `%3' of table `%4' because they have incompatible types! - - - - Unable to create the generalization relationship because the constraint `%1' in table `%2' can not be merged with the constraint `%3' of table `%4' due to their incompatible composition! - - - - An attribute can not be added to a copy or generalization relationship! - - - - The object `%1' (%2) is referencing the object `%3' (%4) which was not found in the model! - - - - Unable to write the file or directory `%1'! Make sure the output directory exists, or if the user has write permissions over it! - - - - Unable to write the file `%1' due to one or more errors in the definition generation process! - - - - There is already a relationship between `%1' (%2) and `%3' (%4) in the model! - - - - The configuration of the relationship `%1' generates a redundancy between the relationships `%2'. Redundancy on identifier or generalization/copy relationships are not accepted since they result in incorrect column spreading making the model inconsistent! - - - - The primary key `%1' can only be allocated if declared within a block of code that defines a table or relationship! - - - - Insertion of a role which already exists in the role list of the permission! - - - - There is already a permission on object `%1' (%2) which has one or more equal roles from those present on permission to be assigned to the object! - - - - A permission is referencing the object `%1' (%2) which was not found in the model! - - - - The object `%1' (%2) can not be created because its not being assigned to any schema! - + Reference to a column which index is out of the capacity of the column list! + Referência a uma coluna com índice fora da capacidade da lista de colunas! - The tablespace `%1' can not be inserted into the model because it points to the same directory as the tablespace `%2'! - + Assignment of not allocated object! + Atribuição de um objeto não alocado! - The function `%1' can not get a source code as a definition because its language is set to C. Use the attributes symbol and dynamic library instead! - + Removing an object of an invalid type! + Remoção de objeto de tipo inválido! - The function `%1' can have the attributes symbol and dynamic library configured only if the language is set to C. For all other cases you must specify a source code that defines it in the DBMS! - + Obtaining an object of an invalid type! + Obtenção de um objeto com tipo inválido! - The operator `%1' can not be assigned as a comutator of operator `%2' because it has incompatible settings! - + Assignment of empty name to table return type! + Atribuição de nome vazio ao tipo de retorno de tabela! - The operator `%1' can not be assigned as negator of operator `%2' because it has incompatible settings! - + Reference to an event which does not belongs to trigger! + Referência a um evento não pertecente ao gatilho! - The type `%1' can not self refer in the attributes `element' or `copy type' or be used as a data type of an attribute in the configuration of a composite type! - + Assignment of a function which language is invalid! + Atribuição de função com linguagem inválida! - Assignment of invalid element to type `%1'! - + Assignment of empty name to an object! + Atribuição de nome vazio a um objeto! - Assignment of invalid alignment to type `%1'! - + Assignment of schema object which type is invalid! + Atribuição de um objeto esquema com tipo inválido! - The relationship `%1' can not make use of the special primary key because it is marked as identifier or it is a self relationship! - + Assignment of tablespace object with invalid type! + Atribuição de objeto espaço de tabela com tipo inválido! - The object `%1' (%2) can not be edited or deleted because it was automatically included through a relationship! If the object is an attribute or constraint the modifications must be done on the relationship editing form. - + Assignment of tablespace to an invalid object! + Atribuição de um espaço de tabela a um objeto de tipo inválido! - The object `%1' (%2) can not be deleted because it is protected! - + Assignment of tablespace to a constraint which type is invalid! To belong to a tablespace the constraint must be a primary key or unique! + Atribuição de um objeto espaço de tabela a uma restrição de tipo inválido! A restrição deve ser uma chave-primária ou única para pode pertencer a um espaço de tabela! - The group `%1' has already been declared earlier! - + Assignment of owner object which type is invalid! + Atribuição de um objeto papel com tipo inválido! - The group `%1' can not be built in the groups declaration block (%2)! - + Assignment of owner to an invalid object! + Atribuição de um dono a um objeto de tipo inválido! - The group `%1' was built but not declared in the groups declaration block (%2)! - + Reference to a function with invalid type! + Referência a uma função com tipo inválido! - The group `%1' can not be built without possessing child elements! - + Reference to an argument of the operator with invalid type! + Referência a um argumento do operador com tipo inválido! - The group `%1' can not be built once more because this was done in previous blocks! - + Reference to an operator with invalid type! + Referência a um operador com tipo inválido! - The group `%1' has been declared but not built! - + Reference to an invalid role type! + Referência a um tipo de papel inválido! - Reference to a column of the objects table with invalid index! - + Assignment of an object that already belongs to another table! + Atribuição de um objeto o qual já pertence a outra tabela! - Reference to a row of the objects table with invalid index! - + Assignment of a schema to the sequence which differs from the schema of the owner table! + Atribuição de esquema à seqüência o qual difere do esquema da tabela possuidora! - The object `%1' (%2) can not be manipulated because it is reserved to PostgreSQL! This object is present in the database model only as a reference! - + Assignment of an invalid value to one of the sequence attributes! + Atribuição de valor inválido a um dos atributos da seqüência! - The new configuration of the function invalidates the object `%1' (%2)! In this case it is needed to undo the relationship between the affected object and function in order to the new configuration to take effect! - + Assignment of a minimum value to the sequence which is greater than the maximum value! + Atribuição de valor mínimo da seqüência maior do que o valor máximo! - A view reference must be used in at least one these SQL scopes: View Definition, SELECT-FROM, FROM-WHERE or After WHERE! - + Assignment of a null increment value to the sequence! + Atribuição de incremento de seqüência com valor nulo! - Could not find the default settings file `%1'! To restore default settings check the existence of the file and try again! - + Assignment of null cache value to the sequence! + Atribuição de cache de seqüência com valor nulo! - Could not load the plugin `%1' from the library `%2'! Message returned by plugin manager: `%3' - + Allocation of object with invalid type! + Alocação de objeto com tipo inválido! - Invalid instruction `%1' on file %2, line %3, column %4! - + Assignment of not allocated language! + Atribuição de linguagem não alocada! - Unknown attribute `%1' in file %2, line %3, column %4! - + Assignment of language object which type is invalid! + Atribuição de linguagem com tipo inválido! - Invalid metacharacter `%1' in file %2, line %3, column %4! - + Reference to data type with an index outside the capacity of data types list! + Referência a tipo de dado com índice fora da capacidade da lista de tipos de dados! - Invalid operator `%1' in comparison expression, file %2, line %3, column %4! - + Assignment of invalid type to the object! + Atribuição de um tipo inválido ao objeto! - Attribute `%1' with an undefined value in file %2, line %3, column %4! - + Obtaining types with invalid quantity! + Obtenção de tipos com quantidade inválida! - Attribute `%1' with an invalid name in file %2, line %3, column %4! - + Insertion of item which already exists in the attributes list of the type! + Inserção de item já existente na lista de atibutos do tipo! - Error while interpreting XML buffer at line %1 column %2. -Message generated by the parser: %3. %4 - + Insertion of invalid item in the attributes list of the type! + Inserção de item inválido na lista de atibutos do tipo! - Attempt to start a connection already stablished! - + Insertion of item which already exists in the enumarations list of the type! + Inserção de item já existente na lista de enumerações do tipo! - Could not connect to the database. -Message returned: `%1' - + Insertion of invalid item in the enumerations list of the type! + Inserção de item inválido na lista de emumerações do tipo! - Unable to allocate command result for the SQL because the server has generated a fatal error! -Message returned by the DBMS: `%1' - + Assignment of invalid configuration to the type! + Atribuição de configuração inválida ao tipo! - Reference to a tuple with an invalid index or the result is empty (no tuples)! - + Assignment of an invalid strategy/support number to an operator class element! + Atribuição de valor inválido ao número de estratégia/suporte do elemento de classe de operadores! - Reference to a column of a tuple which was not yet initialized (tuple navigation not started)! - + Insertion of element which already exists in the element list! + Inserção de elemento já existente na lista de elementos! - Could not execute the SQL command. - Message returned: `%1' - + Removal of an object not allocated! + Remoção de objeto não alocado! - Invalid use of a view reference as whole SQL definition! The assigned reference must be an expression! - + Operation with object(s) which type(s) is invalid! + Operação com objeto(s) de tipo(s) inválido(s)! - Assignment of a second definition expression to the view! - + Reference to object with invalid type! + Referência a um objeto com tipo inválido! - It is not possible mix ordinary references (SELECT-FROM, FROM-WHERE, After WHERE) with references used as view SQL definition! - + Operation with object not allocated! + Operação com objeto não alocado! - Assignment of collation object which type is invalid! - + The relationship of the type 1-1 where both tables are mandatory participation is not implemented because it requires fusion between the tables that breaks the modeling done by the user! + O relacionamento do tipo 1-1 onde ambas as tabelas são de participação obrigatória não é implementado por necessitar de fusão entre tabelas o que quebra a modelagem feita pelo usuário! - At the moment pgModeler does not support the creation of primary keys which some columns were generated by relationship connection. To create primary keys with this feature you can use the field `Identifier' or the tab `Primary key' on relationship editing form! - + Assignment of an invalid expression to the object! + Atribuição de expressão inválida ao objeto! - Collations must be created at least with attributes LC_COLLATE and LC_CTYPE defined! - + Assignment of a primary key to a table which already has one! + Atribuição de chave primária à uma tabela a qual já possui uma! - The object `%1' (%2) cannot reference itself! This operation is not permitted for this kind of object! - + A foreign key can not be added to a relationship because is created automatically when this is connected! + Uma chave estrangeira não pode ser adicionado a um relacionamento pois esta é criada automaticamente no momento da ligação do mesmo! - Only operator families which uses `btree' as indexing method are accepted by operator class elements! - + Reference to an user-defined data type that not exists in the model! + Referência a tipo de dado definido pelo usuário o qual não existe no modelo! - Reference to an invalid copy table option! - + Assignment of invalid maximum size to operation list! + Atribuição de tamanho máximo inválido à lista de operações! - Copy relationship between tables `%1' and `%2' cannot be done because the first one already copies attributes from `%3'! Tables can have only one copy table! - + One or more objects were invalidated and automatically removed because they were referencing table columns which were included through relationships and which no longer exists due to disconnection of relationships or exclusion of such generated columns! + Um ou mais objetos foram invalidados e automaticamente removidos pois os mesmos referenciavam colunas de tabelas as quais foram incluídas através de relacionamentos e que deixaram de existir devido a desconexão ou exclusão dos relacionamentos geradores de tais colunas! - The INSTEAD OF mode cannot be used on triggers that belongs to tables! This is available only for view triggers! - + Reference to an invalid privilege type! + Referência a um tipo de privilégio inválido! - The TRUNCATE event can only be used when the trigger executes for each statement and belongs to a table! - + Assignment of privilege incompatible with the type of object referenced by permission! + Atribuição de privilégio incompatível com o tipo do objeto referenciado pela permissão! - The INSTEAD OF mode cannot be used on view triggers that executes for each statement! - + It is not possible to create arrays of domains or sequences (dimension >= 1)! PostgreSQL does not yet implement this feature! + Não é possível criar arrays de domínios ou sequências (dimensão >= 1)! O PostgreSQL ainda não implementa esta funcionalidade! - Constraint triggers can only be executed on AFTER events and for each row! - + Assignment of invalid name to the table generated from N-N relationship! + Atribuição de nome inválido à tabela gerada por relacionamento N-N! - A view trigger cannot be AFTER/BEFORE when it executes for each row! - + Constraints like primary key, foreign key or unique must have at least one column related to them! For foreign keys must be selected, in addition, the referenced columns! + Restrições do tipo chave-primária, chave-estrangeira ou única devem possuir pelo menos uma coluna relacionada às mesmas! Para chaves-estrangeira devem ser selecionadas, adicionalmente, as colunas referenciadas! - A trigger cannot make reference to columns when using INSTEAD OF mode and UPDATE event! - + The export process failed due to an error triggered by the PostgreSQL server in an attempt to execute a SQL command. For more details about the error check the exception stack! + +** Executed SQL command: ** + +%1 + O processo de exportação falhou devido a um erro disparado pelo servidor PostgreSQL na tentativa de execução de um comando SQL. Para obter mais detalhes sobre erro cheque a pilha de exceções! + +** Comando SQL executado: ** + +%1 - Assignment of a column which has no parent table to the object `%1' (%2)! - + One or more plugins were not activated due to errors during the loading process! Check the exception stack for more details. + Um ou mais plugins não foram ativados devido a erros no processo de carregamento! Verifique a pilha de exceções para mais detalhes. - Only constraint triggers can be deferrable or reference another table! - + Assignment of empty XML buffer to parser! + Atribuição de buffer de código XML vazio ao parser! - Reference to a function id which is incompatible with the user define type configuration! - + Assignment of empty DTD file name! + Atribuição de nome de arquivo DTD vazio! - The operator class assigned to the object `%1' (%2) must use `btree' as indexing method! - + Assignment of empty name to the DTD declaration! + Atribuição de nome vazio à declaração DTD! - Unsupported PostgreSQL version (%1) detected! Valid versions are: %2 - + Operation on unallocated element tree! It is necessary to load the XML parser buffer and interpret it so that the tree is generated! + Operação sobre árvore de elementos não alocada! É necessário carregar o buffer XML do parser e interpretá-lo para que a árvore seja gerada! - The validation process failed due to an error triggered by the validation helper. For more details about the error check the exception stack! - + Operation with unallocated tree element! + Operação com elemento de árvore de elementos não alocado! - The extension `%1' is registered as a data type and cannot have the attribute `handles datatype' modified! - + Operation with element which does not exists in the element tree currently loaded! + Operação com elemento o qual não faz parte da árvore de elementos carregada atualmente! - The fk relationship `%1' cannot be created because the foreign-key that represents it was not created on table `%2'! - + Assignment of a value to an invalid connection parameter! + Atribuição de valor a um parâmetro de conexão inválido! - Assignement of an invalid object name pattern to the relationship `%1'! - + Operation on connection not established! + Operação sobre conexão não estabelecida! - Reference to an invalid object name pattern id on the relationship `%1'! - + Attempt to connect without define configuration parameters! + Tentativa de conexão sem parâmetros de configuração definidos! - Invalid use of variadic parameter mode! This mode can be used only with an array or "any" data type! - + Assignment of not allocated SQL command result! + Atribuição de resultado de comando SQL não alocado! - Mixing incompatibles DBMS export modes: `ignore object duplications', `drop database' or `drop objects' cannot be used with `simulate export'! - + Unable to allocate the result of the SQL command because the response from the DBMS was not understood by the client! + Não foi possível alocar o resultado do comando SQL pois a resposta do SGBD não foi compreendida pelo cliente! - Mixing incompatibles DROP options: `drop database' and `drop objects' cannot be used at the same time! - + Reference to a column of tuple with invalid index! + Referência à uma coluna da tupla com índice inválido! - Invalid object id swapping operation! The objects involved are the same! - + Reference to a column of tuple with invalid name! + Referência à uma coluna da tupla com nome inválido! - Invalid object id swapping operation! The database itself, tablespaces or roles cannot have the ids swapped! + Assignment of a not allocated column to object `%1' (%2)! - The widget already has a parent and cannot be assigned to a different object! + Assignment of a not allocated schema to object `%1' (%2)! - The object `%1' (%2) could not be imported due to one or more errors! Check the exception stack for more details. + The object `%1' (%2) has inconsistent SQL or XML definition! - Could not load the database model file `%1'. Check the error stack to see details. Try to run `pgmodeler-cli --fix-model' in order to correct the structure of the file if that is the case. + The object `%1' (%2) already exists on `%3' (%4)! - The column `%1' cannot reference it's parent table `%2' as data type! + The object `%1' (%2) cannot be assigned because there is already exists in the container object `%3'! - Operation with an invalid element id `%1'! + Assigning object of an invalid type! - Reference to an invalid color id `%1' for element `%2'! + The insertion of the parameter `%1' will not be possible because there is another parameter with same name in the function `%2'! - Assignment of an invalid object to `%1' (%2)! The assigned object must be of type `%3'. + The insertion of the table return type `%1' will not be possible because there is another return type with the same name in the `%2'! - The sequence `%1' can't be assigned to the column `%2' because the data type of the latter is incompatible. The type used must be an integer one! + Reference to a parameter which index is out of the parameter list bounds! - The option to generate temporary object names can only be used in simulation mode! + The column `%1' cannot be assigned to the trigger `%2' because they belongs to different parent tables! - It's not possible convert the type of the column `%1' to serial! It must have an `integer' based type and its default value must be a call to `nextval(seq_name::regclass)' function or a sequence object must be directly assigned to the column! + Assignment of a not allocated function to object `%1' (%2)! - Could not assign the variable `%1' to event trigger's filter. Currently, PostgreSQL supports only the `TAG' variable! + Assignment of a function which return type is different from `%1'! - Could not perform the `%1' operation on `%2' using the data on row `%3'! All changes were rolled back. - - ** Returned error ** - -%4 + Assignment of a function which parameter count is invalid to the object `%1' (%2)! - Malformed unescaped value on row `%1' column `%2'! + Event trigger function must be coded in any language other than SQL! - Trying to undo/redo an invalid operation over an object that does not exists anymore or can't be handled! The operation history will be cleaned up. + Assignment of not allocated table to object `%1' (%2)! - The object `%1' (%2) can't be handled because some needed fields are not set! Please, make sure to fill at least the requires fields in order to properly create or update the object. + Reference to an argument which index is out of argument list bounds! - A relationship can only be swapped by other object of the same kind! + Assignment of a name which contains invalid characters! - A parent table of `%1' which OID is `%2' was not found in the set of imported objects! + Assignment of a name which length exceeds the maximum of 63 characters! - The enumeration `%1' can't be assigned to the type `%2' because contains invalid characters! + Assignment of appended or prepended SQL to an invalid object! - The enumeration `%1' can't be assigned to the type `%2' because is too long! + Assignment of value to an invalid option type on role! - The connection was idle for too long and was automatically closed! + The insertion of the role `%1' is not possible because this is already being referenced by role `%2'! - The connection was unexpectedly closed by the database server `%1' at port `%2'! + Reference redundancy detected by having the role `%1' referencing the role `%2'! - - - ExportHelper - - PostgreSQL %1 version code generation... - Geração de código do PostgreSQL versão %1... - - PostgreSQL version detection overrided. Using version %1... - Detecção de versão do PostgreSQL sobreposta. Usando versão %1... + The role `%1' can not be listed as a member of itself! + - PostgreSQL %1 server detected... - Servidor PostgreSQL %1 detectado... + Reference to a role which index is out of role list bounds! + - Ignoring object duplication error... - Ignorando erro de duplicação de objeto... + Insertion of empty command to the rule! + - Creating object '%1' (%2)... - Criando objeto '%1' (%2)... + Reference to a command which index is out of the command list bounds! + - Creating database '%1'... - Criando banco de dados '%1'... + Is not possible to create a self generalization/copy relationship! The table can not inherit or copy their own attributes! + - Connecting to database '%1'... - Conectando ao banco de dados '%1'... + Assignment of a start value to the sequence which is extrapolating the range defined by minimum and maximum values! + - Creating objects on database '%1'... - Criando objetos no banco de dados '%1'... + Assignment of owner table which is not in the same schema as the sequence `%1'! + - - - ExtensionWidget - Version: - Versão: + Assignment of owner table which does not belong to the same owner of the sequence `%1'! + - Old Version: + Assignment of a nonexistent owner column to the sequence `%1'! - This attribute cannot be changed once the object is created. + Assignment of an owner column to the sequence `%1' that is not related to any table! - Handles data type + Reference to a label which index is out of labels list bounds! - - - FamiliaOperadoresWidget - Indexing: - Indexação: + Assignment of a function with invalid return type to object `%1' (%2)! + - - - FindReplaceWidget - Form - Formulário + Assignment of a function with invalid parameter(s) type(s) to object `%1' (%2)! + - Replace one occurrence + Assignment of a null type to object `%1' (%2)! - Replace + Assignment of an empty directory to object `%1' (%2)! - Replace all occurrences + Reference to an attribute which index is out of the attributes list bounds! - Replace All + Reference to an enumeration which index is out of the enumerations list bounds! - Replace the selection and find the next one + Assignment of an operator which input type count is invalid to aggregate function! - Replace && Find + Assignment of an operator which types of arguments is invalid! - Replace: + Assignment of system reserved name to the object `%1' (%2)! - Find: + One function with invalid configuration is been used by the object `%1' (%2)! - Find previous + Reference to an element which index is out of element list bounds! - Shift+F3 + Reference to an object which index is out of object list bounds! - Find next + The object `%1' (%2) can not be removed because it is being referenced by object `%3' (%4)! - F3 + The object `%1' (%2) can not be removed because it is being referenced by object `%3' (%4) that belongs to `%5' (%6)! - Case sensitive + The creation of the relationship `%1' between the table `%2' and `%3' can not be done because one does not have a primary key. If the relationship is of the type n-n both tables must have primary keys! - Regular expression + Identifier relationship can not be created for a self relationship, relationships of the type n-n, copy or generalization! - Whole words + Unable to create a copy relationship because the column `%1' in table `%2' already exists in table `%3'! - - - FormBasico - &Apply - &Aplicar + Unable to create the generalization relationship because the column `%1' in table `%2' can not be merged with the column `%3' of table `%4' because they have incompatible types! + - &Cancel - &Cancelar + Unable to create the generalization relationship because the constraint `%1' in table `%2' can not be merged with the constraint `%3' of table `%4' due to their incompatible composition! + - - - FormConfiguracao - pgModeler Configuration - Configurações do pgModeler + An attribute can not be added to a copy or generalization relationship! + - &Apply - &Aplicar + The object `%1' (%2) is referencing the object `%3' (%4) which was not found in the model! + - &Cancel - &Cancelar + Unable to write the file or directory `%1'! Make sure the output directory exists, or if the user has write permissions over it! + - Defaults - Padrões + Unable to write the file `%1' due to one or more errors in the definition generation process! + - General - Geral + The configuration of the relationship `%1' generates a redundancy between the relationships `%2'. Redundancy on identifier or generalization/copy relationships are not accepted since they result in incorrect column spreading making the model inconsistent! + - Style - Aparência + The primary key `%1' can only be allocated if declared within a block of code that defines a table or relationship! + - Connetions - Conexões + Insertion of a role which already exists in the role list of the permission! + - Confirmation - Confirmação + There is already a permission on object `%1' (%2) which has one or more equal roles from those present on permission to be assigned to the object! + - Any modification made until now in the current section will be lost! Do you really want to restore default settings? - Qualquer modificação feita até agora na seção atual será perdida! Deseja realmente restaurar as configurações padrão? + A permission is referencing the object `%1' (%2) which was not found in the model! + - - - FormExportacao - Model Export - Exportação do Modelo + The object `%1' (%2) can not be created because its not being assigned to any schema! + - Select the export type: - Selecione o tipo de exportação do modelo: + The tablespace `%1' can not be inserted into the model because it points to the same directory as the tablespace `%2'! + - File: - Arquivo: + The function `%1' can not get a source code as a definition because its language is set to C. Use the attributes symbol and dynamic library instead! + - Select target file - Selecionar arquivo de destino + The function `%1' can have the attributes symbol and dynamic library configured only if the language is set to C. For all other cases you must specify a source code that defines it in the DBMS! + - PostgreSQL version in which the SQL code should be generated - Versão do PostgreSQL no qual do código SQL deve ser gerado + The operator `%1' can not be assigned as a comutator of operator `%2' because it has incompatible settings! + - Check if the system user has write permission on target folder. - Certifique-se que o usuário do sistema possui permissão de gravação sobre a pasta de destino do arquivo SQL. + The operator `%1' can not be assigned as negator of operator `%2' because it has incompatible settings! + - Options: - Opções: + The type `%1' can not self refer in the attributes `element' or `copy type' or be used as a data type of an attribute in the configuration of a composite type! + - Show grid - Exibir grade + Assignment of invalid element to type `%1'! + - Ignore object duplicity - Ignorar duplicidade de objetos + Assignment of invalid alignment to type `%1'! + - The pgModeler ignores errors generated by duplicate objects and creates only model objects that do not exist in the database. This option may be used when an object was created after a later model export. - O pgModeler ignora os erros gerados por duplicidade de objetos e cria apenas objetos do modelo não existentes no banco de dados serão. Esta opção pode ser usada quando um objeto foi criado no modelo posteriormente a uma exportação. + The relationship `%1' can not make use of the special primary key because it is marked as identifier or it is a self relationship! + - Export to DBMS: - Exportação para o SGBD: + The object `%1' (%2) can not be edited or deleted because it was automatically included through a relationship! If the object is an attribute or constraint the modifications must be done on the relationship editing form. + - Connection: - Conexão: + The object `%1' (%2) can not be deleted because it is protected! + - It is recommended to select this option only when the version of the DBMS, somehow, is not identifiable or if you need to generate a specific version of SQL code for testing. - Recomenda-se marcar esta opção somente quando a versão do SGBD, de alguma forma, não seja identificável ou se é necessário gerar uma versão específica de código SQL para testes. + The group `%1' has already been declared earlier! + - &Export - &Exportar + The group `%1' can not be built in the groups declaration block (%2)! + - &Close - &Fechar + The group `%1' was built but not declared in the groups declaration block (%2)! + - Generating source code... - Gerando código-fonte... + The group `%1' can not be built without possessing child elements! + - Initializing model export... - Iniciando exportação do modelo... + The group `%1' can not be built once more because this was done in previous blocks! + - Saving file '%1' - Salvando arquivo '%1' + The group `%1' has been declared but not built! + - Creating object '%1' (%2)... - Criando objeto '%1' (%2)... + Reference to a column of the objects table with invalid index! + - Creating database '%1'... - Criando banco de dados '%1'... + Reference to a row of the objects table with invalid index! + - Connecting to database '%1'... - Conectando ao banco de dados '%1'... + The object `%1' (%2) can not be manipulated because it is reserved to PostgreSQL! This object is present in the database model only as a reference! + - Creating objects on database '%1'... - Criando objetos No banco de dados '%1'... + The new configuration of the function invalidates the object `%1' (%2)! In this case it is needed to undo the relationship between the affected object and function in order to the new configuration to take effect! + - Exporting process sucessfuly ended! - Exportação finalizada com sucesso! + A view reference must be used in at least one these SQL scopes: View Definition, SELECT-FROM, FROM-WHERE or After WHERE! + - Error on export! - Falha na exportação! + Could not find the default settings file `%1'! To restore default settings check the existence of the file and try again! + - Export model as... - Exportar modelo como... + Could not load the plugin `%1' from the library `%2'! Message returned by plugin manager: `%3' + - SQL code (*.sql);;All files (*.*) - Código SQL (*.sql);;Todos os Arquivos (*.*) + Error while interpreting XML buffer at line %1 column %2. +Message generated by the parser: %3. %4 + - PNG image (*.png);;All files (*.*) - Imagem PNG (*.png);;Todos os Arquivos (*.*) + Attempt to start a connection already stablished! + - Export to SQL file: - Exportação para arquivo SQL: + Could not connect to the database. +Message returned: `%1' + - Export to PNG image: - Exportação para imagem PNG: + Unable to allocate command result for the SQL because the server has generated a fatal error! +Message returned by the DBMS: `%1' + - Image: - Imagem: + Reference to a tuple with an invalid index or the result is empty (no tuples)! + - Show the page delimiters - Exibir limites de páginas + Reference to a column of a tuple which was not yet initialized (tuple navigation not started)! + - Check if the system user has write permission on image target folder. - Certifique-se que o usuário do sistema possui permissão de gravação sobre a pasta de destino da imagem. + Could not execute the SQL command. + Message returned: `%1' + - - - FormPrincipal - File - Arquivo + Invalid use of a view reference as whole SQL definition! The assigned reference must be an expression! + - Edit - Editar + Assignment of a second definition expression to the view! + - Help - Ajuda + It is not possible mix ordinary references (SELECT-FROM, FROM-WHERE, After WHERE) with references used as view SQL definition! + - Show - Exibir + Assignment of collation object which type is invalid! + - New - Novo + At the moment pgModeler does not support the creation of primary keys which some columns were generated by relationship connection. To create primary keys with this feature you can use the field `Identifier' or the tab `Primary key' on relationship editing form! + - Save - Salvar + Collations must be created at least with attributes LC_COLLATE and LC_CTYPE defined! + - Zoom - - Diminuir zoom + The object `%1' (%2) cannot reference itself! This operation is not permitted for this kind of object! + - Load - Carregar + Only operator families which uses `btree' as indexing method are accepted by operator class elements! + - Next - Próximo + Reference to an invalid copy table option! + - Previous - Anterior + Copy relationship between tables `%1' and `%2' cannot be done because the first one already copies attributes from `%3'! Tables can have only one copy table! + - Exit - Sair + The INSTEAD OF mode cannot be used on triggers that belongs to tables! This is available only for view triggers! + - About pgModeler - Sobre o pgModeler + The TRUNCATE event can only be used when the trigger executes for each statement and belongs to a table! + - Print - Imprimir + The INSTEAD OF mode cannot be used on view triggers that executes for each statement! + - Undo - Desfazer + Constraint triggers can only be executed on AFTER events and for each row! + - Redo - Refazer + A view trigger cannot be AFTER/BEFORE when it executes for each row! + - Export - Exportar + A trigger cannot make reference to columns when using INSTEAD OF mode and UPDATE event! + - Show grid - Exibir grade + Assignment of a column which has no parent table to the object `%1' (%2)! + - Align to grid - Alinhar à grade + Only constraint triggers can be deferrable or reference another table! + - Fullscreen - Tela cheia + Reference to a function id which is incompatible with the user define type configuration! + - Show the model on fullscreen mode - Exibe o modelo em tela cheia + The operator class assigned to the object `%1' (%2) must use `btree' as indexing method! + - Show the page delimiters - Exibe os limitadores de página + The validation process failed due to an error triggered by the validation helper. For more details about the error check the exception stack! + - Configurations - Configurações + The extension `%1' is registered as a data type and cannot have the attribute `handles datatype' modified! + - Save all models - Salvar modelos + The fk relationship `%1' cannot be created because the foreign-key that represents it was not created on table `%2'! + - Some models were modified! Do you want to save them before finish the pgModeler? - Alguns modelos foram modificados! Deseja salvar todos antes de encerrar o pgModeler? + Assignement of an invalid object name pattern to the relationship `%1'! + - Save '%1' as... - Salvar '%1' como... + Reference to an invalid object name pattern id on the relationship `%1'! + - Print grid - Imprimir grade + Invalid use of variadic parameter mode! This mode can be used only with an array or "any" data type! + - Print page numbers - Imprimir número de páginas + Mixing incompatibles DBMS export modes: `ignore object duplications', `drop database' or `drop objects' cannot be used with `simulate export'! + - Model Options - Opções do modelo + Mixing incompatibles DROP options: `drop database' and `drop objects' cannot be used at the same time! + - Confirmation - Confirmação + Invalid object id swapping operation! The objects involved are the same! + - Load model - Carregar modelo + Invalid object id swapping operation! The database itself, tablespaces or roles cannot have the ids swapped! + - Overview - Visão Geral + The widget already has a parent and cannot be assigned to a different object! + - Show the model overview - Exibe a visão geral do modelo + Could not load the database model file `%1'. Check the error stack to see details. Try to run `pgmodeler-cli --fix-model' in order to correct the structure of the file if that is the case. + - Zoom in - Zoom + + The column `%1' cannot reference it's parent table `%2' as data type! + - Zoom out - Zoom - + Operation with an invalid element id `%1'! + - Save as - Salvar como + Reference to an invalid color id `%1' for element `%2'! + - Close model - Fechar modelo + Assignment of an invalid object to `%1' (%2)! The assigned object must be of type `%3'. + - Normal zoom - Zoom normal + The sequence `%1' can't be assigned to the column `%2' because the data type of the latter is incompatible. The type used must be an integer one! + - Align objects position to grid - Alinhar objetos à grade + The option to generate temporary object names can only be used in simulation mode! + - Show delimiters - Exibir limites + It's not possible convert the type of the column `%1' to serial! It must have an `integer' based type and its default value must be a call to `nextval(seq_name::regclass)' function or a sequence object must be directly assigned to the column! + - Save all - Salvar todos + Could not assign the variable `%1' to event trigger's filter. Currently, PostgreSQL supports only the `TAG' variable! + - Database model printing - Impressão do modelo de banco de dados + Could not perform the `%1' operation on `%2' using the data on row `%3'! All changes were rolled back. + + ** Returned error ** + +%4 + - Changes were detected in the definitions of paper/margin of the model which may cause the incorrect print of the objects. Do you want to continue printing using the new settings? To use the default settings click 'No' or 'Cancel' to abort printing. - Foram detectadas modificações nas definições de papel/margem do modelo o que pode provocar a impressão incorreta dos objetos. Deseja prosseguir com a impressão usando as novas configurações? Para usar as configurações padrão clique 'Não' ou em 'Cancelar' para abortar a impressão. + Malformed unescaped value on row `%1' column `%2'! + - Tools - Ferramentas + Trying to undo/redo an invalid operation over an object that does not exists anymore or can't be handled! The operation history will be cleaned up. + - View - Exibição + The object `%1' (%2) can't be handled because some needed fields are not set! Please, make sure to fill at least the requires fields in order to properly create or update the object. + - Model - Modelo + A relationship can only be swapped by other object of the same kind! + - Database model (*.dbm);;All files (*.*) - Modelo de banco de dados (*.dbm);; Todos os arquivos (*.*) + A parent table of `%1' which OID is `%2' was not found in the set of imported objects! + - Save model - Salvar modelo + The enumeration `%1' can't be assigned to the type `%2' because contains invalid characters! + - The model were modified! Do you want to save it before close? - O modelo foi modificado! Deseja salvá-lo antes de fechar? + The enumeration `%1' can't be assigned to the type `%2' because is too long! + - - - FormRestauracaoModelo - Modified: %1 - Modificado: %1 + The connection was idle for too long and was automatically closed! + - yyyy-MM-dd hh:mm:ss - dd/MM/yyyy hh:mm:ss + The connection was unexpectedly closed by the database server `%1' at port `%2'! + - - - FormRestauracaoModelos - Model restoration - Restauração de modelos + There is already a relationship between `%1' (%2) and `%3' (%4) in the model! When using relationships of the type generalization, copy and one-to-one there can't be other relationships linked to the pair of tables. + - &Restore - &Restaurar + Unable to load the configuration file `%1'! Please check if file exists in its folder and/or if it is not corrupted! + - &Cancel - &Cancelar + Invalid syntax in file `%1', line %2, column %3! + - pgModeler was not closed properly in a previous execution and some models were still being edited. Click 'Restore' to reopen the models or 'Cancel' to abort the restoration. - pgModeler não foi encerrado corretamente em uma execução anterior e alguns modelos ainda estavam em edição. Clique 'Restaurar' para reabrir os modelos ou 'Cancelar' para abortar a restauração. + Invalid instruction `%1' on file `%2', line %3, column %4! + - - - FormSobre - Version %1 - Versão %1 + Unknown attribute `%1' in file `%2', line %3, column %4! + - Close - Fechar + Invalid metacharacter `%1' in file `%2', line %3, column %4! + - Copyright 2006-2012 - Raphael Araújo e Silva <rkhaotix@gmail.com> - -The pgModeler project is a CASE tool for modeling relational databases for PostgreSQL DBMS through the use of modeling techniques from entity-relationship diagrams as well merging concepts that PostgreSQL implements. - -Special thanks to friends of the software development team of the Legislative Assembly, Tocantins, Brazil: Michel de Almeida, Felipe Santana, Jonas Nepomuceno, Ricardo Ishibashi and Álvaro Nunes. - Copyright 2006-2012 - Raphael Araújo e Silva <rkhaotix@gmail.com> - -O projeto pgModeler trata de uma ferramenta CASE para a criação de modelos de bancos de dados relacionais para o SGDB PostgreSQL através do uso de técnicas de modelagem de diagramas entidade-relacionamento, como também mesclando conceitos implementados pelo próprio PostgreSQL. - -Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Assembleia Legislativa, Tocantins, Brasil: Michel de Almeida, Felipe Santana, Jonas Nepomuceno, Ricardo Ishibashi and Álvaro Nunes. + Invalid operator `%1' in comparison expression, file `%2', line %3, column %4! + - About pgModeler - Sobre o pgModeler + Attribute `%1' with an undefined value in file `%2', line %3, column %4! + - Design, configure, deploy - Desenhe, configure, implante + Attribute `%1' with an invalid name in file `%2', line %3, column %4! + - - - FuncaoAgregacaoWidget - Final Function: - Função Final: + Could not access the file or directory `%1'! Make sure that it exists or if the user has access permissions on it! + - Transition Function: - Função de Transição: + Could not load file `%1'. The same appears to be inconsistent or one of its dependencies (DTD files) has errors or is missing! + - Sort Operator: - Operador de Ordenação: + Unsupported PostgreSQL version (%1) detected! Valid versions are between %2 and %3. + - Final Condition: - Condição Inicial: + The object `%1' (%2), oid `%3', could not be imported due to one or more errors! Check the exception stack for more details. `HINT:' if the object somehow references objects in `pg_catalog' or `information_schema' consider enable the importing of system objects. + - Funtion Inputs - Entradas da Função + Failed to drop the database `%1' because it is defined as the default database for the connection `%2'! + - Function State - Estado da Função + The column `%1' must be `NOT NULL' because it composes the primary key of the table `%2'. You need to remove the column from the mentioned contraint in order to disable the `NOT NULL' on it! + - Input Data Type - Tipo de Dados de Entrada + The identity column `%1' has an invalid data type! The data type must be `smallint', `integer' or `bigint'. + - State Data Type - Tipo de Dado de Estado + Reference to an invalid affected command in policy `%1'! + - An aggregate function that accepts the types <em><strong>typeA</strong></em> and <em><strong>typeB</strong></em> as input types and which type of state is <em><strong>state_type</strong></em>, must obey the following rules: <br/><br/> <strong> &nbsp;&nbsp;&nbsp;• Final Function:</strong> <em>void final_function(<strong>state_type</strong>)</em><br/> <strong> &nbsp;&nbsp;&nbsp;• Transition Function:</strong> <em><strong>state_type</strong> transition_function(<strong>state_type</strong>, <strong>typeA</strong>, <strong>typeB</strong>)</em> - Uma função de agregação que aceita os tipos <em><strong>tipoA</strong></em> e <em><strong>tipoB</strong></em> como entrada e cujo tipo de estado seja <em><strong>tipo_estado</strong></em>, deve obedecer às seguintes regras:<br/><br/> <strong> &nbsp;&nbsp;&nbsp;• Função Final:</strong> <em>void funcao_final(<strong>tipo_estado</strong>)</em><br/> <strong> &nbsp;&nbsp;&nbsp;• Função Transição:</strong> <em><strong>tipo_estado</strong> funcao_transicao(<strong>tipo_estado</strong>, <strong>tipoA</strong>, <strong>tipoB</strong>)</em> + Reference to an invalid special role in policy `%1'! + - FuncaoWidget - - Attributes - Atributos - + ExtensionWidget - Langague: - Linguagem: + Version: + Versão: - Function Type: - Tipo de Função: + Old Version: + - Window Function: - Função Janela: + This attribute cannot be changed once the object is created. + - Execution Cost: - Custo de Execução: + Handles data type + + + + FindReplaceWidget - Rows Returned: - Linhas Retornadas: + Form + Formulário - Behavior: - Comportamento: + Replace one occurrence + - Security: - Segurança: + Replace + - Return Method: - Método de Retorno: + Replace all occurrences + - Simple - Simples + Replace All + - Set - Conjunto + Replace the selection and find the next one + - Table - Tabela + Replace && Find + - Parameters - Parâmetros + Replace: + - Definition - Definição + Find: + - Dynamic Library: - Biblioteca Dinâmica: + Find previous + - Symbol: - Símbolo: + Shift+F3 + - Library: - Biblioteca: + Find next + - Source code: - Código-Fonte: + F3 + - Column - Coluna + Case sensitive + - Type - Tipo + Regular expression + - Name - Nome + Whole words + - Default Value - Valor Padrão + Hide this widget + - Return Table - Tabela de retorno + ... + FunctionWidget - - Form - Formulário - Attributes Atributos @@ -6698,26 +4271,10 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Function Type: Tipo de Função: - - Langague: - Linguagem: - - - Simple - Simples - Set Conjunto - - Table - Tabela - - - Window Function: - Função Janela: - Return Table Tabela de Retorno @@ -6786,68 +4343,9 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Mode - - - GatilhoWidget - - Triggering Mode: - Modo Disparo: - - - Execute per row - Executar por linha - - - Event: - Evento: - - - Deferrable: - Postergável: - - - Deferral: - Postergação: - - - Referenced Table: - Tab. Referenciada: - - - Conditional Expr.: - Expr. Condicional: - - - Columns - Colunas - - - Column: - Coluna: - - - Arguments - Argumentos - - - Argument: - Argumento: - - Function: - Função: - - - Column - Coluna - - - Type - Tipo - - - Constraint Trigger: - Gatilho Restrição: + Language: + @@ -6856,14 +4354,6 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Form Formulário - - Printing Options: - Opções de Impressão: - - - Save widgets position - Salvar posição dos widgets - Milimeters Milímetros @@ -6880,10 +4370,6 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Centimeter Centímetro - - Save current session - Salvar sessão atual - A0 (841 x 1189 mm) @@ -7004,10 +4490,6 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Tabloid (279 x 432 mm) Tablóide (279 x 432 mm) - - Custom (Based on margins) - Personalizado (Baseado nas margens) - Paper: Papel: @@ -7016,18 +4498,6 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Orientation: Orientação: - - Margins: - Margens: - - - Autosave interval: - Intervalo de Auto salvamento: - - - Grid size: - Tamanho da grade: - Operation history: Histórico de operações: @@ -7077,20 +4547,8 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Retrato - Print page numbers - Imprimir número de páginas - - - minute(s) - minuto(s) - - - items - itens - - - pixels - pixeis + Print page numbers + Imprimir número de páginas General && Design @@ -7100,18 +4558,10 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da General Geral - - The opened models will be saved periodically - - Check if there is a new version on server - - Check for updates at startup - - Design @@ -7140,14 +4590,6 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Move canvas by keep mouse on corners - - By default panning mode is triggered with left click and range selection with Shift + left click. - - - - Swap panning and range selection triggers - - Graphical objects (table, views and textboxes) will be created in a single step without the need to click on canvas @@ -7288,245 +4730,174 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da The little brown fox jumps over the lazy dog - - - GraphicalView - Connected rels: %1 + Minimum object opacity (%): - - - HintTextWidget - - Form - Formulário - - - - IndexWidget - Form - Formulário + Defines the minimum opacity percentage applied to the objects when using the fade out feature. A zero opacity causes the object to be completely hidden not being possible to interact with it in the canvas area. + - Fill Factor: - Fator Preenc.: + Canvas grid size: + - Indexing: - Indexação: + Defines the vertical and horizontal grid size. This value affects the spacing of objects when using object grid alignment feature. + - Options: - Opções: + By default the range selection is triggered with Shift + left click. By checking this option range selection will be activated only with a single click and move. + - Concurrent - Concorrente + Trigger range selection with a single click + - Unique - Único + Defines the maximum amount of elements held in the operation history. Once reached the maximum number the history is automatically cleaned. + - Fast update - Atual. Rápida + Defines the period when the opened models will be saved automatically. + - Conditional Expr.: - Expr. Condicional: + Autosave interval (minutes): + - Elements - Elementos + Replaces any straight line in relationship by curved ones in order to improve the model's visualization. + - Column: - Coluna: + Use curved lines for relationships + - Expression: - Expressão: + Souce code editor args: + - Operator Class: - Classe Operadores: + lines + - Ascending - Ascendente + Clear the entire SQL comand history. + - Descending - Descendente + Clear history + - Nulls first - Nulos primeiro + Open in file manager + Abrir gerenciador de arquivos - Sorting: - Ordenação: + Overrides the default user interface language defined by the system. Requires restarting the program. <strong>NOTE:</strong> UI translations are third party collaborations thus any typo or mistake should be reported directly to their respective maintainers. + - Element - Elemento + SQL history max. length: + - Type - Tipo + Check updates at startup + - Sorting - Ordenação + User interface language: + - Nulls First - Nulos Primeiro + Browse the source code editor application + - Expression - Expressão + Souce code editor: + - Yes - Sim + Configurations directory: + - No - Não + System default + - Attributes - Atributos + All files (*.*) + - Buffering + Load file + + + GenericSQLWidget - Predicate: + SQL code - IndiceWidget + HintTextWidget - Indexing Type: - Tipo Indexação: + Form + Formulário + + + IndexWidget Fill Factor: - Fator Preenc.: + Fator Preenc.: + + + Indexing: + Indexação: Options: - Opções: + Opções: Concurrent - Concorrente + Concorrente - Check duplicates - Checar duplicados + Unique + Único Fast update - Atual. Rápida - - - Conditional Expr.: - Expr. Condicional: + Atual. Rápida Elements - Elementos - - - Column: - Coluna: - - - Expression: - Expressão: - - - Operator Class: - Classe Operadores: - - - Sorting: - Ordenação: - - - Ascending - Ascendente - - - Descending - Descendente - - - Nulls first - Nulos primeiro - - - Type - Tipo - - - Operator Class - Classe Operadores - - - Sorting - Ordenação - - - Element - Elemento - - - Nulls First - Nulos Primeiro + Elementos - Expressão - Expressão + Attributes + Atributos - Sim - Sim + Buffering + - Não - Não + Predicate: + LanguageWidget - - Form - Formulário - Trusted: Confiável: - - Handler Function: - Função Manipuladora: - - - Validator Function: - Função Validadora: - - - Inline Function: - Função em Linha: - The functions to be assigned to the language should have, respectively, the following signatures:<br/><br/> <strong>Handler Function:</strong> <em>language_handler function()</em><br/> <strong>Validator Function:</strong> <em>void function(oid)</em><br/> <strong>Inline Function:</strong> <em>void function(internal)</em> As funções a serem atribuídas à linguagem devem possuir, respectivamente, as seguintes assinaturas:<br/><br/> <strong>Função Manipuladora:</strong> <em>language_handler funcao()</em><br/> <strong>Função Validadora:</strong> <em>void funcao(oid)</em><br/> <strong>Função em Linha:</strong> <em>void funcao(internal)</em> @@ -7536,148 +4907,12 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da - Handler Func.: - - - - Inline Func.: - - - - - LinguagemWidget - - Trusted: - Confiável: - - - Handler Function: - Função Handler: - - - Validator Function: - Função Validator: - - - Inline Function: - Função Inline: - - - The functions to be assigned to the language should have, respectively, the following signatures:<br/><br/> <strong>Handler Function:</strong> <em>language_handler function()</em><br/> <strong>Validator Function:</strong> <em>void function(oid)</em><br/> <strong>Inline Function:</strong> <em>void function(internal)</em> - As funções a serem atribuídas à linguagem devem possuir, respectivamente, as seguintes assinaturas:<br/><br/> <strong>Função Handler:</strong> <em>language_handler funcao()</em><br/> <strong>Função Validator:</strong> <em>void funcao(oid)</em><br/> <strong>Função Inline:</strong> <em>void funcao(internal)</em> - - - - ListaObjetosWidget - - Dependencies - Dependências - - - Object - Objeto - - - Type - Tipo - - - Parent Object - Objeto Pai - - - Parent Type - Tipo Pai - - - References - Referências - - - Dependeces / References of Object - Dependências / Referências do Objeto - - - - ListaOperacoes - - Undoing operation on object: %1 (%2) - Desfazendo operação no objeto: %1 (%2) - - - Redoing operation on object:: %1 (%2) - Refazendo operação no objeto: %1 (%2) - - - - ListaOperacoesWidget - - Executed Operations - Operações Executadas - - - Operations: - Operações: - - - Position: - Posição: - - - Delete operation history - Excluir histórico de operações - - - Undo - Desfazer - - - Redo - Refazer - - - Object: %1 - Objeto: %1 - - - Name: %1 - Nome: %1 - - - removed - removido - - - modified - modificado - - - moved - movimentado - - - Operation: %1 - Operação: %1 - - - Undoing operations... - Desfazendo operações... - - - Redoing operations... - Refazendo operações... - - - Operation history exclusion - Exclusão de histórico de operações - - - Delete the executed operations history is an irreversible action, do you want to continue? - Excluir o histórico de operações executadas é uma ação irreversível, deseja realmente prosseguir? + Handler Func.: + - created - criado + Inline Func.: + @@ -7694,34 +4929,10 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da &Edit &Editar - - &Help - A&juda - &Show &Mostrar - - &Tools - &Ferramentas - - - File - Arquivo - - - View - Ver - - - Edit - Editar - - - Model - Modelo - Plugins @@ -7734,10 +4945,6 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Ctrl+N - - Save - Salvar - Ctrl+S @@ -7762,66 +4969,26 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Ctrl+- - - Load - Carregar - Ctrl+O - - Next - Próximo - - - Previous - Anterior - - - Save as - Salvar como - - - Exit - Sair - Ctrl+Q - - About pgModeler - Sobre o pgModeler - - - Print - Imprimir - Ctrl+P - - Undo - Desfazer - Ctrl+Z - - Redo - Refazer - Ctrl+Y - - Export - Exportar - Ctrl+Shift+S @@ -7834,42 +5001,18 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Ctrl+G - - Close model - Fechar modelo - Ctrl+W - - Normal zoom - Zoom normal - Ctrl+0 - - Align to grid - Alinhar à grade - Align objects position to grid Alinhar objetos à grade - - Fullscreen - Tela inteira - - - Show the model on fullscreen mode - Mostra o modelo em tela inteira - - - Show delimiters - Mostrar delimitadores - Show the page delimiters Mostrar os delimitadores da página @@ -7878,46 +5021,22 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Ctrl+L - - Configurations - Configurações - Save all Salvar todos - - Overview - Visão Geral - Show the model overview Mostra a visão geral do modelo - - pgModeler Wiki - Wiki pgModeler - F1 - - Save all models - Salvar todos os modelos - - - Some models were modified! Do you want to save them before finish the pgModeler? - Alguns modelos foram modificados! Deseja salvá-los antes de encerrar o pgModeler? - Save model Salvar modelo - - The model were modified! Do you want to save it before close? - O modelo foi modificado! Deseja salvá-lo antes de fechar? - Save '%1' as... Salvar '%1' como... @@ -7942,22 +5061,10 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Load model Carregar modelo - - Open Wiki pages - Abrir Páginas Wiki - This action will open a web browser window! Want to proceed? Esta ação abrirá uma janela do navegador de internet! Deseja prosseguir? - - Ctrl+Right - Ctrl+Direita - - - Ctrl+Left - Ctrl+Esquerda - Ctrl+H @@ -8242,10 +5349,6 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da &Diff - - Determine the changes between model and database - - Ctrl+Shift+D @@ -8410,52 +5513,33 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Executing pending <strong>%1</strong> operation... - - - MessageBox - - Dialog - Diálogo - - - Show excpetion stack in text format (useful to report errors). - Mostra a pilha de exceções em formato texto (útil para reportar erros). - - - Show/hide exceptions stack. - Mostrar/Esconder pilha de exceções. - - Exceptions - Exceções - - - &Yes - &Sim + Determine the changes between model/database and another database + - &No - &Não + Arrange objects + - Cancel - Cancelar + Rearrange objects over the canvas + - Error - Erro + Grid + - Alert - Alerta + Hierarchical + - Information - Informação + Scattered + - &Cancel - &Cancelar + Rearrange objects over the canvas is an irreversible operation! Would like to proceed? + @@ -8603,18 +5687,10 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Custom SQL commands - - Save textboxes to the output file when extracting metadata. When loading the file textboxes are recreated and duplicated ones are ignored. - - Textbox objects - - Save tags to the output file when extracting metadata. When loading the file tags are recreated and duplicated ones are ignored. - - Tag objects @@ -8640,102 +5716,122 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da - Extracts the objects metadata from one of the loaded models and apply to the current model. + Output - Extract from a &model + Progress label... + Rótulo de progresso... + + + model not saved yet - Reads the objects metadata from a previously saved backup file and apply to the current model. + The backup file cannot be the same as the input model! - Restore a bac&kup file + Extracting metadata to file `%1' - Output + Saving backup metadata to file `%1' - Progress label... - Rótulo de progresso... + Applying metadata from file `%1' + - model not saved yet + Metadata processing aborted! - The backup file cannot be the same as the input model! + Objects metadata file (*.omf);;All files (*.*) - Extracting metadata to file `%1' + Handles the objects' fade out status in the metadata file. - Saving backup metadata to file `%1' + Objects' fade out status - Applying metadata from file `%1' + Save tags to the output file when extracting metadata. When loading the file, the tags are recreated and duplicated ones are ignored. - Metadata processing aborted! + Save textboxes to the output file when extracting metadata. When loading the file, the textboxes are recreated and duplicated ones are ignored. - Objects metadata file (*.omf);;All files (*.*) + Handles the tables' and views' extended attributes display status in the metadata file. - - - ModelDatabaseDiffForm - Database model diff + Tables' extended attributes display - Generate diff from model + Save generic SQL objects to the output file when extracting metadata. When loading the file, the objects are recreated and duplicated ones are ignored. - Settings + Generic SQL objects - Input database + Extracts the objects' metadata from the loaded models and apply to the current focused model. A backup file can be specified to where the focused model's current metadata will be saved. - Connection: - Conexão: + &Extract and restore + - Database: + Extracts the objects metadata from one of the loaded models saving the info to a backup file. - Options + Extract &only - Ignores as many as possible errors on import step. This option generates an incomplete diff. + Reads the objects' metadata from a previously saved backup file and apply to the current model. - Ignore import errors + &Restore a backup file + + + ModelDatabaseDiffForm - Clears the data of all tables which will have columns modified. This is useful to avoid errors related to type casting. <strong>WARNING:</strong> DO NOT use this option on production servers and always make a backup before use it. + Settings + + + + Connection: + Conexão: + + + Database: + + + + Ignores as many as possible errors on import step. This option generates an incomplete diff. + + + + Ignore import errors - Trucate tables before alter columns + Clears the data of all tables which will have columns modified. This is useful to avoid errors related to type casting. <strong>WARNING:</strong> DO NOT use this option on production servers and always make a backup before use it. @@ -8927,94 +6023,150 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da - Importing database <strong>%1</strong>... + Confirmation + Confirmação + + + <strong>WARNING:</strong> The generated diff is ready to be exported! Once started this process will cause irreversible changes on the database. Do you really want to proceed? - Comparing the model <strong>%1</strong> and database <strong>%2</strong>... + Apply diff - Confirmation - Confirmação + Preview diff + - <strong>WARNING:</strong> The generated diff is ready to be exported! Once started this process will cause irreversible changes on the database. Do you really want to proceed? + Diff process paused. Waiting user action... - Apply diff + Saving diff to file <strong>%1</strong> - Preview diff + Diff process sucessfully ended! - Exporting diff to database <strong>%1</strong>... + No operations left. - Diff process paused. Waiting user action... + Operation cancelled by the user. - Saving diff to file <strong>%1</strong> + Process aborted due to errors! - Diff process sucessfully ended! + + +-- SQL code purposely truncated at this point in demo version! + + + + -- No differences were detected between model and database. -- + + + + Error code <strong>%1</strong> found and ignored. Proceeding with export. + + + + Save diff as... + + + + SQL code (*.sql);;All files (*.*) + Código SQL (*.sql);;Todos os Arquivos (*.*) + + + Diff tool + + + + Generate diff code + + + + Source database - No operations left. + Current model: + + + + (model) + + + + Compare to + + + + Diff + + + + Froce the generation of DROP commands for columns and constraints that exist in database but not in the model. This is useful when diff a partial model against the complete database and the user needs to drop columns and constraint but preserve the rest of the objects. + + + + Drop missing columns and constraints + + + + Truncate tables before alter columns + + + + Import && Export + + + + Import + + + + Export + Exportar + + + This advanced option causes pgModeler to ignore extra errors by their numeric codes. These errors must be informed in the input below and separeted by space. For the complete list of error codes check the PostgreSQL docs, section <strong> Appendix A. PostgreSQL Error Codes</strong>. <strong>WARNING:</strong> use this option with extreme care since it can interfere in final export result. - Operation cancelled by the user. + Ignore error codes - Process aborted due to errors! + model not saved yet - - --- SQL code purposely truncated at this point in demo version! + (none) - -- No differences were detected between model and database. -- + Step %1/%2: Importing database <strong>%3</strong>... - Error code <strong>%1</strong> found and ignored. Proceeding with export. + Step %1/%2: Comparing <strong>%3</strong> and <strong>%4</strong>... - Save diff as... + Step %1/%2: Exporting diff to database <strong>%3</strong>... - - SQL code (*.sql);;All files (*.*) - Código SQL (*.sql);;Todos os Arquivos (*.*) - ModelExportForm - - Model Export - Exportação do Modelo - - - Select the export type: - Selecione o tipo de exportação: - - - Export to SQL file: - Exportação para arquivo SQL: - File: Arquivo: @@ -9035,54 +6187,18 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da PostgreSQL version in which the SQL code should be generated Versão do PostgreSQL no qual o código SQL deve ser gerado - - Check if the system user has write permission on target folder. - Verifique se o usuário do sistema possui permissão de gravação sobre a pasta de destino. - - - Export to PNG image: - Exportação para imagem PNG: - - - Image: - Imagem: - - - Options: - Opções: - Show grid Mostrar grade - - Show the page delimiters - Mostrar delimitadores de página - - - Check if the system user has write permission on image target folder. - Verifique se o usuário do sistema possui permissão de gravação sobre a pasta de destino da imagem. - Connection: Conexão: - - It is recommended to select this option only when the version of the DBMS, somehow, is not identifiable or if you need to generate a specific version of SQL code for testing. - É recomendado selecionar esta opção somente quando a versão do SGBD, de alguma forma, não seja identificável ou se é necessário gerar uma versão específica de código SQL para testes. - Ignore object duplicity Ignorar duplicidade de objetos - - The pgModeler ignores errors generated by duplicate objects and creates only model objects that do not exist in the database. This option may be used when an object was created after a later model export. - O pgModeler ignora os erros gerados por duplicidade de objetos e cria apenas objetos do modelo não existentes no banco de dados. Esta opção pode ser usada quando um objeto foi criado depois de uma posterior exportação do modelo. - - - Export to DBMS: - Exportação para o SGBD: - Progress label... Rótulo de progresso... @@ -9095,10 +6211,6 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da &Close &Fechar - - Generating source code... - Gerando código-fonte... - Initializing model export... Iniciando exportação do modelo... @@ -9107,42 +6219,14 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Saving file '%1' Salvando arquivo '%1' - - Creating object '%1' (%2)... - Criando objeto '%1' (%2)... - - - Creating database '%1'... - Criando banco de dados '%1'... - - - Connecting to database '%1'... - Conectando ao banco de dados '%1'... - - - Creating objects on database '%1'... - Criando objetos No banco de dados '%1'... - Exporting process sucessfuly ended! Processo de exportação finalizado com sucesso! - - Error on export! - Erro na exportação! - Export model as... Exportar modelo como... - - SQL code (*.sql);;All files (*.*) - Código SQL (*.sql);;Todos os Arquivos (*.*) - - - PNG image (*.png);;All files (*.*) - Imagem PNG (*.png);;Todos os Arquivos (*.*) - Export model @@ -9187,10 +6271,6 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Graphics file - - Image (PNG) - - Type: Tipo: @@ -9199,10 +6279,6 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Zoom: - - Vectorial (SVG) - - Show delimiters @@ -9251,6 +6327,22 @@ Agradecimentos especiais aos amigos da equipe de desenvolvimento de software da Exporting process canceled by user! + + This advanced option causes pgModeler to ignore extra errors by their numeric codes. These errors must be informed in the input below and separeted by space. For the complete list of error codes check the PostgreSQL docs, section <strong> Appendix A. PostgreSQL Error Codes</strong>. <strong>WARNING:</strong> use this option with extreme care since it can interfere in final export result. + + + + Ignore error codes + + + + I&mage (PNG) + + + + &Vectorial (SVG) + + ModelExportHelper @@ -9515,10 +6607,6 @@ p, li { white-space: pre-wrap; } Parent Type Tipo Pai - - Visible Object Types - Tipos de Objeto Visíveis - Select All Selecionar Todos @@ -9587,6 +6675,14 @@ p, li { white-space: pre-wrap; } By ID + + Visible object types + + + + Model objects + + ModelOverviewWidget @@ -9594,6 +6690,11 @@ p, li { white-space: pre-wrap; } Model overview Visão geral do modelo + + Failed to generate the overview image. +The requested size %1 x %2 was too big and there was not enough memory to allocate! + + ModelRestorationForm @@ -9609,18 +6710,6 @@ p, li { white-space: pre-wrap; } &Cancel &Cancelar - - pgModeler was not closed properly in a previous execution and some models were still being edited. Click 'Restore' to reopen the models or 'Cancel' to abort the restoration. - pgModeler não foi encerrado corretamente em uma execução anterior e alguns modelos ainda estavam em edição. Clique 'Restaurar' para reabrir os modelos ou 'Cancelar' para abortar a restauração. - - - Modified: %1 - Modificado: %1 - - - yyyy-MM-dd hh:mm:ss - dd/MM/yyyy hh:mm:ss - pgModeler was not closed properly in a previous execution and some models were still being edited. Click <strong>Restore</strong> to reopen the models or <strong>Cancel</strong> to abort the restoration. @@ -9711,10 +6800,6 @@ p, li { white-space: pre-wrap; } Try to resolve the reported issues. - - Apply Fix - - Ctrl+S @@ -9723,10 +6808,6 @@ p, li { white-space: pre-wrap; } Change the creation order for two objects by swapping their ids - - Swap Ids - - Va&lidate @@ -9823,6 +6904,22 @@ p, li { white-space: pre-wrap; } Processing object: %1 + + Apply fixes + + + + Swap ids + + + + The column <strong>%1</strong> on <strong>%2</strong> <em>(%3)</em> is referencing the geospatial data type <strong>%4</strong> but the <strong>postgis</strong> extension is not present in the model! + + + + <strong>HINT:</strong> Create the extension in the model or let it be created by applying the needed fixes. + + ModelWidget @@ -9830,14 +6927,6 @@ p, li { white-space: pre-wrap; } Copy Copiar - - Generalization - Generalização - - - <strong>CAUTION:</strong> The object model is protected! New objects will be inserted only when the protection is removed! - <strong>ATENÇÃO:</strong> O modelo de objetos está protegido! Novos objetos só poderão ser inseridos quando a proteção for removida! - Source code Código fonte @@ -9866,18 +6955,10 @@ p, li { white-space: pre-wrap; } Protects object(s) from modifications Protege objeto(s) contra modificações - - Unprotect objetc(s) from modifications - Desprotege objeto(s) contra modificações - Delete Apagar - - Delete the selected object(s) - Apaga o(s) objeto(s) selecionado(s) - Select all Selecionar todos @@ -9886,50 +6967,18 @@ p, li { white-space: pre-wrap; } Selects all the graphical objects in the model Seleciona todos os objetos gráficos no modelo - - Convert rel. n-n - Converter rel. n-n - - - Converts the n-n relationship into table - Converte o relacionamento n-n em tabela - - - Copy the selected objects(s) - Copia o(s) objeto(s) selecionado(s) - Paste Colar - - Paste the previous copied object(s) - Cola o(s) objeto(s) copiados previamente - Cut Recortar - - Cut the selected object(s) - Recorta o(s) objeto(s) selecionado(s) - - - Displays objects that reference and that are dependent of the selected object - Exibe os objetos que referenciam e os que são dependentes do objeto selecionado - - - New object - Novo objeto - Add a new object in the model Adiciona um novo objeto no modelo - - Quick actions - Ações rápidas - Rename Renomear @@ -9942,50 +6991,18 @@ p, li { white-space: pre-wrap; } Move to schema Mover para o esquema - - Move the object to another schema - Mover o objeto para outro esquema - Edit permissions Editar permissões - - Edit object's permissions - Editar permissões do objeto - Change owner Mudar proprietário - - Change object's owner - Mudar proprietário do objeto - Select children Selecionar filhos - - Selects all the children graphical objects on the selected schema - Seleciona todos os objetos gráficos filhos no esquema selecionado - - - Highlight - Destacar - - - Clears the current selection and centers the model view on the selected object. - Limpa a seleção atual e centraliza a visualização do modelo no objeto selecionado. - - - Confirmation - Confirmação - - - Do you really want to convert the relationship? - Deseja realmente converter o relacionamento? - Loading database model Carregando modelo de banco de dados @@ -10002,26 +7019,10 @@ p, li { white-space: pre-wrap; } Pasting objects... Colando objetos... - - Validating object: %1 (%2) - Validando o objeto: %1 (%2) - - - Generating XML code of object: %1 (%2) - Gerando código XML do objeto: %1 (%2) - - - Pasting object: %1 (%2) - Colando o objeto: %1 (%2) - Not all objects were pasted to the model due to errors returned during the process! Refer to error stack for more details! Nem todos objetos foram colados ao modelo devido a erros retornados durante o processo! Consulte a pilha de erros para mais detalhes! - - CAUTION: Remove multiple objects at once can cause irreversible invalidations to other objects in the model. Do you really want to delete ALL selected objects? - ATENÇÃO: Remover vários objetos de uma só vez pode provocar invalidações irreversíveis de outros objetos no modelo. Tem certeza de que deseja excluir TODOS os objetos selecionados? - Do you really want to delete the selected object? Deseja realmente apagar o objeto selecionado? @@ -10034,18 +7035,6 @@ p, li { white-space: pre-wrap; } Constraints Restrições - - Dependencies - Dependências - - - CAUTION: Remove multiple objects at once can cause irreversible invalidations to other objects in the model. Such invalid objects will be deleted too. Do you really want to delete ALL selected objects? - ATENÇÃO: Remover múltiplos objetos de uma vez pode causar invalidações irreversíveis a outros objetos no modelo. Tais objetos inválidos serão apagados também. Deseja realmente apagar TODOS os objetos selecionados? - - - CAUTION: Remove a relationship can cause irreversible invalidations to other objects in the model. Such invalid objects will be deleted too. Do you really want to delete the relationship? - ATENÇÃO: Remover um relacionamento pode causar invalidações irreversíveis a outros objetos no modelo. Tais objetos inválidos serão apagados também. Deseja realmente apagar o relacionamento? - One to One (1-1) @@ -10238,179 +7227,93 @@ p, li { white-space: pre-wrap; } The cascade deletion found some problems when running! Some objects could not be deleted or registered in the operation's history! Please, refer to error stack for more details. - - - ModeloBD - - Loading object: %1 (%2) - Carregando objeto: %1 (%2) - - - Generating %1 of the object: %2 (%3) - Gerando %1 do objeto: %2 (%3) - - - - ModeloWidget - - Generalization - Generalização - - - <strong>CAUTION:</strong> The object model is protected! New objects will be inserted only when the protection is removed! - <strong>ATENÇÃO:</strong> O modelo de objetos encontra-se protegido! Novos objetos só poderão ser inseridos quando esta situação for revertida! - - - Source code - Código-fonte - - - Show object source code - Exibe o código-fonte do objeto - - - Properties - Propriedades - - - Edit the object properties - Edita as propriedades do objeto - - - Protect - Proteger - - - Unprotect - Desproteger - - - Pretects the object(s) against modifications - Protege o(s) objeto(s) contra modificações - - - Removes from the objetc(s) the protection against modifications - Remove a proteção contra modificação do(s) objeto(s) - - - Delete - Excluir - - - Delete the selected object(s) - Exclui o(s) objeto(s) selecionado(s) - - - Select all - Selecionar todos - - - Selects all the graphical objects in the model - Seleciona todos os objetos gráficos no modelo - - - Converts the n-n relationship into table - Converte o relacionamento n-n para tabela própria - - - Copy - Copiar - - - Copy the selected objects(s) - Copia o(s) objeto(s) selecionado(s) - - Paste - Colar - - - Paste the previos copied object(s) - Cola o(s) objeto(s) anteriormente copiado(s) + Edit data + - Cut - Recortar + Select tagged + - Displays objects that reference and that are dependent of the selected object - Exibe os objetos que referenciam e os que são dependência do objeto selecionado + Select + Selecionar - New object - Novo objeto + Duplicate + - Add a new object in the model - Adiciona um novo objeto no modelo + Ctrl+D + - Loading database model - Carregando modelo de banco de dados + Extended attributes + - Saving database model - Salvando modelo de banco de dados + Show + Exibir - Confirmation - Confirmação + Hide + - Also copy all dependencies of selected objects? This minimizes the breakdown of references when copied objects are pasted into another model. - Deseja copiar também todas dependências dos objetos selecionados? Isso minimiza a quebra de referências quando os objetos copiados forem colados em outro modelo. + Jump to table + - Pasting objects... - Colando objetos... + Schemas rectangles + - Not all objects were pasted to the model due to errors returned during the process! Refer to error stack for more details! - Nem todos objetos foram colados ao modelo devido a erros retornados durante o processo! Consulte a pilha de erros para mais detalhes! + Fade in/out + - Do you really want to delete the selected object? - Tem certeza de que deseja excluir o objeto selecionado? + Fade in + - Constraints - Restrições + Fade out + - Convert a relationship is an irreversible operation and causes the deletion of all operation history! Do you want to continue? - Converter um relacionamento é uma operação irreversível e provoca a exclusão de todo histórico de operações! Deseja continuar? + Relationships + - Dependence - Dependência + Swap ids + - Convert rel. n-n - Converter rel n-n + Edit the objects creation order by swapping their ids + - Cut the selected object(s) - Recortar o(s) objeto(s) selecionado(s) + All objects + - Relationship - Relacionamento + Schemas + - CAUTION: Remove multiple objects at once can cause irreversible invalidations to other objects in the model. Do you really want to delete ALL selected objects? - ATENÇÃO: Remover vários objetos de uma só vez pode provocar invalidações irreversíveis de outros objetos no modelo. Tem certeza de que deseja excluir TODOS os objetos selecionados? + Tables + Tabelas - Validating object: %1 (%2) - Validando o objeto: %1 (%2) + Views + - Pasting object: %1 (%2) - Colando o objeto: %1 (%2) + Textboxes + - Generating XML code of object: %1 (%2) - Gerando código XML do objeto: %1 (%2) + None + @@ -10702,6 +7605,18 @@ p, li { white-space: pre-wrap; } 0 + + Generic SQL + + + + Policy + + + + 8 + + NumberedTextEditor @@ -10721,13 +7636,45 @@ p, li { white-space: pre-wrap; } Ident left + + Load + Carregar + + + Load the object's source code from an external file + + + + Edit + Editar + + + Edit the source code in the preferred external editor + + + + Clear + + + + SQL file (*.sql);;All files (*.*) + + + + Load file + + + + The source editor `%1' is running on `pid: %2'. + + + + Could not start the source code editor application `%1'! Make to sure that the source editor path defined in the general settings points to a valid executable and the current user has permission to run the application. Error message returned: `%2' + + ObjectDepsRefsWidget - - Form - Formulário - Dependencies Dependências @@ -10752,10 +7699,6 @@ p, li { white-space: pre-wrap; } References Referências - - Dependences / References of Object - Dependências / Referências de Objeto - Object's dependencies & references @@ -10803,14 +7746,6 @@ p, li { white-space: pre-wrap; } Clear - - Highlight graphical objects when selecting them or their children on the result list - - - - Highlight - Destacar - ... @@ -10871,6 +7806,30 @@ p, li { white-space: pre-wrap; } No objects found. + + (Un)selects the graphical objects in the results grid + + + + Select + Selecionar + + + Fades outs all the graphical objects in the results grid (or those not listed). The current fade in/out state of all objects is modified. + + + + Fade out + + + + Listed + + + + Not listed + + ObjectRenameWidget @@ -10915,343 +7874,106 @@ p, li { white-space: pre-wrap; } - ObjectTableWidget + ObjectsTableWidget Form - Formulário + Formulário Add Item - Adicionar Item + Adicionar Item Ins - + Remove Item - Remover Item + Remover Item Del - + Update Item - Atualizar Item + Atualizar Item Alt+R - + Remove All - Remover Todos + Shift+Del - - - - Edit Item - Editar Item - - - Space - - - - Move Up - Mover para cima - - - Ctrl+Up - - - - Move Down - Mover para baixo - - - Ctrl+Down - - - - Move to start - Mover para o início - - - Ctrl+Home - - - - Move to end - Mover para o final - - - Ctrl+End, Ctrl+S - - - - Confirmação - Confirmação - - - Do you really want to remove the selected item? - Deseja realmente remover o item selecionado? - - - Do you really want to remove the all items? - Deseja realmente remover todos os itens? - - - Confirmation - Confirmação - - - - ObjetoBase - - Column - Coluna - - - Constraint - Restrição - - - Function - Função - - - Trigger - Gatilho - - - Index - Índice - - - Rule - Regra - - - Table - Tabela - - - View - Visão - - - Domain - Domínio - - - Schema - Esquema - - - Aggregate - Função de Agregação - - - Operator - Operador - - - Sequence - Seqüência - - - Role - Papel - - - Conversion - Conversão de Codificação - - - Cast - Conversão de Tipo - - - Language - Linguagem - - - Type - Tipo - - - Tablespace - Espaço de Tabela - - - Operator Family - Família de Operadores - - - Operator Class - Classe de Operadores - - - Database - Banco de Dados - - - Table-Table Relationship - Relacionamento Tabela-Tabela - - - Textbox - Caixa de Texto - - - Permission - Permissão - - - Parameter - Parâmetro - - - Table-View Relationship - Relacionamento Tabela-Visão - - - - ObjetoBaseWidget - - Name: - Nome: - - - Comment: - Comentário: - - - Tablespace: - Esp. de Tabela: - - - Owner: - Dono: - - - Schema: - Esquema: - - - Permissions: - Permissões: - - - This object is protected thus no change in form will be applied to it. - Este o objeto encontra-se protegido, assim nenhuma alteração no formulário será aplicada ao mesmo. - - - Parent Object: - Objeto Pai: - - - Value(s) - Valor(es) - - - Version - Versão - - - The field(s) or value(s) highlighted on the form is(are) for the exclusive use and/or mandatory in specific versions of PostgreSQL. Failure to complete that may cause errors in the generation of SQL code for each version shown in tool tips of the highlighted fields. - O(s) campo(s) ou valor(es) destacado(s) no formulário é(são) de uso exclusivo e/ou obrigatório em versões específicas do PostgreSQL. O não preenchimento do(s) mesmo(s) pode ocasionar erros na geração de código SQL de cada versão indicada nas dicas de ferramenta dos campos destacados. - - - Criate / Edit: - Criação / Edição: - - - Edit Permissions - Editar Permissões - - - - OperadorWidget - - Options: - Opções: + - Arguments - Argumentos + Duplicate item + - Functions - Funções + Ctrl+D + - Constraints: - Restrição: + Edit Item + Editar Item - Operator: - Operador: + Space + - Operators - Operadores + Move Up + Mover para cima - Commutation: - Comutação: + Ctrl+Up + - Negation: - Negação: + Move Down + Mover para baixo - Sort (1): - Ordenação (1): + Ctrl+Down + - Sort (2): - Ordenação (2): + Move to start + Mover para o início - Less than: - Menor que: + Ctrl+Home + - Greater then: - Maior que: + Move to end + - Right Argument Type - Tipo Argumento Direita + Ctrl+End, Ctrl+S + - Left Argument Type - Tipo Argumento Esquerda + Confirmation + Confirmação - To create a unary operator it is necessary to specify as <strong><em>'any'</em></strong> one of its arguments. Additionally, the function that defines the operator must have only one parameter and this, in turn, must have the same data type of the the argument of unary operator. - Para a criação de um operador unário é necessário especificar como <strong><em>'any'</em></strong> um de seus argumentos. Adicionalmente, a função que define o operador deve possuir apenas uma parâmetro e este, por sua vez, deve ter o tipo de dado igual ao tipo de dado do argumento do operador unário. + Do you really want to remove the selected item? + - Join: - Junção: + Do you really want to remove all the items? + OperationList - - Undoing operation on object: %1 (%2) - Desfazendo operação no objeto: %1 (%2) - - - Redoing operation on object:: %1 (%2) - Refazendo operação no objeto: %1 (%2) - (invalid object) @@ -11319,14 +8041,6 @@ p, li { white-space: pre-wrap; } Operation: %1 Operação: %1 - - Undoing operations... - Desfazendo operações... - - - Redoing operations... - Refazendo operações... - Operation history exclusion Exclusão de histórico de operações @@ -11346,10 +8060,6 @@ p, li { white-space: pre-wrap; } OperatorClassWidget - - Form - Formulário - Default Class: Classe Padrão: @@ -11362,10 +8072,6 @@ p, li { white-space: pre-wrap; } Elements Elementos - - Elemente Type: - Tipo de Elemento: - Operator Operador @@ -11390,14 +8096,6 @@ p, li { white-space: pre-wrap; } Support/Strategy: Suporte/Estratégia: - - Recheck - Rechecar - - - Family: - Família: - Storage Type Tipo de Armazenamento @@ -11414,14 +8112,6 @@ p, li { white-space: pre-wrap; } Support/Strategy Suporte/Estratégia - - Yes - Sim - - - No - Não - Element Type: Tipo de Elemento: @@ -11437,10 +8127,6 @@ p, li { white-space: pre-wrap; } OperatorFamilyWidget - - Form - Formulário - Indexing: Indexação: @@ -11448,10 +8134,6 @@ p, li { white-space: pre-wrap; } OperatorWidget - - Form - Formulário - HASHES @@ -11468,46 +8150,10 @@ p, li { white-space: pre-wrap; } Arguments Argumentos - - Functions - Funções - Join: Junção: - - Operator: - Operador: - - - Operators - Operadores - - - Commutation: - Comutação: - - - Negation: - Negação: - - - Sort (1): - Ordenação (1): - - - Sort (2): - Ordenação (2): - - - Less than: - Menor que: - - - Greater then: - Maior que: - Right Argument Type Tipo Argumento Direita @@ -11528,10 +8174,6 @@ p, li { white-space: pre-wrap; } Restrict: Restrito: - - Commutator - Comutador - Negator: Negador: @@ -11546,579 +8188,645 @@ p, li { white-space: pre-wrap; } - PapelWidget + ParameterWidget - Password: - Senha: + Default Value: + Valor Padrão: - Validity: - Validade: + Mode: + Modo: - Connections: - Conexões: + IN + - Attributes - Atributos + OUT + - Superuser - Superusuário + VARIADIC + + + + PermissionWidget - Inherit Permissions - Herdar Permissões + Roles + Papéis - Create Database - Criar Banco de Dados + ID: + - Can Login - Permitir Login + Permissions + Permissões - Create Users/Groups - Criar Usuários/Grupos + Add Permission + Adicionar Permissão - Encrypted Password - Senha Criptografada + Update Permission + Atualizar Permissão - Members - Membros + Cancel Operation + Cancelar Operação - Role - Papel + Privileges + Privilégios - Validity - Validade + Privilege + Privilégio - Members (Admin.) - Membros (Admin.) + GRANT OPTION + - Member of - Membro de + Id + - - - ParameterWidget - Form - Formulário + Disable SQL code + Desabilitar código SQL - Default Value: - Valor Padrão: + Cascade + Cascata - Mode: - Modo: + Edit permissions + Editar permissões - IN - + &Grant + - OUT - + Re&voke + - VARIADIC + Code Preview + Previsão de Código + + + -- No permissions defined for the specified object! - - - ParametroWidget - Default Value: - Valor Padrão: + /* Could not generate the SQL code preview for permissions! + - Mode: - Modo: + Name + Nome + + + Leave the <em><strong>Roles</strong></em> grid empty in order to create a %1 applicable to <strong><em>PUBLIC</em></strong>. + - PermissaoWidget + PgModelerCLI - Roles - Papéis + Unrecognized option '%1'. + Opção '%1' não reconehcida. - Privileges - Privilégios + Value not specified for option '%1'. + Valor não specificado para a opção '%1'. - Cancel Operation - Cancelar Operação + Option '%1' does not accept values. + Opção '%1' não aceita valores. - Update Permission - Atualizar Permissão + Usage: pgmodeler-cli [OPTIONS] + Uso: pgmodeler-cli [OPÇÕES] - Add Permission - Adicionar Permissão + command line interface. + interface da linha de comando. - Type: - Tipo: + DBMS export options: + Opções da exportação SGBD: - Role - Papel + Input file must be different from output! + Arquivo de entrada deve ser diferente do de saída! + + + Incomplete connection information! + Informação de conexão incompleta! + + + Starting model export... + Iniciando exportação de modelo... + + + General options: + + + + PNG and SVG export options: + + + + Miscellaneous options: + + + + There are no connections configured. + + + + Invalid zoom specified! + + + + Invalid action specified to update mime option! + + + + Starting model fixing... + + + + Starting mime update... + + + + Model successfully fixed! + + + + Extracting objects' XML... + + + + Invalid input file! It seems that is not a pgModeler generated model or the file is corrupted! + + + + Recreating objects... + + + + +** Object(s) that couldn't fixed: + + + + WARNING: There are objects that maybe can't be fixed. Trying again... (tries %1/%2) + + + + Database model files (.dbm) are already associated to pgModeler! + - Permissions - Permissões + There is no file association related to pgModeler and .dbm files! + - Privilege - Privilégio + Mime database operation: %1 + - - - PermissionWidget - Form - Formulário + Can't erase the file %1! Check if the current user has permissions to delete it and if the file exists. + - Roles - Papéis + Running update-mime-database command... + - ID: - + Connection aliased as '%1' was not found in the configuration file. + - Permissions - Permissões + PostgreSQL Database Modeler Project - pgmodeler.io + - Add Permission - Adicionar Permissão + Copyright 2006-2018 Raphael A. Silva <raphael@pgmodeler.io> + - Update Permission - Atualizar Permissão + This CLI tool provides several operations over models and databases without the need to perform them +in pgModeler's graphical interface. All available options are described below. + - Cancel Operation - Cancelar Operação + %1, %2 [FILE] Input model file (.dbm). This is mandatory for fix, export operations. + - Privileges - Privilégios + %1, %2 [DBNAME] Input database name. This is mandatory for import operation. + - Privilege - Privilégio + %1, %2 [FILE] Output file. This is mandatory for fixing model or exporting to file, png or svg. + - GRANT OPTION - + %1, %2 Try to fix the structure of the input model file in order to make it loadable again. + - Type: - Tipo: + %1, %2 [NUMBER] Model fix tries. When reaching the maximum count the invalid objects will be discarded. + - Role - Papel + %1, %2 Export the input model to a sql script file. + - Id - + %1, %2 Export the input model to a png image. + - Disable SQL code - Desabilitar código SQL + %1, %2 Export the input model to a svg file. + - Grant - Conceder + %1, %2 Export the input model directly to a PostgreSQL server. + - Revoke - Revogar + %1, %2 Import a database to an output file. + - Cascade - Cascata + %1, %2 Compares a model and a database or two databases generating the SQL script to synch the latter in relation to the first. + - Leave the <em><strong>Roles</strong></em> empty to create a permission applicable to <strong><em>PUBLIC</em></strong>. - Deixe os <em><strong>Papéis</strong></em> em branco para criar uma permissão aplicável a <strong><em>PUBLIC</em></strong>. + %1, %2 Force the PostgreSQL version of generated SQL code. + - Edit permissions - Editar permissões + %1, %2 Silent execution. Only critical messages and errors are shown during process. + - &Grant + %1, %2 Show this help menu. - Re&voke + Connection options: - Code Preview - Previsão de Código + %1, %2 List available connections in file %3. + - -- No permissions defined for the specified object! + %1, %2 [ALIAS] Connection configuration alias to be used. - /* Could not generate the SQL code preview for permissions! + %1, %2 [HOST] PostgreSQL host in which a task will operate. - - - PgModelerCLI - Unrecognized option '%1'. - Opção '%1' não reconehcida. + %1, %2 [PORT] PostgreSQL host listening port. + - Value not specified for option '%1'. - Valor não specificado para a opção '%1'. + %1, %2 [USER] PostgreSQL username. + - Option '%1' does not accept values. - Opção '%1' não aceita valores. + %1, %2 [PASSWORD] PostgreSQL user password. + - Connection aliased as '%1' was not found on configuration file. - Conexão apelidada de '%1' não foi encontrada no arquivo de configuração. + %1, %2 [DBNAME] Connection's initial database. + - Usage: pgmodeler-cli [OPTIONS] - Uso: pgmodeler-cli [OPÇÕES] + %1, %2 Draws the grid in the exported image. + - command line interface. - interface da linha de comando. + %1, %2 Draws the page delimiters in the exported image. + - PostgreSQL Database Modeler Project - pgmodeler.com.br - Projeto Modelador de Banco de Dados PostgreSQL - pgmodeler.com.br + %1, %2 Each page will be exported in a separated png image. (Only for PNG images) + - This tool provides a way to export pgModeler's database models without -the need to load them on graphical interface. All available exporting -modes are described below. - Esta ferramenta provê um modo de exportar modelos de banco de dados do pgModeler sem -a necessidade de carregá-los na interface gráfica. Todos os modos de exportações -disponíveis estão descritos abaixo. + %1, %2 [FACTOR] Applies a zoom (in percent) before export to png image. Accepted zoom interval: %3-%4 (Only for PNG images) + - Options: - Opções: + %1, %2 Ignores errors related to duplicated objects that eventually exist in the server. + - %1, %2=[FILE] Input model file (.dbm). - %1, %2=[ARQUIVO] Arquivo de entrada do modelo (.dbm). + %1, %2 [CODES] Ignores additional errors by their codes. A comma-separated list of alphanumeric codes should be provided. + - %1, %2=[FILE] Output file. Available only on export to file or png. - %1, %2=[ARQUIVO] Arquivo de saída. Disponível apenas ao exportar para arquivo ou png. + %1, %2 Drop the database before execute a export process. + - %1, %2 Export to a sql script file. - %1, %2 Exportar para um arquivo de script sql. + %1, %2 Runs the DROP commands attached to SQL-enabled objects. + - %1, %2 Export to a png image. - %1, %2 Exportar para uma imagem png. + %1, %2 Simulates an export process by executing all steps but undoing any modification in the end. + - %1, %2 Export directly to a PostgreSQL server. - %1, %2 Exportar diretamente para um servidor PostgreSQL. + %1, %2 Generates temporary names for database, roles and tablespaces when in simulation mode. + - %1, %2 Version of generated SQL code. Only for file or dbms export. - %1, %2 Versão de código SQL gerado. Exportação apenas para arquivo ou SGDB. + Database import options: + - %1, %2 Silent execution. Only critical errors are shown during process. - %1, %2 Execução silenciosa. Apenas erros críticos são mostrados durante o processo. + %1, %2 Ignore all errors and try to create as many as possible objects. + - %1, %2 Show this help menu. - %1, %2 Mostrar este menu de ajuda. + %1, %2 Import system built-in objects. This option causes the model bloating due to the importing of unneeded objects. + - PNG export options: - Opções de exportação PNG: + %1, %2 Import extension objects. This option causes the model bloating due to the importing of unneeded objects. + - %1, %2 Draws the grid on the exported png image. - %1, %2 Desenha a grade na imagem png exportada. + %1, %2 Run import in debug mode printing all queries executed in the server. + - %1, %2 Draws the page delimiters on the exported png image. - %1, %2 Desenha os delimitadores de página na imagem png exportada. + Diff options: + - DBMS export options: - Opções da exportação SGBD: + %1, %2 [DBNAME] The database used in the comparison. All the SQL code generated is applied to it. + - %1, %2 Ignores errors related to duplicated objects that eventually exists on server side. - %1, %2 Ignora erros relacionados a objetos duplicados que eventualmente existam no lado servidor. + %1, %2 Save the generated diff code to output file. + - %1, %2=[ALIAS] Connection configuration alias to be used. - %1, %2=[APELIDO] Apelido da configuração da conexão a ser usada. + %1, %2 Apply the generated diff code on the database server. + - %1, %2=[HOST] PostgreSQL host which export will operate. - %1, %2=[SERVIDOR] Servidor PostgreSQL no qual a exportação irá operar. + %1, %2 Don't preview the generated diff code when applying it to the server. + - %1, %2=[PORT] PostgreSQL host listening port. - %1, %2=[PORTA] Porta de escuta do servidor PostgreSQL. + %1, %2 Drop cluster level objects like roles and tablespaces. + - %1, %2=[USER] PosrgreSQL username. - %1, %2=[USUARIO] Nome de usuário PostgreSQL. + %1, %2 Revoke permissions already set on the database. New permissions configured in the input model are still applied. + - %1, %2=[PASSWORD] PosrgreSQL user password. - %1, %2=[SENHA] Senha de usuário PosrgreSQL. + %1, %2 Drop missing objects. Generates DROP commands for objects that are present in the input model but not in the compared database. + - %1, %2=[DBNAME] Connection's initial database. - %1, %2=[NOMEBD] Banco de dados inicial da conexão. + %1, %2 Force the drop of missing columns and constraints. Causes only columns and constraints to be dropped, other missing objects aren't removed. + - No export mode specified! - Modo de exportação não especificado! + %1, %2 Rename the destination database when the names of the involved databases are different. + - Multiple export mode especified! - Modo de exportação múltiplo especificado! + %1, %2 Don't drop or truncate objects in cascade mode. + - No input file specified! - Arquivo de entrada não especificado! + %1, %2 Truncate tables prior to alter columns. Avoids errors related to type casting when the new type of a column isn't compatible to the old one. + - No output file specified! - Arquivo de saída não especificado! + %1, %2 Don't reuse sequences on serial columns. Drop the old sequence assigned to a serial column and creates a new one. + - Input file must be different from output! - Arquivo de entrada deve ser diferente do de saída! + %1, %2 Don't force the recreation of objects. Avoids the usage of a DROP and CREATE commands to create a new version of the objects. + - Incomplete connection information! - Informação de conexão incompleta! + %1, %2 Don't recreate the unmodifiable objects. These objects are the ones which can't be changed via ALTER command. + - Starting model export... - Iniciando exportação de modelo... + %1, %2 [ACTION] Handles the file association to .dbm files. The ACTION can be [%3 | %4]. + - Loading input file: - Carregando arquivo de entrada: + ** The diff process allows the usage of the following options related to import and export operations: + - Export to PNG image: - Exportar para imagem PNG: + * Export: + - Export to SQL script file: - Exportar para arquivo de script SQL: + * Import: + - Export to DBMS: - Exportar para SGBD: + ** When running the diff using two databases (%1 and %2) there's the need to specify two connections/aliases. + - Export successfully ended! - Exportação finalizada com sucesso! + If only one connection is set it will be used to import the input database as well to retrieve database used in the comparison. + - Copyright 2006-2015 Raphael A. Silva <raphael@pgmodeler.com.br> + A second connection can be specified by appending a 1 on any connection configuration parameter listed above. - This CLI tool provides the operations to export pgModeler's database models without - the need to load them on graphical interface as well to fix model files to the most recent - accepted structure. All available options are described below. + Available connections (alias : connection string) - General options: + No operation mode was specified! - %1, %2=[FILE] Input model file (.dbm). Mandatory use when fixing a model or exporting it. + Export, fix model, import database, diff and update mime operations can't be used at the same time! - %1, %2=[FILE] Output file. Mandatory use when fixing model or export to file or png. + Multiple export mode was specified! - %1, %2 Try to fix the structure of the input model file in order to make it loadable again. + No input file was specified! - %1, %2 Model fix tries. When reaching the maximum count the invalid objects will be discard. + No input database was specified! - %1, %2 Export to a svg file. + No output file was specified! - %1, %2 List available connections on %3 file. + No input file or database was specified! - PNG and SVG export options: + The input file and database can't be used at the same time! - %1, %2 Each page will be exported on a separated png image. (Only for PNG) + No database to be compared was specified! - %1, %2=[FACTOR] Applies a zoom (in percent) before export to png image. Accepted zoom interval: %3-%4 (Only for PNG) + No diff action (save or apply) was specified! - %1, %2 Drop the database before execute a export process. + No output file for the diff code was specified! - %1, %2 Runs the DROP commands attached to SQL-enabled objects. + ** Error code `%1' found and ignored. Proceeding with export. - %1, %2 Simulates a export process. Actually executes all steps but undoing any modification. + ** Command: %1 - %1, %2 Generates temporary names for database, roles and tablespaces when in simulation mode. + Loading input file: %1 - %1, %2=[USER] PostgreSQL username. + Fixed model file: %1 - %1, %2=[PASSWORD] PostgreSQL user password. + Export to PNG image: %1 - Miscellaneous options: + Export to SVG file: %1 - %1, %2=[ACTION] Handles the file association to .dbm files. The ACTION can be [%3 | %4]. + Export to SQL script file: %1 - There are no connections configured. + Export to DBMS: %1 - Available connections (alias : conn. string) + Export successfully ended! + - Export, fix model and update mime operations can't be used at the same time! + Starting database import... - Multiple export mode specified! + Input database: %1 - Invalid zoom specified! + Saving the imported database to file... - Invalid action specified to update mime option! + Import successfully ended! + - Starting model fixing... + Starting diff process... - Starting mime update... + Input model: %1 - Fixed model file: + Compare to: %1 - Model successfully fixed! + Loading input model... - Mime database successfully updated. + Importing the database `%1'... - Export to SVG file: + Comparing the generated models... - Extracting objects' XML... + No differences were detected. - Invalid input file! It seems that is not a pgModeler generated model or the file is corrupted! + Saving diff to file `%1' - Recreating objects... + ** WARNING: You are about to apply the generated diff code to the server. Data can be lost in the process! - -** Object(s) that couldn't fixed: + ** Proceed with the diff applying? (yes/no) > - WARNING: There are objects that maybe can't be fixed. Trying again... (tries %1/%2) + yes - Database model files (.dbm) are already associated to pgModeler! + no - There is no file association related to pgModeler and .dbm files! + Diff code not applied to the server. - Mime database operation: %1 + Applying diff to the database `%1'... - Can't erase the file %1! Check if the current user has permissions to delete it and if the file exists. + Diff successfully ended! + - Running update-mime-database command... + Mime database successfully updated! + @@ -12245,10 +8953,6 @@ disponíveis estão descritos abaixo. Loaded plug-ins Plugins carregados - - <html><head/><body><p>Details about plugins development and installation can be found at <a href="http://www.pgmodeler.com.br/wiki/doku.php?id=plugins"><span style=" text-decoration: underline; color:#0057ae;">pgModeler Wiki</span></a>. <span style=" font-weight:600;">Note:</span> plugin installation requires pgModeler to be restarted.</p></body></html> - <html><head/><body><p>Detalhes sobre o desenvolvimento e instalação de plugins podem ser encontrados em <a href="http://www.pgmodeler.com.br/wiki/doku.php?id=plugins"><span style=" text-decoration: underline; color:#0057ae;">Wiki pgModeler</span></a>. <span style=" font-weight:600;">Nota:</span> a instalação de plugins requer que o pgModeler seja reiniciado.</p></body></html> - Plugin @@ -12263,190 +8967,53 @@ disponíveis estão descritos abaixo. - ProgressoTarefa - - Executing tasks - Executando tarefas - - - - QObject - - new_database - novo_banco_de_dados - - - %1 (line: %2) - %1 (linha: %2) - - - - QuickRenameWidget - - Form - Formulário - - - to: - para: - - - Rename - Renomear - - - Cancel - Cancelar - - - - RegraWidget - - Event: - Evento: - - - Execution Type: - Tipo Execução: - - - Conditional Expr.: - Expr. Condicional: - - - Executed Commands - Comandos Executados - - - SQL Command: - Comando SQL: - - - To create a rule that does not perform any action (<strong>DO NOTHING</strong>) simply do not specify commands in the SQL commands table. - Para se criar uma regra que não execute ação alguma (<strong>DO NOTHING</strong>) basta não especificar comandos na tabela de comandos SQL. - - - SQL command - Comando SQL - - - - RelacionamentoWidget - - General - Geral - - - Relationship: - Relacionamento: - - - One to one relationship - Relacionamento de um para um - - - One to many relationship - Relacionamento de um para muitos - - - Many to many relationship - Relacionamento de muitos para muitos - - - Generalization relationship (inheritance) - Relacionamento de generalização (herança) - - - Dependency relationship - Relacionamento de dependência entre tabelas ou entre uma tabela e visão - - - Identifier - Identificador - - - Source Table: - Tabela Origem: - - - Target Table: - Tabela Destino: - - - Cardinality: - Cardinalidade: - - - Source Required - Origem Obrigatória - - - Target Required - Destino Obrigatória - - - Name of the table generated from many to many relationship - Nome da tabela gerada pelo relacionamento muitos para muitos - - - Table Name: - Nome Tab. N-N: - - - Foreign key - Chave-estrangeira - + PolicyWidget - Deferrable: - Postergável: - - - Deferral: - Postergação: - - - Attributes - Atributos + Basics + - Constraints - Restrições + Command: + - Primary key - Chave-primária + Permissive + - Attribute - Atributo + Roles + Papéis - Type - Tipo + Expressions + - Constraint - Restrição + USING: + - Editing attributes of an existing relationship is allowed, but must be done carefully because it may break references to columns and cause invalidation of objects such as triggers, indexes, constraints and sequences. - A edição de atributos de um relacionamento já existente é permitida, porém, deve ser feita com atenção pois pode quebrar referências à colunas e causar a invalidez de objetos como gatilhos, índices, restrições e sequências. + CHECK: + - Use the special primary key if you want to include a primary key containing inherited / copied columns to the receiving table. This is a feature available only for generalization / dependency relationships. - Utilize o recurso de chave-primária especial caso queira incluir uma chave-primária contendo as colunas heradas/copiadas na tabela receptora. Este é um recurso disponível apenas para relacionamentos de generalização/dependência. + Name + Nome - Automatic Suffix - Sufixo Automático + Leave the <em><strong>Roles</strong></em> grid empty in order to create a %1 applicable to <strong><em>PUBLIC</em></strong>. + + + + QObject - Source Suffix: - Sufixo Origem: + new_database + novo_banco_de_dados - Target Suffix: - Sufixo Destino: + %1 (line: %2) + %1 (linha: %2) @@ -12482,18 +9049,10 @@ disponíveis estão descritos abaixo. Connection Mode - - This mode is available only for <strong>one-to-one</strong>, <strong>one-to-many</strong> and <strong>fk relationships</strong> but provides a better semantics when linking tables by placing the lines on the exact point where the relationship occurs. - - Connect FK to PK columns - - This mode is the classical one. It connects the relationship to tables through their central points. - - Connect tables' center points @@ -12606,21 +9165,37 @@ disponíveis estão descritos abaixo. Default Padrão + + This mode renders the relationships in crow's foot notation which has a better semantics and readability. It also determines the optimal point where the relationship is connected on the tables' edges taking their position into account. + + + + Crow's foot notation + + + + This mode determines the optimal point where the relationship is connected on the tables' edges taking their position into account. It implies the usage of the classical ER notation. + + + + Connect tables' edges + + + + This mode is available only for <strong>one-to-one</strong>, <strong>one-to-many</strong> and <strong>fk relationships</strong> but provides a better semantics when linking tables by placing the lines on the exact point where the relationship occurs. It implies the usage of the classical ER notation. + + + + This mode is the classical one. It connects the relationship to tables through their central points. It implies the usage of the classical ER notation. + + RelationshipWidget - - Form - Formulário - General Geral - - Relationship: - Relacionamento: - One to one relationship Relacionamento de um para um @@ -12689,22 +9264,6 @@ disponíveis estão descritos abaixo. Name of the table generated from many to many relationship Nome da tabela gerada pelo relacionamento muitos para muitos - - Table Name: - Nome Tab.: - - - Source Suffix: - Sufixo Origem: - - - Target Suffix: - Sufixo Destino: - - - Foreign key - Chave estrangeira - Deferrable: Postergável: @@ -12713,10 +9272,6 @@ disponíveis estão descritos abaixo. Deferral: Postergação: - - Automatic Suffix - Sufixo Automático - Attributes Atributos @@ -12749,14 +9304,6 @@ disponíveis estão descritos abaixo. Name Nome - - Editing attributes of an existing relationship is allowed, but must be done carefully because it may break references to columns and cause invalidation of objects such as triggers, indexes, constraints and sequences. - A edição de atributos de um relacionamento já existente é permitida, porém deve ser feita cuidadosamente, pois pode quebrar referências à colunas e causar a invalidação de objetos como gatilhos, índices, restrições e sequências. - - - Use the special primary key if you want to include a primary key containing inherited / copied columns to the receiving table. This is a feature available only for generalization / copy relationships. - Use a chave primária especial se você quer incluir uma chave primária contendo colunas herdadas / copiadas para a tabela receptora. Esta é uma característica disponível apenas para relacionamentos de generalização / cópia. - This advanced tab shows the objects (columns or table) auto created by the relationship's connection as well the foreign keys that represents the link between the participant tables. Esta aba avançada mostra os objetos (colunas ou tabela) auto criados pela conexão do relacionamento, bem como as chaves estrangeiras que representam a ligação entre as tabelas participantes. @@ -12809,22 +9356,6 @@ disponíveis estão descritos abaixo. STORAGE - - Reference Suffix: - Sufixo de Referência: - - - Table 1 - Tabela 1 - - - Suffix: - Sufixo: - - - Table 2 - Tabela 2 - Name Patterns @@ -12991,74 +9522,18 @@ disponíveis estão descritos abaixo. - RestricaoWidget - - Constraint Type: - Tipo de Restrição: - - - Check Expr.: - Expr.Checagem: - - - Fill Factor: - Fator Preenc.: - - - Comparison: - Comparação: - - - Deferrable: - Postergável: - - - Deferral: - Postergação: - - - Columns - Colunas - - - Column: - Coluna: - - - Referenced Columns - Colunas Referenciadas - - - Table: - Tabela: - - - Column - Coluna - + ResultSetModel - Type - Tipo - - - Columns which were included by relationship can not be added / removed manually from the primary key. If done such changes they will be ignored. To create primary key using columns included by relationship use the feature attributes, constraints and primary key on the relationship form. - Colunas as quais foram incluídas por relacionamento não podem ser adicionadas/removidas manualmente das chaves-primárias. Caso isso ocorra tais alterações serão ignoradas. Para criar chaves-primárias usando colunas incluídas por relacionamentos utilize o recurso de atributos, restrições e chave-primária no formulário de edição relacionamentos. + [binary data] + RoleWidget - - Form - Formulário - Password: Senha: - - Validity: - Validade: - Connections: Conexões: @@ -13071,26 +9546,6 @@ disponíveis estão descritos abaixo. Superuser Superusuário - - Inherit Permissions - Herdar Permissões - - - Create Database - Criar Banco de Dados - - - Can Login - Pode Logar - - - Create Users/Groups - Criar Usuários/Grupos - - - Encrypted Password - Senha Criptografada - Members Membros @@ -13112,40 +9567,44 @@ disponíveis estão descritos abaixo. Validade - Can create Database - Pode criar Banco de Dados + Encrypted + Encriptado + + + yyyy-MMM-dd hh:mm:ss + - Can create Role - Pode criar Papel + Assigning <strong><em>-1</em></strong> to <strong><em>Connections</em></strong> creates a role without connection limit.<br/> Unchecking <strong><em>Validity</em></strong> creates an role that never expires. + - Can use Replication - Pode usar Replicação + Inherit permissions + - Encrypted - Encriptado + Can create database + - Assigning <strong><em>-1</em></strong> to <strong><em>Connections</em></strong> creates a role without connection limit.<br/> Unchecking <strong><em>Validity</em></strong> creates an role that never expires. - Atribuindo <strong><em>-1</em></strong> à <strong><em>Conexões</em></strong> cria um papel sem limite de conexão.<br/> Desmarcando <strong><em>Validade</em></strong> cria um papel que nunca expira. + Bypass RLS + - yyyy-MMM-dd hh:mm:ss + Can use replication - Assigning <strong><em>-1</em></strong> to <strong><em>Connections</em></strong> creates a role without connection limit.<br/> Unchecking <strong><em>Validity</em></strong> creates an role that never expires. + Can login + + + + Can create role RuleWidget - - Form - Formulário - Event: Evento: @@ -13158,10 +9617,6 @@ disponíveis estão descritos abaixo. Conditional Expr.: Expr. Condicional: - - Executed Commands - Comandos Executados - SQL Command: Comando SQL: @@ -13185,30 +9640,14 @@ disponíveis estão descritos abaixo. Form Formulário - - Load SQL script - - - - &Load - - Save SQL commands - - &Save - - Search in SQL code - - &Find - - Alt+F @@ -13293,10 +9732,6 @@ disponíveis estão descritos abaixo. Results (%1) - - [%1]: SQL command successfully executed. <em>%2 <strong>%3</strong></em> - - Rows affected @@ -13329,6 +9764,90 @@ disponíveis estão descritos abaixo. Clear history + + Close the current SQL script + + + + SQL script currently handled + + + + (not saved) + + + + Handle external SQL script + + + + &Script + + + + Fi&nd + + + + Alt+T + + + + Alt+X + + + + Current working database + + + + Load + Carregar + + + Save + Salvar + + + Save as + Salvar como + + + [%1]: SQL command successfully executed in <em><strong>%2</strong></em>. <em>%3 <strong>%4</strong></em> + + + + Plain format + + + + CVS format + + + + This action will wipe out all the SQL commands history for all connections! Do you really want to proceed? + + + + Save history + + + + Reload history + + + + Find in history + + + + Hide find tool + + + + This action will wipe out all the SQL commands history for the current connection! Do you really want to proceed? + + SQLToolWidget @@ -13384,51 +9903,59 @@ disponíveis estão descritos abaixo. <strong>ATTENTION:</strong> Disconnect from all databases will close any opened tab in this view! Do you really want to proceed? + + + SceneInfoWidget - <strong>CAUTION:</strong> You are about to drop the entire database <strong>%1</strong>! All data will be completely wiped out. Do you really want to proceed? + Form + Formulário + + + Current position of the mouse in the canvas - You're running a demonstration version! The data manipulation feature is available only in the full version! + - - - - SchemaWidget - Form - Formulário + Current zoom factor + - Show rectangle - Mostrar retângulo + Currently selected object(s) + - Fill color: - Cor de preenchimento: + Dimensions of the selected object(s) + - Select fill color - Seleciona cor de preenchimento + No selection + + + + N/A + + + + Sel. objects: %1 + - SeletorObjetoWidget + SchemaWidget - Clear field - Limpar campo + Show rectangle + Mostrar retângulo - Select Object - Selecionar Objeto + Fill color: + Cor de preenchimento: SequenceWidget - - Form - Formulário - Cyclic: Cíclica: @@ -13453,44 +9980,17 @@ disponíveis estão descritos abaixo. Cache: Cache: - - Owner: - Proprietário: - Owner Col.: - - - SequenciaWidget - - Cyclic: - Cíclica: - - - Start: - Início: - - - Maximum: - Máximo: - - - Minimum: - Mínimo: - - - Increment: - Incremento: - - Cache: - Cache: + Defualt values: + - Owner: - Possuidora: + User defined + @@ -13624,10 +10124,6 @@ disponíveis estão descritos abaixo. SourceCodeWidget - - Form - Formulário - Version: Versão: @@ -13648,10 +10144,6 @@ disponíveis estão descritos abaixo. XML - - Type: - Tipo: - Source code visualization Visualização de código fonte @@ -13743,10 +10235,6 @@ disponíveis estão descritos abaixo. Before: - - It's recommended to use this feature only when the SQL validation fails in cases when a object is being referenced in portions where the ordinary validation couldn't reach, e.g., inside of a rule command or check constraint expression. - - Swap the values of the fields @@ -13755,135 +10243,41 @@ disponíveis estão descritos abaixo. Swap values - - - TabelaObjetosWidget - - Add Item - Adicionar Item - - - Remove Item - Remover Item - - - Update Item - Atualizar Item - - - Remove All - Excluir Todos - - - Edit Item - Editar Item - - - Move Up - Mover para cima - - - Move Down - Mover para baixo - - - Move to start - Mover para o início - - - Move to end - Mover para o fim - - - Do you really want to remove the selected item? - Tem certeza de que deseja remover o item selecionado? - - - Do you really want to remove the all items? - Tem certeza de que deseja remover todos os itens? - - - Confirmação - Confirmation - - - - TabelaWidget - - Columns - Colunas - - - Constraints - Restrições - - - Triggers - Gatilhos - - Rules - Rules + Change the objects creation order is an irreversible operation and cause the operations history to be automatically erased. Note that the creation order configured in this form is not definitive and may change after a model validation. + - Indexes - Índices + Swap the object ids changing their creation order + - Tables - Tabelas + Swap ids + - Ancestor Tables: - Tabelas Ancestrais: + Filter: + - Copied Tables: - Tabelas Copiadas: + ID + - Name - Nome + Object + Objeto Type - Tipo - - - Default Value - Valor Padrão - - - Refer. Table - Tab. Refer. - - - Events - Eventos - - - Execution - Execução - - - Event - Evento - - - Indexing - Indexação - - - With OIDs: - Com OIDs: + Tipo - Attribute - Atributo + Parent Object + Objeto Pai - Firing - Disparo + Parent Type + Tipo Pai @@ -13907,18 +10301,10 @@ disponíveis estão descritos abaixo. Add empty rows - - Add - Adicionar - Ins - - Some invalid or duplicated columns were detected. In order to solve this issue double-click the header of the highlighted ones in order to define the correct name in which the data belongs to or delete the entire column. Note that these columns are completely igored when generating the <strong>INSERT</strong> commands. - - Add an empty column @@ -13927,10 +10313,6 @@ disponíveis estão descritos abaixo. Remove all rows from the grid preserving columns - - Clear - - Shift+Del @@ -13939,26 +10321,14 @@ disponíveis estão descritos abaixo. Delete the selected rows - - Delete - - Del - - <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in <span style=" font-weight:600;">{}</span>. To use <span style=" font-weight:600;">{</span> or <span style=" font-weight:600;">}</span> as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\{</span> or <span style=" font-weight:600;">\}</span>.</p></body></html> - - Duplicate the selected rows - - Duplicate - - Ctrl+D @@ -13996,67 +10366,88 @@ disponíveis estão descritos abaixo. - (no columns) + Copy items on the grid - - - TableObjectView - -Relationship: %1 + Copy + Copiar + + + Add row - - - TableView - Connected rels: %1 + Delete column - - - TableWidget - Form - Formulário + Paste items on the grid + - With OIDs: - Com OIDs: + Paste + Colar - Columns - Colunas + Ctrl+V + - Constraints - Restrições + Fills the grid using a CSV file + - Triggers - Gatilhos + <html><head/><body><p>Some invalid or duplicated columns were detected. In order to solve this issue double-click the header of the highlighted ones in order to define the correct name in which the data belongs to or delete the entire column. Note that these columns are completely ignored when generating the <span style=" font-weight:600;">INSERT</span> commands.</p></body></html> + - Rules - Regras + Add column + - Indexes - Índices + Duplicate rows + - Tables - Tabelas + Change the values of all selected cells at once + + + + Bulk data edit + + + + Ctrl+E + + + + Delete all columns + + + + Delete rows + - Ancestor Tables: - Tabelas Ancestrais: + <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in two slashes, e.g., <span style=" font-weight:600;">/value/</span>. To use a slash as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\/</span>.</p></body></html> + + + + Delete all rows + + + + TableObjectView - Copied Tables: - Tabelas Copiadas: + +Relationship: %1 + + + + TableWidget Name Nome @@ -14069,10 +10460,6 @@ Relationship: %1 Default Value Valor Padrão - - Attribute - Atributo - ON DELETE @@ -14114,61 +10501,117 @@ Relationship: %1 Pai - Copy - Copiar + Copy + Copiar + + + Options + + + + Tag: + + + + With OID + + + + Generate ALTER for columns/constraints + + + + Unlogged + + + + &Columns + + + + Co&nstraints + + + + Tri&ggers + + + + &Rules + + + + &Indexes + + + + &Tables + - Options + Edit data - Tag: + Define initial data for the table - With OID + Enable row level security - Generate ALTER for columns/constraints + Force RLS for owner - Unlogged + &Policies - &Columns + PK - Co&nstraints + Attribute(s) - Tri&ggers + It is not possible to mark a column as primary key when the table already has a primary key which was created by a relationship! This action should be done in the section <strong>Primary key</strong> of the relationship's editing form. - &Rules + It is not possible to mark a column created by a relationship as primary key! This action should be done in the section <strong>Primary key</strong> of the relationship's editing form. - &Indexes + Command - &Tables + Permissive - Edit data + USING expression - Define initial data for the table + CHECK expression + + Roles + Papéis + + + Yes + Sim + + + No + Não + TablespaceWidget @@ -14221,10 +10664,6 @@ Relationship: %1 TextboxWidget - - Form - Formulário - Bold Negrito @@ -14258,142 +10697,8 @@ Relationship: %1 - - TipoPgSQLWidget - - Data Type - Tipo de Dado - - - Type: - Tipo: - - - Length - Comprimento - - - Precision - Precisão - - - Dimension - Dimensão - - - Interval: - Intervalo: - - - Format: - Formato: - - - Spatial: - Espacial: - - - Variation: - Variação: - - - - TipoWidget - - Configuration: - Configuração: - - - Base Type - Tipo Base - - - Enumeration - Enumeração - - - Composite - Composto - - - Enumerations - Enumerações - - - Enumeration: - Enumeração: - - - Attributes - Atributos - - - Internal Length: - Comp. Interno: - - - Storage: - Armazenamento: - - - By Value: - Por Valor: - - - Category: - Categoria: - - - Preferred: - Preferido: - - - Delimiter: - Delimitador: - - - Alignment: - Alinhamento: - - - Default Value: - Valor Padrão: - - - Functions - Funções - - - Copy Type - Tipo Cópia - - - Element Type - Tipo Elemento - - - Name - Nome - - - Type - Tipo - - - The functions to be assigned to a type should be written in C language and possess, respectively, the following signatures:<br/> <table> <tr> <td><strong>INPUT:</strong> <em>any function(cstring, oid, integer)</em></td> <td><strong>OUTPUT:</strong> <em>cstring function(any)</em></td> </tr> <tr> <td><strong>SEND:</strong> <em>byta function(any)</em></td> <td><strong>RECV:</strong> <em>any function(internal, oid, integer)</em></td> </tr> <tr> <td><strong>TPMOD_IN:</strong> <em>integer function(cstring[])</em></td> <td><strong>TPMOD_OUT:</strong> <em>cstring function(integer)</em></td> </tr> <tr> <td><strong>ANALYZE:</strong> <em>boolean function(internal)</em></td> <tr> </table> - As funções a serem atribuídas ao tipo devem ser todas escritas em linguagem C e possuirem, respectivamente, as seguintes assinaturas:<br/> <table> <tr> <td><strong>INPUT:</strong> <em>any funcao(cstring, oid, integer)</em></td> <td><strong>OUTPUT:</strong> <em>cstring funcao(any)</em></td> </tr> <tr> <td><strong>SEND:</strong> <em>byta funcao(any)</em></td> <td><strong>RECV:</strong> <em>any funcao(internal, oid, integer)</em></td> </tr> <tr> <td><strong>TPMOD_IN:</strong> <em>integer funcao(cstring[])</em></td> <td><strong>TPMOD_OUT:</strong> <em>cstring funcao(integer)</em></td> </tr> <tr> <td><strong>ANALYZE:</strong> <em>boolean funcao(internal)</em></td> <tr> </table> - - TriggerWidget - - Form - Formulário - - - Execute per row - Executar por linha - Event: Evento: @@ -14418,18 +10723,6 @@ Relationship: %1 Deferrable: Postergável: - - Deferral: - Postergação: - - - Referenced Table: - Tab. Referenciada: - - - Conditional Expr.: - Expr. Condicional: - Columns Colunas @@ -14450,10 +10743,6 @@ Relationship: %1 Function: Função: - - Constraint Trigger: - Gatilho Restrição: - Column Coluna @@ -14489,10 +10778,6 @@ Relationship: %1 TypeWidget - - Form - Formulário - Configuration: Configuração: @@ -14505,10 +10790,6 @@ Relationship: %1 Enumeration Enumeração - - Composite - Composto - Enumerations Enumerações @@ -14529,18 +10810,10 @@ Relationship: %1 Storage: Armazenamento: - - By Value: - Por Valor: - Category: Categoria: - - Preferred: - Preferido: - Delimiter: Delimitador: @@ -14732,22 +11005,10 @@ Relationship: %1 Get source code - - Recover a package - - - - Purchase a new package - - Failed to check updates - - The update notifier failed to check for new versions! Please, verify your internet connectivity and try again! Connection error returned: <strong>%1</strong>. - - No updates found @@ -14760,21 +11021,17 @@ Relationship: %1 The update notifier failed to check for new versions! A HTTP status code was returned: <strong>%1</strong> + + The update notifier failed to check for new versions! Please, verify your internet connectivity and try again! Connection error returned: <em>%1</em> - <strong>%2</strong>. + + ViewWidget - - Form - Formulário - References Referências - - Type: - Tipo: - Column Coluna @@ -14787,18 +11044,6 @@ Relationship: %1 Used in: Usado em: - - SELECT-FROM - - - - FROM-WHERE - - - - After WHERE - Após WHERE - Table: Tabela: @@ -14839,15 +11084,6 @@ Relationship: %1 Alias Col. Apelido Col. - - To reference all columns in a table (*) just do not fill the field <strong>Column</strong>, this is the same as write <em><strong>[schema].[tablel].*</strong></em> - Versão em inglês com erro! (tablel) - Para referenciar todas as colunas de uma tabela (*) basta não preencher o campo <strong>Coluna</strong>, isso é equivalente a escrever <em><strong>[esquema].[tabela].*</strong></em> - - - -- Could not generate the code. Make sure all attributes are correctly filled! -- - -- Impossível gerar código. Verifique se todos os atributos foram preenchidos corretamente! -- - Reference Type: Tipo Referência: @@ -14868,10 +11104,6 @@ Relationship: %1 Table Expression Expressão de Tabela - - Flags: SF FW AW VD - Sinalizadores: SF FW AW VD - Name Nome @@ -14928,137 +11160,64 @@ Relationship: %1 With no data - - - VisaoGeralWidget - - Model overview - Visão geral do modelo - - - - VisaoObjetosWidget - - Objects of Model - Objetos do Modelo - - - Visible Objects Type - Tipos de Objetos Visíveis - - - Select All - Marcar Todos - - - Clear All - Desmarcar Todos - - - Select - Selecionar - - - Cancel - Cancelar - - - Objects view configuration - Configuração da visão de objetos - - - Tree view - Visão em árvore - - - List view - Visão em lista - - - Object - Objeto - - - Type - Tipo - - - Parent Object - Objeto Pai - - - Parent Type - Tipo Pai - - - - VisaoWidget - - References - Referências - - Type: - Tipo: - - - Column - Coluna + The element will be used as part of the SELECT statement to retrieve columns or expressions that will compose the view's columns + - Expression - Expressão + SELECT ... + - Used in: - Usado em: + The element will be used as part of the WHERE clause in form of conditional expression + - After WHERE - Após WHERE + WHERE ... + - Table: - Tabela: + The element is used in the FROM portion of the command in order to reference tables or construct JOIN statements + - Table Alias: - Alias Tabela: + FROM ... + - Column: - Coluna: + The element's expression is used exclusively as the view's definition + - Column Alias: - Alias Coluna: + The element will be appended to the very end of the view's definition. This is useful when using GROUP BY/HAVING statements + - Expression: - Expressão: + End expression + - Expression Alias: - Alias Expressão: + Indexes + Índices - Code Preview - Previsão de Código + Flags: SF FW AW EX VD + - To reference all columns in a table (*) just do not fill the field <strong>Column</strong>, this is the same as write <em><strong>[schema].[tablel].*</strong></em> - Para se referenciar todas as colunas de uma tabela (*) basta não preencher o campo <strong>Coluna</strong>, isso é equivalente a se escrever <em><strong>[esquema].[tabela].*</strong></em> + To reference all columns in a table (*) just do not fill the field <strong>Column</strong>, this is the same as write <em><strong>[schema].[table].*</strong></em> + - -- Could not generate the code. Make sure all attributes are correctly filled! -- - -- Impossível gerar código. Verifique se todos os atributos foram preenchidos corretamente! -- + Indexing + Indexando WelcomeWidget Form - Formulário + Formulário New model diff --git a/lang/zh_CN.qm b/lang/zh_CN.qm index 45596b5ae3..aad7da52c4 100644 Binary files a/lang/zh_CN.qm and b/lang/zh_CN.qm differ diff --git a/lang/zh_CN.ts b/lang/zh_CN.ts index deba0c9869..c5c9a72669 100644 --- a/lang/zh_CN.ts +++ b/lang/zh_CN.ts @@ -1,61 +1,6 @@ - - AboutForm - - Version %1 - 版本 %1 - - - Close - 关闭 - - - PostgreSQL Database Modeler - PostgreSQL 数据库建模工具 - - - 0.0.0.0 - 0.0.0.0 - - - <html><head/><body><p><a href="http://pgmodeler.com.br"><span style=" font-size:11pt; font-style:italic; text-decoration: underline; color:#0057ae;">http://pgmodeler.com.br</span></a></p></body></html> - <html><head/><body><p><a href="http://pgmodeler.com.br"><span style=" font-size:11pt; font-style:italic; text-decoration: underline; color:#0057ae;">http://pgmodeler.com.br</span></a></p></body></html> - - - Copyright 2006-2012 - Raphael Araújo e Silva <rkhaotix@gmail.com> - -The pgModeler project is a CASE tool for modeling relational databases for PostgreSQL DBMS through the use of modeling techniques from entity-relationship diagrams as well merging concepts that PostgreSQL implements. - -Special thanks to friends of the software development team of the Legislative Assembly, Tocantins, Brazil: Michel de Almeida, Felipe Santana, Jonas Nepomuceno, Ricardo Ishibashi and Álvaro Nunes. - 版权所有 2006-2012 - Raphael Araújo e Silva <rkhaotix@gmail.com> - -pgModeler 项目是通过使用实体-关系图并结合 PostgreSQL 实现的相关理论概念,对 PostgreSQL DBMS 关系型数据库进行建模的 CASE 工具。 - -特别感谢巴西托坎廷斯立法大会软件开发团队的朋友们:Michel de Almeida,Felipe Santana,Jonas Nepomuceno,Ricardo Ishibashi 和 Álvaro Nunes。 - - - This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 3. - -This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - -The complete text of GPLv3 is at LICENSE file on source code root directory. Also, you can get the complete GNU General Public License at <http://www.gnu.org/licenses/> - 本软件是自由软件。你可以遵照自由软件基金会发布的 GNU 通用公共授权协议第三版本 (GPLv3) 所有条文来修改和重新发布这一程序。 - -发布这一程序的目的是希望它有用,但没有任何担保;亦无对适售性或特定目的适用性所为的默示性担保。详情请参照GNU通用公共授权。 - -GPLv3 的完整内容放在源代码根目录的 LICENSE 文件中。完整的 GNU 通用公共授权协议请见<http://www.gnu.org/licenses/> - - - About pgModeler - 关于 pgModeler - - - Design, configure, deploy - 设计, 配置, 部署 - - AboutWidget @@ -70,22 +15,10 @@ GPLv3 的完整内容放在源代码根目录的 LICENSE 文件中。完整的 G Open source data modeling tool designed for PostgreSQL. No more DDL commands written by hand, let pgModeler do the job for you! This software reunites the concepts of entity-relationship diagrams and the features that PostgreSQL implements as extensions of SQL standards. - - Design, configure, deploy - 设计, 配置, 部署 - - - <a href="http://pgmodeler.com.br">http://pgmodeler.com.br</a> - - pgModeler is proudly a brazilian software! - - <html><head/><body><p>Copyright 2006-2016 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.com.br</span></a>&gt;</p></body></html> - - Hide this widget @@ -94,18 +27,6 @@ GPLv3 的完整内容放在源代码根目录的 LICENSE 文件中。完整的 G ... - - 0.0.0.0 - 0.0.0.0 - - - (CODE_NAME) - - - - Build: - - (BUILD_NUM) @@ -115,139 +36,19 @@ GPLv3 的完整内容放在源代码根目录的 LICENSE 文件中。完整的 G - Contributors - - - - <html><head/><body><p>This page is dedicated to all contributors who gave a bit of their time in make pgModeler a better software somehow. The complete list of people that helped pgModeler can be found at <a href="https://github.com/pgmodeler/pgmodeler/graphs/contributors"><span style=" text-decoration: underline; color:#00a489;">GitHub</span></a>.</p><p>If you have a great idea to improve pgModeler please submit it <a href="http://github.com/pgmodeler/pgmodeler/issues"><span style=" text-decoration: underline; color:#00a489;">here</span></a>. No ideas for now but want to help? Why not donate a few bucks <a href="http://pgmodeler.com.br/#donate"><span style=" text-decoration: underline; color:#00a489;">here</span></a>!?</p></body></html> - - - - 1 - 1 - - - 2 - 2 - - - 3 - 3 - - - 4 - 4 - - - 5 - 5 - - - 6 - 6 - - - 7 - 7 - - - 8 - 8 - - - Name - 名称 - - - Country - - - - Contribution - - - - Damien Degois - - - - France - - - - French UI translation and several improvements in auxiliary scripts. - - - - Ji Bin - - - - China - - - - Chinese UI translation and small fixes. - - - - Pierre-Samuel LE STANG - - - - French UI translation. - - - - Lisandro Damián Nicanor - - - - Argentina - - - - Improvements on build scripts enabling the custom packaging in Linux distros; Per-user settings; pgModeler's package maintainer in Debian Linux. - - - - Pavel Alexeev - - - - Russia - - - - Additional work for packaging in Linux distros; pgModeler's package maintainer in Fedora Linux. - - - - Mariusz Fik - - - - Poland - - - - Custom packaging first ideas. Tester of first version of custom packaging patch. - - - - Jonathan DUPRE - + 0.0.0 + 0.0.0 - Gilberto Castillo + build: - Cuba + <html><head/><body><p><a href="http://pgmodeler.com.br"><span style=" text-decoration: underline; color:#2980b9;">https://pgmodeler.io</span></a></p></body></html> - Spanish UI translation. + <html><head/><body><p>Copyright 2006-2018 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.io</span></a>&gt;</p></body></html> @@ -257,18 +58,10 @@ GPLv3 的完整内容放在源代码根目录的 LICENSE 文件中。完整的 G Final Function: 最终处理函数: - - Transition Function: - 状态转换函数: - Sort Operator: 排序操作符: - - Final Condition: - 最终条件: - Funtion Inputs 函数输入 @@ -289,10 +82,6 @@ GPLv3 的完整内容放在源代码根目录的 LICENSE 文件中。完整的 G An aggregate function that accepts the types <em><strong>typeA</strong></em> and <em><strong>typeB</strong></em> as input types and which type of state is <em><strong>state_type</strong></em>, must obey the following rules: <br/><br/> <strong> &nbsp;&nbsp;&nbsp;• Final Function:</strong> <em>void final_function(<strong>state_type</strong>)</em><br/> <strong> &nbsp;&nbsp;&nbsp;• Transition Function:</strong> <em><strong>state_type</strong> transition_function(<strong>state_type</strong>, <strong>typeA</strong>, <strong>typeB</strong>)</em> 聚合函数接受类型 <em><strong>typeA</strong></em> 和 <em><strong>typeB</strong></em> 作为输入类型,并且类型状态为 <em><strong>state_type</strong></em>, 函数必须遵循如下规则:<br/><br/> <strong> &nbsp;&nbsp;&nbsp;•最终处理函数:</strong> <em>void final_function(<strong>state_type</strong>)</em><br/> <strong> &nbsp;&nbsp;&nbsp;• 过渡处理函数:</strong> <em><strong>state_type</strong> transition_function(<strong>state_type</strong>, <strong>typeA</strong>, <strong>typeB</strong>)</em> - - Form - Form - Initial Condition: @@ -484,18 +273,6 @@ GPLv3 的完整内容放在源代码根目录的 LICENSE 文件中。完整的 G Colors: 颜色: - - Font color / Fill color 1 - 字体颜色/填充颜色1 - - - Fill color 2 - 填充颜色2 - - - Border color - 边框颜色 - Underline 下划线 @@ -544,13 +321,17 @@ GPLv3 的完整内容放在源代码根目录的 LICENSE 文件中。完整的 G Placeholder: Body + + Constraint: Name + + + + Constraint: Descriptor + + Application - - Error - 错误 - Unknown exception caught! 捕捉到未知异常! @@ -560,6 +341,13 @@ GPLv3 的完整内容放在源代码根目录的 LICENSE 文件中。完整的 G + + BaseConfigWidget + + A backup of the previous settings was saved into <strong>%1</strong>! + + + BaseForm @@ -673,10 +461,6 @@ GPLv3 的完整内容放在源代码根目录的 LICENSE 文件中。完整的 G Database 数据库 - - Table-Table Relationship - 表-表关系 - Textbox 文本框 @@ -689,10 +473,6 @@ GPLv3 的完整内容放在源代码根目录的 LICENSE 文件中。完整的 G Parameter 参数 - - Table-View Relationship - 表-视图关系 - Collation @@ -727,6 +507,14 @@ GPLv3 的完整内容放在源代码根目录的 LICENSE 文件中。完整的 G Basic Relationship + + Policy + + + + Generic SQL + + BaseObjectView @@ -757,18 +545,10 @@ GPLv3 的完整内容放在源代码根目录的 LICENSE 文件中。完整的 G Schema: 模式: - - Permissions: - 权限: - This object is protected thus no change in form will be applied to it. 此对象处于受保护状态,无法对它应用任何修改。 - - Parent Object: - 父对象: - Value(s) @@ -777,26 +557,10 @@ GPLv3 的完整内容放在源代码根目录的 LICENSE 文件中。完整的 G Version 版本 - - The field(s) or value(s) highlighted on the form is(are) for the exclusive use and/or mandatory in specific versions of PostgreSQL. Failure to complete that may cause errors in the generation of SQL code for each version shown in tool tips of the highlighted fields. - 窗口中高亮显示的字段或值只能用于特定版本的 PostgreSQL。在生成高亮字段工具提示中显示的各版本 SQL 代码时可能会发生错误,导致无法完成操作。 - - - Form - Form - icone icone - - Criate / Edit: - 创建/修改: - - - Edit Permissions - 修改权限 - Edit permissions 编辑权限 @@ -846,6 +610,17 @@ This will disable the code of all child and referrer objects. + + BaseTableView + + Toggles the extended attributes display + + + + Connected rels: %1 + + + BugReportForm @@ -922,15 +697,14 @@ This will disable the code of all child and referrer objects. - CastWidget + BulkDataEditWidget - Conversion Type: - 转换类型: - - - Implicit - 隐式转换 + Bulk data edit + + + + CastWidget Assignment 强制转换 @@ -939,18 +713,10 @@ This will disable the code of all child and referrer objects. Input / Output 输入 / 输出 - - Conversion Function: - 转换函数: - The function to be assigned to a cast from <em><strong>typeA</strong></em> to <em><strong>typeB</strong></em> must have the following signature: <em><strong>typeB</strong> function(<strong>typeA</strong>, integer, boolean)</em>. 将<em><strong>类型 A</strong></em>转换成 <em><strong>类型 B</strong></em>的函数签名:<em><strong>typeB</strong> function(<strong>typeA</strong>, integer, boolean)</em>. - - Form - Form - Source data type 原始数据类型 @@ -978,10 +744,6 @@ This will disable the code of all child and referrer objects. CodeCompletionWidget - - Make persistent - - Makes the widget closable only by ESC key or mouse click on other controls. @@ -994,13 +756,13 @@ This will disable the code of all child and referrer objects. (no items found.) + + Make &persistent + + CollationWidget - - Form - Form - Locale: @@ -1052,23 +814,27 @@ This will disable the code of all child and referrer objects. 默认值: - Form - Form + E&xpression: + - Not Null: - 非空: + &NOT NULL + - E&xpression: + Se&quence: - &NOT NULL + Edit the underlying sequence's attributes - Se&quence: + Edit sequence + + + + Identity: @@ -1094,22 +860,10 @@ This will disable the code of all child and referrer objects. General 常规 - - Style - 样式 - - - Connetions - 连接 - Plug-ins 插件 - - Confirmation - 确认 - Any modification made until now in the current section will be lost! Do you really want to restore default settings? 当前部分所做的修改将会丢失!要恢复到默认设置吗? @@ -1130,6 +884,14 @@ This will disable the code of all child and referrer objects. Snippets + + In some cases restore the default settings related to it may solve the problem. Would like to do that? + + + + Restore + + ConnectionsConfigWidget @@ -1209,18 +971,10 @@ This will disable the code of all child and referrer objects. Revoked Certs.: 已吊销证书: - - Kerberus Server: - Kerberus 服务器: - Force GSSAPI 强制 GSSAPI - - Options: - 选项: - Add 新建 @@ -1233,10 +987,6 @@ This will disable the code of all child and referrer objects. Test 测试 - - Form - Form - Delete selected connection 删除选中的连接 @@ -1269,10 +1019,6 @@ This will disable the code of all child and referrer objects. Success 成功 - - Connection successfuly stablished! - 成功建立连接! - Edit database connections @@ -1333,16 +1079,6 @@ This will disable the code of all child and referrer objects. Indicates in which operations (diff, export, import or validation) the connection is used if none is explicitly specified by the user. - - Connection successfuly stablished! - -Server details: - -PID: `%1' -Protocol: `%2' -Version: `%3' - - There is a connection being created or edited! Do you want to save it? @@ -1359,6 +1095,16 @@ Version: `%3' Edit connections + + Connection successfully established! + +Server details: + +PID: `%1' +Protocol: `%2' +Version: `%3' + + ConstraintWidget @@ -1366,18 +1112,10 @@ Version: `%3' Constraint Type: 约束类型: - - Check Expr.: - 检查表达式: - Fill Factor: 填充因子: - - Comparison: - 比较: - Deferrable: 可延迟: @@ -1410,10 +1148,6 @@ Version: `%3' Type 类型 - - Form - Form - ON DELETE: ON DELETE: @@ -1422,10 +1156,6 @@ Version: `%3' ON UPDATE: ON UPDATE: - - Columns which were included by relationship can not be added / removed manually from the primary key. If done such changes they will be ignored. To create primary key using columns included by relationship use the feature attributes, constraints and primary key on the relationship form. - 包含在关系中的列不能被手动添加/删除主键。这样的操作会被忽略。要将关系中的列创建为主键,请使用“创建/编辑:关系”窗口中的特征属性和主键约束。 - Match: @@ -1465,10 +1195,6 @@ Version: `%3' Target Encoding: 目标编码: - - Conversion Function: - 转换函数: - Default Conversion: 默认转换: @@ -1477,136 +1203,142 @@ Version: `%3' The function to be assigned to an encoding conversion must have the following signature: <em>void function(integer, integer, cstring, internal, integer)</em>. 编码转换的函数签名:<em>void function(integer, integer, cstring, internal, integer)</em>。 - - Form - Form - Conversion Func.: - CrashHandler + CrashHandlerForm - pgModeler Crash Handler - pgModeler 故障处理程序 + Crash Handler + - Oops! pgModeler just crashed! - 糟糕!pgModeler 崩溃了! + Stack trace + 堆栈跟踪信息 - Create - 创建 + Input: + - &Cancel - 取消(&C) + Load report file for analysis + - We apologize for what happened! It is clear that a nasty bug caused it. Please fill out the form below describing your actions before pgModeler quit unexpectedly. This will help on bug extermination and improve the software. - 我们为此深表歉意!显然,这是由讨厌的 bug 引起的。请描述一下在 pgModule 意外退出前你所做过的操作,并填写在下面的输入框内。这些将有助于我们错误的消除和软件的改进。 + Save the attached model file on the filesystem + - Report - 报告 + pgModeler bug report (*.bug);;All files (*.*) + - Actions made before the crash: - 崩溃前的操作: + Load report + - Loaded Model - 已打开的模型 + Save model + 保存模型 - Attach the below database model file that possibly generates the crash. - 附上可能导致软件崩溃的数据库模型文件。 + Database model (*.dbm);;All files (*.*) + 数据库模型 (*.dbm);; 所有文件 (*.*) - Stack trace - 堆栈跟踪信息 + Crash handler + - pgModeler crash file analysis - pgModeler 崩溃文件分析 + Bug report analysis mode activated. + - Error - 错误 + Oops! pgModeler just crashed! + 糟糕!pgModeler 崩溃了! - File: %1 -Size: %2 bytes - - - 文件: %1 -大小: %2 bytes - - + We apologize for what happened! It is clear that a nasty bug caused that. Please fill out the form below describing your actions before pgModeler quit unexpectedly. This will help on bug extermination and improve the software. + + + + CsvLoadWidget - Information - 信息 + Form + Form - Crash report successfuly generated! Please send the file '%1' to %2 in order be debugged. Thank you for the collaboration! - 成功生成故障报告!请将文件 ‘%1' 发送到 %2,以便用于调试。感谢您的合作! + Load CSV + - - - CrashHandlerForm - Crash Handler + CSV File: - Stack trace - 堆栈跟踪信息 + Select output file + - Input: + ... - Load report file for analysis + Separator: - Save the attached model file on the filesystem + Use the first row as column names in the CSV file. By unchecking this option the first row is used as data. - pgModeler bug report (*.bug);;All files (*.*) + Columns in the first row - Load report + Load + 打开 + + + Semicolon (;) - Save model - 保存模型 + Comma (,) + - Database model (*.dbm);;All files (*.*) - 数据库模型 (*.dbm);; 所有文件 (*.*) + Space + Space - Crash handler + Tabulation - Bug report analysis mode activated. + Other - Oops! pgModeler just crashed! - 糟糕!pgModeler 崩溃了! + ; + - We apologize for what happened! It is clear that a nasty bug caused that. Please fill out the form below describing your actions before pgModeler quit unexpectedly. This will help on bug extermination and improve the software. + Text delimiter: + + + + " + + + + Load CSV file + + + + Comma-separted values (*.csv);;All files (*.*) @@ -1681,10 +1413,6 @@ Unchecking this will cause the SQL to be appended at the end of CREATE DATABASE <html><head/><body><p>Use custom commands with extreme caution because you can change the semantics of the entire model when running SQL validation or export processes. Additionally, depending on the amount of commands, those processes can have their performance sensibly degradated.</p></body></html> - - Type: - 类型: - Generic INSERT @@ -1732,18 +1460,10 @@ Unchecking this will cause the SQL to be appended at the end of CREATE DATABASE &Close 关闭(&C) - - <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in <span style=" font-weight:600;">{}</span>. To use <span style=" font-weight:600;">{</span> or <span style=" font-weight:600;">}</span> as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\{</span> or <span style=" font-weight:600;">\}</span>.</p></body></html> - - Refresh listing - - Refresh - - F5 F5 @@ -1752,34 +1472,14 @@ Unchecking this will cause the SQL to be appended at the end of CREATE DATABASE Save changes - - Save - 保存 - Ctrl+S Ctrl+S - - Copy the selection as CSV buffer - - - - Copy - 复制 - - - Ctrl+C - - Export results to CSV file - - Export - 导出 - Ctrl+X @@ -1788,10 +1488,6 @@ Unchecking this will cause the SQL to be appended at the end of CREATE DATABASE Undo modifications - - Undo - 撤销 - Ctrl+Z Ctrl+Z @@ -1800,10 +1496,6 @@ Unchecking this will cause the SQL to be appended at the end of CREATE DATABASE Add empty rows - - Add - 新建 - Ins Ins @@ -1812,10 +1504,6 @@ Unchecking this will cause the SQL to be appended at the end of CREATE DATABASE Mark the selected rows to be deleted - - Delete - 删除 - Del Del @@ -1824,10 +1512,6 @@ Unchecking this will cause the SQL to be appended at the end of CREATE DATABASE Duplicate the selected rows - - Duplicate - - Ctrl+D @@ -1968,29 +1652,93 @@ Unchecking this will cause the SQL to be appended at the end of CREATE DATABASE insert - - - DatabaseExplorerWidget - Form - Form + <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in two slashes, e.g., <span style=" font-weight:600;">/value/</span>. To use a slash as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\/</span>.</p></body></html> + - Toggles the display of system objects. + Copy items on the grid - System + Paste items on the grid - Toggles the display of extension objects + Ctrl+V - Extension + Browse referenced tables + + + + Change the values of all selected cells at once + + + + Ctrl+E + + + + Add new rows from a CSV file + + + + Copy as CSV + + + + Copy as text + + + + Copy items + + + + Pase items + + + + Browse tables + + Duplicate row(s) + + + + Delete row(s) + + + + Edit cell(s) + + + + Column + + + + Referenced tables + + + + (none) + + + + Referrer tables + + + + + DatabaseExplorerWidget + + Form + Form + Open the grid to visualize or edit data @@ -2019,10 +1767,6 @@ Unchecking this will cause the SQL to be appended at the end of CREATE DATABASE Update the objects tree - - Ctrl+S - Ctrl+S - Drop this database @@ -2761,131 +2505,251 @@ Ref. column(s): %2 -- Source code unavailable for the object %1 (%2). -- - - - DatabaseImportForm - Database Import + Toggle the display of filter widget as well the system/extension objects. - Database import + Sort items alphabetically. When unchecked, items are sorted by OID. - Settings + Sort alphabetically - Options + Client encoding - Connection: - 连接: + Configuration file + - Origin point: + Data directory - Starting point where objects will be put. + Dynamic library path - Tables per row: + Dynamic shared memory - Tables per row + Hba file - Spacing: + Listen addresses - Schemas per row + Max. connections - Spacing between objects + Listen port - Schemas per row: + Server encoding - Resolve some of the object's dependencies by querying the catalog when a needed object does not exists on the loaded set. In some cases it's necessary to combine this option with others below. This option does not applies to database level objects like role, tablespace and language as well for data types, extensions. + SSL - Automatically resolve dependencies + SSL ca file - Random colors will be assigned to imported relationships facilitating the identification of links between tables mainly in large models. + SSL cert file - Random colors for relationships + SSL crl file - Enables the import of system built-in objects. It's recommend to select only those objects that are directly referenced by the ones to be imported. WARNING: Try to import a huge set of system objects can bloat the resultant model or even crash pgModeler due to memory/cpu overuse. + SSL key file - Import system objects + Server version - Enables the import of objects created by extensions. Generally there is no need to check this option but if there are objects in the database that directly references this category of objects this mode must be enabled. + Ident file - Import extension objects + Password encryption - pgModeler ignores import errors and will try to create as many as possible objects. By checking this option the import operation will be not aborted but an incomplete model will be constructed. This option generates a log file on pgModeler's temp directory. + Connection ID - Ignore import errors + Server PID - All catalog queries as well the created objects' source code are printed to standard output (stdout). + Server protocol - Debug mode + Referrers - Create all imported objects in the current working model instead of create a new one. + Identity - Import objects to the working model + Command - Database - 数据库 + USING expr. + - Filter: + CHECK expr. - Filter object by it's OID - + Roles + 角色 - By OID + RLS enabled + + + + RLS forced + + + + Show objects filter + + + + Show system objects + + + + Show extension objects + + + + -- Source code unavailable for this kind of object -- + + + + Also restart sequences + + + + Warning + + + + You're running a demonstration version! The data manipulation feature is available only in the full version! + + + + <strong>CAUTION:</strong> You are about to drop the entire database <strong>%1</strong>! All data will be completely wiped out. Do you really want to proceed? + + + + + DatabaseImportForm + + Settings + + + + Options + + + + Connection: + 连接: + + + Resolve some of the object's dependencies by querying the catalog when a needed object does not exists on the loaded set. In some cases it's necessary to combine this option with others below. This option does not applies to database level objects like role, tablespace and language as well for data types, extensions. + + + + Automatically resolve dependencies + + + + Random colors will be assigned to imported relationships facilitating the identification of links between tables mainly in large models. + + + + Random colors for relationships + + + + Enables the import of system built-in objects. It's recommend to select only those objects that are directly referenced by the ones to be imported. WARNING: Try to import a huge set of system objects can bloat the resultant model or even crash pgModeler due to memory/cpu overuse. + + + + Import system objects + + + + Enables the import of objects created by extensions. Generally there is no need to check this option but if there are objects in the database that directly references this category of objects this mode must be enabled. + + + + Import extension objects + + + + pgModeler ignores import errors and will try to create as many as possible objects. By checking this option the import operation will be not aborted but an incomplete model will be constructed. This option generates a log file on pgModeler's temp directory. + + + + Ignore import errors + + + + All catalog queries as well the created objects' source code are printed to standard output (stdout). + + + + Debug mode + + + + Create all imported objects in the current working model instead of create a new one. + + + + Import objects to the working model + + + + Database + 数据库 + + + Filter: + + + + Filter object by it's OID + + + + By OID @@ -2965,15 +2829,19 @@ Ref. column(s): %2 - Retrieving objects of table `%1'... + This is a PostgreSQL built-in data type and cannot be imported. - This is a PostgreSQL built-in data type and cannot be imported. + This is a pgModeler's built-in object. It will be ignored if checked by user. - This is a pgModeler's built-in object. It will be ignored if checked by user. + Import database + + + + Retrieving objects of `%1' (%2)... @@ -2991,10 +2859,6 @@ Ref. column(s): %2 Creating object `%1' (%2)... - - Trying to recreate object `%1' (%2)... - - Import failed to recreate some objects in `%1' tries. @@ -3031,17 +2895,17 @@ Ref. column(s): %2 Assigning sequences to columns... - - - DatabaseModel - Loading object: %1 (%2) - 正在载入对象:%1 (%2) + Creating object `%1' (%2), oid `%3'... + - Generating %1 of the object: %2 (%3) - 正在生成对象的 %1:%2 (%3) + Trying to recreate object `%1' (%2), oid `%3'... + + + + DatabaseModel The demonstration version can create only `%1' instances of each object type! You've reach this limit for the type: `%2' @@ -3054,10 +2918,6 @@ Ref. column(s): %2 Validating relationships... - - Generating %1 of the object `%2' (%3) - - Saving object `%1' (%2) @@ -3094,6 +2954,10 @@ Ref. column(s): %2 Metadata file successfully loaded! + + Generating %1 code: `%2' (%3) + + DatabaseWidget @@ -3113,10 +2977,6 @@ Ref. column(s): %2 Default 默认 - - Form - Form - Template DB: 数据库模板: @@ -3161,6 +3021,18 @@ Ref. column(s): %2 Use the above fields to specify the default attributes assigned to new objects created on the database model. Leaving a field empty will cause PostgreSQL to use the default values when exporting the model. + + Options: + 选项: + + + Allow connections + + + + Is template + + DomainWidget @@ -3169,32 +3041,32 @@ Ref. column(s): %2 默认值: - Constraint Name: - 约束名称: + Name: + 名称: - Check Expression: - 检查表达式: + Attributes + 属性 - Form - Form + Not null + - Not Null: - 非空: + Check constraints + - Constraint - 约束 + Expression: + - Name: - 名称: + Name + 名称 - Check Expr.: - 检查表达式: + Expression + 表达式 @@ -3332,18 +3204,10 @@ Ref. column(s): %2 Exception - - Insufficient memory space to allocate the object! - 内存不足,无法分配对象! - Assignment of a pseudo-type to the type of the column! 列类型不能为伪类型! - - Zero length assignment! - 长度不能为 0! - Assignment of a precision greater than the length of the type! 精度不能大于类型长度! @@ -3352,10 +3216,6 @@ Ref. column(s): %2 Assignment of an invalid precision to type time, timestamp or interval. The precision in this case must be equal to or less than 6! 类型 time,timestamp 或 interval 的精度设置无效。精度必须小于等于 6! - - Assignment of a not allocated column to object '%1' (%2)! - 必须给对象'%1' (%2) 设置列! - Reference to a column which index is out of the capacity of the column list! 不能引用不在列列表中的列! @@ -3364,26 +3224,6 @@ Ref. column(s): %2 Assignment of not allocated object! 必须设置对象! - - Assignment of a not allocated schema to object '%1' (%2)! - 必须给对象 '%1' (%2) 设置模式! - - - The object '%1' (%2) has inconsistent configuration (invalid SQL/XML definition)! - 对象 '%1' (%2) 设置冲突 (无效的 SQL/XML 定义)! - - - The object '%1' (%2) already exists in the list of elements of the same type in the object '%3' (%4)! - 对象 '%1' (%2) 已经存在于对象 '%3' (%4) 的同类型元素列表中! - - - The object '%1' (%2) can't be assigned because there is already exists in the container object '%3'! - 对象 '%1' (%2) 不能被赋值,因其已存在于容器对象 '%3'! - - - Assignment of object of an invalid type! - 设置的对象无效! - Removing an object of an invalid type! 不能移除无效类型的对象! @@ -3396,62 +3236,18 @@ Ref. column(s): %2 Assignment of empty name to table return type! 表的返回值类型的名称不能为空! - - The insertion of the parameter '%1' will not be possible because there is another parameter with same name in the function '%2'! - 无法插入参数 '%1',因为函数 '%2' 中已经存在一个相同名称的参数了! - - - The insertion of the table return type '%1' will not be possible because there is another return type with the same name in the '%2'! - 无法插入表返回类型 '%1',因为在 '%2' 中已经存在一个相同名称的返回类型! - - - Reference to a parameter which index is out of the parameter list capacity! - 不能引用不在参数列表中的参数! - Reference to an event which does not belongs to trigger! 不能引用不属于触发器的事件! - - The column '%1' can't be assigned to the trigger '%2' because does not belongs to the trigger parent table! - 列 '%1' 无法赋值给触发器 '%2',因为它不属于触发器父表! - - - Assignment of a not allocated function to object '%1' (%2)! - 必须给对象 '%1' (%2) 设置函数! - - - Assignment of a function which return type is different from 'trigger'! - 函数的返回值类型与‘触发器’的不一致! - - - Assignment of a function which parameter count is invalid to the object '%1' (%2)! - 对于对象 '%1' (%2),函数的参数数目不匹配! - Assignment of a function which language is invalid! 语言转换函数无效! - - Assignment of not allocated table to object '%1' (%2)! - 必须给对象 '%1'(%2) 设置表! - - - Reference to an argument which index is out of argument list capacity! - 引用的参数超出参数列表范围! - - - Insertion of a column which name is already registered to another column of the object! - 要插入的列名称已经被注册给了另一个列的对象! - Assignment of empty name to an object! 对象名称不能为空! - - Assignment of invalid name to an object! - 对象名称无效! - Assignment of schema object which type is invalid! 模式对象类型无效! @@ -3488,42 +3284,10 @@ Ref. column(s): %2 Reference to an operator with invalid type! 引用了无效的操作符类型! - - Assigment of value to an invalid option type on role! - 角色选项值的类型无效! - Reference to an invalid role type! 引用了无效的角色类型! - - The insertion of the role '%1' is not possible because this is already being referenced by role '%2'! - 无法插件角色 '%1',因为它已经被角色 '%2' 引用了! - - - Reference redundance detected by having the role '%1' referencing the role '%2'! - 发现角色 '%1' 到角色 '%2' 的引用冗余! - - - The role '%1' can not be listed as a member of itself! - 角色 '%1' 不能列入自身的成员中! - - - Reference to a paper which index is out of paper list capacity! - 纸型引用超出纸型列表范围! - - - Insertion of null command to the rule! - 不能规则插入空命令! - - - Reference to a command which index is out of the command list capacity! - 引用的命令超出命令列表范围! - - - Is not possible to create a self generalization/dependecy relationship! The table can not inherit or copy their own attributes! - 无法创建自身泛化的关系/自身依赖的关系!表不能继承或复制自身的属性! - Assignment of an object that already belongs to another table! 对象已属于另一个表! @@ -3540,10 +3304,6 @@ Ref. column(s): %2 Assignment of a minimum value to the sequence which is greater than the maximum value! 序列的最小值大于其最大值! - - Assignment of a start value to the sequence which is extrapolating the range defined by minimum and maximum values​​! - 序列的起始值不在序列的最小值与最大值的范围内! - Assignment of a null increment value to the sequence! 不能给序列设置空的自增值! @@ -3552,38 +3312,10 @@ Ref. column(s): %2 Assignment of null cache value to the sequence! 序列缓冲值不能为空! - - Assignment of owner table which is not in the same schema as the sequence '%1'! - 表与序列 '%1' 不在同一模式中! - - - Assignment of owner table which does not belong to the same owner of the sequence '%1'! - 表与序列 '%1' 的所有者不同! - - - Assignment of a nonexistent owner column to the sequence '%1'! - 序列 '%1' 的列不存在! - - - Assignment of an owner column to the sequence '%1' that is not related to any table! - 序列 '%1' 的列未关联到任何表! - - - Reference to a label which index is out of labels list capacity! - 引用的标签不在标签列表的范围内! - Allocation of object with invalid type! 不能创建类型无效的对象! - - Assignment of a function with invalid return type to object '%1' (%2)! - 对象 '%1'(%2) 函数的返回类型无效! - - - Assignment of a function with invalid parameter(s) type(s) to object '%1' (%2)! - 对象 '%1'(%2) 函数的参数类型无效! - Assignment of not allocated language! 没有指定语言! @@ -3596,18 +3328,10 @@ Ref. column(s): %2 Reference to data type with an index outside the capacity of data types list! 引用的数据类型不在数据类型列表的范围内! - - Assignment of a null type to to object '%1' (%2)! - 对象 '%1'(%2) 类型不能为空! - Assignment of invalid type to the object! 对象的类型无效! - - Assignment of an empty directory to object '%1' (%2)! - 对象 '%1'(%2) 的目录不能为空! - Obtaining types with invalid quantity! 正确获取的类型的数量无效! @@ -3628,69 +3352,21 @@ Ref. column(s): %2 Insertion of invalid item in the enumerations list of the type! 插入类型枚举列表的项目无效! - - Reference to an attribute which index is out of the attributes list capacity! - 引用的属性超出属性列表的范围! - - - Reference to an enumeration which index is out of the enumerations list capacity! - 引用的枚举值超出枚举值列表的范围! - Assignment of invalid configuration to the type! 类型的配置无效! - The data type '%1' can not be assigned because it already exists in the types list of the aggregate function '%2'! - 无法指派数据类型 '%1',因其已存在于聚合函数 '%2' 的类型列表! + Assignment of an invalid strategy/support number to an operator class element! + 操作符类元素的策略/支持值无效! - Assignment of an operator which input type count is invalid to aggregate function! - 聚合函数的操作符输入类型的数目无效! + Insertion of element which already exists in the element list! + 插入的元素已存在于元素列表! - Assigment of an operator which types of arguments is invalid! - 操作符的参数类型无效! - - - Assignment of system reserved name to the object '%1' (%2)! - 对象 '%1'(%2) 使用了系统保留名称! - - - One function with invalid configuration is been used by the object '%1' (%2)! - 用于对象 '%1'(%2) 的函数的配置无效! - - - Assignment of invalid id to the user! - 无效的用户ID! - - - Assignment of an invalid strategy/support number to an operator class element! - 操作符类元素的策略/支持值无效! - - - Insertion of element which already exists in the element list! - 插入的元素已存在于元素列表! - - - Reference to an element which index is out of element list capacity! - 引用的元素不在元素列表的范围内! - - - Reference to an object which index is out of object list capacity! - 引用的对象不在对象列表的范围内! - - - Removal of an object not allocated! - 不能移除未分配的对象! - - - The object '%1' (%2) can not be removed because it is being referenced by object '%3' (%4)! - 无法移除对象 '%1'(%2),因其被对象 '%3'(%4) 引用了! - - - The object '%1' (%2) can not be removed because it is being referenced by object '%3' (%4) that belongs to '%5' (%6)! - 无法移除对象 '%1'(%2),因其已被对象 '%5'(%6) 中的对象 '%3'(%4) 引用了! + Removal of an object not allocated! + 不能移除未分配的对象! Operation with object(s) which type(s) is invalid! @@ -3704,10 +3380,6 @@ Ref. column(s): %2 Operation with object not allocated! 无法操作未分配的对象! - - The creation of the relationship '%1' between the table '%2' and '%3' can not be done because one does not have a primary key. If the relationship is of the type n-n both tables must have primary keys! - 无法创建关系 '%1',因为表 '%2' 或表 '%3' 缺少主键。如果创建的是 N-N 关系,则两个表都必须有主键! - The relationship of the type 1-1 where both tables are mandatory participation is not implemented because it requires fusion between the tables that breaks the modeling done by the user! 强制执行两表 1-1 关系的功能尚未实现,因为它结合模型中由用户定义的两人互相分离的表! @@ -3720,30 +3392,10 @@ Ref. column(s): %2 Assignment of a primary key to a table which already has one! 表的主键已存在! - - Identifier relationship can not be created for a self relationship, relationships of the type n-n, dependency or generalization! - 不能给自引用关系,N-N 类型关系,依赖关系或泛化关系创建标识符关系! - - - Unable to create a dependency relationship because the column '%1' in table '%2' already exists in table '%3'! - 无法创建依赖关系,因为表 '%2'中的列 '%1' 已经存在于表 '%3'! - - - Unable to create the generalization relationship because the column '%1' in table '%2' can not be merged with the column '%3' of table '%4' because they have incompatible types! - 无法创建泛化关系,因为表 '%2' 中的列 '%1' 不能被合并到表 '%4' 中的列 '%3',因为他们的类型不兼容! - - - An attribute can not be added to a dependence or generalization relationship! - 属性无法添加到依赖关系或者泛化关系中! - A foreign key can not be added to a relationship because is created automatically when this is connected! 无法给关系添加外键,因为在连接时已经自动添加了! - - The object '%1' (%2) is referencing the object '%3' (%4) which was not found in the list of objects of the same type in the model! - 对象 '%1'(%2) 所引用的对象 '%3'(%4) 不存在于模型中同类型的对象列表! - Reference to an user-defined data type that not exists in the model! 引用的用户自定义类型不存在于模型! @@ -3752,166 +3404,30 @@ Ref. column(s): %2 Assignment of invalid maximum size to operation list! 操作列表的最大值无效! - - Unable to write the file %1! Make sure the directory exists, or if the user has access permissions on it! - 无法写入文件 %1!请确保该目录存在,或者检查用户是否具有访问权限! - - - Unable to write the model in the file %1 due to one or more errors in the definition generation process! - 无法保存模式到文件 %1,因为在定义生成过程中出现一个或多个错误! - - - There is already a relationship between '%1' (%2) and '%3' (%4) in the model! - 模型中已存在 '%1'(%2) 和 '%3'(%4) 的关系! - - - The configuration of the relationship '%1' generates a redundancy between the relationships '%2'. Redundancy on identifier or generalization/dependency relationships are not accepted since they result in incorrect column spreading making the model inconsistent! - 关系 “%1”的配置产生了一个在关系'%2' 中的冗余。标识符或者泛化 / 依赖关系不支持冗余,因为他们会生成错误的列从而导致模型错误! - One or more objects were invalidated and automatically removed because they were referencing table columns which were included through relationships and which no longer exists due to disconnection of relationships or exclusion of such generated columns! 一个或者多个对象无效,并自动删除了。因为他们引用的表列所在的关系已经不存在了,由于连接中断或者排除生成的列! - - The primary key '%1' can only be allocated if declared within a block of code that defines a table or relationship! - 主键 '%1' 只有在表或关系定义的代码块中声明之后才可以被分配! - Reference to an invalid privilege type! 引用了无效的权限类型! - - Insertion of an role which already exists in the role list of the permission! - 插入的角色已存在于权限角色列表! - Assignment of privilege incompatible with the type of object referenced by permission! 权限与被允许引用的对象的类型不一致! - - There is already a permission on object '%1' (%2) which has one or more equal roles from those present on permission to be assigned to the object! - 对象 '%1'(%2) 已经有一个权限,分配给此对象权限的角色中有一个或多个功能相当的角色! - - - A permission is referencing the object '%1' (%2) which was not found in the model! - 权限所引用的对象 '%1'(%2) 不存在模型中! - - - The object '%1' (%2) can not be created by not being assigned to any schema! - 无法创建对象 '%1'(%2),因为还没有给它指定模式! - - - The tablespace '%1' can not be inserted into the model because it points to the same directory as the tablespace '%2'! - 表空间 '%1' 无法被加到模型中。因为它指向的目录和表空间 '%2' 的相同! - It is not possible to create arrays of domains or sequences (dimension >= 1)! PostgreSQL does not yet implement this feature! 无法创建维数 > = 1域或序列数组!PostgreSQL 尚未实现此功能! - - The function '%1' can not get a source code as a definition because its language is set to C. Use the attributes symbol and dynamic library instead! - 函数 '%1' 无法获取定义的源代码,因为它的语言被设成了 C 语言。请使用属性号和动态库代替! - - - The function '%1' can have the attributes symbol and dynamic library configured only if the language is set to C. For all other cases you must specify a source code that defines it in the DBMS! - 函数 '%1'只有当语言被设置成 C 语言时,才需要属性符号和动态库配置。其他情况下,您必须在 DBMS 中定义它的源代码! - - - The operator '%1' can not be assigned as a comutator of operator '%2' because it has incompatible settings! - 操作符 '%1' 不能被设置成操作符 '%2' 的转接器,因为两者的设置不兼容! - - - The operator '%1' can not be assigned as negator of operator '%2' because it has incompatible settings! - 操作符 '%1' 不能被设置成操作符 '%2' 的否定操作符,因为两者的设置不兼容! - - - The type '%1' can not self refer in the attributes 'element' or 'copy type' or be used as a data type of an attribute in the configuration of a composite type! - 类型 '%1' 不能对'元素’或'复制类型'进行自引用,或被用作组合类型配置中属性的数据类型! - - - Assignment of invalid element to type '%1'! - 指派给类型 '%1' 的元素无效! - - - Assignment of invalid alignment to type '%1'! - 指派了无效的对齐给类型 ‘%1'! - Assignment of invalid name to the table generated from N-N relationship! 分配无效名称给由 N-N 关系生成的表! - - The relationship '%1' can not make use of the special primary key. Only generalization/dependency relationships have access to this resource! - 关系 '%1' 无法使用特殊主键。只有泛化 / 依赖关系才能! - - - Assignment of invalid suffix to the relationship '%1'! - 分配无效前缀给关系 '%1'! - - - The object '%1' (%2) can not be edited or deleted because it was automatically included through a relationship! To manipulate the object is necessary to make it from the edit form of the relationship that holds it. - 无法修改或删除对象 '%1'(%2),因为它已经被关系自动包含了!要修改对象请到对应的关系修改窗口中操作。 - - - The object '%1' (%2) can not be deleted because it is protected! - 无法删除对象 '%1'(%2),因为它是被保护的! - - - The group '%1' has already been declared earlier! - 组 '%1'已经声明过了! - - - The group '%1' can not be built in the groups declaration block ('%2')! - 组 '%1'无法在组声明区域 (%2) 中构建! - - - The group '%1' was built but not declared in the groups declaration block ('%2')! - 组 '%1'已被构建,但是不是在组声明区域 (%2) 中声明的! - - - The group '%1' can not be built without possessing child elements! - 无法构建组 '%1',因为没有子元素! - - - The group '%1' can not be built once more because this was done in previous blocks! - 无法重新构建组 '%1',因为之前已经做过了! - - - The group '%1' has been declared but not built! - 组 '%1' 已经声明,但是没构建! - - - Reference to a column of objects table with invalid index! - 请参考索引无效的对象表中的一列! - - - Reference to a row of objects table with invalid index! - 请参考索引无效的对象表中的一行! - - - The schema public and the languages plpgsql, c and sql can not be manipulated because they are reserved to PostgreSQL! They are present in the model database only as a reference! - 模式 public 和语言 plpgsql,C,SQL 都无法修改,因为它们是系统保留的!它们在模型数据库中只是一个参考! - - - The new configuration function invalidates the object '%1' (%2)! In this case it is needed to undo the relationship between the affected object and function so that the new configuration of the latter to take effect! - 新的配置函数使对象 '%1'(%2) 无效!在这种情况下,需要重新配置下对象与函数的关系,然后,新的配置就会起作用了! - - - A vision reference must have at least one SQL application : SELECT, FROM, FROM-WHERE or After WHERE! - 一个视图引用必须至少有一个 SQL 应用:SELECT,FROM,FROM-WHERE 或者 WHERE 后! - Constraints like primary key, foreign key or unique must have at least one column related to them! For foreign keys must be selected, in addition, the referenced columns! 主键,外键,唯一键等约束必须有至少一列来关联他们!对于外键约束引用列必须被选中! - - Unable to load one or more configuration files! Please check if files exists in the configuration folder and if they are not corrupted to preventing this error to occur again on the next startup! - 无法载入一个或多少配置文件!请检查文件是否存在配置目录中或者文件错误来防止错误继续在下一次启动中发生! - - - Could not find the default settings file '%1'! To restore default settings check the existence of the file and try again! - 没有发现默认的配置文件 '%1'!重新保存默认设置到文件中! - The export process failed due to an error triggered by the PostgreSQL server in an attempt to execute a SQL command. For more details about the error check the exception stack! @@ -3924,42 +3440,14 @@ Ref. column(s): %2 %1 - - Could not load the plugin '%1' from the library '%2'! Message returned by plugin manager: '%3' - 无法从库 '%2' 中加载插件 '%1'!插件管理器的返回信息:'%3' - One or more plugins were not activated due to errors during the loading process! Check the exception stack for more details. 插件加载发生错误,一个或多个插件没有激活!详情请查看异常信息。 - - Invalid syntax in file %1, line %2, column %3! - 错误语法位于文件 %1,行 %2,列 %3 有! - - - Invalid conditional instruction '%1' on file %2, line %3, column %4! - 错误的条件结构 '%1' 位于文件 %2,行 %3,列 %4! - - - Unknown attribute '%1' in file %2, line %3, column %4! - 未知属性 '%1' 位于文件 %2,行 %3,列 %4! - - - Invalid metacharacter '%1' in file %2, line %3, column %4! - 错误的字符 '%1' 位于文件 %2,行 %3,列 %4! - - - Attribute '%1' with an undefined value in file %2, line %3, column %4! - 未赋值的属性 '%1' 位于文件 %2,行 %3,列 %4! - Assignment of empty XML buffer to parser! 分配空白 XML 缓存给解析器! - - Could not access the file or directory %1! Make sure that it exists or if the user has access permissions on it! - 无法访问文件或目录 %1!请确保它存在,或者检查用户具有访问权限! - Assignment of empty DTD file name! 分配一个空 DTD 文件名! @@ -3968,19 +3456,10 @@ Ref. column(s): %2 Assignment of empty name to the DTD declaration! 分配空白名称给 DTD 声明! - - Error while interpreting XML buffer at line %1 column %2. -Message generated by the parser: '%3'. %4 - 解析 XML 缓存发生错误,错误位于行 %1 列 %2。解析器生成的消息:'%3'。%4 - Operation on unallocated element tree! It is necessary to load the XML parser buffer and interpret it so that the tree is generated! 操作在未分配的元素树上!必须要先载入 XML 解析器缓存并执行解析,这样树才能生成! - - Could not load file %1. The same appears to be inconsistent or one of its dependencies (DTD files) has errors or is missing! - 无法载入文件 %1。它出现了不一致性或其中有的依赖项出现错误或已经丢失! - Operation with unallocated tree element! 操作在未分配的树元素上! @@ -4001,12 +3480,6 @@ Message generated by the parser: '%3'. %4 Attempt to connect without define configuration parameters! 尝试没有定义配置参数的连接! - - Could not connect to the database. -Message returned: '%1' - 无法连接数据库。 -返回的信息:'%1' - Assignment of not allocated SQL command result! 指定的 SQL 命令结果不存在! @@ -4015,15 +3488,6 @@ Message returned: '%1' Unable to allocate the result of the SQL command because the response from the DBMS was not understood by the client! 无法获得 SQL 命令结果,因为服务器端的反馈客户端无法识别! - - Unable to allocate command result for the SQL because the server has generated a fatal error! -Message returned by the DBMS: %1 - 无法获取 SQL 的命令结果,因为服务端产生了严重错误!数据库服务器返回的信息:%1 - - - Unable to allocate the result of the SQL command because the command passed was an empty SQL! - 无法获取 SQL 命令的结果,因为命令是一条空 SQL! - Reference to a column of tuple with invalid index! 引用的一列元组索引无效! @@ -4032,16 +3496,6 @@ Message returned by the DBMS: %1 Reference to a column of tuple with invalid name! 引用的一列元组名字无效! - - Reference to a tuple with index invalid or the result is empty (no tuples)! - 引用的元组索引无效或者结果为空(没有)! - - - Could not execute the SQL command. - Message returned: %1 - 无法执行 SQL 命令。 -返回的信息: %1 - Assignment of a not allocated column to object `%1' (%2)! @@ -4266,10 +3720,6 @@ Message returned by the DBMS: %1 Unable to write the file `%1' due to one or more errors in the definition generation process! - - There is already a relationship between `%1' (%2) and `%3' (%4) in the model! - - The configuration of the relationship `%1' generates a redundancy between the relationships `%2'. Redundancy on identifier or generalization/copy relationships are not accepted since they result in incorrect column spreading making the model inconsistent! @@ -4390,30 +3840,6 @@ Message returned by the DBMS: %1 Could not load the plugin `%1' from the library `%2'! Message returned by plugin manager: `%3' - - Invalid instruction `%1' on file %2, line %3, column %4! - - - - Unknown attribute `%1' in file %2, line %3, column %4! - - - - Invalid metacharacter `%1' in file %2, line %3, column %4! - - - - Invalid operator `%1' in comparison expression, file %2, line %3, column %4! - - - - Attribute `%1' with an undefined value in file %2, line %3, column %4! - - - - Attribute `%1' with an invalid name in file %2, line %3, column %4! - - Error while interpreting XML buffer at line %1 column %2. Message generated by the parser: %3. %4 @@ -4526,10 +3952,6 @@ Message returned by the DBMS: `%1' The operator class assigned to the object `%1' (%2) must use `btree' as indexing method! - - Unsupported PostgreSQL version (%1) detected! Valid versions are: %2 - - The validation process failed due to an error triggered by the validation helper. For more details about the error check the exception stack! @@ -4574,10 +3996,6 @@ Message returned by the DBMS: `%1' The widget already has a parent and cannot be assigned to a different object! - - The object `%1' (%2) could not be imported due to one or more errors! Check the exception stack for more details. - - Could not load the database model file `%1'. Check the error stack to see details. Try to run `pgmodeler-cli --fix-model' in order to correct the structure of the file if that is the case. @@ -4658,24 +4076,77 @@ Message returned by the DBMS: `%1' The connection was unexpectedly closed by the database server `%1' at port `%2'! - - - ExportHelper - Creating object '%1' (%2)... - 正在创建对象 '%1' (%2)... + There is already a relationship between `%1' (%2) and `%3' (%4) in the model! When using relationships of the type generalization, copy and one-to-one there can't be other relationships linked to the pair of tables. + + + + Unable to load the configuration file `%1'! Please check if file exists in its folder and/or if it is not corrupted! + + + + Invalid syntax in file `%1', line %2, column %3! + + + + Invalid instruction `%1' on file `%2', line %3, column %4! + + + + Unknown attribute `%1' in file `%2', line %3, column %4! + + + + Invalid metacharacter `%1' in file `%2', line %3, column %4! + + + + Invalid operator `%1' in comparison expression, file `%2', line %3, column %4! + + + + Attribute `%1' with an undefined value in file `%2', line %3, column %4! + + + + Attribute `%1' with an invalid name in file `%2', line %3, column %4! + + + + Could not access the file or directory `%1'! Make sure that it exists or if the user has access permissions on it! + + + + Could not load file `%1'. The same appears to be inconsistent or one of its dependencies (DTD files) has errors or is missing! + + + + Unsupported PostgreSQL version (%1) detected! Valid versions are between %2 and %3. + + + + The object `%1' (%2), oid `%3', could not be imported due to one or more errors! Check the exception stack for more details. `HINT:' if the object somehow references objects in `pg_catalog' or `information_schema' consider enable the importing of system objects. + + + + Failed to drop the database `%1' because it is defined as the default database for the connection `%2'! + + + + The column `%1' must be `NOT NULL' because it composes the primary key of the table `%2'. You need to remove the column from the mentioned contraint in order to disable the `NOT NULL' on it! + - Creating database '%1'... - 正在创建数据库 '%1'... + The identity column `%1' has an invalid data type! The data type must be `smallint', `integer' or `bigint'. + - Connecting to database '%1'... - 正在连接数据库 '%1'... + Reference to an invalid affected command in policy `%1'! + - Creating objects on database '%1'... - 正在对数据库 '%1' 创建对象... + Reference to an invalid special role in policy `%1'! + @@ -4763,6 +4234,14 @@ Message returned by the DBMS: `%1' Whole words + + Hide this widget + + + + ... + + FunctionWidget @@ -4770,18 +4249,10 @@ Message returned by the DBMS: `%1' Attributes 属性 - - Langague: - 语言: - Function Type: 函数类型: - - Window Function: - 窗口函数: - Execution Cost: 执行开销: @@ -4802,18 +4273,10 @@ Message returned by the DBMS: `%1' Return Method: 返回方法: - - Simple - 简单 - Set - - Table - - Parameters 参数 @@ -4854,18 +4317,10 @@ Message returned by the DBMS: `%1' Default Value 默认值 - - Form - Form - Return Table 返回表 - - IN/OUT - IN/OUT - Si&mple @@ -4886,41 +4341,17 @@ Message returned by the DBMS: `%1' Mode + + Language: + + GeneralConfigWidget - - Grid size: - 网格大小: - Operation history: 操作记录: - - items - - - - Autosave interval: - 自动保存的时间间隔: - - - minute(s) - 分钟 - - - Save widgets position - 保存部件位置 - - - Save current session - 保存当前会话 - - - Printing Options: - 打印选项: - Print grid 打印网格 @@ -4933,10 +4364,6 @@ Message returned by the DBMS: `%1' Paper: 纸型: - - Custom (Based on margins) - 定制 (基于边框) - Orientation: 方向: @@ -4949,10 +4376,6 @@ Message returned by the DBMS: `%1' Landscape 横向 - - Margins: - 边距: - Milimeters 毫米 @@ -4993,10 +4416,6 @@ Message returned by the DBMS: `%1' Form Form - - pixels - 像素 - A0 (841 x 1189 mm) A0 (841 x 1189 mm) @@ -5137,18 +4556,10 @@ Message returned by the DBMS: `%1' General 常规 - - The opened models will be saved periodically - - Check if there is a new version on server - - Check for updates at startup - - Design @@ -5177,14 +4588,6 @@ Message returned by the DBMS: `%1' Move canvas by keep mouse on corners - - By default panning mode is triggered with left click and range selection with Shift + left click. - - - - Swap panning and range selection triggers - - Graphical objects (table, views and textboxes) will be created in a single step without the need to click on canvas @@ -5325,118 +4728,146 @@ Message returned by the DBMS: `%1' The little brown fox jumps over the lazy dog - - - GraphicalView - Connected rels: %1 + Minimum object opacity (%): - - - HintTextWidget - Form - Form + Defines the minimum opacity percentage applied to the objects when using the fade out feature. A zero opacity causes the object to be completely hidden not being possible to interact with it in the canvas area. + - - - IndexWidget - Indexing Type: - 索引类型: + Canvas grid size: + - Fill Factor: - 填充因子: + Defines the vertical and horizontal grid size. This value affects the spacing of objects when using object grid alignment feature. + - Options: - 选项: + By default the range selection is triggered with Shift + left click. By checking this option range selection will be activated only with a single click and move. + - Concurrent - 并发 + Trigger range selection with a single click + - Check duplicates - 检查重复 + Defines the maximum amount of elements held in the operation history. Once reached the maximum number the history is automatically cleaned. + - Fast update - 快速更新 + Defines the period when the opened models will be saved automatically. + - Conditional Expr.: - 条件表达式: + Autosave interval (minutes): + - Elements - 元素 + Replaces any straight line in relationship by curved ones in order to improve the model's visualization. + - Column: - 列: + Use curved lines for relationships + - Expression: - 表达式: + Souce code editor args: + - Operator Class: - 操作符类: + lines + - Sorting: - 正在排序: + Clear the entire SQL comand history. + - Ascending - 升序 + Clear history + - Descending - 降序 + Open in file manager + 在文件管理器中打开 - Nulls first - Null 值优先 + Overrides the default user interface language defined by the system. Requires restarting the program. <strong>NOTE:</strong> UI translations are third party collaborations thus any typo or mistake should be reported directly to their respective maintainers. + - Type - 类型 + SQL history max. length: + - Operator Class - 操作符类 + Check updates at startup + - Sorting - 排序 + User interface language: + + + + Browse the source code editor application + + + + Souce code editor: + + + + Configurations directory: + + + + System default + + + + All files (*.*) + + + + Load file + + + + + GenericSQLWidget + + SQL code + + + + HintTextWidget Form - Form + Form + + + IndexWidget - Element - 元素 + Fill Factor: + 填充因子: - Nulls First - Null 值优先 + Options: + 选项: - Expressão - 表达式 + Concurrent + 并发 - Sim - + Fast update + 快速更新 - Não - + Elements + 元素 Attributes @@ -5465,26 +4896,10 @@ Message returned by the DBMS: `%1' Trusted: 可信: - - Handler Function: - 处理函数: - - - Validator Function: - 验证函数: - - - Inline Function: - 内联函数: - The functions to be assigned to the language should have, respectively, the following signatures:<br/><br/> <strong>Handler Function:</strong> <em>language_handler function()</em><br/> <strong>Validator Function:</strong> <em>void function(oid)</em><br/> <strong>Inline Function:</strong> <em>void function(internal)</em> 语言处理函数的签名分别为:<br/><br/> <strong>处理函数:</strong> <em>language_handler function()</em><br/> <strong>验证函数:</strong> <em>void function(oid)</em><br/> <strong>内联函数:</strong> <em>void function(internal)</em> - - Form - Form - Validator Func.: @@ -5508,134 +4923,30 @@ Message returned by the DBMS: `%1' &Edit 编辑(&E) - - &Help - 帮助(&H) - &Show 视图(&S) - - &Tools - 工具(&T) - - - &Plugins - 插件(&P) - - - File - 文件 - - - Edit - 编辑 - - - Help - 帮助 - - - Show - 显示 - New 新建 - - Save - 保存 - Zoom - 缩小 - - Load - 打开 - - - Next - 下一个 - - - Previous - 上一个 - - - Exit - 退出 - - - About pgModeler - 关于 pgModeler - - - Print - 打印 - - - Undo - 撤销 - - - Redo - 重做 - - - Export - 导出 - Show grid 显示网格 - - Align to grid - 对齐到网格 - - - Fullscreen - 全屏 - - - Show the model on fullscreen mode - 在全屏模式下显示模型 - Show the page delimiters 显示分页符 - - Configurations - 配置 - - - Save all models - 保存全部模型 - - - Some models were modified! Do you want to save them before finish the pgModeler? - 模型已被修改!你要在关闭 pgModeler 之前保存它们吗? - Save '%1' as... 保存 '%1' 为... - - Print grid - 打印网格 - - - Print page numbers - 打印页码 - - - Model Options - 模型选项 - Confirmation 确认 @@ -5644,10 +4955,6 @@ Message returned by the DBMS: `%1' Load model 打开模型 - - Overview - 概览 - Show the model overview 显示模型概览 @@ -5688,14 +4995,6 @@ Message returned by the DBMS: `%1' Ctrl+O Ctrl+O - - Save as - 另存为 - - - F2 - F2 - Ctrl+P Ctrl+P @@ -5712,14 +5011,6 @@ Message returned by the DBMS: `%1' Ctrl+G Ctrl+G - - Close model - 关闭模型 - - - Normal zoom - 正常比例 - Ctrl+0 Ctrl+0 @@ -5728,22 +5019,10 @@ Message returned by the DBMS: `%1' Align objects position to grid 对齐对象到网格 - - F11 - F11 - - - Show delimiters - 显示分页符 - Ctrl+L Ctrl+L - - Widgets - 部件 - Save all 保存全部 @@ -5756,18 +5035,6 @@ Message returned by the DBMS: `%1' Changes were detected in the definitions of paper/margin of the model which may cause the incorrect print of the objects. Do you want to continue printing using the new settings? To use the default settings click 'No' or 'Cancel' to abort printing. 模型的纸型/页边距已改变,这可能导致对象打印出错。要使用新的设置继续打印吗?要使用默认设置,请单击“否”或“取消”中止打印。 - - Tools - 工具 - - - View - 视图 - - - Model - 模型 - Database model (*.dbm);;All files (*.*) 数据库模型 (*.dbm);; 所有文件 (*.*) @@ -5776,18 +5043,10 @@ Message returned by the DBMS: `%1' Save model 保存模型 - - The model were modified! Do you want to save it before close? - 模型已被修改!要在关闭前保存吗? - Ctrl+Q - - F3 - F3 - Ctrl+Shift+S @@ -6088,10 +5347,6 @@ Message returned by the DBMS: `%1' &Diff - - Determine the changes between model and database - - Ctrl+Shift+D @@ -6256,64 +5511,33 @@ Message returned by the DBMS: `%1' Executing pending <strong>%1</strong> operation... - - - MessageBox - - Show/hide exceptions stack. - 显示/隐藏异常堆栈。 - - - &Yes - 是(&Y) - - - &No - 否(&N) - - - Cancel - 取消 - - - Error - 错误 - - - Alert - 警告 - - - Information - 信息 - - &Cancel - 取消(&C) + Determine the changes between model/database and another database + - Dialog - Dialog + Arrange objects + - ... - ...... + Rearrange objects over the canvas + - msg - 信息 + Grid + - &Ok - 确定(&O) + Hierarchical + - Exceptions - 异常 + Scattered + - Show excpetion stack in text format (useful to report errors). - 以文本形式显示异常堆栈(有助于报告错误)。 + Rearrange objects over the canvas is an irreversible operation! Would like to proceed? + @@ -6462,138 +5686,150 @@ Message returned by the DBMS: `%1' - Save textboxes to the output file when extracting metadata. When loading the file textboxes are recreated and duplicated ones are ignored. + Textbox objects - Textbox objects + Tag objects - Save tags to the output file when extracting metadata. When loading the file tags are recreated and duplicated ones are ignored. + Backup file: - Tag objects + Select file - Backup file: + ... - Select file + Apply to: - ... + Operation: - Apply to: + Output - Operation: + Progress label... + 处理标签... + + + model not saved yet - Extracts the objects metadata from one of the loaded models and apply to the current model. + The backup file cannot be the same as the input model! - Extract from a &model + Extracting metadata to file `%1' - Reads the objects metadata from a previously saved backup file and apply to the current model. + Saving backup metadata to file `%1' - Restore a bac&kup file + Applying metadata from file `%1' - Output + Metadata processing aborted! - Progress label... - 处理标签... + Objects metadata file (*.omf);;All files (*.*) + - model not saved yet + Handles the objects' fade out status in the metadata file. - The backup file cannot be the same as the input model! + Objects' fade out status - Extracting metadata to file `%1' + Save tags to the output file when extracting metadata. When loading the file, the tags are recreated and duplicated ones are ignored. - Saving backup metadata to file `%1' + Save textboxes to the output file when extracting metadata. When loading the file, the textboxes are recreated and duplicated ones are ignored. - Applying metadata from file `%1' + Handles the tables' and views' extended attributes display status in the metadata file. - Metadata processing aborted! + Tables' extended attributes display - Objects metadata file (*.omf);;All files (*.*) + Save generic SQL objects to the output file when extracting metadata. When loading the file, the objects are recreated and duplicated ones are ignored. - - - ModelDatabaseDiffForm - Database model diff + Generic SQL objects - Generate diff from model + Extracts the objects' metadata from the loaded models and apply to the current focused model. A backup file can be specified to where the focused model's current metadata will be saved. - Settings + &Extract and restore - Input database + Extracts the objects metadata from one of the loaded models saving the info to a backup file. - Connection: - 连接: + Extract &only + - Database: + Reads the objects' metadata from a previously saved backup file and apply to the current model. - Options + &Restore a backup file + + + ModelDatabaseDiffForm - Ignores as many as possible errors on import step. This option generates an incomplete diff. + Settings - Ignore import errors + Connection: + 连接: + + + Database: - Clears the data of all tables which will have columns modified. This is useful to avoid errors related to type casting. <strong>WARNING:</strong> DO NOT use this option on production servers and always make a backup before use it. + Ignores as many as possible errors on import step. This option generates an incomplete diff. + + + + Ignore import errors - Trucate tables before alter columns + Clears the data of all tables which will have columns modified. This is useful to avoid errors related to type casting. <strong>WARNING:</strong> DO NOT use this option on production servers and always make a backup before use it. @@ -6784,14 +6020,6 @@ Message returned by the DBMS: `%1' Waiting process to start... - - Importing database <strong>%1</strong>... - - - - Comparing the model <strong>%1</strong> and database <strong>%2</strong>... - - Confirmation 确认 @@ -6808,10 +6036,6 @@ Message returned by the DBMS: `%1' Preview diff - - Exporting diff to database <strong>%1</strong>... - - Diff process paused. Waiting user action... @@ -6858,136 +6082,136 @@ Message returned by the DBMS: `%1' SQL code (*.sql);;All files (*.*) SQL 代码 (*.sql);;所有文件 (*.*) - - - ModelExportForm - Model Export - 导出模型 + Diff tool + - Select the export type: - 选择导出类型: + Generate diff code + - File: - 文件: + Source database + - Select target file - 选择目标文件 + Current model: + - PostgreSQL version in which the SQL code should be generated - 生成 SQL 代码的 PostgreSQL 版本 + (model) + - Check if the system user has write permission on target folder. - 检查系统用户是否具有目标文件夹的写权限。 + Compare to + - Options: - 选项: + Diff + - Show grid - 显示网格 + Froce the generation of DROP commands for columns and constraints that exist in database but not in the model. This is useful when diff a partial model against the complete database and the user needs to drop columns and constraint but preserve the rest of the objects. + - Ignore object duplicity - 忽略重复对象 + Drop missing columns and constraints + - The pgModeler ignores errors generated by duplicate objects and creates only model objects that do not exist in the database. This option may be used when an object was created after a later model export. - pgModeler 忽略重复对象的错误,并只会创建数据库中不存在的模型对象。此选项可用在模型导出以后才创建的对象。 + Truncate tables before alter columns + - Export to DBMS: - 导出到数据库系统: + Import && Export + - Connection: - 连接: + Import + - It is recommended to select this option only when the version of the DBMS, somehow, is not identifiable or if you need to generate a specific version of SQL code for testing. - 当无法确定数据库系统的版本或想生成用于测试的特定版本 SQL 代码时,建议选择此项。 + Export + 导出 - &Export - 导出(&E) + This advanced option causes pgModeler to ignore extra errors by their numeric codes. These errors must be informed in the input below and separeted by space. For the complete list of error codes check the PostgreSQL docs, section <strong> Appendix A. PostgreSQL Error Codes</strong>. <strong>WARNING:</strong> use this option with extreme care since it can interfere in final export result. + - &Close - 关闭(&C) + Ignore error codes + - Generating source code... - 正在生成源代码... + model not saved yet + - Initializing model export... - 正在初始化模型导出... + (none) + - Saving file '%1' - 正在保存文件 '%1' + Step %1/%2: Importing database <strong>%3</strong>... + - Creating object '%1' (%2)... - 正在创建对象 '%1' (%2)... + Step %1/%2: Comparing <strong>%3</strong> and <strong>%4</strong>... + - Creating database '%1'... - 正在创建数据库 '%1'... + Step %1/%2: Exporting diff to database <strong>%3</strong>... + + + + ModelExportForm - Connecting to database '%1'... - 正在连接数据库 '%1'... + File: + 文件: - Creating objects on database '%1'... - 正在对数据库 '%1' 创建对象... + Select target file + 选择目标文件 - Exporting process sucessfuly ended! - 成功导出! + PostgreSQL version in which the SQL code should be generated + 生成 SQL 代码的 PostgreSQL 版本 - Error on export! - 导出出错! + Show grid + 显示网格 - Export model as... - 导出模型为... + Ignore object duplicity + 忽略重复对象 - SQL code (*.sql);;All files (*.*) - SQL 代码 (*.sql);;所有文件 (*.*) + Connection: + 连接: - PNG image (*.png);;All files (*.*) - PNG 图像 (*.png);; 所有文件 (*.*) + &Export + 导出(&E) - Export to SQL file: - 导出到 SQL 文件: + &Close + 关闭(&C) - Export to PNG image: - 导出到 PNG 图像: + Initializing model export... + 正在初始化模型导出... - Image: - 图像: + Saving file '%1' + 正在保存文件 '%1' - Show the page delimiters - 显示分页符 + Exporting process sucessfuly ended! + 成功导出! - Check if the system user has write permission on image target folder. - 检查系统用户是否有图像目标文件夹的写权限。 + Export model as... + 导出模型为... ... @@ -7001,10 +6225,6 @@ Message returned by the DBMS: `%1' Progress label... 处理标签... - - ico - ico - Export model @@ -7049,10 +6269,6 @@ Message returned by the DBMS: `%1' Graphics file - - Image (PNG) - - Type: 类型: @@ -7061,10 +6277,6 @@ Message returned by the DBMS: `%1' Zoom: - - Vectorial (SVG) - - Show delimiters 显示分页符 @@ -7113,6 +6325,22 @@ Message returned by the DBMS: `%1' Exporting process canceled by user! + + This advanced option causes pgModeler to ignore extra errors by their numeric codes. These errors must be informed in the input below and separeted by space. For the complete list of error codes check the PostgreSQL docs, section <strong> Appendix A. PostgreSQL Error Codes</strong>. <strong>WARNING:</strong> use this option with extreme care since it can interfere in final export result. + + + + Ignore error codes + + + + I&mage (PNG) + + + + &Vectorial (SVG) + + ModelExportHelper @@ -7377,10 +6605,6 @@ p, li { white-space: pre-wrap; } Parent Type 父类型 - - Visible Object Types - - Select All 选择全部 @@ -7449,6 +6673,14 @@ p, li { white-space: pre-wrap; } By ID + + Visible object types + + + + Model objects + + ModelOverviewWidget @@ -7456,17 +6688,14 @@ p, li { white-space: pre-wrap; } Model overview 模型概览 + + Failed to generate the overview image. +The requested size %1 x %2 was too big and there was not enough memory to allocate! + + ModelRestorationForm - - Modified: %1 - 修改:%1 - - - yyyy-MM-dd hh:mm:ss - yyyy-MM-dd hh:mm:ss - Model restoration 模型恢复 @@ -7479,10 +6708,6 @@ p, li { white-space: pre-wrap; } &Cancel 取消(&C) - - pgModeler was not closed properly in a previous execution and some models were still being edited. Click 'Restore' to reopen the models or 'Cancel' to abort the restoration. - pgModeler 在之前运行时没有正常关闭且部分模型还处于编辑状态。单击“恢复”重新打开模型或“取消”放弃恢复。 - pgModeler was not closed properly in a previous execution and some models were still being edited. Click <strong>Restore</strong> to reopen the models or <strong>Cancel</strong> to abort the restoration. @@ -7573,10 +6798,6 @@ p, li { white-space: pre-wrap; } Try to resolve the reported issues. - - Apply Fix - - Ctrl+S Ctrl+S @@ -7585,10 +6806,6 @@ p, li { white-space: pre-wrap; } Change the creation order for two objects by swapping their ids - - Swap Ids - - Va&lidate @@ -7685,17 +6902,25 @@ p, li { white-space: pre-wrap; } Processing object: %1 - - - ModelWidget - Generalization - 泛化 + Apply fixes + - <strong>CAUTION:</strong> The object model is protected! New objects will be inserted only when the protection is removed! - <STRONG>警告:</STRONG>对象模型处于受保护状态!只有在移除保护之后才可以插入对象! + Swap ids + + + + The column <strong>%1</strong> on <strong>%2</strong> <em>(%3)</em> is referencing the geospatial data type <strong>%4</strong> but the <strong>postgis</strong> extension is not present in the model! + + + <strong>HINT:</strong> Create the extension in the model or let it be created by applying the needed fixes. + + + + + ModelWidget Source code 源代码 @@ -7720,22 +6945,10 @@ p, li { white-space: pre-wrap; } Unprotect 取消保护 - - Pretects the object(s) against modifications - 添加修改保护 - - - Removes from the objetc(s) the protection against modifications - 移除修改保护 - Delete 删除 - - Delete the selected object(s) - 删除选中对象 - Select all 选择全部 @@ -7744,46 +6957,22 @@ p, li { white-space: pre-wrap; } Selects all the graphical objects in the model 选择模型中的全部图形对象 - - Converts the n-n relationship into table - 将 N-N 关系转换成表 - Copy 复制 - - Copy the selected objects(s) - 复制选中对象 - Paste 粘贴 - - Paste the previos copied object(s) - 粘贴已复制的对象 - Cut 剪切 - - Displays objects that reference and that are dependent of the selected object - 显示选中对象的引用对象和依赖对象 - - - New object - 新建对象 - Add a new object in the model 添加新对象到模型中 - - Quick actions - 快速操作 - Rename 重命名 @@ -7796,34 +6985,18 @@ p, li { white-space: pre-wrap; } Move to schema 移动到模式 - - Move the object to another schema - 将此对象移动到另一个模式 - Edit permissions 编辑权限 - - Edit object's permissions - 编辑对象的权限 - Change owner 变更所有者 - - Change object's owner - 变更对象的所有者 - Select children 选择子对象 - - Selects all the children graphical objects on the selected schema - 选择所选定模式的所有子图形对象 - Loading database model 正在载入数据库模型 @@ -7832,10 +7005,6 @@ p, li { white-space: pre-wrap; } Saving database model 正在保存数据库模型 - - Confirmation - 确认 - Also copy all dependencies of selected objects? This minimizes the breakdown of references when copied objects are pasted into another model. 同时复制选中对象的依赖对象吗?这会最大限度减小已复制对象被粘贴到其他模型时,发生引用失效的机会。 @@ -7857,80 +7026,32 @@ p, li { white-space: pre-wrap; } 约束 - Convert a relationship is an irreversible operation and causes the deletion of all operation history! Do you want to continue? - 转换关系是不可逆操作并会删除所有操作记录!要继续吗? + Protects object(s) from modifications + - Dependence - 依赖 + (no objects) + - Convert rel. n-n - 转换 N-N 关系 + One to One (1-1) + - Cut the selected object(s) - 剪切选中的对象 + One to Many (1-n) + - Depend. / Refer. - 依赖/引用 + Many to Many (n-n) + - Relationship - 关系 + Inheritance + - CAUTION: Remove multiple objects at once can cause irreversible invalidations to other objects in the model. Do you really want to delete ALL selected objects? - 注意:同时删除多个对象可能会造成模型中其他对象不可逆的失效。要删除所有选中的对象吗? - - - Validating object: %1 (%2) - 正在验证对象:%1 (%2) - - - Pasting object: %1 (%2) - 正在粘贴对象:%1 (%2) - - - Generating XML code of object: %1 (%2) - 正在生成对象 %1 (%2) 的 XML 代码 - - - Protects object(s) from modifications - - - - Dependencies - 依赖 - - - Highlight - - - - (no objects) - - - - One to One (1-1) - - - - One to Many (1-n) - - - - Many to Many (n-n) - - - - Inheritance - - - - <strong>ATTENTION:</strong> The database model is protected! Operations that could modify it are disabled! - + <strong>ATTENTION:</strong> The database model is protected! Operations that could modify it are disabled! + Source @@ -8104,6 +7225,94 @@ p, li { white-space: pre-wrap; } The cascade deletion found some problems when running! Some objects could not be deleted or registered in the operation's history! Please, refer to error stack for more details. + + Edit data + + + + Select tagged + + + + Select + 选择 + + + Duplicate + + + + Ctrl+D + + + + Extended attributes + + + + Show + 显示 + + + Hide + + + + Jump to table + + + + Schemas rectangles + + + + Fade in/out + + + + Fade in + + + + Fade out + + + + Relationships + + + + Swap ids + + + + Edit the objects creation order by swapping their ids + + + + All objects + + + + Schemas + + + + Tables + + + + Views + + + + Textboxes + + + + None + + ModelsDiffHelper @@ -8394,6 +7603,18 @@ p, li { white-space: pre-wrap; } 0 0 + + Generic SQL + + + + Policy + + + + 8 + 8 + NumberedTextEditor @@ -8413,6 +7634,42 @@ p, li { white-space: pre-wrap; } Ident left + + Load + 打开 + + + Load the object's source code from an external file + + + + Edit + 编辑 + + + Edit the source code in the preferred external editor + + + + Clear + + + + SQL file (*.sql);;All files (*.*) + + + + Load file + + + + The source editor `%1' is running on `pid: %2'. + + + + Could not start the source code editor application `%1'! Make to sure that the source editor path defined in the general settings points to a valid executable and the current user has permission to run the application. Error message returned: `%2' + + ObjectDepsRefsWidget @@ -8440,14 +7697,6 @@ p, li { white-space: pre-wrap; } References 引用 - - Dependeces / References of Object - 对象的依赖/引用 - - - Form - Form - Object's dependencies & references @@ -8495,14 +7744,6 @@ p, li { white-space: pre-wrap; } Clear - - Highlight graphical objects when selecting them or their children on the result list - - - - Highlight - - ... @@ -8563,6 +7804,30 @@ p, li { white-space: pre-wrap; } No objects found. + + (Un)selects the graphical objects in the results grid + + + + Select + 选择 + + + Fades outs all the graphical objects in the results grid (or those not listed). The current fade in/out state of all objects is modified. + + + + Fade out + + + + Listed + + + + Not listed + + ObjectRenameWidget @@ -8607,110 +7872,106 @@ p, li { white-space: pre-wrap; } - ObjectTableWidget + ObjectsTableWidget - Add Item - 添加项目 - - - Remove Item - 移除项目 + Form + Form - Update Item - 更新项目 + Add Item + 添加项目 - Remove All - 删除全部 + Ins + Ins - Edit Item - 编辑项目 + Remove Item + 移除项目 - Move Up - 上移 + Del + Del - Move Down - 下移 + Update Item + 更新项目 - Move to start - 移至开头 + Alt+R + Alt+R - Move to end - 移至末尾 + Remove All + 删除全部 - Do you really want to remove the selected item? - 要移除选中的项目吗? + Shift+Del + Shift+Del - Do you really want to remove the all items? - 要移除全部项目吗? + Duplicate item + - Form - Form + Ctrl+D + - Ins - Ins + Edit Item + 编辑项目 - Del - Del + Space + Space - Alt+R - Alt+R + Move Up + 上移 - Shift+Del - Shift+Del + Ctrl+Up + Ctrl+Up - Space - Space + Move Down + 下移 - Ctrl+Up - Ctrl+Up + Ctrl+Down + Ctrl+Down - Ctrl+Down - Ctrl+Down + Move to start + 移至开头 Ctrl+Home - Ctrl+Home + Ctrl+Home - Ctrl+End, Ctrl+S - Ctrl+End, Ctrl+S + Move to end + 移至末尾 - Confirmação - 确认 + Ctrl+End, Ctrl+S + Ctrl+End, Ctrl+S Confirmation 确认 - - - OperationList - Undoing operation on object: %1 (%2) - 正在撤销对象操作: %1 (%2) + Do you really want to remove the selected item? + 要移除选中的项目吗? - Redoing operation on object:: %1 (%2) - 正在重做对象操作: %1 (%2) + Do you really want to remove all the items? + + + + OperationList (invalid object) @@ -8766,14 +8027,6 @@ p, li { white-space: pre-wrap; } Operation: %1 操作:%1 - - Undoing operations... - 正在撤销操作... - - - Redoing operations... - 正在重做操作... - Operation history exclusion 不显示操作记录 @@ -8817,10 +8070,6 @@ p, li { white-space: pre-wrap; } Elements 元素 - - Elemente Type: - 元素类型: - Operator 操作符 @@ -8845,14 +8094,6 @@ p, li { white-space: pre-wrap; } Support/Strategy: 支持/策略: - - Recheck - 重新检查 - - - Family: - 族: - Storage Type 存储类型 @@ -8870,24 +8111,12 @@ p, li { white-space: pre-wrap; } 支持/策略 - Yes - + Element Type: + - No - - - - Form - Form - - - Element Type: - - - - Op. Family: - + Op. Family: + Operator Family @@ -8900,10 +8129,6 @@ p, li { white-space: pre-wrap; } Indexing: 正在建立索引: - - Form - Form - OperatorWidget @@ -8915,46 +8140,6 @@ p, li { white-space: pre-wrap; } Arguments 参数 - - Functions - 函数 - - - Constraints: - 约束: - - - Operator: - 操作符: - - - Operators - 操作符 - - - Commutation: - 交换: - - - Negation: - 否定: - - - Sort (1): - 排序 (1): - - - Sort (2): - 排序 (2): - - - Less than: - 小于: - - - Greater then: - 大于: - Right Argument Type 右参数类型 @@ -8967,10 +8152,6 @@ p, li { white-space: pre-wrap; } To create a unary operator it is necessary to specify as <strong><em>'any'</em></strong> one of its arguments. Additionally, the function that defines the operator must have only one parameter and this, in turn, must have the same data type of the the argument of unary operator. 在创建单目操作符时必须指定它们参数中的<strong><em>任何</em></strong>一个。另外,作为操作符的函数必须有且只有一个参数,而且这个参数的类型必须与单目操作符参数的类型相同。 - - Form - Form - MERGES 融合连接 (MERGES) @@ -9014,10 +8195,6 @@ p, li { white-space: pre-wrap; } Mode: 模式: - - Form - Form - IN IN @@ -9053,18 +8230,6 @@ p, li { white-space: pre-wrap; } Add Permission 添加权限 - - Type: - 类型: - - - Role - 角色 - - - Form - Form - ID: ID: @@ -9093,10 +8258,6 @@ p, li { white-space: pre-wrap; } Cascade - - Leave the <em><strong>Roles</strong></em> empty to create a permission applicable to <strong><em>PUBLIC</em></strong>. - - Edit permissions 编辑权限 @@ -9121,6 +8282,14 @@ p, li { white-space: pre-wrap; } /* Could not generate the SQL code preview for permissions! + + Name + 名称 + + + Leave the <em><strong>Roles</strong></em> grid empty in order to create a %1 applicable to <strong><em>PUBLIC</em></strong>. + + PgModelerCLI @@ -9137,290 +8306,525 @@ p, li { white-space: pre-wrap; } - Connection aliased as '%1' was not found on configuration file. + Usage: pgmodeler-cli [OPTIONS] - Usage: pgmodeler-cli [OPTIONS] + command line interface. - command line interface. + DBMS export options: - PostgreSQL Database Modeler Project - pgmodeler.com.br + Input file must be different from output! - %1, %2 Export to a sql script file. + Incomplete connection information! - %1, %2 Export to a png image. + Starting model export... - %1, %2 Export directly to a PostgreSQL server. + General options: - %1, %2 Version of generated SQL code. Only for file or dbms export. + PNG and SVG export options: - %1, %2 Silent execution. Only critical errors are shown during process. + Miscellaneous options: - %1, %2 Show this help menu. + There are no connections configured. - %1, %2 Draws the grid on the exported png image. + Invalid zoom specified! - %1, %2 Draws the page delimiters on the exported png image. + Invalid action specified to update mime option! - DBMS export options: + Starting model fixing... + + + + Starting mime update... - %1, %2 Ignores errors related to duplicated objects that eventually exists on server side. + Model successfully fixed! - %1, %2=[ALIAS] Connection configuration alias to be used. + Extracting objects' XML... - %1, %2=[HOST] PostgreSQL host which export will operate. + Invalid input file! It seems that is not a pgModeler generated model or the file is corrupted! - %1, %2=[PORT] PostgreSQL host listening port. + Recreating objects... - %1, %2=[DBNAME] Connection's initial database. + +** Object(s) that couldn't fixed: - No export mode specified! + WARNING: There are objects that maybe can't be fixed. Trying again... (tries %1/%2) - No input file specified! + Database model files (.dbm) are already associated to pgModeler! - No output file specified! + There is no file association related to pgModeler and .dbm files! - Input file must be different from output! + Mime database operation: %1 - Incomplete connection information! + Can't erase the file %1! Check if the current user has permissions to delete it and if the file exists. - Starting model export... + Running update-mime-database command... - Loading input file: + Connection aliased as '%1' was not found in the configuration file. - Export to PNG image: + PostgreSQL Database Modeler Project - pgmodeler.io - Export to SQL script file: + Copyright 2006-2018 Raphael A. Silva <raphael@pgmodeler.io> - Export to DBMS: + This CLI tool provides several operations over models and databases without the need to perform them +in pgModeler's graphical interface. All available options are described below. - Export successfully ended! + %1, %2 [FILE] Input model file (.dbm). This is mandatory for fix, export operations. - Copyright 2006-2015 Raphael A. Silva <raphael@pgmodeler.com.br> + %1, %2 [DBNAME] Input database name. This is mandatory for import operation. - This CLI tool provides the operations to export pgModeler's database models without - the need to load them on graphical interface as well to fix model files to the most recent - accepted structure. All available options are described below. + %1, %2 [FILE] Output file. This is mandatory for fixing model or exporting to file, png or svg. - General options: + %1, %2 Try to fix the structure of the input model file in order to make it loadable again. - %1, %2=[FILE] Input model file (.dbm). Mandatory use when fixing a model or exporting it. + %1, %2 [NUMBER] Model fix tries. When reaching the maximum count the invalid objects will be discarded. - %1, %2=[FILE] Output file. Mandatory use when fixing model or export to file or png. + %1, %2 Export the input model to a sql script file. - %1, %2 Try to fix the structure of the input model file in order to make it loadable again. + %1, %2 Export the input model to a png image. - %1, %2 Model fix tries. When reaching the maximum count the invalid objects will be discard. + %1, %2 Export the input model to a svg file. - %1, %2 Export to a svg file. + %1, %2 Export the input model directly to a PostgreSQL server. - %1, %2 List available connections on %3 file. + %1, %2 Import a database to an output file. - PNG and SVG export options: + %1, %2 Compares a model and a database or two databases generating the SQL script to synch the latter in relation to the first. - %1, %2 Each page will be exported on a separated png image. (Only for PNG) + %1, %2 Force the PostgreSQL version of generated SQL code. - %1, %2=[FACTOR] Applies a zoom (in percent) before export to png image. Accepted zoom interval: %3-%4 (Only for PNG) + %1, %2 Silent execution. Only critical messages and errors are shown during process. - %1, %2 Drop the database before execute a export process. + %1, %2 Show this help menu. - %1, %2 Runs the DROP commands attached to SQL-enabled objects. + Connection options: - %1, %2 Simulates a export process. Actually executes all steps but undoing any modification. + %1, %2 List available connections in file %3. - %1, %2 Generates temporary names for database, roles and tablespaces when in simulation mode. + %1, %2 [ALIAS] Connection configuration alias to be used. - %1, %2=[USER] PostgreSQL username. + %1, %2 [HOST] PostgreSQL host in which a task will operate. - %1, %2=[PASSWORD] PostgreSQL user password. + %1, %2 [PORT] PostgreSQL host listening port. - Miscellaneous options: + %1, %2 [USER] PostgreSQL username. - %1, %2=[ACTION] Handles the file association to .dbm files. The ACTION can be [%3 | %4]. + %1, %2 [PASSWORD] PostgreSQL user password. - There are no connections configured. + %1, %2 [DBNAME] Connection's initial database. - Available connections (alias : conn. string) + %1, %2 Draws the grid in the exported image. - Export, fix model and update mime operations can't be used at the same time! + %1, %2 Draws the page delimiters in the exported image. - Multiple export mode specified! + %1, %2 Each page will be exported in a separated png image. (Only for PNG images) - Invalid zoom specified! + %1, %2 [FACTOR] Applies a zoom (in percent) before export to png image. Accepted zoom interval: %3-%4 (Only for PNG images) - Invalid action specified to update mime option! + %1, %2 Ignores errors related to duplicated objects that eventually exist in the server. - Starting model fixing... + %1, %2 [CODES] Ignores additional errors by their codes. A comma-separated list of alphanumeric codes should be provided. - Starting mime update... + %1, %2 Drop the database before execute a export process. - Fixed model file: + %1, %2 Runs the DROP commands attached to SQL-enabled objects. - Model successfully fixed! + %1, %2 Simulates an export process by executing all steps but undoing any modification in the end. - Mime database successfully updated. + %1, %2 Generates temporary names for database, roles and tablespaces when in simulation mode. - Export to SVG file: + Database import options: - Extracting objects' XML... + %1, %2 Ignore all errors and try to create as many as possible objects. - Invalid input file! It seems that is not a pgModeler generated model or the file is corrupted! + %1, %2 Import system built-in objects. This option causes the model bloating due to the importing of unneeded objects. - Recreating objects... + %1, %2 Import extension objects. This option causes the model bloating due to the importing of unneeded objects. - -** Object(s) that couldn't fixed: + %1, %2 Run import in debug mode printing all queries executed in the server. - WARNING: There are objects that maybe can't be fixed. Trying again... (tries %1/%2) + Diff options: - Database model files (.dbm) are already associated to pgModeler! + %1, %2 [DBNAME] The database used in the comparison. All the SQL code generated is applied to it. - There is no file association related to pgModeler and .dbm files! + %1, %2 Save the generated diff code to output file. - Mime database operation: %1 + %1, %2 Apply the generated diff code on the database server. - Can't erase the file %1! Check if the current user has permissions to delete it and if the file exists. + %1, %2 Don't preview the generated diff code when applying it to the server. - Running update-mime-database command... + %1, %2 Drop cluster level objects like roles and tablespaces. + + + + %1, %2 Revoke permissions already set on the database. New permissions configured in the input model are still applied. + + + + %1, %2 Drop missing objects. Generates DROP commands for objects that are present in the input model but not in the compared database. + + + + %1, %2 Force the drop of missing columns and constraints. Causes only columns and constraints to be dropped, other missing objects aren't removed. + + + + %1, %2 Rename the destination database when the names of the involved databases are different. + + + + %1, %2 Don't drop or truncate objects in cascade mode. + + + + %1, %2 Truncate tables prior to alter columns. Avoids errors related to type casting when the new type of a column isn't compatible to the old one. + + + + %1, %2 Don't reuse sequences on serial columns. Drop the old sequence assigned to a serial column and creates a new one. + + + + %1, %2 Don't force the recreation of objects. Avoids the usage of a DROP and CREATE commands to create a new version of the objects. + + + + %1, %2 Don't recreate the unmodifiable objects. These objects are the ones which can't be changed via ALTER command. + + + + %1, %2 [ACTION] Handles the file association to .dbm files. The ACTION can be [%3 | %4]. + + + + ** The diff process allows the usage of the following options related to import and export operations: + + + + * Export: + + + + * Import: + + + + ** When running the diff using two databases (%1 and %2) there's the need to specify two connections/aliases. + + + + If only one connection is set it will be used to import the input database as well to retrieve database used in the comparison. + + + + A second connection can be specified by appending a 1 on any connection configuration parameter listed above. + + + + Available connections (alias : connection string) + + + + No operation mode was specified! + + + + Export, fix model, import database, diff and update mime operations can't be used at the same time! + + + + Multiple export mode was specified! + + + + No input file was specified! + + + + No input database was specified! + + + + No output file was specified! + + + + No input file or database was specified! + + + + The input file and database can't be used at the same time! + + + + No database to be compared was specified! + + + + No diff action (save or apply) was specified! + + + + No output file for the diff code was specified! + + + + ** Error code `%1' found and ignored. Proceeding with export. + + + + ** Command: %1 + + + + Loading input file: %1 + + + + Fixed model file: %1 + + + + Export to PNG image: %1 + + + + Export to SVG file: %1 + + + + Export to SQL script file: %1 + + + + Export to DBMS: %1 + + + + Export successfully ended! + + + + + Starting database import... + + + + Input database: %1 + + + + Saving the imported database to file... + + + + Import successfully ended! + + + + + Starting diff process... + + + + Input model: %1 + + + + Compare to: %1 + + + + Loading input model... + + + + Importing the database `%1'... + + + + Comparing the generated models... + + + + No differences were detected. + + + + Saving diff to file `%1' + + + + ** WARNING: You are about to apply the generated diff code to the server. Data can be lost in the process! + + + + ** Proceed with the diff applying? (yes/no) > + + + + yes + + + + no + + + + Diff code not applied to the server. + + + + Applying diff to the database `%1'... + + + + Diff successfully ended! + + + + + Mime database successfully updated! + @@ -9547,10 +8951,6 @@ p, li { white-space: pre-wrap; } Loaded plug-ins 已加载的插件 - - <html><head/><body><p>Details about plugins development and installation can be found at <a href="http://www.pgmodeler.com.br/wiki/doku.php?id=plugins"><span style=" text-decoration: underline; color:#0057ae;">pgModeler Wiki</span></a>. <span style=" font-weight:600;">Note:</span> plugin installation requires pgModeler to be restarted.</p></body></html> - <html><head/><body><p>关于插件开发和安装的详细信息可以在<a href="http://www.pgmodeler.com.br/wiki/doku.php?id=plugins"><span style=" text-decoration: underline; color:#0057ae;">pgModeler Wiki</span></a>中找到。 <span style=" font-weight:600;">注意:</span> 安装插件需要重启pgModeler。 - Plugin 插件 @@ -9564,6 +8964,45 @@ p, li { white-space: pre-wrap; } 动态链接库 + + PolicyWidget + + Basics + + + + Command: + + + + Permissive + + + + Roles + 角色 + + + Expressions + + + + USING: + + + + CHECK: + + + + Name + 名称 + + + Leave the <em><strong>Roles</strong></em> grid empty in order to create a %1 applicable to <strong><em>PUBLIC</em></strong>. + + + QObject @@ -9575,21 +9014,6 @@ p, li { white-space: pre-wrap; } %1 (行:%2) - - QuickRenameWidget - - Form - Form - - - Rename - 重命名 - - - Cancel - 取消 - - Relationship @@ -9623,18 +9047,10 @@ p, li { white-space: pre-wrap; } Connection Mode - - This mode is available only for <strong>one-to-one</strong>, <strong>one-to-many</strong> and <strong>fk relationships</strong> but provides a better semantics when linking tables by placing the lines on the exact point where the relationship occurs. - - Connect FK to PK columns - - This mode is the classical one. It connects the relationship to tables through their central points. - - Connect tables' center points @@ -9747,6 +9163,30 @@ p, li { white-space: pre-wrap; } Default 默认 + + This mode renders the relationships in crow's foot notation which has a better semantics and readability. It also determines the optimal point where the relationship is connected on the tables' edges taking their position into account. + + + + Crow's foot notation + + + + This mode determines the optimal point where the relationship is connected on the tables' edges taking their position into account. It implies the usage of the classical ER notation. + + + + Connect tables' edges + + + + This mode is available only for <strong>one-to-one</strong>, <strong>one-to-many</strong> and <strong>fk relationships</strong> but provides a better semantics when linking tables by placing the lines on the exact point where the relationship occurs. It implies the usage of the classical ER notation. + + + + This mode is the classical one. It connects the relationship to tables through their central points. It implies the usage of the classical ER notation. + + RelationshipWidget @@ -9754,10 +9194,6 @@ p, li { white-space: pre-wrap; } General 常规 - - Relationship: - 关系: - One to one relationship 一对一关系 @@ -9774,46 +9210,18 @@ p, li { white-space: pre-wrap; } Generalization relationship (inheritance) 泛化关系 (继承) - - Dependency relationship - 依赖关系 - Identifier 标识符 - - Source Table: - 原始表: - - - Target Table: - 目标表: - Cardinality: 基数: - - Source Required - 原始对象是必须的 - - - Target Required - 目标对象是必须的 - Name of the table generated from many to many relationship 多对多关系生成表的名称 - - Table Name: - 表名称: - - - Foreign key - 外键 - Deferrable: 可延迟: @@ -9846,26 +9254,6 @@ p, li { white-space: pre-wrap; } Constraint 约束 - - Editing attributes of an existing relationship is allowed, but must be done carefully because it may break references to columns and cause invalidation of objects such as triggers, indexes, constraints and sequences. - 编辑现有关系的属性是允许的,但必须小心,因为此操作会导致无效的对象 (如触发器,索引,约束和序列),进而破坏引用列。 - - - Use the special primary key if you want to include a primary key containing inherited / copied columns to the receiving table. This is a feature available only for generalization / dependency relationships. - 如果你想在受方表中包含一个带有继承/复制列的主键,请使用特殊主键。此特性仅适用于泛化/依赖关系。 - - - Automatic Suffix - 自动补充后缀 - - - Form - Form - - - 1-1 - 1-1 - 1-n 1-N @@ -9874,22 +9262,10 @@ p, li { white-space: pre-wrap; } n-n N-N - - gen - gen - dep dep - - Source Suffix: - 原始后缀: - - - Target Suffix: - 目标后缀: - Dependency / Copy relationship @@ -10143,16 +9519,19 @@ p, li { white-space: pre-wrap; } + + ResultSetModel + + [binary data] + + + RoleWidget Password: 密码: - - Validity: - 合法性: - Connections: 连接: @@ -10165,26 +9544,6 @@ p, li { white-space: pre-wrap; } Superuser 超级用户 - - Inherit Permissions - 继承权限 - - - Create Database - 创建数据库 - - - Can Login - 允许登录 - - - Create Users/Groups - 创建用户/组 - - - Encrypted Password - 加密密码 - Members 成员 @@ -10202,47 +9561,43 @@ p, li { white-space: pre-wrap; } 成员(管理员) - Form - Form - - - SysID: - SysID: + Member of + 成员 - yyyy-MMM-dd hh:mm - yyyy-MMM-dd hh:mm + Encrypted + - Member of - 成员 + yyyy-MMM-dd hh:mm:ss + - SysID - SysID + Assigning <strong><em>-1</em></strong> to <strong><em>Connections</em></strong> creates a role without connection limit.<br/> Unchecking <strong><em>Validity</em></strong> creates an role that never expires. + - Can create Database + Inherit permissions - Can create Role + Can create database - Can use Replication + Bypass RLS - Encrypted + Can use replication - yyyy-MMM-dd hh:mm:ss + Can login - Assigning <strong><em>-1</em></strong> to <strong><em>Connections</em></strong> creates a role without connection limit.<br/> Unchecking <strong><em>Validity</em></strong> creates an role that never expires. + Can create role @@ -10260,10 +9615,6 @@ p, li { white-space: pre-wrap; } Conditional Expr.: 条件表达式: - - Executed Commands - 执行的命令 - SQL Command: SQL 命令: @@ -10272,10 +9623,6 @@ p, li { white-space: pre-wrap; } To create a rule that does not perform any action (<strong>DO NOTHING</strong>) simply do not specify commands in the SQL commands table. 创建一个不执行任何操作的规则(<STRONG>DO NOTHING</STRONG>)简单点说,就是 SQL 命令表中没有的命令。 - - Form - Form - SQL command SQL 命令 @@ -10291,30 +9638,14 @@ p, li { white-space: pre-wrap; } Form Form - - Load SQL script - - - - &Load - - Save SQL commands - - &Save - - Search in SQL code - - &Find - - Alt+F @@ -10399,10 +9730,6 @@ p, li { white-space: pre-wrap; } Results (%1) - - [%1]: SQL command successfully executed. <em>%2 <strong>%3</strong></em> - - Rows affected @@ -10435,6 +9762,90 @@ p, li { white-space: pre-wrap; } Clear history + + Close the current SQL script + + + + SQL script currently handled + + + + (not saved) + + + + Handle external SQL script + + + + &Script + + + + Fi&nd + + + + Alt+T + + + + Alt+X + + + + Current working database + + + + Load + 打开 + + + Save + 保存 + + + Save as + 另存为 + + + [%1]: SQL command successfully executed in <em><strong>%2</strong></em>. <em>%3 <strong>%4</strong></em> + + + + Plain format + + + + CVS format + + + + This action will wipe out all the SQL commands history for all connections! Do you really want to proceed? + + + + Save history + + + + Reload history + + + + Find in history + + + + Hide find tool + + + + This action will wipe out all the SQL commands history for the current connection! Do you really want to proceed? + + SQLToolWidget @@ -10490,21 +9901,48 @@ p, li { white-space: pre-wrap; } <strong>ATTENTION:</strong> Disconnect from all databases will close any opened tab in this view! Do you really want to proceed? + + + SceneInfoWidget + + Form + Form + + + Current position of the mouse in the canvas + + - <strong>CAUTION:</strong> You are about to drop the entire database <strong>%1</strong>! All data will be completely wiped out. Do you really want to proceed? + - - You're running a demonstration version! The data manipulation feature is available only in the full version! + Current zoom factor + + + + Currently selected object(s) + + + + Dimensions of the selected object(s) + + + + No selection + + + + N/A + + + + Sel. objects: %1 SchemaWidget - - Form - Form - Show rectangle @@ -10541,15 +9979,15 @@ p, li { white-space: pre-wrap; } 缓存: - Owner: - 所有者: + Owner Col.: + - Form - Form + Defualt values: + - Owner Col.: + User defined @@ -10688,10 +10126,6 @@ p, li { white-space: pre-wrap; } Version: 版本: - - Type: - 类型: - Source code visualization 查看源代码 @@ -10704,10 +10138,6 @@ p, li { white-space: pre-wrap; } -- SQL code unavailable for this type of object -- -- 无法生成此对象类型的 SQL 代码 -- - - Form - Form - PostgreSQL PostgreSQL @@ -10800,20 +10230,52 @@ p, li { white-space: pre-wrap; } ID: - Before: + Before: + + + + Swap the values of the fields + + + + Swap values + + + + Change the objects creation order is an irreversible operation and cause the operations history to be automatically erased. Note that the creation order configured in this form is not definitive and may change after a model validation. + + + + Swap the object ids changing their creation order + + + + Swap ids + + + + Filter: + + + + ID - It's recommended to use this feature only when the SQL validation fails in cases when a object is being referenced in portions where the ordinary validation couldn't reach, e.g., inside of a rule command or check constraint expression. - + Object + 对象 - Swap the values of the fields - + Type + 类型 - Swap values - + Parent Object + 父对象 + + + Parent Type + 父类型 @@ -10837,18 +10299,10 @@ p, li { white-space: pre-wrap; } Add empty rows - - Add - 新建 - Ins Ins - - Some invalid or duplicated columns were detected. In order to solve this issue double-click the header of the highlighted ones in order to define the correct name in which the data belongs to or delete the entire column. Note that these columns are completely igored when generating the <strong>INSERT</strong> commands. - - Add an empty column @@ -10857,10 +10311,6 @@ p, li { white-space: pre-wrap; } Remove all rows from the grid preserving columns - - Clear - - Shift+Del Shift+Del @@ -10869,26 +10319,14 @@ p, li { white-space: pre-wrap; } Delete the selected rows - - Delete - 删除 - Del Del - - <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in <span style=" font-weight:600;">{}</span>. To use <span style=" font-weight:600;">{</span> or <span style=" font-weight:600;">}</span> as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\{</span> or <span style=" font-weight:600;">\}</span>.</p></body></html> - - Duplicate the selected rows - - Duplicate - - Ctrl+D @@ -10926,59 +10364,88 @@ p, li { white-space: pre-wrap; } - (no columns) + Copy items on the grid - - - TableObjectView - -Relationship: %1 + Copy + 复制 + + + Add row - - - TableView - Connected rels: %1 + Delete column - - - TableWidget - Columns - + Paste items on the grid + - Constraints - 约束 + Paste + 粘贴 - Triggers - 触发器 + Ctrl+V + - Rules - 规则 + Fills the grid using a CSV file + - Indexes - 索引 + <html><head/><body><p>Some invalid or duplicated columns were detected. In order to solve this issue double-click the header of the highlighted ones in order to define the correct name in which the data belongs to or delete the entire column. Note that these columns are completely ignored when generating the <span style=" font-weight:600;">INSERT</span> commands.</p></body></html> + - Tables - + Add column + + + + Duplicate rows + + + + Change the values of all selected cells at once + + + + Bulk data edit + + + + Ctrl+E + - Ancestor Tables: - 祖先表: + Delete all columns + + + + Delete rows + + + + <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in two slashes, e.g., <span style=" font-weight:600;">/value/</span>. To use a slash as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\/</span>.</p></body></html> + + + + Delete all rows + + + + TableObjectView - Copied Tables: - 复制的表: + +Relationship: %1 + + + + TableWidget Name 名称 @@ -11011,18 +10478,6 @@ Relationship: %1 Indexing 索引 - - Form - Form - - - With OIDs: - 接受 OIDs: - - - Attribute - 属性 - ON DELETE ON DELETE @@ -11099,6 +10554,62 @@ Relationship: %1 Define initial data for the table + + Enable row level security + + + + Force RLS for owner + + + + &Policies + + + + PK + + + + Attribute(s) + + + + It is not possible to mark a column as primary key when the table already has a primary key which was created by a relationship! This action should be done in the section <strong>Primary key</strong> of the relationship's editing form. + + + + It is not possible to mark a column created by a relationship as primary key! This action should be done in the section <strong>Primary key</strong> of the relationship's editing form. + + + + Command + + + + Permissive + + + + USING expression + + + + CHECK expression + + + + Roles + 角色 + + + Yes + + + + No + + TablespaceWidget @@ -11140,10 +10651,6 @@ Relationship: %1 TaskProgressWidget - - Loading object: [object] (type) - 载入对象:[对象] (类型) - Executing tasks 正在执行的任务 @@ -11167,10 +10674,6 @@ Relationship: %1 Select text color 选择文本颜色 - - Form - Form - Underline 下划线 @@ -11194,14 +10697,6 @@ Relationship: %1 TriggerWidget - - Triggering Mode: - 触发器模式: - - - Execute per row - 逐行执行 - Event: 事件: @@ -11210,18 +10705,6 @@ Relationship: %1 Deferrable: 可延迟: - - Deferral: - 延迟: - - - Referenced Table: - 引用表: - - - Conditional Expr.: - 条件表达式: - Columns @@ -11250,14 +10733,6 @@ Relationship: %1 Type 类型 - - Form - Form - - - INSTEAD OF - INSTEAD OF - INSERT INSERT @@ -11274,10 +10749,6 @@ Relationship: %1 TRUNCATE TRUNCATE - - Constraint Trigger: - 约束触发器: - Constraint 约束 @@ -11317,10 +10788,6 @@ Relationship: %1 Enumeration 枚举 - - Composite - 组合 - Enumerations 枚举 @@ -11341,18 +10808,10 @@ Relationship: %1 Storage: 存储: - - By Value: - 按值: - Category: 类别: - - Preferred: - 首选: - Delimiter: 分隔符: @@ -11369,10 +10828,6 @@ Relationship: %1 Functions 函数 - - Copy Type - 复制类型 - Element Type 元素类型 @@ -11385,10 +10840,6 @@ Relationship: %1 Type 类型 - - Form - Form - char char @@ -11552,22 +11003,10 @@ Relationship: %1 Get source code - - Recover a package - - - - Purchase a new package - - Failed to check updates - - The update notifier failed to check for new versions! Please, verify your internet connectivity and try again! Connection error returned: <strong>%1</strong>. - - No updates found @@ -11580,6 +11019,10 @@ Relationship: %1 The update notifier failed to check for new versions! A HTTP status code was returned: <strong>%1</strong> + + The update notifier failed to check for new versions! Please, verify your internet connectivity and try again! Connection error returned: <em>%1</em> - <strong>%2</strong>. + + ViewWidget @@ -11587,10 +11030,6 @@ Relationship: %1 References 引用 - - Type: - 类型: - Column @@ -11603,10 +11042,6 @@ Relationship: %1 Used in: 被用在: - - After WHERE - WHERE 之后 - Table: 表: @@ -11635,26 +11070,6 @@ Relationship: %1 Code Preview 代码预览 - - To reference all columns in a table (*) just do not fill the field <strong>Column</strong>, this is the same as write <em><strong>[schema].[tablel].*</strong></em> - 要引用表中全部列 (*) 保留空的 <strong>Column</strong> 字段即可,这等同于 <em><strong>[schema].[tablel].*</strong></em> - - - -- Could not generate the code. Make sure all attributes are correctly filled! -- - -- 无法生成代码。请确认已正确填写全部属性! -- - - - Form - Form - - - SELECT-FROM - SELECT-FROM - - - FROM-WHERE - FROM-WHERE - Col./Expr. 列/表达式 @@ -11667,10 +11082,6 @@ Relationship: %1 Alias Col. 列别名 - - SF FW AW - SF FW AW - Reference Type: @@ -11691,10 +11102,6 @@ Relationship: %1 Table Expression - - Flags: SF FW AW VD - - Name 名称 @@ -11751,68 +11158,57 @@ Relationship: %1 With no data - - - VisaoObjetosWidget - - Objects of Model - 模型中的对象 - - - Visible Objects Type - 可见对象类型 - - Select All - 选择全部 + The element will be used as part of the SELECT statement to retrieve columns or expressions that will compose the view's columns + - Clear All - 取消全部 + SELECT ... + - Select - 选择 + The element will be used as part of the WHERE clause in form of conditional expression + - Cancel - 取消 + WHERE ... + - Objects view configuration - 对象视图配置 + The element is used in the FROM portion of the command in order to reference tables or construct JOIN statements + - Tree view - 树视图 + FROM ... + - List view - 列表视图 + The element's expression is used exclusively as the view's definition + - 1 - 1 + The element will be appended to the very end of the view's definition. This is useful when using GROUP BY/HAVING statements + - ... - ... + End expression + - Object - 对象 + Indexes + 索引 - Type - 类型 + Flags: SF FW AW EX VD + - Parent Object - 父对象 + To reference all columns in a table (*) just do not fill the field <strong>Column</strong>, this is the same as write <em><strong>[schema].[table].*</strong></em> + - Parent Type - 父类型 + Indexing + 索引 diff --git a/libobjrenderer/libobjrenderer.pro b/libobjrenderer/libobjrenderer.pro index c01064dd1d..76eb3d3b4f 100644 --- a/libobjrenderer/libobjrenderer.pro +++ b/libobjrenderer/libobjrenderer.pro @@ -25,7 +25,9 @@ HEADERS += src/baseobjectview.h \ src/schemaview.h \ src/roundedrectitem.h \ src/styledtextboxview.h \ - src/beziercurveitem.h + src/beziercurveitem.h \ + src/textpolygonitem.h \ + src/attributestoggleritem.h SOURCES += src/baseobjectview.cpp \ src/textboxview.cpp \ @@ -39,7 +41,9 @@ SOURCES += src/baseobjectview.cpp \ src/schemaview.cpp \ src/roundedrectitem.cpp \ src/styledtextboxview.cpp \ - src/beziercurveitem.cpp + src/beziercurveitem.cpp \ + src/textpolygonitem.cpp \ + src/attributestoggleritem.cpp unix|windows: LIBS += -L$$OUT_PWD/../libpgmodeler/ -lpgmodeler \ -L$$OUT_PWD/../libparsers/ -lparsers \ diff --git a/libobjrenderer/src/attributestoggleritem.cpp b/libobjrenderer/src/attributestoggleritem.cpp new file mode 100644 index 0000000000..3959cb3592 --- /dev/null +++ b/libobjrenderer/src/attributestoggleritem.cpp @@ -0,0 +1,396 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "attributestoggleritem.h" +#include +#include +#include +#include "baseobjectview.h" + +QPolygonF AttributesTogglerItem::btn_polygons[7]; + +AttributesTogglerItem::AttributesTogglerItem(QGraphicsItem *parent) : RoundedRectItem(parent) +{ + createButtonPolygons(); + this->setRoundedCorners(RoundedRectItem::BottomLeftCorner | RoundedRectItem::BottomRightCorner); + sel_rect = new QGraphicsRectItem; + + for(unsigned arr_id = 0; arr_id < 7; arr_id++) + { + buttons[arr_id] = new QGraphicsPolygonItem; + buttons[arr_id]->setPolygon(btn_polygons[arr_id]); + btns_selected[arr_id] = false; + } + + buttons[AttribsExpandBtn]->setToolTip(trUtf8("Expands the currently collapsed section of the object")); + buttons[AttribsCollapseBtn]->setToolTip(trUtf8("Collapses the currently expanded section of the object")); + buttons[NextAttribsPageBtn]->setToolTip(trUtf8("Displays the next attributes page")); + buttons[PrevAttribsPageBtn]->setToolTip(trUtf8("Displays the previous attributes page")); + buttons[NextExtAttribsPageBtn]->setToolTip(trUtf8("Displays the next extended attributes page")); + buttons[PrevExtAttribsPageBtn]->setToolTip(trUtf8("Displays the previous extended attributes page")); + buttons[PaginationTogglerBtn]->setToolTip(trUtf8("Toggles the attributes pagination on the object")); + + has_ext_attribs = false; + pagination_enabled = false; + collapse_mode = CollapseMode::NotCollapsed; + btns_width = btns_height = 0; + + for(unsigned idx = 0; idx < 2; idx++) + current_page[idx] = max_pages[idx] = 0; + + configureButtonsState(); +} + +AttributesTogglerItem::~AttributesTogglerItem(void) +{ + for(unsigned arr_id = 0; arr_id < 7; arr_id++) + delete(buttons[arr_id]); + + delete(sel_rect); +} + +void AttributesTogglerItem::setButtonsBrush(const QBrush &brush) +{ + for(unsigned arr_id = 0; arr_id < 7; arr_id++) + buttons[arr_id]->setBrush(brush); +} + +void AttributesTogglerItem::setButtonsPen(const QPen &pen) +{ + for(unsigned arr_id = 0; arr_id < 7; arr_id++) + buttons[arr_id]->setPen(pen); +} + +void AttributesTogglerItem::setRect(const QRectF &rect) +{ + configureButtons(rect); +} + +void AttributesTogglerItem::setCollapseMode(CollapseMode coll_mode) +{ + //Avoiding setting up extended attributes collapsed when the toggler is configured to not having extended attribs + if(!has_ext_attribs && coll_mode == CollapseMode::ExtAttribsCollapsed) + collapse_mode = CollapseMode::NotCollapsed; + else + collapse_mode = coll_mode; + + configureButtonsState(); +} + +void AttributesTogglerItem::setButtonSelected(const QPointF &pnt, bool clicked) +{ + QRectF rect; + double h_spacing = 4 * BaseObjectView::HorizSpacing; + unsigned coll_mode = static_cast(collapse_mode), section_id = 0; + + this->setToolTip(QString()); + clearButtonsSelection(); + + for(unsigned arr_id = 0; arr_id < 7; arr_id++) + { + rect.setSize(QSizeF(buttons[arr_id]->boundingRect().width() + h_spacing, this->boundingRect().height())); + rect.moveTo(buttons[arr_id]->pos().x() - (h_spacing/2), 0); + btns_selected[arr_id] = rect.contains(pnt) && buttons[arr_id]->isVisible(); + + if(btns_selected[arr_id]) + { + this->setToolTip(buttons[arr_id]->toolTip()); + + if(clicked) + { + if(arr_id == AttribsExpandBtn || arr_id == AttribsCollapseBtn) + { + if(arr_id == AttribsExpandBtn) + coll_mode++; + else if(arr_id == AttribsCollapseBtn) + coll_mode--; + + if(!has_ext_attribs && static_cast(coll_mode) == CollapseMode::ExtAttribsCollapsed) + coll_mode += (arr_id == AttribsExpandBtn ? 1 : -1); + + if(coll_mode > enum_cast(CollapseMode::NotCollapsed)) + collapse_mode = (arr_id == AttribsExpandBtn ? CollapseMode::NotCollapsed : CollapseMode::AllAttribsCollapsed); + else + collapse_mode = static_cast(coll_mode); + } + else if(arr_id == PaginationTogglerBtn) + { + pagination_enabled = !pagination_enabled; + } + else + { + if(arr_id == PrevAttribsPageBtn || arr_id == NextAttribsPageBtn) + section_id = BaseTable::AttribsSection; + else + section_id = BaseTable::ExtAttribsSection; + + if(max_pages[section_id] != 0) + { + if(arr_id == PrevAttribsPageBtn || arr_id == PrevExtAttribsPageBtn) + current_page[section_id]--; + else + current_page[section_id]++; + + if(current_page[section_id] >= max_pages[section_id]) + current_page[section_id] = (arr_id == PrevAttribsPageBtn || arr_id == PrevExtAttribsPageBtn ? 0 : max_pages[section_id] - 1); + } + } + + configureButtons(this->rect()); + clearButtonsSelection(); + configureButtonsState(); + + if(arr_id == PaginationTogglerBtn) + emit s_paginationToggled(pagination_enabled); + else if(arr_id == AttribsExpandBtn || arr_id == AttribsCollapseBtn) + emit s_collapseModeChanged(collapse_mode); + else + emit s_currentPageChanged(section_id, current_page[section_id]); + } + else + { + //Configuring the selection rectangle if the arrows isn't clicked + QRectF rect; + QSizeF size = QSizeF(buttons[AttribsExpandBtn]->boundingRect().size().width() + (2 * BaseObjectView::HorizSpacing), + btns_height + BaseObjectView::VertSpacing); + double px = 0, py = 0, arr_x = buttons[arr_id]->pos().x(); + + rect.setSize(size); + px = arr_x - (((arr_x + size.width()) - (arr_x + buttons[arr_id]->boundingRect().width()))/2); + py = (this->boundingRect().size().height() - size.height())/2.5; + + sel_rect->setBrush(BaseObjectView::getFillStyle(Attributes::ObjSelection)); + sel_rect->setPen(BaseObjectView::getBorderStyle(Attributes::ObjSelection)); + sel_rect->setRect(rect); + sel_rect->setPos(px, py); + } + + break; + } + } +} + +void AttributesTogglerItem::configureButtonsState(void) +{ + buttons[AttribsExpandBtn]->setOpacity(collapse_mode == CollapseMode::ExtAttribsCollapsed || + collapse_mode == CollapseMode::AllAttribsCollapsed? 1 : ButtonMinOpacity); + + buttons[AttribsCollapseBtn]->setOpacity(collapse_mode == CollapseMode::ExtAttribsCollapsed || + collapse_mode == CollapseMode::NotCollapsed ? 1 : ButtonMinOpacity); + + buttons[PrevAttribsPageBtn]->setOpacity(max_pages[BaseTable::AttribsSection] != 0 && current_page[BaseTable::AttribsSection] > 0 ? 1 : ButtonMinOpacity); + buttons[NextAttribsPageBtn]->setOpacity(max_pages[BaseTable::AttribsSection] != 0 && + current_page[BaseTable::AttribsSection] < max_pages[BaseTable::AttribsSection] - 1 ? 1 : ButtonMinOpacity); + + buttons[PrevExtAttribsPageBtn]->setOpacity(has_ext_attribs && max_pages[BaseTable::ExtAttribsSection] != 0 && current_page[BaseTable::ExtAttribsSection] > 0 ? 1 : ButtonMinOpacity); + buttons[NextExtAttribsPageBtn]->setOpacity(has_ext_attribs && max_pages[BaseTable::ExtAttribsSection] != 0 && + current_page[BaseTable::ExtAttribsSection] < max_pages[BaseTable::ExtAttribsSection] - 1 ? 1 : ButtonMinOpacity); + + buttons[PrevAttribsPageBtn]->setVisible(pagination_enabled); + buttons[NextAttribsPageBtn]->setVisible(pagination_enabled); + buttons[PrevExtAttribsPageBtn]->setVisible(pagination_enabled); + buttons[NextExtAttribsPageBtn]->setVisible(pagination_enabled); +} + +void AttributesTogglerItem::setHasExtAttributes(bool value) +{ + has_ext_attribs = value; + configureButtonsState(); +} + +void AttributesTogglerItem::setPaginationEnabled(bool value, bool hide_pag_toggler) +{ + buttons[PaginationTogglerBtn]->setVisible(!hide_pag_toggler); + pagination_enabled = value; + configureButtons(this->boundingRect()); + configureButtonsState(); +} + +void AttributesTogglerItem::setPaginationValues(unsigned section_id, unsigned curr_page, unsigned max_page) +{ + if(!pagination_enabled || section_id > BaseTable::ExtAttribsSection) + return; + + if(curr_page > max_page) + current_page[section_id] = max_pages[section_id] = max_page; + else + { + current_page[section_id] = curr_page; + max_pages[section_id] = max_page; + } +} + +void AttributesTogglerItem::clearButtonsSelection(void) +{ + for(unsigned arr_id = 0; arr_id < 7; arr_id++) + btns_selected[arr_id] = false; + + this->update(); +} + +double AttributesTogglerItem::getButtonsWidth(void) +{ + return(btns_width); +} + +double AttributesTogglerItem::getButtonsHeight(void) +{ + return(btns_height); +} + +void AttributesTogglerItem::configureButtons(const QRectF &rect) +{ + double arr_width = 0, px = 0, + h_spacing = 6 * BaseObjectView::HorizSpacing, + height = 4 * BaseObjectView::VertSpacing; + QRectF new_rect = rect; + + btns_height = btn_polygons[PrevAttribsPageBtn].boundingRect().height(); + height += btns_height; + + if(pagination_enabled) + { + arr_width = btn_polygons[PrevAttribsPageBtn].boundingRect().width() + + btn_polygons[NextAttribsPageBtn].boundingRect().width() + + btn_polygons[PrevExtAttribsPageBtn].boundingRect().width() + + btn_polygons[NextExtAttribsPageBtn].boundingRect().width() + + (4 * h_spacing); + } + + arr_width += btn_polygons[AttribsCollapseBtn].boundingRect().width() + + btn_polygons[AttribsExpandBtn].boundingRect().width() + (2 * h_spacing); + + if(buttons[PaginationTogglerBtn]->isVisible()) + arr_width += btn_polygons[AttribsExpandBtn].boundingRect().width() + h_spacing; + + btns_width = arr_width; + new_rect.setHeight(height); + RoundedRectItem::setRect(new_rect); + + px = (new_rect.width() - arr_width + h_spacing)/2; + + if(buttons[PaginationTogglerBtn]->isVisible()) + { + buttons[PaginationTogglerBtn]->setPos(px, (new_rect.height() - buttons[PaginationTogglerBtn]->boundingRect().height())/2); + px += buttons[PaginationTogglerBtn]->boundingRect().width() + h_spacing; + + if(pagination_enabled) + { + buttons[PrevExtAttribsPageBtn]->setPos(px, (new_rect.height() - buttons[PrevExtAttribsPageBtn]->boundingRect().height())/2); + px += buttons[PrevExtAttribsPageBtn]->boundingRect().width() + h_spacing; + + buttons[PrevAttribsPageBtn]->setPos(px, (new_rect.height() - buttons[PrevAttribsPageBtn]->boundingRect().height())/2); + px += buttons[PrevAttribsPageBtn]->boundingRect().width() + h_spacing; + + buttons[NextAttribsPageBtn]->setPos(px, (new_rect.height() - buttons[NextAttribsPageBtn]->boundingRect().height())/2); + px += buttons[PrevExtAttribsPageBtn]->boundingRect().width() + h_spacing; + + buttons[NextExtAttribsPageBtn]->setPos(px, (new_rect.height() - buttons[NextExtAttribsPageBtn]->boundingRect().height())/2); + px += buttons[NextExtAttribsPageBtn]->boundingRect().width() + h_spacing; + } + } + + buttons[AttribsCollapseBtn]->setPos(px, (new_rect.height() - buttons[AttribsCollapseBtn]->boundingRect().height())/2); + px += buttons[AttribsCollapseBtn]->boundingRect().width() + h_spacing * 0.80; + + buttons[AttribsExpandBtn]->setPos(px, (new_rect.height() - buttons[AttribsExpandBtn]->boundingRect().height())/2); +} + +void AttributesTogglerItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + QGraphicsItem *parent = this->parentItem(); + RoundedRectItem::paint(painter, option, widget); + + for(unsigned arr_id = 0; arr_id < 7; arr_id++) + { + if(!buttons[arr_id]->isVisible()) + continue; + + painter->save(); + painter->translate(buttons[arr_id]->pos()); + painter->setOpacity(buttons[arr_id]->opacity() * (parent ? parent->opacity() : 1)); + buttons[arr_id]->paint(painter, option, widget); + painter->restore(); + + // Drawing the selection rectangle over the button if it isn't faded + if(btns_selected[arr_id] && buttons[arr_id]->opacity() > ButtonMinOpacity) + { + painter->save(); + painter->translate(sel_rect->pos()); + sel_rect->paint(painter, option, widget); + painter->restore(); + } + } +} + +void AttributesTogglerItem::createButtonPolygons(void) +{ + if(!btn_polygons[0].isEmpty()) + return; + + QPolygonF *pol = nullptr; + double fnt_factor = qApp->screens().at(qApp->desktop()->screenNumber(qApp->activeWindow()))->logicalDotsPerInch() / 96.0, + pixel_ratio = qApp->screens().at(qApp->desktop()->screenNumber(qApp->activeWindow()))->devicePixelRatio(), + factor = fnt_factor * pixel_ratio; + + pol = &btn_polygons[PrevAttribsPageBtn]; + pol->append(QPointF(0, 5 * factor)); + pol->append(QPointF(8 * factor, 0)); + pol->append(QPointF(8 * factor, 10 * factor)); + + pol = &btn_polygons[NextAttribsPageBtn]; + pol->append(QPointF(0, 0)); + pol->append(QPointF(8 * factor, 5 * factor)); + pol->append(QPointF(0, 10 * factor)); + + pol = &btn_polygons[PrevExtAttribsPageBtn]; + pol->append(QPointF(0, 0)); + pol->append(QPointF(2 * factor, 0)); + pol->append(QPointF(2 * factor, 4 * factor)); + pol->append(QPointF(8 * factor, 0)); + pol->append(QPointF(8 * factor, 10 * factor)); + pol->append(QPointF(2 * factor, 6 * factor)); + pol->append(QPointF(2 * factor, 10 * factor)); + pol->append(QPointF(0, 10 * factor)); + + pol = &btn_polygons[NextExtAttribsPageBtn]; + pol->append(QPointF(0, 0)); + pol->append(QPointF(6 * factor, 4 * factor)); + pol->append(QPointF(6 * factor, 0 * factor)); + pol->append(QPointF(8 * factor, 0)); + pol->append(QPointF(8 * factor, 10 * factor)); + pol->append(QPointF(6 * factor, 10 * factor)); + pol->append(QPointF(6 * factor, 6 * factor)); + pol->append(QPointF(0, 10 * factor)); + + pol = &btn_polygons[AttribsCollapseBtn]; + pol->append(QPointF(5 * factor, 0)); + pol->append(QPointF(0, 8 * factor)); + pol->append(QPointF(10 * factor, 8 * factor)); + + pol = &btn_polygons[AttribsExpandBtn]; + pol->append(QPointF(0, 0)); + pol->append(QPointF(10 * factor, 0)); + pol->append(QPointF(5 * factor, 8 * factor)); + + pol = &btn_polygons[PaginationTogglerBtn]; + pol->append(QPointF(4 * factor, 0)); + pol->append(QPointF(8 * factor, 4 * factor)); + pol->append(QPointF(4 * factor, 8 * factor)); + pol->append(QPointF(0, 4 * factor)); +} diff --git a/libobjrenderer/src/attributestoggleritem.h b/libobjrenderer/src/attributestoggleritem.h new file mode 100644 index 0000000000..794a4bc1f6 --- /dev/null +++ b/libobjrenderer/src/attributestoggleritem.h @@ -0,0 +1,160 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +/** +\ingroup libobjrenderer +\class AttributesTogglerItem +\brief Implements a basic table's attributes toggler/pagination used by BaseTableView. +*/ + +#ifndef ATTRIBUTES_TOGGLER_ITEM_H +#define ATTRIBUTES_TOGGLER_ITEM_H + +#include +#include +#include "roundedrectitem.h" +#include "basetable.h" + +class AttributesTogglerItem: public QObject, public RoundedRectItem { + private: + Q_OBJECT + + static QPolygonF btn_polygons[7]; + + //! \brief Stores the selection rectangle of the item's internal elements + QGraphicsRectItem *sel_rect; + + //! \brief Stores the current collasping mode related to the table associated to this toggler + CollapseMode collapse_mode; + + //! \brief Stores the polygonal items denoting the control buttons of the toggler + QGraphicsPolygonItem *buttons[7]; + + //! \brief Stores the selected status of the buttons + bool btns_selected[7], + + /*! \brief Indicates if the table associated to this toggler has extended attributes + * This attribute changes the way some buttons are rendered */ + has_ext_attribs, + + //! \brief Indicates if the pagination is enabled for the table associated to this toggler + pagination_enabled; + + //! \brief Stores the width of all visible buttons + double btns_width, + + //! \brief Stores the height of all visible buttons + btns_height; + + //! \brief Store the current page visible on the table associated to this toggler + unsigned current_page[2], + + //! \brief Store the maximum pages allowed for the table associated to this toggler + max_pages[2]; + + //! \brief The minimum opacity factor used to fade buttons + static constexpr double ButtonMinOpacity = 0.40; + + //! \brief Constant used to reference the attributes expand button + static constexpr unsigned AttribsExpandBtn=0, + + //! \brief Constant used to reference the attributes collapse button + AttribsCollapseBtn=1, + + //! \brief Constant used to reference the next page button + NextAttribsPageBtn=2, + + //! \brief Constant used to reference the previous page button + PrevAttribsPageBtn=3, + + //! \brief Constant used to reference the next page button + NextExtAttribsPageBtn=4, + + //! \brief Constant used to reference the previous page button + PrevExtAttribsPageBtn=5, + + //! \brief Constant used to reference the pagination toggler button + PaginationTogglerBtn=6; + + /*! \brief Configures the postion and dimensions of the buttons based on the provided bounding rect + * If the provided rect is smaller than the total width/height of the buttons it will be assumed + * as bouding rect the latter dimensions */ + void configureButtons(const QRectF &rect); + + /*! \brief Configure the buttons visibility and opacity based upon the current values + * of pagination and collapse mode */ + void configureButtonsState(void); + + static void createButtonPolygons(void); + + public: + AttributesTogglerItem(QGraphicsItem *parent = nullptr); + ~AttributesTogglerItem(void); + + //! \brief Configures the buttons brush + void setButtonsBrush(const QBrush &brush); + + //! \brief Configures the buttons pen + void setButtonsPen(const QPen &pen); + + //! \brief Configures the bounding rect of the whole toggler item + void setRect(const QRectF &rect); + + //! \brief Configures the current collapse mode of the toggler + void setCollapseMode(CollapseMode coll_mode); + + /*! \brief Set a button selected (highlighted by the selection rectangle) if the provided + * point is within a button's bouding rect. The parameter 'clicked' indicates if the button + * is also clicked and not only hovered (the default behaviour) which causes addtional actions to be executed */ + void setButtonSelected(const QPointF &pnt, bool clicked = false); + + //! \brief Defines if the toggles is controlling extended attributes pagination/collapsing + void setHasExtAttributes(bool value); + + /*! \brief Toggles the pagination. If the hide_pag_toggler is set then the button that enables/disables + * the pagination will be hidden permanently and the pagination automatically disabled */ + void setPaginationEnabled(bool value, bool hide_pag_toggler = false); + + /*! \brief Defines the current values of the pagination (current page and maximum allowed pages) + * Thes values are used to control the buttons fading when the page navigation reaches one of the limits (min/max) */ + void setPaginationValues(unsigned page_id, unsigned curr_page, unsigned max_page); + + //! \brief Clears the selection status of the buttons + void clearButtonsSelection(void); + + //! \brief Returns the width of the area occupied by all buttons (including spacing between them) + double getButtonsWidth(void); + + //! \brief Returns the height of the area occupied by all buttons (including a vertical spacing) + double getButtonsHeight(void); + + //! \brief Paints the toggler and its internal componets + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr); + + signals: + //! \brief Signal emitted when the current collapse mode changes (the user clicks the collpase/expand buttons) + void s_collapseModeChanged(CollapseMode); + + //! \brief Signal emitted when the current page changes (the user clicks the page navigation buttons) + void s_currentPageChanged(unsigned, unsigned); + + //! \brief Signal emitted when the user clicks the pagination toggler buttons + void s_paginationToggled(bool); +}; + +#endif diff --git a/libobjrenderer/src/baseobjectview.cpp b/libobjrenderer/src/baseobjectview.cpp index 396741816e..0d2884b382 100644 --- a/libobjrenderer/src/baseobjectview.cpp +++ b/libobjrenderer/src/baseobjectview.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -19,11 +19,13 @@ #include "baseobjectview.h" #include "textboxview.h" #include "roundedrectitem.h" +#include "objectsscene.h" map BaseObjectView::font_config; map> BaseObjectView::color_config; unsigned BaseObjectView::global_sel_order=1; bool BaseObjectView::use_placeholder=true; +bool BaseObjectView::compact_view=false; BaseObjectView::BaseObjectView(BaseObject *object) { @@ -31,10 +33,8 @@ BaseObjectView::BaseObjectView(BaseObject *object) protected_icon=nullptr; obj_shadow=nullptr; obj_selection=nullptr; - pos_info_rect=nullptr; - pos_info_txt=nullptr; - sql_disabled_txt=nullptr; - sql_disabled_box=nullptr; + pos_info_item=nullptr; + sql_disabled_item=nullptr; placeholder=nullptr; setSourceObject(object); } @@ -71,13 +71,6 @@ void BaseObjectView::setSourceObject(BaseObject *object) if(!graph_obj) { - if(obj_selection) - { - this->removeFromGroup(obj_selection); - delete(obj_selection); - obj_selection=nullptr; - } - if(obj_shadow) { this->removeFromGroup(obj_shadow); @@ -92,26 +85,18 @@ void BaseObjectView::setSourceObject(BaseObject *object) protected_icon=nullptr; } - if(pos_info_txt) + if(pos_info_item) { - this->removeFromGroup(pos_info_txt); - delete(pos_info_txt); - pos_info_txt=nullptr; - - this->removeFromGroup(pos_info_rect); - delete(pos_info_rect); - pos_info_rect=nullptr; + this->removeFromGroup(pos_info_item); + delete(pos_info_item); + pos_info_item=nullptr; } - if(sql_disabled_box) + if(sql_disabled_item) { - this->removeFromGroup(sql_disabled_txt); - delete(sql_disabled_txt); - sql_disabled_txt=nullptr; - - this->removeFromGroup(sql_disabled_box); - delete(sql_disabled_box); - sql_disabled_box=nullptr; + this->removeFromGroup(sql_disabled_item); + delete(sql_disabled_item); + sql_disabled_item=nullptr; } if(placeholder) @@ -149,56 +134,27 @@ void BaseObjectView::setSourceObject(BaseObject *object) this->addToGroup(protected_icon); } - if(!pos_info_txt) + if(!pos_info_item) { - pos_info_rect=new QGraphicsRectItem; - pos_info_txt=new QGraphicsSimpleTextItem; - pos_info_rect->setZValue(9); - pos_info_txt->setZValue(10); - - this->addToGroup(pos_info_rect); - this->addToGroup(pos_info_txt); + pos_info_item=new TextPolygonItem; + pos_info_item->setZValue(10); + this->addToGroup(pos_info_item); } - if(!sql_disabled_box && object->getObjectType()!=OBJ_TEXTBOX) + if(!sql_disabled_item && object->getObjectType()!=ObjectType::Textbox) { - sql_disabled_txt=new QGraphicsSimpleTextItem; - sql_disabled_box=new QGraphicsRectItem; - sql_disabled_txt->setZValue(100); - sql_disabled_box->setZValue(99); - - this->addToGroup(sql_disabled_box); - this->addToGroup(sql_disabled_txt); + sql_disabled_item=new TextPolygonItem; + sql_disabled_item->setZValue(100); + this->addToGroup(sql_disabled_item); } } } -BaseObject *BaseObjectView::getSourceObject(void) +BaseObject *BaseObjectView::getUnderlyingObject(void) { return(reinterpret_cast(this->data(0).value())); } -void BaseObjectView::resizePolygon(QPolygonF &pol, double width, double height) -{ - QVector::iterator itr,itr_end; - double coef_a, coef_b; - - itr=pol.begin(); - itr_end=pol.end(); - - //Calculates the resize factor - coef_a=width / pol.boundingRect().width(); - coef_b=height / pol.boundingRect().height(); - - //Applies the resize factor to all the polygon points - while(itr!=itr_end) - { - itr->setX(itr->x() * coef_a); - itr->setY(itr->y() * coef_b); - itr++; - } -} - void BaseObjectView::loadObjectsStyle(void) { QTextCharFormat font_fmt; @@ -207,22 +163,22 @@ void BaseObjectView::loadObjectsStyle(void) map::iterator itr; QStringList list; QString elem, - config_file=GlobalAttributes::CONFIGURATIONS_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::OBJECTS_STYLE_CONF + GlobalAttributes::CONFIGURATION_EXT; - XMLParser xmlparser; + config_file=GlobalAttributes::ConfigurationsDir + GlobalAttributes::DirSeparator + + GlobalAttributes::ObjectsStyleConf + GlobalAttributes::ConfigurationExt; + XmlParser xmlparser; try { xmlparser.restartParser(); - xmlparser.setDTDFile(GlobalAttributes::TMPL_CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::OBJECT_DTD_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::OBJECTS_STYLE_CONF + - GlobalAttributes::OBJECT_DTD_EXT, GlobalAttributes::OBJECTS_STYLE_CONF); + xmlparser.setDTDFile(GlobalAttributes::TmplConfigurationDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::ObjectDTDDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::ObjectsStyleConf + + GlobalAttributes::ObjectDTDExt, GlobalAttributes::ObjectsStyleConf); xmlparser.loadXMLFile(config_file); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -231,46 +187,46 @@ void BaseObjectView::loadObjectsStyle(void) xmlparser.getElementAttributes(attribs); elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::GLOBAL) + if(elem==Attributes::Global) { - font.setFamily(attribs[ParsersAttributes::FONT]); - font.setPointSizeF(attribs[ParsersAttributes::SIZE].toDouble()); - font.setBold(attribs[ParsersAttributes::BOLD]==ParsersAttributes::_TRUE_); - font.setItalic(attribs[ParsersAttributes::ITALIC]==ParsersAttributes::_TRUE_); - font.setUnderline(attribs[ParsersAttributes::UNDERLINE]==ParsersAttributes::_TRUE_); + font.setFamily(attribs[Attributes::Font]); + font.setPointSizeF(attribs[Attributes::Size].toDouble()); + font.setBold(attribs[Attributes::Bold]==Attributes::True); + font.setItalic(attribs[Attributes::Italic]==Attributes::True); + font.setUnderline(attribs[Attributes::Underline]==Attributes::True); font_fmt.setFont(font); - font_config[ParsersAttributes::GLOBAL]=font_fmt; + font_config[Attributes::Global]=font_fmt; } - else if(elem==ParsersAttributes::FONT) + else if(elem==Attributes::Font) { - font_config[attribs[ParsersAttributes::ID]]=font_fmt; - itr=font_config.find(attribs[ParsersAttributes::ID]); + font_config[attribs[Attributes::Id]]=font_fmt; + itr=font_config.find(attribs[Attributes::Id]); font=font_fmt.font(); - font.setBold(attribs[ParsersAttributes::BOLD]==ParsersAttributes::_TRUE_); - font.setItalic(attribs[ParsersAttributes::ITALIC]==ParsersAttributes::_TRUE_); - font.setUnderline(attribs[ParsersAttributes::UNDERLINE]==ParsersAttributes::_TRUE_); + font.setBold(attribs[Attributes::Bold]==Attributes::True); + font.setItalic(attribs[Attributes::Italic]==Attributes::True); + font.setUnderline(attribs[Attributes::Underline]==Attributes::True); (itr->second).setFont(font); - (itr->second).setForeground(QColor(attribs[ParsersAttributes::COLOR])); + (itr->second).setForeground(QColor(attribs[Attributes::Color])); } - else if(elem==ParsersAttributes::OBJECT) + else if(elem==Attributes::Object) { - list=attribs[ParsersAttributes::FILL_COLOR].split(','); + list=attribs[Attributes::FillColor].split(','); vector colors; colors.push_back(!list.isEmpty() ? QColor(list[0]) : QColor(0,0,0)); colors.push_back(list.size()==2 ? QColor(list[1]) : colors[0]); - colors.push_back(QColor(attribs[ParsersAttributes::BORDER_COLOR])); + colors.push_back(QColor(attribs[Attributes::BorderColor])); - color_config[attribs[ParsersAttributes::ID]]=colors; + color_config[attribs[Attributes::Id]]=colors; } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(), __PRETTY_FUNCTION__, __FILE__, __LINE__, &e, config_file); + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__, __FILE__, __LINE__, &e, config_file); } } @@ -278,9 +234,9 @@ void BaseObjectView::setFontStyle(const QString &id, QTextCharFormat font_fmt) { QFont font; - if(id!=ParsersAttributes::GLOBAL) + if(id!=Attributes::Global) { - font=font_config[ParsersAttributes::GLOBAL].font(); + font=font_config[Attributes::Global].font(); font.setItalic(font_fmt.font().italic()); font.setBold(font_fmt.font().bold()); font.setUnderline(font_fmt.font().underline()); @@ -342,10 +298,10 @@ QLinearGradient BaseObjectView::getFillStyle(const QString &id) if(!colors.empty()) { - if(id==ParsersAttributes::OBJ_SELECTION || id==ParsersAttributes::PLACEHOLDER) + if(id==Attributes::ObjSelection || id==Attributes::Placeholder) { - colors[0].setAlpha(OBJ_ALPHA_CHANNEL); - colors[1].setAlpha(OBJ_ALPHA_CHANNEL); + colors[0].setAlpha(ObjectAlphaChannel); + colors[1].setAlpha(ObjectAlphaChannel); } grad.setCoordinateMode(QGradient::ObjectBoundingMode); @@ -368,10 +324,10 @@ QPen BaseObjectView::getBorderStyle(const QString &id) if(!colors.empty()) { - if(id==ParsersAttributes::OBJ_SELECTION) - colors[2].setAlpha(OBJ_ALPHA_CHANNEL); + if(id==Attributes::ObjSelection) + colors[2].setAlpha(ObjectAlphaChannel); - pen.setWidthF(OBJ_BORDER_WIDTH); + pen.setWidthF(ObjectBorderWidth); pen.setColor(colors[2]); } } @@ -397,14 +353,27 @@ bool BaseObjectView::isPlaceholderEnabled(void) return(use_placeholder); } +void BaseObjectView::setCompactViewEnabled(bool value) +{ + compact_view = value; +} + +bool BaseObjectView::isCompactViewEnabled(void) +{ + return(compact_view); +} + QVariant BaseObjectView::itemChange(GraphicsItemChange change, const QVariant &value) { if(change==ItemPositionHasChanged) { - BaseGraphicObject *graph_obj=dynamic_cast(this->getSourceObject()); + BaseGraphicObject *graph_obj=dynamic_cast(this->getUnderlyingObject()); if(graph_obj && !graph_obj->isProtected()) { + if(ObjectsScene::isAlignObjectsToGrid()) + this->setPos(ObjectsScene::alignPointToGrid(this->scenePos())); + graph_obj->setPosition(this->scenePos()); this->configurePositionInfo(this->pos()); } @@ -412,12 +381,11 @@ QVariant BaseObjectView::itemChange(GraphicsItemChange change, const QVariant &v else if(change == ItemSelectedHasChanged && obj_selection) { this->setSelectionOrder(value.toBool()); - pos_info_rect->setVisible(value.toBool()); - pos_info_txt->setVisible(value.toBool()); + pos_info_item->setVisible(value.toBool()); obj_selection->setVisible(value.toBool()); this->configurePositionInfo(this->pos()); - emit s_objectSelected(dynamic_cast(this->getSourceObject()), value.toBool()); + emit s_objectSelected(dynamic_cast(this->getUnderlyingObject()), value.toBool()); } return(value); @@ -438,7 +406,7 @@ QRectF BaseObjectView::boundingRect(void) const void BaseObjectView::toggleProtectionIcon(bool value) { - BaseGraphicObject *obj_graf=dynamic_cast(this->getSourceObject()); + BaseGraphicObject *obj_graf=dynamic_cast(this->getUnderlyingObject()); protected_icon->setVisible(value); this->setFlag(QGraphicsItem::ItemIsMovable, !value); @@ -447,85 +415,71 @@ void BaseObjectView::toggleProtectionIcon(bool value) obj_graf->setModified(true); } +void BaseObjectView::configureObjectSelection(void) +{ + RoundedRectItem *rect_item=dynamic_cast(obj_selection); + + if(rect_item) + { + rect_item->setRect(this->boundingRect()); + rect_item->setPos(0, 0); + rect_item->setBorderRadius(5); + rect_item->setBrush(this->getFillStyle(Attributes::ObjSelection)); + rect_item->setPen(this->getBorderStyle(Attributes::ObjSelection)); + } +} + void BaseObjectView::configurePositionInfo(QPointF pos) { if(this->isSelected()) { - QFont fnt=font_config[ParsersAttributes::POSITION_INFO].font(); + QFont fnt=font_config[Attributes::PositionInfo].font(); - pos_info_rect->setBrush(BaseObjectView::getFillStyle(ParsersAttributes::POSITION_INFO)); - pos_info_rect->setPen(BaseObjectView::getBorderStyle(ParsersAttributes::POSITION_INFO)); + pos_info_item->setBrush(BaseObjectView::getFillStyle(Attributes::PositionInfo)); + pos_info_item->setPen(BaseObjectView::getBorderStyle(Attributes::PositionInfo)); fnt.setPointSizeF(fnt.pointSizeF() * 0.95); - pos_info_txt->setFont(fnt); - pos_info_txt->setBrush(font_config[ParsersAttributes::POSITION_INFO].foreground()); + pos_info_item->setFont(fnt); + pos_info_item->setTextBrush(font_config[Attributes::PositionInfo].foreground()); + + pos_info_item->setText(QString(" x:%1 y:%2 ").arg(round(pos.x())).arg(round(pos.y()))); + pos_info_item->setPolygon(QPolygonF(pos_info_item->getTextBoundingRect())); - pos_info_txt->setText(QString(" x:%1 y:%2 ").arg(roundf(pos.x())).arg(roundf(pos.y()))); - pos_info_rect->setRect(pos_info_txt->boundingRect()); - pos_info_txt->setPos(-0.5, -pos_info_txt->boundingRect().height()/2); - pos_info_rect->setPos(-0.5, -pos_info_rect->boundingRect().height()/2); + pos_info_item->setPos(-0.5, -pos_info_item->boundingRect().height()/2); } } void BaseObjectView::configureSQLDisabledInfo(void) { - if(sql_disabled_box) + if(sql_disabled_item) { double px=0, py=0; - sql_disabled_txt->setVisible(this->getSourceObject()->isSQLDisabled()); - sql_disabled_box->setVisible(this->getSourceObject()->isSQLDisabled()); + sql_disabled_item->setVisible(this->getUnderlyingObject()->isSQLDisabled()); - if(this->getSourceObject()->isSQLDisabled()) + if(this->getUnderlyingObject()->isSQLDisabled()) { QTextCharFormat char_fmt; - char_fmt=BaseObjectView::getFontStyle(ParsersAttributes::POSITION_INFO); + char_fmt=BaseObjectView::getFontStyle(Attributes::PositionInfo); char_fmt.setFontPointSize(char_fmt.font().pointSizeF() * 0.80); - sql_disabled_txt->setFont(char_fmt.font()); - sql_disabled_txt->setText(trUtf8("SQL off")); - sql_disabled_txt->setBrush(char_fmt.foreground()); + sql_disabled_item->setFont(char_fmt.font()); + sql_disabled_item->setText(trUtf8("SQL off")); + sql_disabled_item->setTextBrush(char_fmt.foreground()); - sql_disabled_box->setRect(QRectF(QPointF(0,0), sql_disabled_txt->boundingRect().size() + QSizeF(1.5 * HORIZ_SPACING, 1.5 * VERT_SPACING))); - sql_disabled_box->setPen(BaseObjectView::getBorderStyle(ParsersAttributes::POSITION_INFO)); - sql_disabled_box->setBrush(BaseObjectView::getFillStyle(ParsersAttributes::POSITION_INFO)); + sql_disabled_item->setPolygon(QRectF(QPointF(0,0), sql_disabled_item->getTextBoundingRect().size() + QSizeF(1.5 * HorizSpacing, 1.5 * VertSpacing))); + sql_disabled_item->setPen(BaseObjectView::getBorderStyle(Attributes::PositionInfo)); + sql_disabled_item->setBrush(BaseObjectView::getFillStyle(Attributes::PositionInfo)); - px=bounding_rect.width() - sql_disabled_box->boundingRect().width() + (1.5 * HORIZ_SPACING), - py=-(sql_disabled_box->boundingRect().height()/2); + px=bounding_rect.width() - sql_disabled_item->boundingRect().width() + (1.5 * HorizSpacing); + py=-(sql_disabled_item->boundingRect().height()/2); - sql_disabled_txt->setPos(px + (HORIZ_SPACING * 0.75), py + (VERT_SPACING * 0.75)); - sql_disabled_box->setPos(px, py); + sql_disabled_item->setPos(px, py); + sql_disabled_item->setTextPos(HorizSpacing * 0.75, VertSpacing * 0.75); } } } -void BaseObjectView::configureObjectShadow(void) -{ - RoundedRectItem *rect_item=dynamic_cast(obj_shadow); - - if(rect_item) - { - rect_item->setPen(Qt::NoPen); - rect_item->setBrush(QColor(50,50,50,60)); - rect_item->setRect(this->boundingRect()); - rect_item->setPos(3.5,3.5); - } -} - -void BaseObjectView::configureObjectSelection(void) -{ - RoundedRectItem *rect_item=dynamic_cast(obj_selection); - - if(rect_item) - { - rect_item->setRect(this->boundingRect()); - rect_item->setPos(0,0); - rect_item->setBorderRadius(5); - rect_item->setBrush(this->getFillStyle(ParsersAttributes::OBJ_SELECTION)); - rect_item->setPen(this->getBorderStyle(ParsersAttributes::OBJ_SELECTION)); - } -} - void BaseObjectView::configureProtectedIcon(void) { if(protected_icon) @@ -535,7 +489,7 @@ void BaseObjectView::configureProtectedIcon(void) double factor; //Calculates the factor used to resize the protection icon accordding the font size - factor=font_config[ParsersAttributes::GLOBAL].font().pointSizeF()/DEFAULT_FONT_SIZE; + factor=font_config[Attributes::Global].font().pointSizeF()/DefaultFontSize; pol.append(QPointF(2,5)); pol.append(QPointF(2,2)); pol.append(QPointF(3,1)); pol.append(QPointF(4,0)); @@ -545,14 +499,14 @@ void BaseObjectView::configureProtectedIcon(void) pol.append(QPointF(6,2)); pol.append(QPointF(5,2)); pol.append(QPointF(4,3)); pol.append(QPointF(4,5)); - if(factor!=1.0f) - this->resizePolygon(pol, pol.boundingRect().width() * factor, - pol.boundingRect().height() * factor); + if(factor!=1.0) + TextPolygonItem::resizePolygon(pol, pol.boundingRect().width() * factor, + pol.boundingRect().height() * factor); pol_item=dynamic_cast(protected_icon->childItems().at(0)); pol_item->setPolygon(pol); - pol_item->setBrush(this->getFillStyle(ParsersAttributes::LOCKER_ARC)); - pol_item->setPen(this->getBorderStyle(ParsersAttributes::LOCKER_ARC)); + pol_item->setBrush(this->getFillStyle(Attributes::LockerArc)); + pol_item->setPen(this->getBorderStyle(Attributes::LockerArc)); pol.clear(); pol.append(QPointF(1,5)); pol.append(QPointF(10,5)); @@ -560,14 +514,14 @@ void BaseObjectView::configureProtectedIcon(void) pol.append(QPointF(10,10)); pol.append(QPointF(1,10)); pol.append(QPointF(0,9)); pol.append(QPointF(0,6)); - if(factor!=1.0f) - this->resizePolygon(pol, pol.boundingRect().width() * factor, - pol.boundingRect().height() * factor); + if(factor!=1.0) + TextPolygonItem::resizePolygon(pol, pol.boundingRect().width() * factor, + pol.boundingRect().height() * factor); pol_item=dynamic_cast(protected_icon->childItems().at(1)); pol_item->setPolygon(pol); - pol_item->setBrush(this->getFillStyle(ParsersAttributes::LOCKER_BODY)); - pol_item->setPen(this->getBorderStyle(ParsersAttributes::LOCKER_BODY)); + pol_item->setBrush(this->getFillStyle(Attributes::LockerBody)); + pol_item->setPen(this->getBorderStyle(Attributes::LockerBody)); } } @@ -585,7 +539,7 @@ void BaseObjectView::configurePlaceholder(void) void BaseObjectView::__configureObject(void) { - BaseGraphicObject *graph_obj=dynamic_cast(this->getSourceObject()); + BaseGraphicObject *graph_obj=dynamic_cast(this->getUnderlyingObject()); if(graph_obj) { @@ -605,8 +559,8 @@ unsigned BaseObjectView::getSelectionOrder(void) QPointF BaseObjectView::getCenter(void) { - return(QPointF(this->pos().x() + this->boundingRect().width()/2.0f, - this->pos().y() + this->boundingRect().height()/2.0f)); + return(QPointF(this->pos().x() + this->boundingRect().width()/2.0, + this->pos().y() + this->boundingRect().height()/2.0)); } void BaseObjectView::togglePlaceholder(bool visible) @@ -618,10 +572,10 @@ void BaseObjectView::togglePlaceholder(bool visible) if(visible) { - QPen pen=BaseObjectView::getBorderStyle(ParsersAttributes::PLACEHOLDER); + QPen pen=BaseObjectView::getBorderStyle(Attributes::Placeholder); pen.setStyle(Qt::DashLine); - placeholder->setBrush(BaseObjectView::getFillStyle(ParsersAttributes::PLACEHOLDER)); + placeholder->setBrush(BaseObjectView::getFillStyle(Attributes::Placeholder)); placeholder->setPen(pen); placeholder->setRect(QRectF(QPointF(0,0),this->bounding_rect.size())); placeholder->setPos(this->mapToScene(this->bounding_rect.topLeft())); @@ -633,15 +587,35 @@ void BaseObjectView::togglePlaceholder(bool visible) double BaseObjectView::getFontFactor(void) { - return(font_config[ParsersAttributes::GLOBAL].font().pointSizeF()/DEFAULT_FONT_SIZE); + return(font_config[Attributes::Global].font().pointSizeF()/DefaultFontSize); +} + +void BaseObjectView::setLayer(unsigned layer) +{ + BaseGraphicObject *graph_obj = dynamic_cast(this->getUnderlyingObject()); + + if(graph_obj) + graph_obj->setLayer(layer); +} + +unsigned BaseObjectView::getLayer(void) +{ + BaseGraphicObject *graph_obj = dynamic_cast(this->getUnderlyingObject()); + + if(graph_obj) + return(graph_obj->getLayer()); + + return(0); } double BaseObjectView::getScreenDpiFactor(void) { - double factor = qApp->screens().at(qApp->desktop()->screenNumber(qApp->activeWindow()))->logicalDotsPerInch() / 96.0f; + QScreen *screen = qApp->screens().at(qApp->desktop()->screenNumber(qApp->activeWindow())); + double factor = screen->logicalDotsPerInch() / 96.0; + double pixel_ratio = screen->devicePixelRatio(); if(factor < 1) return (1); - return(factor); + return(factor * pixel_ratio); } diff --git a/libobjrenderer/src/baseobjectview.h b/libobjrenderer/src/baseobjectview.h index 5a7aba7614..2b05c1aa0f 100644 --- a/libobjrenderer/src/baseobjectview.h +++ b/libobjrenderer/src/baseobjectview.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -30,6 +30,7 @@ #include "baserelationship.h" #include "xmlparser.h" #include "roundedrectitem.h" +#include "textpolygonitem.h" class BaseObjectView: public QObject, public QGraphicsItemGroup { private: @@ -46,6 +47,11 @@ class BaseObjectView: public QObject, public QGraphicsItemGroup { is incremented each time an object is selected. */ static unsigned global_sel_order; + /*! \brief Stores the current status for object's compact view display. + * In compact view the alias of object's are shown instead of name. Also, data types and constraint types are hidden, + * as well the table's extended area is collapsed by default */ + static bool compact_view; + /*! \brief Stores the selection order of the current object. This attribute is used to know when an item was selected before another in the scene because the implementation of the method QGraphicsScene :: selectedItem() the selected objects are returned without @@ -53,11 +59,8 @@ class BaseObjectView: public QObject, public QGraphicsItemGroup { mainly when creating relationships between tables. */ unsigned sel_order; - //! \brief Graphical text for the position info - QGraphicsSimpleTextItem *pos_info_txt; - - //! \brief Graphical object (rectangle) of the position info - QGraphicsRectItem *pos_info_rect; + //! \brief This item display the current object position on the scene + TextPolygonItem *pos_info_item; //! \brief Stores the objects bounding rect QRectF bounding_rect; @@ -80,17 +83,17 @@ class BaseObjectView: public QObject, public QGraphicsItemGroup { //! \brief Graphical text for the sql disabled info QGraphicsSimpleTextItem *sql_disabled_txt; + //! \brief This items is used to display the sql disabled status of the object + TextPolygonItem *sql_disabled_item; + //! \brief Stores the object font configuration static map font_config; //! \brief Stores the object colors configuration static map> color_config; - //! \brief Resizes to the specified dimension the passed polygon - void resizePolygon(QPolygonF &pol, double width, double height); - //! \brief Configures the objects shadow polygon - void configureObjectShadow(void); + void configureObjectShadow(void) {} //! \brief Configures the object selection polygon void configureObjectSelection(void); @@ -110,13 +113,16 @@ class BaseObjectView: public QObject, public QGraphicsItemGroup { void setSelectionOrder(bool selected); + //! \brief Defines in which layer the object is visible + void setLayer(unsigned layer); + public: - static constexpr double VERT_SPACING=2.0f, - HORIZ_SPACING=2.0f, - DEFAULT_FONT_SIZE=9.0f, - OBJ_BORDER_WIDTH=0.85f; + static constexpr double VertSpacing=2.0, + HorizSpacing=2.0, + DefaultFontSize=9.0, + ObjectBorderWidth=0.85; - static constexpr int OBJ_ALPHA_CHANNEL=128; + static constexpr int ObjectAlphaChannel=128; BaseObjectView(BaseObject *object=nullptr); virtual ~BaseObjectView(void); @@ -128,7 +134,7 @@ class BaseObjectView: public QObject, public QGraphicsItemGroup { QVariant itemChange(GraphicsItemChange change, const QVariant &value); //! \brief Returns the object that is representend by the graphical object - BaseObject *getSourceObject(void); + BaseObject *getUnderlyingObject(void); //! \brief Loads the font / color styels for the objects from a XML configuration file static void loadObjectsStyle(void); @@ -153,6 +159,10 @@ class BaseObjectView: public QObject, public QGraphicsItemGroup { static bool isPlaceholderEnabled(void); + static void setCompactViewEnabled(bool value); + + static bool isCompactViewEnabled(void); + //! \brief Sets the font style for the specified element id static void setFontStyle(const QString &id, QTextCharFormat font_fmt); @@ -183,6 +193,9 @@ class BaseObjectView: public QObject, public QGraphicsItemGroup { //! \brief Returns the current factor between the default font size and the current defined one static double getFontFactor(void); + //! \brief Returns the layer in which the object is visible + unsigned getLayer(void); + protected slots: //! \brief Make the basic object operations void __configureObject(void); @@ -196,6 +209,8 @@ class BaseObjectView: public QObject, public QGraphicsItemGroup { //! \brief Signal emmited whenever the width or height of the table changes void s_objectDimensionChanged(void); + + friend class ObjectsScene; }; #endif diff --git a/libobjrenderer/src/basetableview.cpp b/libobjrenderer/src/basetableview.cpp index 1e50e9beda..203ec33929 100644 --- a/libobjrenderer/src/basetableview.cpp +++ b/libobjrenderer/src/basetableview.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,40 +18,35 @@ #include "basetableview.h" -bool BaseTableView::hide_ext_attribs=false; -bool BaseTableView::hide_tags=false; +bool BaseTableView::hide_ext_attribs = false; +bool BaseTableView::hide_tags = false; +unsigned BaseTableView::attribs_per_page[2] = { 10, 5 }; BaseTableView::BaseTableView(BaseTable *base_tab) : BaseObjectView(base_tab) { if(!base_tab) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject, __PRETTY_FUNCTION__, __FILE__, __LINE__); + pending_geom_update = false; body=new RoundedRectItem; - body->setRoundedCorners(RoundedRectItem::BOTTOMLEFT_CORNER | RoundedRectItem::BOTTOMRIGHT_CORNER); + body->setRoundedCorners(RoundedRectItem::BottomLeftCorner | RoundedRectItem::BottomRightCorner); title=new TableTitleView; + title->setZValue(2); ext_attribs_body=new RoundedRectItem; - ext_attribs_body->setRoundedCorners(RoundedRectItem::NO_CORNERS); - - ext_attribs_toggler=new RoundedRectItem; - ext_attribs_toggler->setRoundedCorners(RoundedRectItem::BOTTOMLEFT_CORNER | RoundedRectItem::BOTTOMRIGHT_CORNER); - ext_attribs_toggler->setZValue(-1); + ext_attribs_body->setRoundedCorners(RoundedRectItem::NoCorners); ext_attribs=new QGraphicsItemGroup; ext_attribs->setZValue(1); - - ext_attribs_tog_arrow=new QGraphicsPolygonItem; - ext_attribs_tog_arrow->setZValue(2); + ext_attribs->setFlag(QGraphicsItem::ItemClipsChildrenToShape); columns=new QGraphicsItemGroup; columns->setZValue(1); + columns->setFlag(QGraphicsItem::ItemClipsChildrenToShape); - tag_name=new QGraphicsSimpleTextItem; - tag_name->setZValue(3); - - tag_body=new QGraphicsPolygonItem; - tag_body->setZValue(2); + tag_item = new TextPolygonItem; + tag_item->setZValue(3); obj_shadow=new RoundedRectItem; obj_shadow->setZValue(-1); @@ -60,43 +55,50 @@ BaseTableView::BaseTableView(BaseTable *base_tab) : BaseObjectView(base_tab) obj_selection->setVisible(false); obj_selection->setZValue(4); + attribs_toggler = new AttributesTogglerItem; + attribs_toggler->setZValue(1); + this->addToGroup(obj_selection); this->addToGroup(obj_shadow); this->addToGroup(columns); this->addToGroup(body); this->addToGroup(title); - this->addToGroup(tag_name); - this->addToGroup(tag_body); + this->addToGroup(tag_item); this->addToGroup(ext_attribs); this->addToGroup(ext_attribs_body); - this->addToGroup(ext_attribs_toggler); - this->addToGroup(ext_attribs_tog_arrow); + this->addToGroup(attribs_toggler); this->setAcceptHoverEvents(true); - sel_child_obj=nullptr; + sel_child_obj_view=nullptr; configurePlaceholder(); + + sel_enabler_timer.setInterval(500); + + connect(attribs_toggler, SIGNAL(s_collapseModeChanged(CollapseMode)), this, SLOT(configureCollapsedSections(CollapseMode))); + connect(attribs_toggler, SIGNAL(s_paginationToggled(bool)), this, SLOT(togglePagination(bool))); + connect(attribs_toggler, SIGNAL(s_currentPageChanged(unsigned,unsigned)), this, SLOT(configureCurrentPage(unsigned,unsigned))); + + connect(&sel_enabler_timer, &QTimer::timeout, [&](){ + this->setFlag(QGraphicsItem::ItemIsSelectable, true); + }); } BaseTableView::~BaseTableView(void) { this->removeFromGroup(body); this->removeFromGroup(title); + this->removeFromGroup(attribs_toggler); this->removeFromGroup(ext_attribs_body); - this->removeFromGroup(ext_attribs_toggler); - this->removeFromGroup(ext_attribs_tog_arrow); this->removeFromGroup(ext_attribs); this->removeFromGroup(columns); - this->removeFromGroup(tag_name); - this->removeFromGroup(tag_body); - delete(ext_attribs_tog_arrow); - delete(ext_attribs_toggler); + this->removeFromGroup(tag_item); + delete(attribs_toggler); delete(ext_attribs_body); delete(ext_attribs); delete(body); delete(title); delete(columns); - delete(tag_name); - delete(tag_body); + delete(tag_item); } void BaseTableView::setHideExtAttributes(bool value) @@ -124,63 +126,100 @@ QVariant BaseTableView::itemChange(GraphicsItemChange change, const QVariant &va if(change==ItemSelectedHasChanged) { this->setToolTip(this->table_tooltip); - BaseObjectView::configureObjectSelection(); + configureObjectSelection(); + attribs_toggler->clearButtonsSelection(); + } + else if(change == ItemVisibleHasChanged) + { + if(value.toBool() && pending_geom_update) + { + this->configureObject(); + pending_geom_update = false; + } } if(change==ItemPositionHasChanged) emit s_objectMoved(); BaseObjectView::itemChange(change, value); - return(value); } void BaseTableView::mousePressEvent(QGraphicsSceneMouseEvent *event) { //Emit a signal containing the select child object if the user right-click the focused item - if(!this->isSelected() && event->buttons()==Qt::RightButton && sel_child_obj) + if(!this->isSelected() && event->buttons()==Qt::RightButton && sel_child_obj_view) { - if(this->scene()) - this->scene()->clearSelection(); - - /* Deactivate the table in order not to hide the child object selection. - The table object is reativated when the context menu is hidden */ - this->setEnabled(false); - - emit s_childObjectSelected(sel_child_obj); + // Avoiding clear selection when the focused child item is amongst the other selected children + if(sel_child_obj_view->getUnderlyingObject() && !sel_child_objs.contains(sel_child_obj_view)) + { + // Forcing the selection clearing when we right click an child object that is not selected yet + emit s_sceneClearRequested(); + clearChildrenSelection(); + + /* Deactivate the table in order not to hide the child object selection. + The table object is reativated when the context menu is hidden */ + this->setEnabled(false); + emit s_popupMenuRequested(dynamic_cast(sel_child_obj_view->getUnderlyingObject())); + } } else { - QPointF pnt = this->ext_attribs_toggler->mapFromScene(event->scenePos()); + QPointF pnt = attribs_toggler->mapFromScene(event->scenePos()); //If the user clicks the extended attributes toggler - if(!this->isSelected() && event->buttons()==Qt::LeftButton && - this->ext_attribs_toggler->boundingRect().contains(pnt)) + if(!this->isSelected() && event->buttons()==Qt::LeftButton && event->modifiers() == Qt::NoModifier && + attribs_toggler->isVisible() && attribs_toggler->boundingRect().contains(pnt)) + attribs_toggler->setButtonSelected(pnt, true); + + /* We select children object only if the have a source object (column, constraint, trigger, etc). View references + * items should not be selected here because they do not have a source object */ + if(sel_child_obj_view && sel_child_obj_view->getUnderlyingObject() && + event->modifiers() == (Qt::ControlModifier | Qt::ShiftModifier)) { - Schema *schema = dynamic_cast(this->getSourceObject()->getSchema()); - - //We need to force the object to be not selectable so further calls to mousePressEvent doesn't select the object this->setFlag(QGraphicsItem::ItemIsSelectable, false); + sel_child_obj_view->setFakeSelection(!sel_child_obj_view->hasFakeSelection()); - dynamic_cast(this->getSourceObject()) - ->setExtAttribsHidden(!dynamic_cast(this->getSourceObject())->isExtAttribsHidden()); + if(!sel_child_obj_view->hasFakeSelection()) + sel_child_objs.removeAll(sel_child_obj_view); + else + sel_child_objs.append(sel_child_obj_view); - //Updating the object geometry to show/hide the extended attributes - this->configureObject(); + sel_child_obj_view = nullptr; + event->ignore(); + emit s_childrenSelectionChanged(); + sel_enabler_timer.start(); + } + else if((this->flags() & QGraphicsItem::ItemIsSelectable) == QGraphicsItem::ItemIsSelectable) + { + // Forcing the scene selection clearing when we right click the table itself directly + if(event->buttons() == Qt::RightButton && !this->isSelected()) + { + emit s_sceneClearRequested(); + this->setSelected(true); + } - obj_selection->setVisible(false); + clearChildrenSelection(); + BaseObjectView::mousePressEvent(event); + } + } +} - // Using a single shot time to restore the selectable flag - QTimer::singleShot(300, [&]{ this->setFlag(QGraphicsItem::ItemIsSelectable, true); }); +void BaseTableView::setAttributesPerPage(unsigned section_id, unsigned value) +{ + if(section_id > BaseTable::ExtAttribsSection) + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); - //Updating the schema box that holds the object (if visible) - schema->setModified(true); + if(value > 0) + attribs_per_page[section_id] = value; +} - emit s_extAttributesToggled(); - } +unsigned BaseTableView::getAttributesPerPage(unsigned section_id) +{ + if(section_id > BaseTable::ExtAttribsSection) + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); - BaseObjectView::mousePressEvent(event); - } + return(attribs_per_page[section_id]); } void BaseTableView::hoverLeaveEvent(QGraphicsSceneHoverEvent *) @@ -188,7 +227,8 @@ void BaseTableView::hoverLeaveEvent(QGraphicsSceneHoverEvent *) if(!this->isSelected() && obj_selection->isVisible()) obj_selection->setVisible(false); - sel_child_obj=nullptr; + attribs_toggler->clearButtonsSelection(); + sel_child_obj_view=nullptr; } void BaseTableView::hoverMoveEvent(QGraphicsSceneHoverEvent *event) @@ -200,36 +240,27 @@ void BaseTableView::hoverMoveEvent(QGraphicsSceneHoverEvent *event) QList items; double cols_height, item_idx, ext_height=0; QRectF rect, rect1; - QPointF pnt = this->ext_attribs_toggler->mapFromScene(event->scenePos()); + QPointF pnt = attribs_toggler->mapFromScene(event->scenePos()); items.append(columns->childItems()); if(!hide_ext_attribs && - !dynamic_cast(this->getSourceObject())->isExtAttribsHidden()) + dynamic_cast(this->getUnderlyingObject())->getCollapseMode() == CollapseMode::NotCollapsed) { items.append(ext_attribs->childItems()); ext_height=ext_attribs->boundingRect().height(); } //Calculates the default item height - cols_height=roundf((columns->boundingRect().height() + ext_height) / static_cast(items.size())); + cols_height=(columns->boundingRect().height() + ext_height + (2*VertSpacing)) / static_cast(items.size()); //Calculates the item index based upon the mouse position rect=this->mapRectToItem(title, title->boundingRect()); item_idx=(event->pos().y() - rect.bottom()) / cols_height; - if(ext_attribs_toggler->isVisible() && this->ext_attribs_toggler->boundingRect().contains(pnt)) + if(attribs_toggler->isVisible() && attribs_toggler->boundingRect().contains(pnt)) { - dynamic_cast(obj_selection)->setBorderRadius(2); - dynamic_cast(obj_selection)->setRect(QRectF(0,0, - title->boundingRect().width() - (2.5 * HORIZ_SPACING), - ext_attribs_toggler->boundingRect().height() * 0.65f)); - - //Sets the selection position as same as item's position - rect1=this->mapRectToItem(ext_attribs_toggler, ext_attribs_toggler->boundingRect()); - obj_selection->setVisible(true); - obj_selection->setPos(QPointF(title->pos().x() + HORIZ_SPACING, -rect1.top() + 1.5f)); - this->setToolTip(trUtf8("Toggles the extended attributes display")); + attribs_toggler->setButtonSelected(pnt); } //If the index is invalid clears the selection else if(item_idx < 0 || item_idx >= items.size()) @@ -239,25 +270,24 @@ void BaseTableView::hoverMoveEvent(QGraphicsSceneHoverEvent *event) } else if(!items.isEmpty()) { - //QPolygonF pol; - BaseObjectView *item=dynamic_cast(items[item_idx]); + TableObjectView *item=dynamic_cast(items[static_cast(item_idx)]); //Configures the selection with the item's dimension - if(obj_selection->boundingRect().height()!=item->boundingRect().height()) + if(obj_selection->boundingRect().height() != item->boundingRect().height()) { dynamic_cast(obj_selection)->setBorderRadius(2); - dynamic_cast(obj_selection)->setRect(QRectF(0,0, - title->boundingRect().width() - (2.5 * HORIZ_SPACING), - item->boundingRect().height())); + dynamic_cast(obj_selection)->setRect(QRectF(0, 0, + title->boundingRect().width() - (2.5 * HorizSpacing), + item->boundingRect().height() - VertSpacing)); } //Sets the selection position as same as item's position rect1=this->mapRectToItem(item, item->boundingRect()); obj_selection->setVisible(true); - obj_selection->setPos(QPointF(title->pos().x() + HORIZ_SPACING,-rect1.top())); + obj_selection->setPos(QPointF(title->pos().x() + HorizSpacing, -rect1.top() + VertSpacing/2)); //Stores the selected child object - sel_child_obj=dynamic_cast(item->getSourceObject()); + sel_child_obj_view = item; this->setToolTip(item->toolTip()); } } @@ -265,12 +295,12 @@ void BaseTableView::hoverMoveEvent(QGraphicsSceneHoverEvent *event) void BaseTableView::addConnectedRelationship(BaseRelationship *base_rel) { - BaseTable *tab = dynamic_cast(getSourceObject()); + BaseTable *tab = dynamic_cast(getUnderlyingObject()); if(!base_rel || (base_rel && - base_rel->getTable(BaseRelationship::SRC_TABLE) != tab && - base_rel->getTable(BaseRelationship::DST_TABLE) != tab)) + base_rel->getTable(BaseRelationship::SrcTable) != tab && + base_rel->getTable(BaseRelationship::DstTable) != tab)) return; connected_rels.push_back(base_rel); @@ -281,12 +311,28 @@ void BaseTableView::removeConnectedRelationship(BaseRelationship *base_rel) connected_rels.erase(std::find(connected_rels.begin(), connected_rels.end(), base_rel)); } -int BaseTableView::getConnectedRelationshipIndex(BaseRelationship *base_rel) +int BaseTableView::getConnectedRelationshipIndex(BaseRelationship *base_rel, bool only_self_rels) { - vector::iterator itr = std::find(connected_rels.begin(), connected_rels.end(), base_rel); + vector::iterator itr; + vector self_rels, *vet_rels = nullptr; - if(itr != connected_rels.end()) - return(itr - connected_rels.begin()); + if(!only_self_rels) + vet_rels = &connected_rels; + else + { + for(auto &rel : connected_rels) + { + if(rel->isSelfRelationship()) + self_rels.push_back(rel); + } + + vet_rels = &self_rels; + } + + itr = std::find(vet_rels->begin(), vet_rels->end(), base_rel); + + if(itr != vet_rels->end()) + return(itr - vet_rels->begin()); return(-1); } @@ -297,10 +343,10 @@ unsigned BaseTableView::getConnectedRelsCount(BaseTable *src_tab, BaseTable *dst for(auto &rel : connected_rels) { - if((rel->getTable(BaseRelationship::SRC_TABLE) == src_tab && - rel->getTable(BaseRelationship::DST_TABLE) == dst_tab) || - (rel->getTable(BaseRelationship::SRC_TABLE) == dst_tab && - rel->getTable(BaseRelationship::DST_TABLE) == src_tab)) + if((rel->getTable(BaseRelationship::SrcTable) == src_tab && + rel->getTable(BaseRelationship::DstTable) == dst_tab) || + (rel->getTable(BaseRelationship::SrcTable) == dst_tab && + rel->getTable(BaseRelationship::DstTable) == src_tab)) count++; } @@ -309,175 +355,234 @@ unsigned BaseTableView::getConnectedRelsCount(BaseTable *src_tab, BaseTable *dst void BaseTableView::configureTag(void) { - BaseTable *tab=dynamic_cast(this->getSourceObject()); + BaseTable *tab=dynamic_cast(this->getUnderlyingObject()); Tag *tag=tab->getTag(); - tag_body->setVisible(tag!=nullptr && !hide_tags); - tag_name->setVisible(tag!=nullptr && !hide_tags); + tag_item->setVisible(tag!=nullptr && !hide_tags); if(!hide_tags && tag) { QPolygonF pol; QPointF p1, p2; double bottom; - QFont fnt=BaseObjectView::getFontStyle(ParsersAttributes::TAG).font(); + QFont fnt=BaseObjectView::getFontStyle(Attributes::Tag).font(); - fnt.setPointSizeF(fnt.pointSizeF() * 0.80f); - tag_name->setFont(fnt); - tag_name->setText(tag->getName()); - tag_name->setBrush(BaseObjectView::getFontStyle(ParsersAttributes::TAG).foreground()); + fnt.setPointSizeF(fnt.pointSizeF() * 0.80); + tag_item->setFont(fnt); + tag_item->setText(tag->getName()); + tag_item->setBrush(BaseObjectView::getFontStyle(Attributes::Tag).foreground()); - p1=tag_name->boundingRect().topLeft(); - p2=tag_name->boundingRect().bottomRight(); + p1=tag_item->getTextBoundingRect().topLeft(); + p2=tag_item->getTextBoundingRect().bottomRight(); bottom=this->boundingRect().bottom(); - pol.append(QPointF(p1.x()-BaseObjectView::HORIZ_SPACING, p1.y() - BaseObjectView::VERT_SPACING)); - pol.append(QPointF(p2.x(), p1.y() - BaseObjectView::VERT_SPACING)); - pol.append(QPointF(p2.x() + BaseObjectView::HORIZ_SPACING + 5, p2.y()/2)); - pol.append(QPointF(p2.x(), p2.y() + BaseObjectView::VERT_SPACING)); - pol.append(QPointF(p1.x(), p2.y() + BaseObjectView::VERT_SPACING)); - pol.append(QPointF(p1.x()-BaseObjectView::HORIZ_SPACING, p2.y() + BaseObjectView::VERT_SPACING)); - - tag_body->setPolygon(pol); - tag_body->setPen(BaseObjectView::getBorderStyle(ParsersAttributes::TAG)); - tag_body->setBrush(BaseObjectView::getFillStyle(ParsersAttributes::TAG)); - - tag_name->setPos(-5, bottom - 1.5f); - tag_body->setPos(-5, bottom - 1.5f); + pol.append(QPointF(p1.x()- HorizSpacing, p1.y() - VertSpacing)); + pol.append(QPointF(p2.x(), p1.y() - VertSpacing)); + pol.append(QPointF(p2.x() + HorizSpacing + 5, p2.y()/2)); + pol.append(QPointF(p2.x(), p2.y() + VertSpacing)); + pol.append(QPointF(p1.x(), p2.y() + VertSpacing)); + pol.append(QPointF(p1.x()-HorizSpacing, p2.y() + VertSpacing)); + + tag_item->setPolygon(pol); + tag_item->setPen(BaseObjectView::getBorderStyle(Attributes::Tag)); + tag_item->setBrush(BaseObjectView::getFillStyle(Attributes::Tag)); + tag_item->setPos(-5, bottom - 1.5); + tag_item->setTextPos(HorizSpacing/2, 0); } } -void BaseTableView::__configureObject(float width) +void BaseTableView::__configureObject(double width) { - BaseTable *tab = dynamic_cast(this->getSourceObject()); + BaseTable *tab = dynamic_cast(getUnderlyingObject()); + double height = 0, + factor = qApp->screens().at(qApp->desktop()->screenNumber(qApp->activeWindow()))->logicalDotsPerInch() / 96.0, + pixel_ratio = qApp->screens().at(qApp->desktop()->screenNumber(qApp->activeWindow()))->devicePixelRatio(); + + QPen pen = body->pen(); + attribs_toggler->setBrush(body->brush()); + attribs_toggler->setPen(body->pen()); + + QLinearGradient grad(QPointF(0,0),QPointF(0,1)); + grad.setCoordinateMode(QGradient::ObjectBoundingMode); + grad.setColorAt(0, body->pen().color().lighter(200)); + grad.setColorAt(1, body->pen().color().lighter()); + pen.setStyle(Qt::SolidLine); + + attribs_toggler->setButtonsBrush(grad); + attribs_toggler->setButtonsPen(body->pen()); + attribs_toggler->setRect(QRectF(0, 0, width, 12 * factor * pixel_ratio)); + attribs_toggler->setCollapseMode(tab->getCollapseMode()); - if(!ext_attribs->childItems().isEmpty() && !hide_ext_attribs) - { - QPen pen = ext_attribs_body->pen(); - float py = 0; - float factor = qApp->screens().at(qApp->desktop()->screenNumber(qApp->activeWindow()))->logicalDotsPerInch() / 96.0f; + //Set the protected icon position to the top-right on the title + protected_icon->setPos(title->pos().x() + (2 * HorizSpacing), title->boundingRect().height() * 0.25); + this->bounding_rect = title->boundingRect(); - ext_attribs_toggler->setVisible(true); - ext_attribs_tog_arrow->setVisible(true); + body->setRoundedCorners(RoundedRectItem::NoCorners); - ext_attribs_toggler->setPen(pen); - ext_attribs_toggler->setBrush(ext_attribs_body->brush()); - ext_attribs_toggler->setRect(QRectF(0, 0, width, 12 * factor)); + height = title->boundingRect().height() + attribs_toggler->boundingRect().height() - VertSpacing; + height += (body->isVisible() ? body->boundingRect().height() : 1); + height += (ext_attribs_body->isVisible() ? ext_attribs_body->boundingRect().height() - VertSpacing + 1 : 0); - if(!tab->isExtAttribsHidden()) - { - py = title->boundingRect().height() + - body->boundingRect().height() + - ext_attribs_body->boundingRect().height() - VERT_SPACING - 1; - } - else - { - py = title->boundingRect().height() + - body->boundingRect().height() - 2; - } + this->bounding_rect.setHeight(height); - ext_attribs_toggler->setPos(ext_attribs_body->pos().x(), py); + attribs_toggler->setPos(title->pos().x(), + height - attribs_toggler->boundingRect().height()); - QPolygonF pol; + this->table_tooltip=this->getUnderlyingObject()->getName(true) + + QString(" (") + this->getUnderlyingObject()->getTypeName() + QString(") \n") + + QString("Id: %1\n").arg(this->getUnderlyingObject()->getObjectId()) + + trUtf8("Connected rels: %1").arg(this->getConnectRelsCount()); - if(!tab->isExtAttribsHidden()) - { - pol.append(QPointF(0,0)); - pol.append(QPointF(-5 * factor, 6 * factor)); - pol.append(QPointF(5 * factor, 6 * factor)); - } - else - { - pol.append(QPointF(0,6 * factor)); - pol.append(QPointF(-5 * factor, 0)); - pol.append(QPointF(5 * factor, 0)); - } + this->setToolTip(this->table_tooltip); + + configureObjectSelection(); + configureObjectShadow(); +} + +double BaseTableView::calculateWidth(void) +{ + /* Calculating the maximum width between the title, columns, extended attributes and the attribs toggler. + * This width is used to set the uniform width of table */ + vector widths = { columns->isVisible() ? columns->boundingRect().width() : 0, + ext_attribs->isVisible() ? ext_attribs->boundingRect().width() : 0, + attribs_toggler->isVisible() ? attribs_toggler->getButtonsWidth() : 0, + title->boundingRect().width() }; + + std::sort(widths.begin(), widths.end()); + return (widths.back() + (2 * HorizSpacing)); +} - QLinearGradient grad(QPointF(0,0),QPointF(0,1)); - grad.setCoordinateMode(QGradient::ObjectBoundingMode); - grad.setColorAt(0, ext_attribs_body->pen().color().lighter(200)); - grad.setColorAt(1, ext_attribs_body->pen().color().lighter()); +int BaseTableView::getConnectRelsCount(void) +{ + return(connected_rels.size()); +} - pen.setStyle(Qt::SolidLine); - ext_attribs_tog_arrow->setPen(pen); - ext_attribs_tog_arrow->setBrush(grad); - ext_attribs_tog_arrow->setPolygon(pol); +void BaseTableView::requestRelationshipsUpdate(void) +{ + emit s_relUpdateRequest(); +} - ext_attribs_tog_arrow->setPos(ext_attribs_body->boundingRect().width() * 0.51f, - ext_attribs_toggler->pos().y() + pol.boundingRect().height() * 0.525f); - } - else - { - ext_attribs_tog_arrow->setVisible(false); - ext_attribs_toggler->setVisible(false); - } +void BaseTableView::togglePlaceholder(bool value) +{ + BaseObjectView::togglePlaceholder(!connected_rels.empty() && value); +} - //Set the protected icon position to the top-right on the title - protected_icon->setPos(title->pos().x() + title->boundingRect().width() * 0.90f, 2 * VERT_SPACING); +void BaseTableView::configureObjectShadow(void) +{ + RoundedRectItem *rect_item=dynamic_cast(obj_shadow); - this->bounding_rect.setTopLeft(title->boundingRect().topLeft()); - this->bounding_rect.setWidth(title->boundingRect().width()); + rect_item->setPen(Qt::NoPen); + rect_item->setBrush(QColor(50,50,50,60)); + rect_item->setRect(this->boundingRect()); + rect_item->setPos(3.5, 4.5); +} - if(!ext_attribs->isVisible()) - { - this->bounding_rect.setHeight(title->boundingRect().height() + - body->boundingRect().height() - 1); - body->setRoundedCorners(RoundedRectItem::BOTTOMLEFT_CORNER | RoundedRectItem::BOTTOMRIGHT_CORNER); - } - else - { - ext_attribs->setVisible(!tab->isExtAttribsHidden()); - ext_attribs_body->setVisible(!tab->isExtAttribsHidden()); +QList BaseTableView::getSelectedChidren(void) +{ + return(sel_child_objs); +} - this->bounding_rect.setHeight(title->boundingRect().height() + - body->boundingRect().height() + - (!tab->isExtAttribsHidden() ? ext_attribs_body->boundingRect().height() : 0) + - ext_attribs_toggler->boundingRect().height() - VERT_SPACING - 1); +void BaseTableView::clearChildrenSelection(void) +{ + if(sel_child_objs.isEmpty()) + return; - body->setRoundedCorners(RoundedRectItem::NO_CORNERS); - } + for(auto &tab_obj : sel_child_objs) + tab_obj->setFakeSelection(false); - this->table_tooltip=this->getSourceObject()->getName(true) + - QString(" (") + this->getSourceObject()->getTypeName() + QString(") \n") + - QString("Id: %1\n").arg(this->getSourceObject()->getObjectId()) + - TableObjectView::CONSTR_DELIM_START + - trUtf8("Connected rels: %1").arg(this->getConnectRelsCount()) + - TableObjectView::CONSTR_DELIM_END; + sel_child_objs.clear(); + emit s_childrenSelectionChanged(); +} - this->setToolTip(this->table_tooltip); +void BaseTableView::startGeometryUpdate(void) +{ + //We need to force the object to be not selectable so further calls to mousePressEvent doesn't select the object + this->setFlag(QGraphicsItem::ItemIsSelectable, false); } -float BaseTableView::calculateWidth(void) +void BaseTableView::finishGeometryUpdate(void) { - /* Calculating the maximum width between the title, columns and extended attributes. - This width is used to set the uniform width of table */ - if(!columns->childItems().isEmpty() && - (columns->boundingRect().width() > title->boundingRect().width() && - (hide_ext_attribs || dynamic_cast(this->getSourceObject())->isExtAttribsHidden() || - (columns->boundingRect().width() > ext_attribs->boundingRect().width())))) - return(columns->boundingRect().width() + (2 * HORIZ_SPACING)); - - if(!ext_attribs->childItems().isEmpty() && !hide_ext_attribs && - !dynamic_cast(this->getSourceObject())->isExtAttribsHidden() && - (ext_attribs->boundingRect().width() > title->boundingRect().width() && - ext_attribs->boundingRect().width() > columns->boundingRect().width())) - return(ext_attribs->boundingRect().width() + (2 * HORIZ_SPACING)); - - return(title->boundingRect().width() + (2 * HORIZ_SPACING)); + //Updating the object's geometry to reflect the geometry change + this->configureObject(); + obj_selection->setVisible(false); + + // Using a single shot time to restore the selectable flag + QTimer::singleShot(300, [&]{ this->setFlag(QGraphicsItem::ItemIsSelectable, true); }); + + //Updating the schema box that holds the object (if visible) + dynamic_cast(this->getUnderlyingObject()->getSchema())->setModified(true); } -int BaseTableView::getConnectRelsCount(void) +bool BaseTableView::configurePaginationParams(unsigned section_id, unsigned total_attrs, unsigned &start_attr, unsigned &end_attr) { - return(connected_rels.size()); + if(section_id > BaseTable::ExtAttribsSection) + return false; + + BaseTable *table = dynamic_cast(getUnderlyingObject()); + unsigned attr_per_page = attribs_per_page[section_id]; + + start_attr = end_attr = 0; + attribs_toggler->setPaginationEnabled(table->isPaginationEnabled()); + + /* If the pagination is enabled for the table and the amount of objects is greater than the + * number of objects per page we configure the pagination parameter */ + if(table->isPaginationEnabled() && total_attrs > attr_per_page) + { + // Calculating the proportions of columns and extended attributes displayed per page + unsigned max_pages = 0, curr_page = table->getCurrentPage(section_id); + + // Determining the maximum amount of pages + max_pages = ceil(total_attrs / static_cast(attr_per_page)); + + // Validating the current page related to the maximum determined + if(curr_page >= max_pages) + curr_page = max_pages - 1; + + // Calculating the start and end columns/ext. attributes for the current page + start_attr = curr_page * attr_per_page; + end_attr = start_attr + attr_per_page; + + // Validating the determined start/end indexes avoiding the extrapolation of limits + if(start_attr > total_attrs) + start_attr = total_attrs; + + if(end_attr > total_attrs) + end_attr = total_attrs; + + // Configure the attributes toggler item withe the calculated pagination parameters + attribs_toggler->setPaginationValues(section_id, curr_page, max_pages); + return(true); + } + else + { + attribs_toggler->setPaginationValues(section_id, 0, 0); + return(false); + } } -void BaseTableView::requestRelationshipsUpdate(void) +void BaseTableView::configureCollapsedSections(CollapseMode coll_mode) { - emit s_relUpdateRequest(); + startGeometryUpdate(); + dynamic_cast(this->getUnderlyingObject())->setCollapseMode(coll_mode); + finishGeometryUpdate(); + emit s_collapseModeChanged(); } -void BaseTableView::togglePlaceholder(bool value) +void BaseTableView::togglePagination(bool enabled) { - BaseObjectView::togglePlaceholder(!connected_rels.empty() && value); + BaseTable *tab = dynamic_cast(this->getUnderlyingObject()); + + startGeometryUpdate(); + tab->setPaginationEnabled(enabled); + tab->resetCurrentPages(); + finishGeometryUpdate(); + emit s_paginationToggled(); } +void BaseTableView::configureCurrentPage(unsigned section_id, unsigned page) +{ + startGeometryUpdate(); + dynamic_cast(this->getUnderlyingObject())->setCurrentPage(section_id, page); + finishGeometryUpdate(); + emit s_currentPageChanged(); +} diff --git a/libobjrenderer/src/basetableview.h b/libobjrenderer/src/basetableview.h index 67b6b75f06..d25963df79 100644 --- a/libobjrenderer/src/basetableview.h +++ b/libobjrenderer/src/basetableview.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -31,37 +31,57 @@ #include "tableobjectview.h" #include "roundedrectitem.h" #include "baserelationship.h" +#include "textpolygonitem.h" +#include "attributestoggleritem.h" class BaseTableView: public BaseObjectView { private: Q_OBJECT + /*! \brief This timer is used to control the selection enabling of the object + * in mouse presse event in order to avoid select it instead of a child. + * See mousePressEvent() for details */ + QTimer sel_enabler_timer; + /*! \brief Stores the references to the relationships connected to this table. */ vector connected_rels; - protected: + protected: + //! \brief Stores the selected child objects in order to retrieve them in ObjectScene/ModelWidget + QList sel_child_objs; + + /*! \brief This attributes indicates that the object's geometry update is pending demanding a + * call to configureObject(). This attribute is set to true only when the objects is invisible + * the the configureObject is called. Once the object gets visible again this attribute is set + * to false and the geometry updated immediately (see BaseTableView::itemChange()) */ + bool pending_geom_update; + //! \brief Item groups that stores columns and extended attributes, respectively QGraphicsItemGroup *columns, + *ext_attribs; - static bool hide_ext_attribs, hide_tags; + //! brief Indicates if the extended attributes body should be hidden + static bool hide_ext_attribs, + + //! brief Indicates if the tag object should be hidden + hide_tags; + + //! brief Controls the maximum amount of attributes visible per page (columns/references + extended attributes) + static unsigned attribs_per_page[2]; //! \brief Polygonal object that defines the table body RoundedRectItem *body, //! \brief Extended table attributes (indexes, rules, triggers) section body - *ext_attribs_body, + *ext_attribs_body; - *placeholder, + AttributesTogglerItem *attribs_toggler; - *ext_attribs_toggler; - - QGraphicsPolygonItem *tag_body, *ext_attribs_tog_arrow; - - QGraphicsSimpleTextItem *tag_name; + TextPolygonItem *tag_item; //! \brief Stores the reference to the child object currently selected on table - TableObject *sel_child_obj; + TableObjectView *sel_child_obj_view; //! \brief Table title TableTitleView *title; @@ -75,21 +95,38 @@ class BaseTableView: public BaseObjectView { void removeConnectedRelationship(BaseRelationship *base_rel); - int getConnectedRelationshipIndex(BaseRelationship *base_rel); + /*! \brief Returns the index of the relationship in the list of the connected relationships + * If 'only_self_rels' is true then only self relationship are searched */ + int getConnectedRelationshipIndex(BaseRelationship *base_rel, bool only_self_rels = false); //! \brief Configures the tag object when the source object has one. void configureTag(void); /*! \brief Configures basic attributes of the table. A width need to be provided so the extended attributes section can follow the same width as the body and title */ - void __configureObject(float width); + void __configureObject(double width); //! \brief Determines the table width based upon its subsection (title, body and extended attribs) - float calculateWidth(void); + double calculateWidth(void); + + /*! \brief This as an auxiliary method called before the object changes its dimensions and it causes + * the object to not being selectable. This method is called whenever one of the signals are captured + * from the attributes toggler: s_paginationToggled s_currentPageChanged s_collapseModeChanged */ + void startGeometryUpdate(void); + + /*! \brief This auxiliary method is called after any geometry change finishes forcing the update of the object + * and in some cases the schema box which contains it */ + void finishGeometryUpdate(void); + + /*! \brief Determines the pagination paramenters for a section of the table. The input parameters are + * the section (BaseTable::AttribsSection | ExtAttribsSection) and the total amount of attributes in the section. + * The other paramenters start_attr and end_attr are reference parameters that will hold the indexes of items + * to be displayed in the current page. See configureObject() on TableView and GraphicalView */ + bool configurePaginationParams(unsigned page_id, unsigned total_attrs, unsigned &start_attr, unsigned &end_attr); public: - static const unsigned LEFT_CONN_POINT=0, - RIGHT_CONN_POINT=1; + static constexpr unsigned LeftConnPoint=0, + RightConnPoint=1; BaseTableView(BaseTable *base_tab); virtual ~BaseTableView(void); @@ -98,6 +135,12 @@ class BaseTableView: public BaseObjectView { void hoverMoveEvent(QGraphicsSceneHoverEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *event); + //! brief Defines the amount of attributes per page to be displayed + static void setAttributesPerPage(unsigned section_id, unsigned value); + + //! brief Returns the current amount of attributes per page to be displayed + static unsigned getAttributesPerPage(unsigned section_id); + //! \brief Hides the table's extended attributes (rules, triggers, indexes). This applies to all table/view instances static void setHideExtAttributes(bool value); @@ -121,6 +164,27 @@ class BaseTableView: public BaseObjectView { unsigned getConnectedRelsCount(BaseTable *src_tab, BaseTable *dst_tab); + //! \brief Configures the shadow for the table + void configureObjectShadow(void); + + //! \brief Returns a list of selected children objects + QList getSelectedChidren(void); + + //! \brief Clear the selection over all selected children + void clearChildrenSelection(void); + + private slots: + /*! \brief This slot reconfigures the table when the attributes toggler emits the signal s_collapseModeChanged + * hiding or exposing the sections related to the current collapse mode */ + void configureCollapsedSections(CollapseMode coll_mode); + + //! \brief This slot reconfigures the table when the attributes toggler emits the signal s_paginationToggled + void togglePagination(bool enabled); + + /*! \brief This slot reconfigures the table when the attributes toggler emits the signal s_currentPageChanged + * causing the the attributes of the current page to be displayed */ + void configureCurrentPage(unsigned section_id, unsigned page); + signals: //! \brief Signal emitted when a table is moved over the scene void s_objectMoved(void); @@ -128,11 +192,23 @@ class BaseTableView: public BaseObjectView { //! \brief Signal emitted to indicate that the relationships attached to the table need to be updated void s_relUpdateRequest(void); - //! \brief Signal emitted when the user right-click a focused table child object - void s_childObjectSelected(TableObject *); + //! \brief Signal emitted when the user right-click a focused table child object requesting a popup menu + void s_popupMenuRequested(TableObject *); + + //! \brief Signal emitted when the user clicks a focused table child object and holding Control+Shift + void s_childrenSelectionChanged(void); + + //! \brief Signal emitted when the user toggles the table's collapse mode + void s_collapseModeChanged(void); + + //! \brief Signal emitted when the user toggles the table's attributes pagination + void s_paginationToggled(void); + + //! \brief Signal emitted when the user changes the current table's attributes page + void s_currentPageChanged(void); - //! \brief Signal emitted when the user toggles the table's extended attributes area - void s_extAttributesToggled(void); + //! \brief Signal emitted when the object need the scene to clear its selection + void s_sceneClearRequested(void); friend class RelationshipView; }; diff --git a/libobjrenderer/src/beziercurveitem.cpp b/libobjrenderer/src/beziercurveitem.cpp index d18f64662d..1bce343ebf 100644 --- a/libobjrenderer/src/beziercurveitem.cpp +++ b/libobjrenderer/src/beziercurveitem.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libobjrenderer/src/beziercurveitem.h b/libobjrenderer/src/beziercurveitem.h index 7f8da09c6d..f367dba0b2 100644 --- a/libobjrenderer/src/beziercurveitem.h +++ b/libobjrenderer/src/beziercurveitem.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libobjrenderer/src/graphicalview.cpp b/libobjrenderer/src/graphicalview.cpp index d1dccd5841..30903c9845 100644 --- a/libobjrenderer/src/graphicalview.cpp +++ b/libobjrenderer/src/graphicalview.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -31,93 +31,159 @@ GraphicalView::GraphicalView(View *view) : BaseTableView(view) void GraphicalView::configureObject(void) { - View *view=dynamic_cast(this->getSourceObject()); - int i, count, count1=0; - Reference ref; + /* If the table isn't visible we abort the current configuration + * and mark its geometry update as pending so in the next call to + * setVisible(true) the geometry can be updated (see BaseObjectView::itemChange()) */ + if(!this->isVisible()) + { + pending_geom_update = true; + return; + } + + View *view=dynamic_cast(this->getUnderlyingObject()); + int i = 0, count = 0; + unsigned start_col = 0, end_col = 0, start_ext = 0, end_ext = 0; QPen pen; TableObjectView *graph_ref=nullptr; QList subitems; - vector tab_objs; + vector tab_objs, ext_tab_objs; + vector view_cols; QGraphicsItemGroup *groups[]={ columns, ext_attribs }; RoundedRectItem *bodies[]={ body, ext_attribs_body }; - QString attribs[]={ ParsersAttributes::VIEW_BODY, ParsersAttributes::VIEW_EXT_BODY }, - tag_attribs[]={ ParsersAttributes::TABLE_BODY, ParsersAttributes::TABLE_EXT_BODY }; + QString attribs[]={ Attributes::ViewBody, Attributes::ViewExtBody }, + tag_attribs[]={ Attributes::TableBody, Attributes::TableExtBody }; double width, type_width=0, px=0; TableObjectView *col_item=nullptr; QList col_items; TableObject *tab_obj=nullptr; Tag *tag=view->getTag(); + CollapseMode collapse_mode = view->getCollapseMode(); + bool has_col_pag = false, has_ext_pag = false; + + // Clear the selected children objects vector since we'll (re)configure the whole view + sel_child_objs.clear(); //Configures the view's title title->configureObject(view); - //Gets the reference count on SELECT part of the SQL definition - count=view->getReferenceCount(Reference::SQL_REFER_SELECT); + for(auto &obj : view->getObjects()) + ext_tab_objs.push_back(dynamic_cast(obj)); - if(count==0) - count=count1=view->getReferenceCount(Reference::SQL_VIEW_DEFINITION); + attribs_toggler->setHasExtAttributes(!hide_ext_attribs && !ext_tab_objs.empty()); - //Moves the references group to the origin to be moved latter - columns->moveBy(-columns->scenePos().x(), - -columns->scenePos().y()); + view_cols = view->getColumns(); + has_col_pag = configurePaginationParams(BaseTable::AttribsSection, view_cols.size(), start_col, end_col); + has_ext_pag = configurePaginationParams(BaseTable::ExtAttribsSection, + collapse_mode != CollapseMode::ExtAttribsCollapsed ? ext_tab_objs.size() : 0, + start_ext, end_ext); - subitems=columns->childItems(); + //Moves the references group to the origin to be moved latter + columns->moveBy(-columns->scenePos().x(), -columns->scenePos().y()); + columns->setVisible(view->getCollapseMode() != CollapseMode::AllAttribsCollapsed && start_col < static_cast(view_cols.size())); + body->setVisible(columns->isVisible()); - for(i=0; i < count; i++) + if(!columns->isVisible()) + { + for(auto &item : columns->childItems()) + { + columns->removeFromGroup(item); + delete(item); + } + } + else { - if(count1==0) - ref=view->getReference(i, Reference::SQL_REFER_SELECT); + vector aux_view_cols; + + if(has_col_pag) + aux_view_cols.assign(view_cols.begin() + start_col, view_cols.begin() + end_col); else - ref=view->getReference(i, Reference::SQL_VIEW_DEFINITION); + aux_view_cols = view_cols; + + count = aux_view_cols.size(); + subitems=columns->childItems(); - //Reuses the subitem if it was allocated before - if(!subitems.isEmpty() && i < subitems.size()) + for(i=0; i < count; i++) { - graph_ref=dynamic_cast(subitems[i]); + //Reuses the subitem if it was allocated before + if(!subitems.isEmpty() && i < subitems.size()) + { + graph_ref=dynamic_cast(subitems[i]); - //Moves the reference to the origin to be moved latter - graph_ref->moveBy(-graph_ref->scenePos().x(), - -graph_ref->scenePos().y()); + //Moves the reference to the origin to be moved latter + graph_ref->moveBy(-graph_ref->scenePos().x(), + -graph_ref->scenePos().y()); + } + else + graph_ref=new TableObjectView; + + graph_ref->configureObject(aux_view_cols[i]); + graph_ref->moveBy(HorizSpacing, (i * graph_ref->boundingRect().height()) + VertSpacing); + + /* Calculates the width of the name + type of the object. This is used to align all + the constraint labels on table */ + width=graph_ref->getChildObject(TableObjectView::ObjDescriptor)->boundingRect().width() + + graph_ref->getChildObject(TableObjectView::NameLabel)->boundingRect().width() + (8 * HorizSpacing); + if(px < width) px=width; + + //Gets the maximum width of the column type label to align all at same horizontal position + if(type_width < graph_ref->getChildObject(TableObjectView::TypeLabel)->boundingRect().width()) + type_width=graph_ref->getChildObject(TableObjectView::TypeLabel)->boundingRect().width() + (3 * HorizSpacing); + + col_items.push_back(graph_ref); } - else - graph_ref=new TableObjectView; - columns->removeFromGroup(graph_ref); - graph_ref->configureObject(ref); - graph_ref->moveBy(HORIZ_SPACING, (i * graph_ref->boundingRect().height()) + VERT_SPACING); - columns->addToGroup(graph_ref); + //Destroy the graphical references not used + i=subitems.size()-1; + while(i > count-1) + { + graph_ref=dynamic_cast(subitems[i]); + columns->removeFromGroup(graph_ref); + delete(graph_ref); + i--; + } + + //Set all items position + while(!col_items.isEmpty()) + { + col_item=dynamic_cast(col_items.front()); + columns->removeFromGroup(col_item); + col_items.pop_front(); + + //Positioning the type label + col_item->setChildObjectXPos(TableObjectView::TypeLabel, px); + + //Positioning the constraints label + col_item->setChildObjectXPos(TableObjectView::ConstrAliasLabel, px + type_width); + columns->addToGroup(col_item); + } } - //Destroy the graphical references not used - i=subitems.size()-1; - while(i > count-1) + if(!hide_ext_attribs && view->getCollapseMode() == CollapseMode::NotCollapsed) { - graph_ref=dynamic_cast(subitems[i]); - columns->removeFromGroup(graph_ref); - delete(graph_ref); - i--; + if(view->isPaginationEnabled() && has_ext_pag) + tab_objs.assign(ext_tab_objs.begin() + start_ext, ext_tab_objs.begin() + end_ext); + else + tab_objs.assign(ext_tab_objs.begin(), ext_tab_objs.end()); } - tab_objs.assign(view->getObjectList(OBJ_RULE)->begin(), - view->getObjectList(OBJ_RULE)->end()); - tab_objs.insert(tab_objs.end(), - view->getObjectList(OBJ_TRIGGER)->begin(), - view->getObjectList(OBJ_TRIGGER)->end()); - tab_objs.insert(tab_objs.end(), - view->getObjectList(OBJ_INDEX)->begin(), - view->getObjectList(OBJ_INDEX)->end()); + ext_attribs->setVisible(!tab_objs.empty() && view->getCollapseMode() == CollapseMode::NotCollapsed); + ext_attribs_body->setVisible(ext_attribs->isVisible()); - ext_attribs->setVisible(!tab_objs.empty() && !hide_ext_attribs); - ext_attribs_body->setVisible(!tab_objs.empty() && !hide_ext_attribs); - - if(!tab_objs.empty()) + if(tab_objs.empty()) + { + for(auto &item : ext_attribs->childItems()) + { + ext_attribs->removeFromGroup(item); + delete(item); + } + } + else { count=tab_objs.size(); //Gets the subitems of the current group subitems=ext_attribs->childItems(); - ext_attribs->moveBy(-ext_attribs->scenePos().x(), - -ext_attribs->scenePos().y()); + ext_attribs->moveBy(-ext_attribs->scenePos().x(), -ext_attribs->scenePos().y()); for(i=0; i < count; i++) { tab_obj=tab_objs.at(i); @@ -129,24 +195,24 @@ void GraphicalView::configureObject(void) col_item->setSourceObject(tab_obj); col_item->configureObject(); col_item->moveBy(-col_item->scenePos().x(), - -col_item->scenePos().y()); + -col_item->scenePos().y()); } else col_item=new TableObjectView(tab_obj); //Configures the item and set its position col_item->configureObject(); - col_item->moveBy(HORIZ_SPACING, (i * col_item->boundingRect().height()) + VERT_SPACING); + col_item->moveBy(HorizSpacing, (i * col_item->boundingRect().height()) + VertSpacing); /* Calculates the width of the name + type of the object. This is used to align all the constraint labels on table */ - width=col_item->getChildObject(0)->boundingRect().width() + - col_item->getChildObject(1)->boundingRect().width() + (3 * HORIZ_SPACING); + width=col_item->getChildObject(TableObjectView::ObjDescriptor)->boundingRect().width() + + col_item->getChildObject(TableObjectView::NameLabel)->boundingRect().width() + (3 * HorizSpacing); if(px < width) px=width; //Gets the maximum width of the column type label to align all at same horizontal position - if(type_width < col_item->getChildObject(2)->boundingRect().width()) - type_width=col_item->getChildObject(2)->boundingRect().width() + (3 * HORIZ_SPACING); + if(type_width < col_item->getChildObject(TableObjectView::TypeLabel)->boundingRect().width()) + type_width=col_item->getChildObject(TableObjectView::TypeLabel)->boundingRect().width() + (3 * HorizSpacing); col_items.push_back(col_item); } @@ -169,10 +235,10 @@ void GraphicalView::configureObject(void) col_items.pop_front(); //Positioning the type label - col_item->setChildObjectXPos(2, px); + col_item->setChildObjectXPos(TableObjectView::TypeLabel, px); //Positioning the constraints label - col_item->setChildObjectXPos(3, px + type_width); + col_item->setChildObjectXPos(TableObjectView::ConstrAliasLabel, px + type_width); ext_attribs->addToGroup(col_item); } } @@ -185,27 +251,41 @@ void GraphicalView::configureObject(void) //Resizes the columns/extended attributes using the new width for(int idx=0; idx < 2; idx++) { - bodies[idx]->setRect(QRectF(0,0, width, groups[idx]->boundingRect().height() + (2 * VERT_SPACING))); - - pen=this->getBorderStyle(attribs[idx]); - pen.setStyle(Qt::DashLine); - + /* Configuring the brush and pen of the bodies even if they aren't visible + * the attributes toggler at the bottom of the view uses the color of the attributes body + * this will avoid the creation of a transparent toggler */ if(!tag) + { bodies[idx]->setBrush(this->getFillStyle(attribs[idx])); + pen=this->getBorderStyle(attribs[idx]); + } else { bodies[idx]->setBrush(tag->getFillStyle(tag_attribs[idx])); - pen.setColor(tag->getElementColor(tag_attribs[idx], Tag::BORDER_COLOR)); + pen.setColor(tag->getElementColor(tag_attribs[idx], Tag::BorderColor)); } + pen.setStyle(Qt::DashLine); bodies[idx]->setPen(pen); + // We avoid the construction of the rect related to the current body item if the related group isn't visible + if(!groups[idx]->isVisible()) + continue; + + bodies[idx]->setRect(QRectF(0,0, width, groups[idx]->boundingRect().height() + (2 * VertSpacing))); + if(idx==0) - bodies[idx]->setPos(title->pos().x(), title->boundingRect().height()-1); + bodies[idx]->setPos(title->pos().x(), title->boundingRect().height() - 1); else - bodies[idx]->setPos(title->pos().x(), - title->boundingRect().height() + - bodies[0]->boundingRect().height() - 2); + { + if(bodies[0]->isVisible()) + bodies[idx]->setPos(title->pos().x(), + title->boundingRect().height() + + bodies[0]->boundingRect().height() - 2); + else + bodies[idx]->setPos(title->pos().x(), title->boundingRect().height()-1); + } + groups[idx]->setPos(bodies[idx]->pos()); subitems=groups[idx]->childItems(); @@ -213,8 +293,8 @@ void GraphicalView::configureObject(void) { col_item=dynamic_cast(subitems.front()); subitems.pop_front(); - col_item->setChildObjectXPos(3, width - - col_item->boundingRect().width() - (2 * HORIZ_SPACING) - 1); + col_item->setChildObjectXPos(TableObjectView::ConstrAliasLabel, + width - col_item->getChildObject(3)->boundingRect().width() - (2 * HorizSpacing)); } } @@ -222,6 +302,13 @@ void GraphicalView::configureObject(void) this->bounding_rect.setWidth(title->boundingRect().width()); BaseTableView::__configureObject(width); + + if(!view->getAlias().isEmpty()) + table_tooltip += QString("\nAlias: %1").arg(view->getAlias()); + + if(!view->getComment().isEmpty()) + table_tooltip += QString("\n---\n%1").arg(view->getComment()); + BaseObjectView::__configureObject(); BaseObjectView::configureObjectShadow(); BaseObjectView::configureObjectSelection(); diff --git a/libobjrenderer/src/graphicalview.h b/libobjrenderer/src/graphicalview.h index 74f559582f..0fc2b85d91 100644 --- a/libobjrenderer/src/graphicalview.h +++ b/libobjrenderer/src/graphicalview.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libobjrenderer/src/objectsscene.cpp b/libobjrenderer/src/objectsscene.cpp index 64bb7337a9..d6b8e32193 100644 --- a/libobjrenderer/src/objectsscene.cpp +++ b/libobjrenderer/src/objectsscene.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -32,12 +32,15 @@ bool ObjectsScene::invert_rangesel_trigger=false; ObjectsScene::ObjectsScene(void) { + layers.push_back(trUtf8("Default layer")); + active_layers.push_back(layers.at(0)); + moving_objs=move_scene=false; enable_range_sel=true; this->setBackgroundBrush(grid); - sel_ini_pnt.setX(NAN); - sel_ini_pnt.setY(NAN); + sel_ini_pnt.setX(DNaN); + sel_ini_pnt.setY(DNaN); selection_rect=new QGraphicsPolygonItem; selection_rect->setVisible(false); @@ -62,17 +65,17 @@ ObjectsScene::ObjectsScene(void) object_move_timer.stop(); }); - scene_move_timer.setInterval(SCENE_MOVE_TIMEOUT); - corner_hover_timer.setInterval(SCENE_MOVE_TIMEOUT * 10); - object_move_timer.setInterval(SCENE_MOVE_TIMEOUT * 10); + scene_move_timer.setInterval(SceneMoveTimeout); + corner_hover_timer.setInterval(SceneMoveTimeout * 10); + object_move_timer.setInterval(SceneMoveTimeout * 10); } ObjectsScene::~ObjectsScene(void) { QGraphicsItemGroup *item=nullptr; QList items; - ObjectType obj_types[]={ OBJ_RELATIONSHIP, OBJ_TEXTBOX, - OBJ_VIEW, OBJ_TABLE, OBJ_SCHEMA }; + ObjectType obj_types[]={ ObjectType::Relationship, ObjectType::Textbox, + ObjectType::View, ObjectType::Table, ObjectType::Schema }; unsigned i, count=sizeof(obj_types)/sizeof(ObjectType); this->removeItem(selection_rect); @@ -95,12 +98,12 @@ ObjectsScene::~ObjectsScene(void) /* Case the object is converted to a item group and can be converted to database objects, indicates that the object can be removed from the scene */ if(item && !item->parentItem() && - ((dynamic_cast(item) && obj_types[i]==OBJ_RELATIONSHIP) || - (dynamic_cast(item) && obj_types[i]==OBJ_TEXTBOX) || - (dynamic_cast(item) && obj_types[i]==OBJ_TEXTBOX) || - (dynamic_cast(item) && obj_types[i]==OBJ_VIEW) || - (dynamic_cast(item) && obj_types[i]==OBJ_TABLE) || - (dynamic_cast(item) && obj_types[i]==OBJ_SCHEMA))) + ((dynamic_cast(item) && obj_types[i]==ObjectType::Relationship) || + (dynamic_cast(item) && obj_types[i]==ObjectType::Textbox) || + (dynamic_cast(item) && obj_types[i]==ObjectType::Textbox) || + (dynamic_cast(item) && obj_types[i]==ObjectType::View) || + (dynamic_cast(item) && obj_types[i]==ObjectType::Table) || + (dynamic_cast(item) && obj_types[i]==ObjectType::Schema))) { this->removeItem(item); @@ -119,6 +122,225 @@ ObjectsScene::~ObjectsScene(void) } } +QString ObjectsScene::formatLayerName(const QString &name) +{ + QString fmt_name; + unsigned idx = 1; + + //Removing invalid chars + for(auto &chr : name) + { + if(chr.isLetterOrNumber() || chr == ' ' || chr == '_') + fmt_name.append(chr); + else + fmt_name.append('_'); + } + + //Doing the desambiguation (if needed) + while(layers.contains(fmt_name)) + fmt_name = QString("%1 %2").arg(name).arg(QString::number(idx++)); + + return(fmt_name); +} + +QString ObjectsScene::addLayer(const QString &name) +{ + if(name.isEmpty()) + return(QString()); + + QString fmt_name = formatLayerName(name); + layers.push_back(fmt_name); + + emit s_layersChanged(); + return(fmt_name); +} + +QString ObjectsScene::renameLayer(unsigned idx, const QString &name) +{ + if(name.isEmpty() || idx >= static_cast(layers.size())) + return (QString()); + + if(name != layers[idx]) + layers[idx] = formatLayerName(name); + + emit s_layersChanged(); + return(layers[idx]); +} + +void ObjectsScene::removeLayer(const QString &name) +{ + int idx = layers.indexOf(name); + + if(idx > 0) + { + moveObjectsToLayer(idx, DefaultLayer); + layers.removeAll(name); + active_layers.removeAll(name); + emit s_layersChanged(); + } +} + +void ObjectsScene::removeLayers(void) +{ + BaseObjectView *obj_view = nullptr; + QString def_layer = layers[DefaultLayer]; + bool is_active = active_layers.contains(def_layer); + + layers.clear(); + active_layers.clear(); + layers.push_back(def_layer); + + if(is_active) + active_layers.push_back(def_layer); + + for(auto &item : this->items()) + { + obj_view = dynamic_cast(item); + + if(obj_view && !obj_view->parentItem() && obj_view->getLayer() != DefaultLayer) + { + obj_view->setLayer(DefaultLayer); + obj_view->setVisible(is_active); + } + } + + emit s_layersChanged(); + updateActiveLayers(); +} + +void ObjectsScene::setActiveLayers(QStringList act_layers) +{ + QList layers_idxs; + int idx = -1; + + for(auto &layer : act_layers) + { + idx = layers.indexOf(layer); + + if(idx >= 0) + layers_idxs.push_back(idx); + } + + setActiveLayers(layers_idxs); +} + +void ObjectsScene::setActiveLayers(QList layers_idxs) +{ + BaseObjectView *obj_view = nullptr; + active_layers.clear(); + + if(!layers_idxs.isEmpty()) + { + bool is_in_layer = false; + unsigned layer_cnt = static_cast(layers.size()); + SchemaView *sch_view = nullptr; + + for(auto &item : this->items()) + { + obj_view = dynamic_cast(item); + + if(obj_view && !obj_view->parentItem() && obj_view->getLayer() < layer_cnt) + { + sch_view = dynamic_cast(obj_view); + is_in_layer = layers_idxs.contains(obj_view->getLayer()); + + if(!obj_view->isVisible() && is_in_layer) + { + if(!sch_view || + (sch_view && dynamic_cast(sch_view->getUnderlyingObject())->isRectVisible())) + obj_view->setVisible(true); + } + else if(obj_view->isVisible() && !is_in_layer) + obj_view->setVisible(false); + } + } + + for(auto &idx : layers_idxs) + { + if(idx < layer_cnt) + active_layers.push_back(layers[idx]); + } + } + else + { + for(auto &item : this->items()) + { + obj_view = dynamic_cast(item); + + if(obj_view && !obj_view->parentItem()) + obj_view->setVisible(false); + } + } + + emit s_activeLayersChanged(); +} + +void ObjectsScene::moveObjectsToLayer(unsigned old_layer, unsigned new_layer) +{ + BaseObjectView *obj_view = nullptr; + unsigned total_layers = layers.size(); + + if(old_layer == new_layer || old_layer >= total_layers || new_layer >= total_layers) + return; + + for(auto &item : this->items()) + { + obj_view = dynamic_cast(item); + + if(obj_view && !obj_view->parentItem() && obj_view->getLayer() == old_layer) + { + obj_view->setLayer(new_layer); + obj_view->setVisible(isLayerActive(layers[new_layer])); + } + } + + emit s_objectsMovedLayer(); +} + +bool ObjectsScene::isLayerActive(const QString &name) +{ + return(active_layers.contains(name)); +} + +bool ObjectsScene::isLayerActive(unsigned layer_id) +{ + if(layer_id >= static_cast(layers.size())) + return(false); + + return(active_layers.contains(layers[layer_id])); +} + +QStringList ObjectsScene::getActiveLayers(void) +{ + return(active_layers); +} + +QList ObjectsScene::getActiveLayersIds(void) +{ + QList list; + + for(auto &layer : active_layers) + list.push_back(layers.indexOf(layer)); + + return(list); +} + +QStringList ObjectsScene::getLayers(void) +{ + return(layers); +} + +unsigned ObjectsScene::getLayerId(const QString &name) +{ + int idx = layers.contains(name); + return(idx < 0 ? InvalidLayer : static_cast(idx)); +} + +void ObjectsScene::updateActiveLayers(void) +{ + setActiveLayers(active_layers); +} + void ObjectsScene::setEnableCornerMove(bool enable) { ObjectsScene::corner_move=enable; @@ -136,13 +358,13 @@ bool ObjectsScene::isCornerMoveEnabled(void) QPointF ObjectsScene::alignPointToGrid(const QPointF &pnt) { - QPointF p(roundf(pnt.x()/grid_size) * grid_size, - roundf(pnt.y()/grid_size) * grid_size); + int px = static_cast(round(pnt.x()/static_cast(grid_size))) * grid_size, + py = static_cast(round(pnt.y()/static_cast(grid_size))) * grid_size; - if(p.x() < 0) p.setX(0); - if(p.y() < 0) p.setY(0); + if(px < 0) px = 0; + if(py < 0) py = 0; - return(p); + return(QPointF(px, py)); } void ObjectsScene::setSceneRect(const QRectF &rect) @@ -169,12 +391,12 @@ QRectF ObjectsScene::itemsBoundingRect(bool seek_only_db_objs, bool selected_onl if(obj_view && obj_view->isVisible()) { - graph_obj=dynamic_cast(obj_view->getSourceObject()); + graph_obj=dynamic_cast(obj_view->getUnderlyingObject()); if(graph_obj) { - if(graph_obj->getObjectType()!=OBJ_RELATIONSHIP && - graph_obj->getObjectType()!=BASE_RELATIONSHIP) + if(graph_obj->getObjectType()!=ObjectType::Relationship && + graph_obj->getObjectType()!=ObjectType::BaseRelationship) pnt=graph_obj->getPosition(); else pnt=dynamic_cast(obj_view)->__boundingRect().topLeft(); @@ -187,8 +409,8 @@ QRectF ObjectsScene::itemsBoundingRect(bool seek_only_db_objs, bool selected_onl if(selected_only) { - if(graph_obj->getObjectType()!=OBJ_RELATIONSHIP && - graph_obj->getObjectType()!=BASE_RELATIONSHIP) + if(graph_obj->getObjectType()!=ObjectType::Relationship && + graph_obj->getObjectType()!=ObjectType::BaseRelationship) pnt = pnt + dynamic_cast(obj_view)->boundingRect().bottomRight(); else pnt = pnt + dynamic_cast(obj_view)->__boundingRect().bottomRight(); @@ -231,8 +453,8 @@ void ObjectsScene::setGridSize(unsigned size) height=aux_size.height()/static_cast(size) * size; //Calculates the grid pixmpa size - img_w=ceil(width/size)*size; - img_h=ceil(height/size)*size; + img_w=ceil(width/size) * size; + img_h=ceil(height/size) * size; grid_size=size; grid_img=QImage(img_w, img_h, QImage::Format_ARGB32); @@ -255,7 +477,7 @@ void ObjectsScene::setGridSize(unsigned size) { pen.setColor(QColor(75,115,195)); pen.setStyle(Qt::DashLine); - pen.setWidthF(1.0f); + pen.setWidthF(1.0); painter.setPen(pen); painter.drawLine(width-1, 0,width-1,img_h-1); painter.drawLine(0, height-1,img_w-1,height-1); @@ -286,13 +508,13 @@ void ObjectsScene::showRelationshipLine(bool value, const QPointF &p_start) object=dynamic_cast(items.front()); - if(object && object->getSourceObject()) + if(object && object->getUnderlyingObject()) { - base_obj=dynamic_cast(object->getSourceObject()); + base_obj=dynamic_cast(object->getUnderlyingObject()); if(!value && base_obj && - base_obj->getObjectType()!=OBJ_RELATIONSHIP && - base_obj->getObjectType()!=BASE_RELATIONSHIP && + base_obj->getObjectType()!=ObjectType::Relationship && + base_obj->getObjectType()!=ObjectType::BaseRelationship && !base_obj->isProtected()) flags=QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable | @@ -324,11 +546,19 @@ void ObjectsScene::setGridOptions(bool show_grd, bool align_objs_grd, bool show_ } } -void ObjectsScene::getGridOptions(bool &show_grd, bool &align_objs_grd, bool &show_pag_dlm) +bool ObjectsScene::isAlignObjectsToGrid(void) +{ + return(align_objs_grid); +} + +bool ObjectsScene::isShowGrid(void) +{ + return(show_grid); +} + +bool ObjectsScene::isShowPageDelimiters(void) { - show_grd=ObjectsScene::show_grid; - align_objs_grd=ObjectsScene::align_objs_grid; - show_pag_dlm=ObjectsScene::show_page_delim; + return(show_page_delim); } void ObjectsScene::setPaperConfiguration(QPrinter::PaperSize paper_sz, QPrinter::Orientation orient, QRectF margins, QSizeF custom_size) @@ -350,7 +580,7 @@ void ObjectsScene::getPaperConfiguration(QPrinter::PaperSize &paper_sz, QPrinter void ObjectsScene::configurePrinter(QPrinter *printer) { if(!printer) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject ,__PRETTY_FUNCTION__,__FILE__,__LINE__); if(paper_size!=QPrinter::Custom) printer->setPaperSize(paper_size); @@ -400,28 +630,30 @@ void ObjectsScene::configurePrinter(QPrinter *printer, const QSizeF &custom_size custom_paper_size=orig_custom_sz; } -void ObjectsScene::emitObjectModification(BaseGraphicObject *object) +void ObjectsScene::handlePopupMenuRequested(TableObject *child_obj) { - emit s_objectModified(object); + emit s_popupMenuRequested(child_obj); } -void ObjectsScene::emitExtAttributesToggled(void) +void ObjectsScene::handleObjectSelection(BaseGraphicObject *object, bool selected) { - emit s_extAttributesToggled(); + if(object) + emit s_objectSelected(object, selected); } -void ObjectsScene::emitChildObjectSelection(TableObject *child_obj) +void ObjectsScene::handleChildrenSelectionChanged(void) { - /* Treats the TableView::s_childObjectSelect() only when there is no - other object selected on the scene */ - if(this->selectedItems().isEmpty()) - emit s_popupMenuRequested(child_obj); -} + BaseTableView *tab_view = dynamic_cast(sender()); -void ObjectsScene::emitObjectSelection(BaseGraphicObject *object, bool selected) -{ - if(object) - emit s_objectSelected(object, selected); + if(!tab_view) + return; + + if(tab_view->getSelectedChidren().empty()) + tabs_sel_children.removeAll(tab_view); + else if(!tabs_sel_children.contains(tab_view)) + tabs_sel_children.append(tab_view); + + emit s_childrenSelectionChanged(); } void ObjectsScene::addItem(QGraphicsItem *item) @@ -433,20 +665,21 @@ void ObjectsScene::addItem(QGraphicsItem *item) BaseObjectView *obj=dynamic_cast(item); if(rel) - connect(rel, SIGNAL(s_relationshipModified(BaseGraphicObject*)), - this, SLOT(emitObjectModification(BaseGraphicObject*))); + connect(rel, SIGNAL(s_relationshipModified(BaseGraphicObject*)), this, SIGNAL(s_objectModified(BaseGraphicObject*))); else if(tab) { - connect(tab, SIGNAL(s_childObjectSelected(TableObject*)), - this, SLOT(emitChildObjectSelection(TableObject*))); - connect(tab, SIGNAL(s_extAttributesToggled()), - this, SLOT(emitExtAttributesToggled())); + connect(tab, SIGNAL(s_popupMenuRequested(TableObject*)), this, SLOT(handlePopupMenuRequested(TableObject*))); + connect(tab, SIGNAL(s_childrenSelectionChanged()), this, SLOT(handleChildrenSelectionChanged())); + connect(tab, SIGNAL(s_collapseModeChanged()), this, SIGNAL(s_collapseModeChanged())); + connect(tab, SIGNAL(s_paginationToggled()), this, SIGNAL(s_paginationToggled())); + connect(tab, SIGNAL(s_currentPageChanged()), this, SIGNAL(s_currentPageChanged())); + connect(tab, SIGNAL(s_sceneClearRequested()), this, SLOT(clearSelection())); } if(obj) { - connect(obj, SIGNAL(s_objectSelected(BaseGraphicObject*,bool)), - this, SLOT(emitObjectSelection(BaseGraphicObject*,bool))); + obj->setVisible(isLayerActive(obj->getLayer())); + connect(obj, SIGNAL(s_objectSelected(BaseGraphicObject*,bool)), this, SLOT(handleObjectSelection(BaseGraphicObject*,bool))); } QGraphicsScene::addItem(item); @@ -470,8 +703,8 @@ void ObjectsScene::removeItem(QGraphicsItem *item) if(object) { disconnect(object, nullptr, this, nullptr); - disconnect(object, nullptr, dynamic_cast(object->getSourceObject()), nullptr); - disconnect(dynamic_cast(object->getSourceObject()), nullptr, object, nullptr); + disconnect(object, nullptr, dynamic_cast(object->getUnderlyingObject()), nullptr); + disconnect(dynamic_cast(object->getUnderlyingObject()), nullptr, object, nullptr); removed_objs.push_back(object); } } @@ -499,7 +732,7 @@ void ObjectsScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) BaseObjectView *obj=dynamic_cast(this->selectedItems().at(0)); if(obj) - emit s_objectDoubleClicked(dynamic_cast(obj->getSourceObject())); + emit s_objectDoubleClicked(dynamic_cast(obj->getUnderlyingObject())); } else //Emit a signal indicating that no object was selected @@ -509,8 +742,8 @@ void ObjectsScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) void ObjectsScene::mousePressEvent(QGraphicsSceneMouseEvent *event) { //Gets the item at mouse position - QGraphicsItem* item=this->itemAt(event->scenePos().x(), event->scenePos().y(), QTransform()); - bool is_deselection = !this->selectedItems().isEmpty() && !this->itemAt(event->scenePos(), QTransform()); + QGraphicsItem* item=this->itemAt(event->scenePos(), QTransform()); + bool is_deselection = !this->selectedItems().isEmpty() && !item; if(selectedItems().empty()) emit s_objectsScenePressed(event->buttons()); @@ -525,6 +758,12 @@ void ObjectsScene::mousePressEvent(QGraphicsSceneMouseEvent *event) if(is_deselection) this->blockItemsSignals(true); + /* If we're handling a deselection of the user selected another object whitout being holding Control + * we need to deselect the tables' children objects too */ + if(is_deselection || (event->buttons()==Qt::LeftButton && (event->modifiers() & Qt::ControlModifier) != Qt::ControlModifier)) + //Forcing the clear on all selected table children object + clearTablesChildrenSelection(); + QGraphicsScene::mousePressEvent(event); if(is_deselection) @@ -577,17 +816,17 @@ bool ObjectsScene::mouseIsAtCorner(void) if(rect.contains(pos)) { - if(pos.x() <= SCENE_MOVE_THRESHOLD) - scene_move_dx=-SCENE_MOVE_STEP; - else if(pos.x() >= (view->width() - view->verticalScrollBar()->width() - SCENE_MOVE_THRESHOLD)) - scene_move_dx=SCENE_MOVE_STEP; + if(pos.x() <= SceneMoveThreshold) + scene_move_dx=-SceneMoveStep; + else if(pos.x() >= (view->width() - view->verticalScrollBar()->width() - SceneMoveThreshold)) + scene_move_dx=SceneMoveStep; else scene_move_dx=0; - if(pos.y() <= SCENE_MOVE_THRESHOLD) - scene_move_dy=-SCENE_MOVE_STEP; - else if(pos.y() >= (view->height() - view->horizontalScrollBar()->height() - SCENE_MOVE_THRESHOLD)) - scene_move_dy=SCENE_MOVE_STEP; + if(pos.y() <= SceneMoveThreshold) + scene_move_dy=-SceneMoveStep; + else if(pos.y() >= (view->height() - view->horizontalScrollBar()->height() - SceneMoveThreshold)) + scene_move_dy=SceneMoveStep; else scene_move_dy=0; @@ -701,7 +940,7 @@ void ObjectsScene::keyPressEvent(QKeyEvent *event) event->key() == Qt::Key_Left || event->key() == Qt::Key_Right) && !selectedItems().isEmpty()) { - float dx = 0, dy = 0; + double dx = 0, dy = 0; BaseObjectView *obj_view=nullptr; QRectF brect = itemsBoundingRect(true, true); @@ -795,8 +1034,10 @@ void ObjectsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) if(!rel_line->isVisible()) { + int sel_items_count = this->selectedItems().size(); + //Case the user starts a object moviment - if(!this->selectedItems().isEmpty() && !moving_objs /*&& event->modifiers()==Qt::NoModifier*/) + if(sel_items_count != 0 && !moving_objs) { if(BaseObjectView::isPlaceholderEnabled()) { @@ -815,7 +1056,7 @@ void ObjectsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) } //If the alignment to grid is active, adjust the event scene position - if(align_objs_grid && !selection_rect->isVisible()) + if(align_objs_grid && !selection_rect->isVisible() && sel_items_count <= 1) event->setScenePos(this->alignPointToGrid(event->scenePos())); else if(selection_rect->isVisible()) { @@ -825,8 +1066,8 @@ void ObjectsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) pol.append(QPointF(event->scenePos().x(), event->scenePos().y())); pol.append(QPointF(sel_ini_pnt.x(), event->scenePos().y())); selection_rect->setPolygon(pol); - selection_rect->setBrush(BaseObjectView::getFillStyle(ParsersAttributes::OBJ_SELECTION)); - selection_rect->setPen(BaseObjectView::getBorderStyle(ParsersAttributes::OBJ_SELECTION)); + selection_rect->setBrush(BaseObjectView::getFillStyle(Attributes::ObjSelection)); + selection_rect->setPen(BaseObjectView::getBorderStyle(Attributes::ObjSelection)); } } } @@ -862,8 +1103,8 @@ void ObjectsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) selection_rect->setVisible(false); selection_rect->setPolygon(pol); - sel_ini_pnt.setX(NAN); - sel_ini_pnt.setY(NAN); + sel_ini_pnt.setX(DNaN); + sel_ini_pnt.setY(DNaN); if(!this->selectedItems().isEmpty()) emit s_objectsSelectedInRange(); @@ -872,7 +1113,6 @@ void ObjectsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) void ObjectsScene::finishObjectsMove(const QPointF &pnt_end) { - unsigned i, count; QList items=this->selectedItems(), rel_list; double x1,y1,x2,y2, dx, dy; QRectF rect; @@ -885,6 +1125,7 @@ void ObjectsScene::finishObjectsMove(const QPointF &pnt_end) RelationshipView *rel=nullptr; BaseObjectView *obj_view=nullptr; BaseTableView *tab_view=nullptr; + TableObjectView *tab_obj_view=nullptr; QSet tables; //Gathering the relationships inside the selected schemsa in order to move their points too @@ -893,6 +1134,11 @@ void ObjectsScene::finishObjectsMove(const QPointF &pnt_end) obj_view=dynamic_cast(item); sch_view=dynamic_cast(item); tab_view=dynamic_cast(item); + tab_obj_view=dynamic_cast(item); + + // Ignoring table objects items + if(tab_obj_view) + continue; if(obj_view) obj_view->togglePlaceholder(false); @@ -902,13 +1148,13 @@ void ObjectsScene::finishObjectsMove(const QPointF &pnt_end) else if(sch_view) { //Get the schema object - Schema *schema=dynamic_cast(sch_view->getSourceObject()); + Schema *schema=dynamic_cast(sch_view->getUnderlyingObject()); if(!schema->isProtected()) { //Get the table-table and table-view relationships - rels=dynamic_cast(schema->getDatabase())->getObjects(OBJ_RELATIONSHIP, schema); - base_rels=dynamic_cast(schema->getDatabase())->getObjects(BASE_RELATIONSHIP, schema); + rels=dynamic_cast(schema->getDatabase())->getObjects(ObjectType::Relationship, schema); + base_rels=dynamic_cast(schema->getDatabase())->getObjects(ObjectType::BaseRelationship, schema); rels.insert(rels.end(), base_rels.begin(), base_rels.end()); for(auto &rel : rels) @@ -917,9 +1163,9 @@ void ObjectsScene::finishObjectsMove(const QPointF &pnt_end) /* If the relationship contains points and it is not selected then it will be included on the list in order to move their custom line points */ - if(!dynamic_cast(base_rel->getReceiverObject())->isSelected() && + if(!dynamic_cast(base_rel->getOverlyingObject())->isSelected() && !base_rel->getPoints().empty()) - rel_list.push_back(dynamic_cast(base_rel->getReceiverObject())); + rel_list.push_back(dynamic_cast(base_rel->getOverlyingObject())); } tables.unite(sch_view->getChildren().toSet()); @@ -938,33 +1184,36 @@ void ObjectsScene::finishObjectsMove(const QPointF &pnt_end) dx=pnt_end.x() - sel_ini_pnt.x(); dy=pnt_end.y() - sel_ini_pnt.y(); - count=items.size(); - for(i=0; i < count; i++) + for(auto &item : items) { - rel=dynamic_cast(items[i]); + // Ignoring table objects items + tab_obj_view=dynamic_cast(item); + if(tab_obj_view) continue; + + rel=dynamic_cast(item); if(!rel) { if(align_objs_grid) - items[i]->setPos(alignPointToGrid(items[i]->pos())); + item->setPos(alignPointToGrid(item->pos())); else { - QPointF p=items[i]->pos(); + QPointF p=item->pos(); if(p.x() < 0) p.setX(0); if(p.y() < 0) p.setY(0); - items[i]->setPos(p); + item->setPos(p); } - rect.setTopLeft(items[i]->pos()); - rect.setSize(items[i]->boundingRect().size()); + rect.setTopLeft(item->pos()); + rect.setSize(item->boundingRect().size()); } else { /* If the relationship has points added to the line is necessary to move the points too. Since relationships cannot be moved naturally (by user) this will be done by the scene. NOTE: this operation is done ONLY WHEN there is more than one object selected! */ - points=rel->getSourceObject()->getPoints(); - if(count > 1 && !points.empty()) + points=rel->getUnderlyingObject()->getPoints(); + if(items.size() > 1 && !points.empty()) { itr=points.begin(); while(itr!=points.end()) @@ -981,7 +1230,7 @@ void ObjectsScene::finishObjectsMove(const QPointF &pnt_end) } //Assing the new points to relationship and reconfigure its line - rel->getSourceObject()->setPoints(points); + rel->getUnderlyingObject()->setPoints(points); rel->configureLine(); } @@ -1003,8 +1252,8 @@ void ObjectsScene::finishObjectsMove(const QPointF &pnt_end) { rect=this->itemsBoundingRect(); rect.setTopLeft(QPointF(0,0)); - rect.setWidth(rect.width() * 1.05f); - rect.setHeight(rect.height() * 1.05f); + rect.setWidth(rect.width() * 1.05); + rect.setHeight(rect.height() * 1.05); this->setSceneRect(rect); } @@ -1016,7 +1265,7 @@ void ObjectsScene::finishObjectsMove(const QPointF &pnt_end) if(align_objs_grid) { tab_view->setPos(alignPointToGrid(tab_view->pos())); - schemas.insert(dynamic_cast(tab_view->getSourceObject()->getSchema())); + schemas.insert(dynamic_cast(tab_view->getUnderlyingObject()->getSchema())); } if(BaseObjectView::isPlaceholderEnabled()) @@ -1029,8 +1278,8 @@ void ObjectsScene::finishObjectsMove(const QPointF &pnt_end) emit s_objectsMoved(true); moving_objs=false; - sel_ini_pnt.setX(NAN); - sel_ini_pnt.setY(NAN); + sel_ini_pnt.setX(DNaN); + sel_ini_pnt.setY(DNaN); } void ObjectsScene::alignObjectsToGrid(void) @@ -1056,20 +1305,20 @@ void ObjectsScene::alignObjectsToGrid(void) else if(rel) { //Align the relationship points - points=rel->getSourceObject()->getPoints(); + points=rel->getUnderlyingObject()->getPoints(); count1=points.size(); for(i1=0; i1 < count1; i1++) points[i1]=this->alignPointToGrid(points[i1]); if(count1 > 0) { - rel->getSourceObject()->setPoints(points); + rel->getUnderlyingObject()->setPoints(points); rel->configureLine(); } //Align the labels - for(i1=BaseRelationship::SRC_CARD_LABEL; - i1<=BaseRelationship::REL_NAME_LABEL; i1++) + for(i1=BaseRelationship::SrcCardLabel; + i1<=BaseRelationship::RelNameLabel; i1++) { lab=rel->getLabel(i1); if(lab) @@ -1079,7 +1328,7 @@ void ObjectsScene::alignObjectsToGrid(void) else if(!dynamic_cast(items[i])) items[i]->setPos(this->alignPointToGrid(items[i]->pos())); else - schemas.push_back(dynamic_cast(dynamic_cast(items[i])->getSourceObject())); + schemas.push_back(dynamic_cast(dynamic_cast(items[i])->getUnderlyingObject())); } } @@ -1097,6 +1346,20 @@ void ObjectsScene::update(void) QGraphicsScene::update(this->sceneRect()); } +void ObjectsScene::clearTablesChildrenSelection(void) +{ + for(auto &tab_obj_view : tabs_sel_children) + tab_obj_view->clearChildrenSelection(); + + tabs_sel_children.clear(); +} + +void ObjectsScene::clearSelection(void) +{ + clearTablesChildrenSelection(); + QGraphicsScene::clearSelection(); +} + vector ObjectsScene::getPagesForPrinting(const QSizeF &paper_size, const QSizeF &margin, unsigned &h_page_cnt, unsigned &v_page_cnt) { vector pages; @@ -1105,12 +1368,12 @@ vector ObjectsScene::getPagesForPrinting(const QSizeF &paper_size, const unsigned h_page=0, v_page=0, start_h=99999, start_v=99999; QList list; - page_width=ceilf(paper_size.width() - margin.width()-1); - page_height=ceilf(paper_size.height() - margin.height()-1); + page_width=ceil(paper_size.width() - margin.width()-1); + page_height=ceil(paper_size.height() - margin.height()-1); //Calculates the horizontal and vertical page count based upon the passed paper size - h_page_cnt=roundf(this->sceneRect().width()/page_width) + 1; - v_page_cnt=roundf(this->sceneRect().height()/page_height) + 1; + h_page_cnt=round(this->sceneRect().width()/page_width) + 1; + v_page_cnt=round(this->sceneRect().height()/page_height) + 1; //Calculates the maximum count of horizontal and vertical pages for(v_page=0; v_page < v_page_cnt; v_page++) @@ -1140,8 +1403,8 @@ vector ObjectsScene::getPagesForPrinting(const QSizeF &paper_size, const } //Re calculates the maximum page count based upon the maximum page size - h_page_cnt=roundf(max_rect.width()/page_width); - v_page_cnt=roundf(max_rect.height()/page_height); + h_page_cnt=round(max_rect.width()/page_width); + v_page_cnt=round(max_rect.height()/page_height); //Inserts the page rectangles on the list for(v_page=static_cast(start_v); v_page < v_page_cnt; v_page++) @@ -1170,3 +1433,24 @@ bool ObjectsScene::isMovingObjects(void) { return(moving_objs); } + +QList ObjectsScene::selectedItems(void) const +{ + if(tabs_sel_children.empty()) + return(QGraphicsScene::selectedItems()); + + QList items = QGraphicsScene::selectedItems(); + + for(auto &tab_view :tabs_sel_children) + { + for(auto &tab_obj : tab_view->getSelectedChidren()) + items.append(tab_obj); + } + + return(items); +} + +bool ObjectsScene::hasOnlyTableChildrenSelection() const +{ + return(QGraphicsScene::selectedItems().isEmpty() && !tabs_sel_children.isEmpty()); +} diff --git a/libobjrenderer/src/objectsscene.h b/libobjrenderer/src/objectsscene.h index ff080597e4..188de734d1 100644 --- a/libobjrenderer/src/objectsscene.h +++ b/libobjrenderer/src/objectsscene.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -37,8 +37,14 @@ class ObjectsScene: public QGraphicsScene { private: Q_OBJECT + //! \brief Holds the names of the layers on the scene used to separate in the objects on the canvas + QStringList layers, active_layers; + vector removed_objs; + //! \brief Holds the tables/views which have selected children objects + QList tabs_sel_children; + //! \brief Indicates if the corner move is enabled for the scene static bool corner_move, @@ -49,9 +55,9 @@ class ObjectsScene: public QGraphicsScene { //! \brief Indicates if the scene need to be moved bool move_scene; - static const int SCENE_MOVE_STEP=20, - SCENE_MOVE_TIMEOUT=50, - SCENE_MOVE_THRESHOLD=30; + static constexpr int SceneMoveStep=20, + SceneMoveTimeout=50, + SceneMoveThreshold=30; //! \brief Timer responsible to move the scene QTimer scene_move_timer, @@ -105,23 +111,25 @@ class ObjectsScene: public QGraphicsScene { //! \brief Line used as a guide when inserting new relationship QGraphicsLineItem *rel_line; - //! \brief Aligns the specified point in relation to the grid - static QPointF alignPointToGrid(const QPointF &pnt); - /*! \brief Indicates if the mouse cursor is under a move spot portion of scene. Additionally this method configures the direction of movement when returning true */ bool mouseIsAtCorner(void); QGraphicsView *getActiveViewport(void); - //! brief Performs the final steps when moving the objects like adjusting position to grid, moving children object, etc + //! \brief Performs the final steps when moving the objects like adjusting position to grid, moving children object, etc void finishObjectsMove(const QPointF &pnt_end); - /*! brief Performs the scene position adjustment when pressing/releasing the arrow keys to avoid objects to be hidden in the corners. + /*! \brief Performs the scene position adjustment when pressing/releasing the arrow keys to avoid objects to be hidden in the corners. This method will adjust the scene size automatically when moving objects right or down if the selected items bounding rects exceeds the scene's size limits */ void adjustScenePositionOnKeyEvent(int key); + //! \brief Formats the name of the layer removing any invalid chars and doing the desambiguation in case the name already exists + QString formatLayerName(const QString &name); + + void clearTablesChildrenSelection(void); + protected: //! \brief Brush used to draw the grid over the scene static QBrush grid; @@ -134,21 +142,72 @@ class ObjectsScene: public QGraphicsScene { void keyReleaseEvent(QKeyEvent *event); //! \brief Draws a line from the point 'p_start' to the cursor position and simulates the relationship creation - void showRelationshipLine(bool value, const QPointF &p_start=QPointF(NAN,NAN)); + void showRelationshipLine(bool value, const QPointF &p_start=QPointF(DNaN,DNaN)); void blockItemsSignals(bool block); public: + static constexpr unsigned DefaultLayer = 0, + InvalidLayer = UINT_MAX; + ObjectsScene(void); ~ObjectsScene(void); + /*! \brief Add a new layer to the scene. In case of duplicated name this method + * automatically does the desambiguation. The name of the new layer is returned. */ + QString addLayer(const QString &name); + + /*! \brief Rename the layer of the provided index. In case of duplicated name this method + * automatically does the desambiguation. */ + QString renameLayer(unsigned idx, const QString &name); + + //! \brief Remove the named layer. Objects in the destroyed layer are automatically moved to the default one + void removeLayer(const QString &name); + + //! \brief Destroy all layers (except the default one) moving all objects from the destroyed layers to the default one + void removeLayers(void); + + //! \brief Set the named layers as active. Activating a layer causes objects attached to it to be visible + void setActiveLayers(QStringList act_layers); + + //! \brief Set the layers with the provided indexes as active. Activating a layer causes objects attached to it to be visible + void setActiveLayers(QList ids); + + /*! \brief Move the objects from a layer to another. This method automatically hides/show the objects in the new layer + * according to the activation status of the destination layer */ + void moveObjectsToLayer(unsigned old_layer, unsigned new_layer); + + //! \brief Returns true when the named layer is currenctly activated + bool isLayerActive(const QString &name); + + //! \brief Returns true when the layer with the provided id is currenctly activated + bool isLayerActive(unsigned layer_id); + + //! \brief Returns a list containing the names of the active layers + QStringList getActiveLayers(void); + + //! \brief Returns a list containing the ids of the active layers + QList getActiveLayersIds(void); + + //! \brief Returns a list containing the names of all layers in the scene + QStringList getLayers(void); + + //! \brief Returns the id of the named layer. If the layer does not exist the constant ObjectsScene::InvalidLayer is returned + unsigned getLayerId(const QString &name); + + //! \brief This method causes objects in the active layers to have their visibility state updated. + void updateActiveLayers(void); + static void setEnableCornerMove(bool enable); static void setInvertRangeSelectionTrigger(bool invert); static bool isCornerMoveEnabled(void); static void setGridSize(unsigned size); static void setGridOptions(bool show_grd, bool align_objs_grd, bool show_page_dlm); - static void getGridOptions(bool &show_grd, bool &align_objs_grd, bool &show_pag_dlm); + + static bool isAlignObjectsToGrid(void); + static bool isShowGrid(void); + static bool isShowPageDelimiters(void); static void setPaperConfiguration(QPrinter::PaperSize paper_sz, QPrinter::Orientation orient, QRectF margins, QSizeF custom_size=QSizeF(0,0)); static void getPaperConfiguration(QPrinter::PaperSize &paper_sz, QPrinter::Orientation &orient, QRectF &margins, QSizeF &custom_size); @@ -160,6 +219,9 @@ class ObjectsScene: public QGraphicsScene { void removeItem(QGraphicsItem *item); void setSceneRect(const QRectF &rect); + //! \brief Aligns the specified point in relation to the grid + static QPointF alignPointToGrid(const QPointF &pnt); + /*! \brief Returns the items bounding rect. By default the method returns the same as QGraphicsScene::itemsBoundingRect. If the parameter seek_only_db_objs is true the returned rect will have the origin point calculated based upon the visible objects that inherits BaseObjectView and are database model objects (tables, views, textboxes, schemas and relationships). @@ -178,9 +240,13 @@ class ObjectsScene: public QGraphicsScene { bool isRelationshipLineVisible(void); bool isMovingObjects(void); + QList selectedItems(void) const; + bool hasOnlyTableChildrenSelection(void) const; + public slots: void alignObjectsToGrid(void); void update(void); + void clearSelection(void); //! \brief Toggles the object range selection void enableRangeSelection(bool value); @@ -193,17 +259,14 @@ class ObjectsScene: public QGraphicsScene { //! \brief Moves the scene when the user puts the mouse cursor on one of scene's edges void moveObjectScene(void); - //! \brief Handles and redirects the signal emitted by the modified object - void emitObjectModification(BaseGraphicObject *object); - //! \brief Handles and redirects the signal emitted by the selected child object - void emitChildObjectSelection(TableObject *child_obj); + void handlePopupMenuRequested(TableObject *child_obj); //! \brief Handles and redirects the signal emitted by the selected object - void emitObjectSelection(BaseGraphicObject *object, bool selected); + void handleObjectSelection(BaseGraphicObject *object, bool selected); - //! \brief Handles and redirects the signal emitted by the tables/views when the extended attributes are toggled - void emitExtAttributesToggled(void); + //! \brief Handles the tables children objects selection changes + void handleChildrenSelectionChanged(void); signals: //! \brief Signal emitted when the user start or finalizes a object movement. @@ -212,8 +275,14 @@ class ObjectsScene: public QGraphicsScene { //! \brief Signal emitted when a object is modified on scene void s_objectModified(BaseGraphicObject *objeto); - //! \brief Signal emitted when the user toggles a table's extended attributes in the scene - void s_extAttributesToggled(void); + //! \brief Signal emitted when the user toggles a table's collapse mode in the scene + void s_collapseModeChanged(void); + + //! \brief Signal emitted when the user toggles a table's attributes pagination + void s_paginationToggled(void); + + //! \brief Signal emitted when the user changes a table's attributes page + void s_currentPageChanged(void); //! \brief Signal emitted when the user right-click a specific object on the scene requesting the popup menu void s_popupMenuRequested(BaseObject *); @@ -230,9 +299,21 @@ class ObjectsScene: public QGraphicsScene { //! \brief Signal emitted when objects are selected via range selection void s_objectsSelectedInRange(void); - //! \brief Signal emtted when a blank area of the canvas is pressed + //! \brief Signal emitted when a blank area of the canvas is pressed void s_objectsScenePressed(Qt::MouseButtons); + //! \brief Signal emitted when the active layers change + void s_activeLayersChanged(void); + + //! \brief Signal emitted when the layers change (add, remove, rename) + void s_layersChanged(void); + + //! \brief Signal emitted when objects are moved from a layer to another + void s_objectsMovedLayer(void); + + //! \brief Signal emitted when tables children objects have their selection statuses changed + void s_childrenSelectionChanged(void); + friend class ModelWidget; }; diff --git a/libobjrenderer/src/relationshipview.cpp b/libobjrenderer/src/relationshipview.cpp index 56f02bc645..bee6ae454d 100644 --- a/libobjrenderer/src/relationshipview.cpp +++ b/libobjrenderer/src/relationshipview.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -21,20 +21,20 @@ bool RelationshipView::hide_name_label=false; bool RelationshipView::use_curved_lines=true; bool RelationshipView::use_crows_foot=false; -unsigned RelationshipView::line_conn_mode=RelationshipView::CONNECT_FK_TO_PK; +unsigned RelationshipView::line_conn_mode=RelationshipView::ConnectFkToPk; RelationshipView::RelationshipView(BaseRelationship *rel) : BaseObjectView(rel) { if(!rel) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject, __PRETTY_FUNCTION__, __FILE__, __LINE__); - for(unsigned i=BaseRelationship::SRC_CARD_LABEL; - i <= BaseRelationship::REL_NAME_LABEL; i++) + for(unsigned i=BaseRelationship::SrcCardLabel; + i <= BaseRelationship::RelNameLabel; i++) { if(rel->getLabel(i)) { labels[i]=new TextboxView(rel->getLabel(i), true); - labels[i]->setZValue(i==BaseRelationship::REL_NAME_LABEL ? 1 : 2); + labels[i]->setZValue(i==BaseRelationship::RelNameLabel ? 1 : 2); this->addToGroup(labels[i]); } else @@ -67,7 +67,7 @@ RelationshipView::RelationshipView(BaseRelationship *rel) : BaseObjectView(rel) cf_descriptors[i] = nullptr; line_circles[i]=new QGraphicsEllipseItem; - line_circles[i]->setRect(QRectF(0,0,GRAPHIC_PNT_RADIUS,GRAPHIC_PNT_RADIUS)); + line_circles[i]->setRect(QRectF(0,0,GraphicPointRadius,GraphicPointRadius)); line_circles[i]->setZValue(0); line_circles[i]->setVisible(false); this->addToGroup(line_circles[i]); @@ -170,7 +170,7 @@ void RelationshipView::setCrowsFoot(bool value) use_crows_foot = value; if(value) - line_conn_mode=RelationshipView::CONNECT_TABLE_EGDES; + line_conn_mode=RelationshipView::ConnectTableEdges; } bool RelationshipView::isCrowsFoot(void) @@ -181,11 +181,11 @@ bool RelationshipView::isCrowsFoot(void) void RelationshipView::setLineConnectionMode(unsigned mode) { if(use_crows_foot) - line_conn_mode=CONNECT_TABLE_EGDES; + line_conn_mode=ConnectTableEdges; else { - if(mode > CONNECT_TABLE_EGDES) - mode=CONNECT_TABLE_EGDES; + if(mode > ConnectTableEdges) + mode=ConnectTableEdges; line_conn_mode=mode; } @@ -199,19 +199,19 @@ unsigned RelationshipView::getLineConnectinMode(void) QPointF RelationshipView::getConnectionPoint(unsigned table_idx) { if(table_idx > 2) - throw Exception(ERR_REF_ELEM_INV_INDEX ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefElementInvalidIndex ,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(conn_points[table_idx]); } -BaseRelationship *RelationshipView::getSourceObject(void) +BaseRelationship *RelationshipView::getUnderlyingObject(void) { - return(dynamic_cast(this->BaseObjectView::getSourceObject())); + return(dynamic_cast(this->BaseObjectView::getUnderlyingObject())); } TextboxView *RelationshipView::getLabel(unsigned lab_idx) { - if(lab_idx > BaseRelationship::REL_NAME_LABEL) + if(lab_idx > BaseRelationship::RelNameLabel) return(nullptr); else return(labels[lab_idx]); @@ -227,12 +227,11 @@ QVariant RelationshipView::itemChange(GraphicsItemChange change, const QVariant { unsigned i, count; QPen pen; - QColor color, line_color=this->getSourceObject()->getCustomColor(); + QColor color, line_color=this->getUnderlyingObject()->getCustomColor(); vector rel_lines; this->setSelectionOrder(value.toBool()); - pos_info_rect->setVisible(value.toBool()); - pos_info_txt->setVisible(value.toBool()); + pos_info_item->setVisible(value.toBool()); obj_selection->setVisible(value.toBool() && descriptor->isVisible()); this->configurePositionInfo(); @@ -249,17 +248,17 @@ QVariant RelationshipView::itemChange(GraphicsItemChange change, const QVariant //Alter the relationship line color when it is selected if(line_color==Qt::transparent) - line_color=BaseObjectView::getBorderStyle(ParsersAttributes::RELATIONSHIP).color(); + line_color=BaseObjectView::getBorderStyle(Attributes::Relationship).color(); if(value.toBool()) { - QColor cor1=BaseObjectView::getBorderStyle(ParsersAttributes::OBJ_SELECTION).color(), + QColor cor1=BaseObjectView::getBorderStyle(Attributes::ObjSelection).color(), cor2=line_color; - color.setRedF((cor1.redF() + cor2.greenF())/2.0f); - color.setGreenF((cor1.greenF() + cor2.greenF())/2.0f); - color.setBlueF((cor1.blueF() + cor2.blueF())/2.0f); - color.setAlphaF((cor1.alphaF() + cor2.alphaF())/2.0f); + color.setRedF((cor1.redF() + cor2.greenF())/2.0); + color.setGreenF((cor1.greenF() + cor2.greenF())/2.0); + color.setBlueF((cor1.blueF() + cor2.blueF())/2.0); + color.setAlphaF((cor1.alphaF() + cor2.alphaF())/2.0); } else color=line_color; @@ -288,7 +287,7 @@ QVariant RelationshipView::itemChange(GraphicsItemChange change, const QVariant { vector lines; QVector grad_stops = descriptor->brush().gradient()->stops(); - QColor sel_color = BaseObjectView::getBorderStyle(ParsersAttributes::OBJ_SELECTION).color(); + QColor sel_color = BaseObjectView::getBorderStyle(Attributes::ObjSelection).color(); QLinearGradient grad(QPointF(0,0),QPointF(0,1)); int color_id = 0; @@ -310,9 +309,9 @@ QVariant RelationshipView::itemChange(GraphicsItemChange change, const QVariant for(auto &stop : grad_stops) { color = stop.second; - color.setRedF((color.redF() + sel_color.greenF())/2.0f); - color.setGreenF((color.greenF() + sel_color.greenF())/2.0f); - color.setBlueF((color.blueF() + sel_color.blueF())/2.0f); + color.setRedF((color.redF() + sel_color.greenF())/2.0); + color.setGreenF((color.greenF() + sel_color.greenF())/2.0); + color.setBlueF((color.blueF() + sel_color.blueF())/2.0); grad.setColorAt(color_id++, color); } @@ -321,7 +320,7 @@ QVariant RelationshipView::itemChange(GraphicsItemChange change, const QVariant else round_cf_descriptors[idx]->setBrush(descriptor->brush()); - if(this->getSourceObject()->getRelationshipType() == BaseRelationship::RELATIONSHIP_FK) + if(this->getUnderlyingObject()->getRelationshipType() == BaseRelationship::RelationshipFk) pen.setStyle(Qt::DashLine); round_cf_descriptors[idx]->setPen(pen); @@ -333,7 +332,7 @@ QVariant RelationshipView::itemChange(GraphicsItemChange change, const QVariant for(i=0; i < count; i++) attributes[i]->childItems().at(3)->setVisible(value.toBool()); - emit s_objectSelected(dynamic_cast(this->getSourceObject()), value.toBool()); + emit s_objectSelected(dynamic_cast(this->getUnderlyingObject()), value.toBool()); } return(value); @@ -346,9 +345,9 @@ void RelationshipView::mousePressEvent(QGraphicsSceneMouseEvent *event) BaseObjectView::mousePressEvent(event); this->setFlag(QGraphicsItem::ItemIsMovable, false); - if(!this->getSourceObject()->isProtected()) + if(!this->getUnderlyingObject()->isProtected()) { - BaseRelationship *base_rel=this->getSourceObject(); + BaseRelationship *base_rel=this->getUnderlyingObject(); //Resets the labels position when mid-button is pressed if(event->buttons()==Qt::LeftButton && event->modifiers()==(Qt::AltModifier | Qt::ShiftModifier)) @@ -461,7 +460,7 @@ void RelationshipView::mousePressEvent(QGraphicsSceneMouseEvent *event) void RelationshipView::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { if(this->isSelected() && event->buttons()==Qt::LeftButton && - !this->getSourceObject()->isProtected()) + !this->getUnderlyingObject()->isProtected()) { if(dynamic_cast(sel_object)) { @@ -473,7 +472,7 @@ void RelationshipView::mouseMoveEvent(QGraphicsSceneMouseEvent *event) //We only include the point if it is not inside the tables' bounding rect if(!brect.contains(event->pos()) && !brect1.contains(event->pos())) { - BaseRelationship *rel_base=this->getSourceObject(); + BaseRelationship *rel_base=this->getUnderlyingObject(); vector points=rel_base->getPoints(); points[sel_object_idx]=event->pos(); @@ -490,7 +489,7 @@ void RelationshipView::mouseMoveEvent(QGraphicsSceneMouseEvent *event) void RelationshipView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - BaseRelationship *base_rel=this->getSourceObject(); + BaseRelationship *base_rel=this->getUnderlyingObject(); if(event->button()==Qt::LeftButton) { @@ -512,7 +511,7 @@ void RelationshipView::disconnectTables(void) { if(tables[0] && tables[1]) { - BaseRelationship *rel_base=this->getSourceObject(); + BaseRelationship *rel_base=this->getUnderlyingObject(); tables[0]->removeConnectedRelationship(rel_base); @@ -547,10 +546,10 @@ void RelationshipView::connectTables(void) void RelationshipView::configureObject(void) { - BaseRelationship *rel_base=this->getSourceObject(); + BaseRelationship *rel_base=this->getUnderlyingObject(); - tables[0]=dynamic_cast(rel_base->getTable(BaseRelationship::SRC_TABLE)->getReceiverObject()); - tables[1]=dynamic_cast(rel_base->getTable(BaseRelationship::DST_TABLE)->getReceiverObject()); + tables[0]=dynamic_cast(rel_base->getTable(BaseRelationship::SrcTable)->getOverlyingObject()); + tables[1]=dynamic_cast(rel_base->getTable(BaseRelationship::DstTable)->getOverlyingObject()); tables[0]->addConnectedRelationship(rel_base); @@ -567,10 +566,8 @@ void RelationshipView::configurePositionInfo(void) if(this->isSelected()) { BaseObjectView::configurePositionInfo(descriptor->pos()); - pos_info_txt->setPos(descriptor->pos().x(), - descriptor->pos().y() - pos_info_txt->boundingRect().height()); - pos_info_rect->setPos(descriptor->pos().x(), - descriptor->pos().y() - pos_info_rect->boundingRect().height()); + pos_info_item->setPos(descriptor->pos().x(), + descriptor->pos().y() - pos_info_item->boundingRect().height()); } } @@ -585,7 +582,7 @@ void RelationshipView::configureLine(void) if(!configuring_line) { - BaseRelationship *base_rel=this->getSourceObject(); + BaseRelationship *base_rel=this->getUnderlyingObject(); Relationship *rel=dynamic_cast(base_rel); vector points, fk_points, pk_points; QGraphicsLineItem *lin=nullptr; @@ -606,10 +603,10 @@ void RelationshipView::configureLine(void) if(base_rel->isSelfRelationship()) { - double fnt_factor=font_config[ParsersAttributes::GLOBAL].font().pointSizeF()/DEFAULT_FONT_SIZE, + double fnt_factor=font_config[Attributes::Global].font().pointSizeF()/DefaultFontSize, pos_factor = 0, offset = 0; - unsigned rel_cnt = tables[0]->getConnectedRelsCount(base_rel->getTable(BaseRelationship::SRC_TABLE), - base_rel->getTable(BaseRelationship::DST_TABLE)); + unsigned rel_cnt = tables[0]->getConnectedRelsCount(base_rel->getTable(BaseRelationship::SrcTable), + base_rel->getTable(BaseRelationship::DstTable)); /* Sefl-relationshihp line format: @@ -625,16 +622,16 @@ void RelationshipView::configureLine(void) if(rel_cnt > 1) { - int idx = tables[0]->getConnectedRelationshipIndex(base_rel); + int idx = tables[0]->getConnectedRelationshipIndex(base_rel, true); double min_val = min(rect.width(), rect.height()); if(idx < 0) idx =0; - pos_factor = min_val * 0.08f * idx; + pos_factor = min_val * 0.08 * idx; } p_central[0].setX(pos.x() + rect.width()); - p_central[0].setY(pos.y() + (rect.height() / 3.0f) + pos_factor); - p_central[1].setX(pos.x() + (rect.width() / 1.5f) - pos_factor); + p_central[0].setY(pos.y() + (rect.height() / 3.0) + pos_factor); + p_central[1].setX(pos.x() + (rect.width() / 1.5) - pos_factor); p_central[1].setY(pos.y()); if(p_central[0].y() > pos.y() + rect.height()) @@ -654,19 +651,19 @@ void RelationshipView::configureLine(void) else { Relationship *rel=dynamic_cast(base_rel); - bool rel_1n= (rel_type==Relationship::RELATIONSHIP_11 || - rel_type==Relationship::RELATIONSHIP_1N || - rel_type==Relationship::RELATIONSHIP_FK); + bool rel_1n= (rel_type==Relationship::Relationship11 || + rel_type==Relationship::Relationship1n || + rel_type==Relationship::RelationshipFk); if(rel && - rel->getRelationshipType()==Relationship::RELATIONSHIP_11 && + rel->getRelationshipType()==Relationship::Relationship11 && rel->isIdentifier()) { - tables[0]=dynamic_cast(rel->getReferenceTable()->getReceiverObject()); - tables[1]=dynamic_cast(rel->getReceiverTable()->getReceiverObject()); + tables[0]=dynamic_cast(rel->getReferenceTable()->getOverlyingObject()); + tables[1]=dynamic_cast(rel->getReceiverTable()->getOverlyingObject()); } - if(line_conn_mode==CONNECT_CENTER_PNTS || line_conn_mode==CONNECT_TABLE_EGDES || !rel_1n) + if(line_conn_mode==ConnectCenterPoints || line_conn_mode==ConnectTableEdges || !rel_1n) { vector *> ref_lines={ &fk_lines, &pk_lines }; @@ -685,7 +682,7 @@ void RelationshipView::configureLine(void) } } } - else if(line_conn_mode==CONNECT_FK_TO_PK && rel_1n) + else if(line_conn_mode==ConnectFkToPk && rel_1n) { QPointF pnt; QRectF rec_tab_rect, ref_tab_rect; @@ -697,8 +694,8 @@ void RelationshipView::configureLine(void) if(!rel) { - ref_tab=dynamic_cast
(base_rel->getTable(BaseRelationship::DST_TABLE)); - rec_tab=dynamic_cast
(base_rel->getTable(BaseRelationship::SRC_TABLE)); + ref_tab=dynamic_cast
(base_rel->getTable(BaseRelationship::DstTable)); + rec_tab=dynamic_cast
(base_rel->getTable(BaseRelationship::SrcTable)); } else { @@ -707,8 +704,8 @@ void RelationshipView::configureLine(void) } rec_tab->getForeignKeys(fks, true, ref_tab); - ref_tab_view=dynamic_cast(ref_tab->getReceiverObject()); - rec_tab_view=dynamic_cast(rec_tab->getReceiverObject()); + ref_tab_view=dynamic_cast(ref_tab->getOverlyingObject()); + rec_tab_view=dynamic_cast(rec_tab->getOverlyingObject()); //Create the table's rectangles to detect where to connect the relationship ref_tab_rect=QRectF(ref_tab_view->pos(), ref_tab_view->boundingRect().size()); @@ -723,37 +720,37 @@ void RelationshipView::configureLine(void) conn_same_sides = true; if(rec_tab_rect.center().x() >= ref_tab_rect.center().x()) - pk_pnt_type=fk_pnt_type=BaseTableView::LEFT_CONN_POINT; + pk_pnt_type=fk_pnt_type=BaseTableView::LeftConnPoint; else if(rec_tab_rect.center().x() < ref_tab_rect.center().x()) - pk_pnt_type=fk_pnt_type=BaseTableView::RIGHT_CONN_POINT; + pk_pnt_type=fk_pnt_type=BaseTableView::RightConnPoint; } else { //Connecting the relationship on the opposite sides depending on the tables' position if(ref_tab_rect.right() <= rec_tab_rect.left()) { - pk_pnt_type=BaseTableView::RIGHT_CONN_POINT; - fk_pnt_type=BaseTableView::LEFT_CONN_POINT; + pk_pnt_type=BaseTableView::RightConnPoint; + fk_pnt_type=BaseTableView::LeftConnPoint; } else { - pk_pnt_type=BaseTableView::LEFT_CONN_POINT; - fk_pnt_type=BaseTableView::RIGHT_CONN_POINT; + pk_pnt_type=BaseTableView::LeftConnPoint; + fk_pnt_type=BaseTableView::RightConnPoint; } } for(auto &constr : fks) { - cnt=constr->getColumnCount(Constraint::SOURCE_COLS); + cnt=constr->getColumnCount(Constraint::SourceCols); for(i=0; i < cnt; i++) { - pnt=rec_tab_view->getConnectionPoints(constr->getColumn(i, Constraint::SOURCE_COLS), fk_pnt_type); + pnt=rec_tab_view->getConnectionPoints(constr->getColumn(i, Constraint::SourceCols), fk_pnt_type); fk_py+=pnt.y(); fk_px=pnt.x(); fk_points.push_back(this->mapFromItem(rec_tab_view, pnt)); - pnt=ref_tab_view->getConnectionPoints(constr->getColumn(i, Constraint::REFERENCED_COLS), pk_pnt_type); + pnt=ref_tab_view->getConnectionPoints(constr->getColumn(i, Constraint::ReferencedCols), pk_pnt_type); pk_py+=pnt.y(); pk_px=pnt.x(); pk_points.push_back(this->mapFromItem(ref_tab_view, pnt)); @@ -762,13 +759,13 @@ void RelationshipView::configureLine(void) if(!fks.empty()) { - double pk_dx=(pk_pnt_type==BaseTableView::LEFT_CONN_POINT ? -CONN_LINE_LENGTH : CONN_LINE_LENGTH), - fk_dx=(fk_pnt_type==BaseTableView::LEFT_CONN_POINT ? -CONN_LINE_LENGTH : CONN_LINE_LENGTH); + double pk_dx=(pk_pnt_type==BaseTableView::LeftConnPoint ? -ConnLineLength : ConnLineLength), + fk_dx=(fk_pnt_type==BaseTableView::LeftConnPoint ? -ConnLineLength : ConnLineLength); pk_pnt=this->mapFromItem(ref_tab_view, QPointF(pk_px + pk_dx, pk_py/pk_points.size())); fk_pnt=this->mapFromItem(rec_tab_view, QPointF(fk_px + fk_dx, fk_py/fk_points.size())); - if(rel_type==Relationship::RELATIONSHIP_FK) + if(rel_type==Relationship::RelationshipFk) { p_central[1]=pk_pnt; p_central[0]=fk_pnt; @@ -786,7 +783,7 @@ void RelationshipView::configureLine(void) * This situation may happen when the relationship is being validated and the needed fks was not * created yet. In a second interaction of the rel. validation they are created * and the relationship is properly configured */ - if(rel_type==Relationship::RELATIONSHIP_FK) + if(rel_type==Relationship::RelationshipFk) { p_central[1]=pk_pnt=ref_tab_view->getCenter(); p_central[0]=fk_pnt=rec_tab_view->getCenter(); @@ -812,15 +809,15 @@ void RelationshipView::configureLine(void) graph_points.push_back(pol); pol->setZValue(0); pol->setPolygon(pol_aux); - pol->setBrush(BaseObjectView::getFillStyle(ParsersAttributes::OBJ_SELECTION)); - pol->setPen(BaseObjectView::getBorderStyle(ParsersAttributes::OBJ_SELECTION)); + pol->setBrush(BaseObjectView::getFillStyle(Attributes::ObjSelection)); + pol->setPen(BaseObjectView::getBorderStyle(Attributes::ObjSelection)); this->addToGroup(pol); } else pol=graph_points[i]; pol->setPos(points[i]); - pol->moveBy(-GRAPHIC_PNT_RADIUS/2, -GRAPHIC_PNT_RADIUS/2); + pol->moveBy(-GraphicPointRadius/2, -GraphicPointRadius/2); pol->setVisible(this->isSelected()); } @@ -836,7 +833,7 @@ void RelationshipView::configureLine(void) } } - if(base_rel->isSelfRelationship() || line_conn_mode != CONNECT_TABLE_EGDES) + if(base_rel->isSelfRelationship() || line_conn_mode != ConnectTableEdges) { conn_points[0]=p_central[0]; conn_points[1]=p_central[1]; @@ -844,24 +841,24 @@ void RelationshipView::configureLine(void) points.insert(points.begin(),p_central[0]); points.push_back(p_central[1]); } - else if(line_conn_mode == CONNECT_TABLE_EGDES) + else if(line_conn_mode == ConnectTableEdges) { QRectF brect; QPolygonF pol; QLineF edge, line = QLineF(tables[0]->getCenter(), tables[1]->getCenter()); QPointF pi, center, p_aux[2]; - double font_factor=(font_config[ParsersAttributes::GLOBAL].font().pointSizeF()/DEFAULT_FONT_SIZE) * BaseObjectView::getScreenDpiFactor(), + double font_factor=(font_config[Attributes::Global].font().pointSizeF()/DefaultFontSize) * BaseObjectView::getScreenDpiFactor(), size_factor = 1, - border_factor = CONN_LINE_LENGTH * 0.30, + border_factor = ConnLineLength * 0.30, min_lim = 0, max_lim = 0, conn_rels_factors[2] = { 0, 0 }; unsigned conn_rels_cnt[2] = { 0, 0 }; for(int tab_idx = 0; tab_idx < 2; tab_idx++) { - conn_rels_cnt[tab_idx] = tables[tab_idx]->getConnectedRelsCount(base_rel->getTable(BaseRelationship::SRC_TABLE), - base_rel->getTable(BaseRelationship::DST_TABLE)); - conn_rels_factors[tab_idx] = conn_rels_cnt[tab_idx] == 1 ? 1 : 0.08f * (tables[tab_idx]->getConnectedRelationshipIndex(base_rel)); + conn_rels_cnt[tab_idx] = tables[tab_idx]->getConnectedRelsCount(base_rel->getTable(BaseRelationship::SrcTable), + base_rel->getTable(BaseRelationship::DstTable)); + conn_rels_factors[tab_idx] = conn_rels_cnt[tab_idx] == 1 ? 1 : 0.08 * (tables[tab_idx]->getConnectedRelationshipIndex(base_rel)); if(!points.empty()) { @@ -871,27 +868,28 @@ void RelationshipView::configureLine(void) line = QLineF(tables[1]->getCenter(), points[points.size() - 1]); } - if(rel_type==BaseRelationship::RELATIONSHIP_GEN || rel_type==BaseRelationship::RELATIONSHIP_DEP) + if(rel_type==BaseRelationship::RelationshipGen || rel_type==BaseRelationship::RelationshipDep || rel_type==BaseRelationship::RelationshipPart) size_factor = 0.40; else if(use_crows_foot) { - if(rel_type==BaseRelationship::RELATIONSHIP_NN || - (tab_idx == 1 && rel_type==BaseRelationship::RELATIONSHIP_FK) || - (tab_idx == 0 && rel_type==BaseRelationship::RELATIONSHIP_1N && base_rel->isTableMandatory(BaseRelationship::SRC_TABLE)) || - (tab_idx == 0 && rel_type==BaseRelationship::RELATIONSHIP_11 && base_rel->isTableMandatory(BaseRelationship::SRC_TABLE)) || - (tab_idx == 1 && rel_type==BaseRelationship::RELATIONSHIP_11 && base_rel->isTableMandatory(BaseRelationship::DST_TABLE))) + if(rel_type==BaseRelationship::RelationshipNn || + (tab_idx == 1 && rel_type==BaseRelationship::RelationshipFk) || + (tab_idx == 0 && rel_type==BaseRelationship::Relationship1n && base_rel->isTableMandatory(BaseRelationship::SrcTable)) || + (tab_idx == 0 && rel_type==BaseRelationship::Relationship11 && base_rel->isTableMandatory(BaseRelationship::SrcTable)) || + (tab_idx == 1 && rel_type==BaseRelationship::Relationship11 && base_rel->isTableMandatory(BaseRelationship::DstTable))) size_factor = 1 * font_factor; else size_factor = 1.5 * font_factor; - if(rel_type == BaseRelationship::RELATIONSHIP_GEN || - rel_type == BaseRelationship::RELATIONSHIP_DEP || - rel_type == BaseRelationship::RELATIONSHIP_11 || - (tab_idx == 0 && rel_type == BaseRelationship::RELATIONSHIP_1N) || - (tab_idx == 1 && rel_type == BaseRelationship::RELATIONSHIP_FK)) - border_factor = CONN_LINE_LENGTH * 0.30; + if(rel_type == BaseRelationship::RelationshipPart || + rel_type == BaseRelationship::RelationshipGen || + rel_type == BaseRelationship::RelationshipDep || + rel_type == BaseRelationship::Relationship11 || + (tab_idx == 0 && rel_type == BaseRelationship::Relationship1n) || + (tab_idx == 1 && rel_type == BaseRelationship::RelationshipFk)) + border_factor = ConnLineLength * 0.30; else - border_factor = CONN_LINE_LENGTH * 0.75; + border_factor = ConnLineLength * 0.75; } else size_factor = 0.65 * font_factor; @@ -960,18 +958,18 @@ void RelationshipView::configureLine(void) if(edge.dx() == 0) { if(pi.x() < center.x()) - pi.setX(pi.x() - CONN_LINE_LENGTH * size_factor); + pi.setX(pi.x() - ConnLineLength * size_factor); else - pi.setX(pi.x() + CONN_LINE_LENGTH * size_factor); + pi.setX(pi.x() + ConnLineLength * size_factor); conn_vert_sides[tab_idx] = true; } else { if(pi.y() < center.y()) - pi.setY(pi.y() - CONN_LINE_LENGTH * size_factor); + pi.setY(pi.y() - ConnLineLength * size_factor); else - pi.setY(pi.y() + CONN_LINE_LENGTH * size_factor); + pi.setY(pi.y() + ConnLineLength * size_factor); conn_horiz_sides[tab_idx] = true; } @@ -1004,11 +1002,12 @@ void RelationshipView::configureLine(void) pen.setColor(base_rel->getCustomColor()); else //Using the default color - pen=BaseObjectView::getBorderStyle(ParsersAttributes::RELATIONSHIP); + pen=BaseObjectView::getBorderStyle(Attributes::Relationship); } - //For dependency relationships the line is dashed - if(rel_type==BaseRelationship::RELATIONSHIP_DEP) + //For dependency/partition relationships the line is dashed + if(rel_type==BaseRelationship::RelationshipDep || + rel_type == BaseRelationship::RelationshipPart) pen.setStyle(Qt::DashLine); /* For identifier relationships an additional point is created on the center of the @@ -1027,12 +1026,12 @@ void RelationshipView::configureLine(void) p_central[1]=points[idx_lin_desc-1]; //Calculates the middle point and inserts it on the point vector - p_int.setX((p_central[0].x() + p_central[1].x())/2.0f); - p_int.setY((p_central[0].y() + p_central[1].y())/2.0f); + p_int.setX((p_central[0].x() + p_central[1].x())/2.0); + p_int.setY((p_central[0].y() + p_central[1].y())/2.0); points.insert(points.begin() + idx_lin_desc, p_int); } - if(line_conn_mode==CONNECT_FK_TO_PK) + if(line_conn_mode==ConnectFkToPk) { vector ref_points={ fk_pnt, pk_pnt }; vector *> ref_pnt_vects={ &fk_points, &pk_points }; @@ -1060,9 +1059,9 @@ void RelationshipView::configureLine(void) //If the relationship is identifier or bidirectional, the line has its thickness modified if(rel && (rel->isIdentifier() && vet_idx==0)) - pen.setWidthF(OBJ_BORDER_WIDTH * 1.90f); + pen.setWidthF(ObjectBorderWidth * 1.90); else - pen.setWidthF(OBJ_BORDER_WIDTH * 1.45f); + pen.setWidthF(ObjectBorderWidth * 1.45); lin->setLine(QLineF(ref_pnt->at(i), ref_points[vet_idx])); lin->setPen(pen); @@ -1097,9 +1096,9 @@ void RelationshipView::configureLine(void) //If the relationship is identifier or bidirectional, the line has its thickness modified if(rel && (rel->isIdentifier() && i >= idx_lin_desc)) - pen.setWidthF(OBJ_BORDER_WIDTH * 1.90f); + pen.setWidthF(ObjectBorderWidth * 1.90); else - pen.setWidthF(OBJ_BORDER_WIDTH * 1.45f); + pen.setWidthF(ObjectBorderWidth * 1.45); lin->setLine(QLineF(points[i], points[i+1])); lin->setPen(pen); @@ -1121,18 +1120,19 @@ void RelationshipView::configureLine(void) } //Exposing the line ending circles - if((!base_rel->isSelfRelationship() && line_conn_mode==CONNECT_CENTER_PNTS && !use_crows_foot) || + if((!base_rel->isSelfRelationship() && line_conn_mode==ConnectCenterPoints && !use_crows_foot) || (!base_rel->isSelfRelationship() && - ((line_conn_mode != CONNECT_TABLE_EGDES && rel_type==BaseRelationship::RELATIONSHIP_DEP) || - (line_conn_mode != CONNECT_TABLE_EGDES && rel_type==BaseRelationship::RELATIONSHIP_GEN) || - (line_conn_mode != CONNECT_TABLE_EGDES && rel_type==BaseRelationship::RELATIONSHIP_NN && !use_crows_foot)))) + ((line_conn_mode != ConnectTableEdges && rel_type==BaseRelationship::RelationshipDep) || + (line_conn_mode != ConnectTableEdges && rel_type==BaseRelationship::RelationshipGen) || + (line_conn_mode != ConnectTableEdges && rel_type==BaseRelationship::RelationshipPart) || + (line_conn_mode != ConnectTableEdges && rel_type==BaseRelationship::RelationshipNn && !use_crows_foot)))) { for(i=0; i < 2; i++) { line_circles[i]->setVisible(true); line_circles[i]->setPen(pen); line_circles[i]->setBrush(pen.color()); - line_circles[i]->setPos(p_central[i]-QPointF(GRAPHIC_PNT_RADIUS/2, GRAPHIC_PNT_RADIUS/2)); + line_circles[i]->setPos(p_central[i]-QPointF(GraphicPointRadius/2, GraphicPointRadius/2)); } } else @@ -1221,14 +1221,21 @@ void RelationshipView::configureLine(void) /* Making a little tweak on the foreign key type name. Despite being of class BaseRelationship, for semantics purposes shows the type of this relationship as "Relationship" unlike "Link" */ - if(rel_type==BaseRelationship::RELATIONSHIP_FK) + if(rel_type==BaseRelationship::RelationshipFk) tool_tip=base_rel->getName(true) + - QString(" (") + BaseObject::getTypeName(OBJ_RELATIONSHIP) + QString(")"); + QString(" (") + BaseObject::getTypeName(ObjectType::Relationship) + QString(")"); else tool_tip=base_rel->getName(true) + QString(" (") + base_rel->getTypeName() + QString(")"); - tool_tip += QString("\nId: %1").arg(base_rel->getObjectId()); + tool_tip += QString("\nId: %1\n").arg(base_rel->getObjectId()) + + TableObjectView::ConstrDelimStart + + QString(" %1 ").arg(base_rel->getRelationshipTypeName()) + + TableObjectView::ConstrDelimEnd; + + if(!base_rel->getAlias().isEmpty()) + tool_tip += QString("\nAlias: %1").arg(base_rel->getAlias()); + this->setToolTip(tool_tip); for(i=0; i < 3; i++) @@ -1238,6 +1245,18 @@ void RelationshipView::configureLine(void) } descriptor->setToolTip(tool_tip); + + for(auto &curve : curves) + curve->setToolTip(tool_tip); + + for(int i = 0; i < 2; i++) + { + if(cf_descriptors[i]) + cf_descriptors[i]->setToolTip(tool_tip); + + if(round_cf_descriptors[i]) + round_cf_descriptors[i]->setToolTip(tool_tip); + } } } @@ -1245,11 +1264,11 @@ void RelationshipView::configureDescriptor(void) { QLineF lin; QPolygonF pol; - BaseRelationship *base_rel=this->getSourceObject(); + BaseRelationship *base_rel=this->getUnderlyingObject(); Relationship *rel=dynamic_cast(base_rel); unsigned rel_type=base_rel->getRelationshipType(); double x, y, x1, y1, angle = 0, - factor=(font_config[ParsersAttributes::GLOBAL].font().pointSizeF()/DEFAULT_FONT_SIZE) * BaseObjectView::getScreenDpiFactor(); + factor=(font_config[Attributes::Global].font().pointSizeF()/DefaultFontSize) * BaseObjectView::getScreenDpiFactor(); QPen pen; QPointF pnt; vector points=base_rel->getPoints(); @@ -1262,9 +1281,10 @@ void RelationshipView::configureDescriptor(void) pen.setColor(base_rel->getCustomColor()); else //Using the default color - pen=BaseObjectView::getBorderStyle(ParsersAttributes::RELATIONSHIP); + pen=BaseObjectView::getBorderStyle(Attributes::Relationship); - if(rel_type==BaseRelationship::RELATIONSHIP_DEP) + if(rel_type==BaseRelationship::RelationshipDep || + rel_type == BaseRelationship::RelationshipPart) pen.setStyle(Qt::DashLine); descriptor->setPen(pen); @@ -1273,7 +1293,7 @@ void RelationshipView::configureDescriptor(void) { QColor colors[2]; QLinearGradient grad; - BaseObjectView::getFillStyle(ParsersAttributes::RELATIONSHIP, colors[0], colors[1]); + BaseObjectView::getFillStyle(Attributes::Relationship, colors[0], colors[1]); for(unsigned i=0; i < 2; i++) { @@ -1287,13 +1307,19 @@ void RelationshipView::configureDescriptor(void) descriptor->setBrush(grad); } else - descriptor->setBrush(BaseObjectView::getFillStyle(ParsersAttributes::RELATIONSHIP)); + descriptor->setBrush(BaseObjectView::getFillStyle(Attributes::Relationship)); - if(rel_type==BaseRelationship::RELATIONSHIP_DEP || - rel_type==BaseRelationship::RELATIONSHIP_GEN) + if(rel_type==BaseRelationship::RelationshipDep || + rel_type==BaseRelationship::RelationshipGen) + { + pol.append(QPointF(0,0)); pol.append(QPointF(18,10)); + pol.append(QPointF(0,20)); pol.append(QPointF(0,10)); + } + else if(rel_type==BaseRelationship::RelationshipPart) { - pol.append(QPointF(0,0)); pol.append(QPointF(18,10)); - pol.append(QPointF(0,20)); pol.append(QPointF(0,10)); + pol.append(QPointF(0,4)); pol.append(QPointF(4,0)); + pol.append(QPointF(18,12)); pol.append(QPointF(4,24)); + pol.append(QPointF(0,20)); pol.append(QPointF(10,12)); } else { @@ -1302,10 +1328,10 @@ void RelationshipView::configureDescriptor(void) } //Resizes the polygon according the font factor - if(factor!=1.0f) - this->resizePolygon(pol, - pol.boundingRect().width() * factor , - pol.boundingRect().height() * factor); + if(factor!=1.0) + TextPolygonItem::resizePolygon(pol, + pol.boundingRect().width() * factor , + pol.boundingRect().height() * factor); if(base_rel->isSelfRelationship()) pnt=points.at(points.size()/2); @@ -1329,7 +1355,9 @@ void RelationshipView::configureDescriptor(void) /* Workaround to avoid the inheritance / dependency relationship to get the descriptor rotated to the wrong side * We create and auxiliary line with points from the position at 65% of the curve to the 45% and use the * angle of that line instead of the angle at 50% of the curve */ - if((rel_type == BaseRelationship::RELATIONSHIP_DEP || rel_type == BaseRelationship::RELATIONSHIP_GEN) && + if((rel_type == BaseRelationship::RelationshipDep || + rel_type == BaseRelationship::RelationshipGen || + rel_type == BaseRelationship::RelationshipPart) && curve->isControlPointsInverted() && !curve->isSimpleCurve() && !curve->isStraightLine()) { QLineF lin_aux = QLineF(path.pointAtPercent(0.65), path.pointAtPercent(0.45)); @@ -1352,8 +1380,8 @@ void RelationshipView::configureDescriptor(void) pnt=lin.p1(); else { - pnt.setX((lin.p1().x() + lin.p2().x()) / 2.0f); - pnt.setY((lin.p1().y() + lin.p2().y()) / 2.0f); + pnt.setX((lin.p1().x() + lin.p2().x()) / 2.0); + pnt.setY((lin.p1().y() + lin.p2().y()) / 2.0); } angle = -lin.angle(); @@ -1364,17 +1392,16 @@ void RelationshipView::configureDescriptor(void) obj_shadow->setRotation(angle); } - x=x1=pnt.x() - (pol.boundingRect().width()/2.0f); - y=y1=pnt.y() - (pol.boundingRect().height()/2.0f); + x=x1=pnt.x() - (pol.boundingRect().width()/2.0); + y=y1=pnt.y() - (pol.boundingRect().height()/2.0); - protected_icon->setPos(x + ((pol.boundingRect().width()/2.0f) * 0.60f), - y + ((pol.boundingRect().height()/2.0f) * 0.55f)); + protected_icon->setPos(x + ((pol.boundingRect().width()/2.0) * 0.60), + y + ((pol.boundingRect().height()/2.0) * 0.55)); configureSQLDisabledInfo(); - x1+=6 * HORIZ_SPACING; - y1-=3 * VERT_SPACING; - sql_disabled_box->setPos(x1, y1); - sql_disabled_txt->setPos(x1 + HORIZ_SPACING, y1 + VERT_SPACING); + x1+=6 * HorizSpacing; + y1-=3 * VertSpacing; + sql_disabled_item->setPos(x1, y1); descriptor->setPolygon(pol); descriptor->setTransformOriginPoint(descriptor->boundingRect().center()); @@ -1384,13 +1411,13 @@ void RelationshipView::configureDescriptor(void) pol_item->setPolygon(pol); pol_item->setTransformOriginPoint(obj_selection->boundingRect().center()); pol_item->setPos(x,y); - pol_item->setBrush(this->getFillStyle(ParsersAttributes::OBJ_SELECTION)); - pol_item->setPen(this->getBorderStyle(ParsersAttributes::OBJ_SELECTION)); + pol_item->setBrush(this->getFillStyle(Attributes::ObjSelection)); + pol_item->setPen(this->getBorderStyle(Attributes::ObjSelection)); pol_item=dynamic_cast(obj_shadow); pol_item->setPolygon(pol); pol_item->setTransformOriginPoint(obj_shadow->boundingRect().center()); - pol_item->setPos(x + 2.5f, y + 3.5f); + pol_item->setPos(x + 2.5, y + 3.5); pol_item->setPen(Qt::NoPen); pol_item->setBrush(QColor(50,50,50,60)); @@ -1398,24 +1425,25 @@ void RelationshipView::configureDescriptor(void) this->configurePositionInfo(); /* If the crow's feet is enabled the relationship descriptor is hidden - * for 1:1, 1:n, n:n and fk relationship. For generalization and dependency + * for 1:1, 1:n, n:n and fk relationship. For generalization, dependency and partitioning * relationships the descriptor is still displayed. */ descriptor->setVisible(!use_crows_foot || (use_crows_foot && ( - rel_type == BaseRelationship::RELATIONSHIP_DEP || - rel_type == BaseRelationship::RELATIONSHIP_GEN))); + rel_type == BaseRelationship::RelationshipDep || + rel_type == BaseRelationship::RelationshipGen || + rel_type == BaseRelationship::RelationshipPart))); obj_shadow->setVisible(descriptor->isVisible()); } void RelationshipView::configureCrowsFootDescriptors(void) { - BaseRelationship * base_rel = dynamic_cast(this->getSourceObject()); + BaseRelationship * base_rel = dynamic_cast(this->getUnderlyingObject()); Relationship *rel=dynamic_cast(base_rel); //Hiding all descriptors related to crow's foot when the notation is not being used - if(!use_crows_foot && cf_descriptors[BaseRelationship::SRC_TABLE]) + if(!use_crows_foot && cf_descriptors[BaseRelationship::SrcTable]) { - for(unsigned tab_id = BaseRelationship::SRC_TABLE; tab_id <= BaseRelationship::DST_TABLE; tab_id++) + for(unsigned tab_id = BaseRelationship::SrcTable; tab_id <= BaseRelationship::DstTable; tab_id++) { for(auto &item : cf_descriptors[tab_id]->childItems()) { @@ -1428,45 +1456,45 @@ void RelationshipView::configureCrowsFootDescriptors(void) } } else if(use_crows_foot && base_rel && - (base_rel->getRelationshipType() == BaseRelationship::RELATIONSHIP_11 || - base_rel->getRelationshipType() == BaseRelationship::RELATIONSHIP_1N || - base_rel->getRelationshipType() == BaseRelationship::RELATIONSHIP_NN || - base_rel->getRelationshipType() == BaseRelationship::RELATIONSHIP_FK)) + (base_rel->getRelationshipType() == BaseRelationship::Relationship11 || + base_rel->getRelationshipType() == BaseRelationship::Relationship1n || + base_rel->getRelationshipType() == BaseRelationship::RelationshipNn || + base_rel->getRelationshipType() == BaseRelationship::RelationshipFk)) { QGraphicsLineItem *line_item = nullptr; QGraphicsEllipseItem *circle_item = nullptr; unsigned rel_type = base_rel->getRelationshipType(); - double factor=(font_config[ParsersAttributes::GLOBAL].font().pointSizeF()/DEFAULT_FONT_SIZE) * BaseObjectView::getScreenDpiFactor(); + double factor=(font_config[Attributes::Global].font().pointSizeF()/DefaultFontSize) * BaseObjectView::getScreenDpiFactor(); int signal = 1; BaseTableView *tables[2] = { nullptr, nullptr }; bool mandatory[2] = { false, false }; - if(rel_type == BaseRelationship::RELATIONSHIP_NN || rel_type == BaseRelationship::RELATIONSHIP_FK) + if(rel_type == BaseRelationship::RelationshipNn || rel_type == BaseRelationship::RelationshipFk) { - tables[BaseRelationship::SRC_TABLE] = dynamic_cast(base_rel->getTable(BaseRelationship::SRC_TABLE)->getReceiverObject()); - tables[BaseRelationship::DST_TABLE] = dynamic_cast(base_rel->getTable(BaseRelationship::DST_TABLE)->getReceiverObject()); - mandatory[BaseRelationship::SRC_TABLE] = base_rel->isTableMandatory(BaseRelationship::SRC_TABLE); - mandatory[BaseRelationship::DST_TABLE] = base_rel->isTableMandatory(BaseRelationship::DST_TABLE); + tables[BaseRelationship::SrcTable] = dynamic_cast(base_rel->getTable(BaseRelationship::SrcTable)->getOverlyingObject()); + tables[BaseRelationship::DstTable] = dynamic_cast(base_rel->getTable(BaseRelationship::DstTable)->getOverlyingObject()); + mandatory[BaseRelationship::SrcTable] = base_rel->isTableMandatory(BaseRelationship::SrcTable); + mandatory[BaseRelationship::DstTable] = base_rel->isTableMandatory(BaseRelationship::DstTable); } else { - tables[BaseRelationship::SRC_TABLE] = dynamic_cast(rel->getReferenceTable()->getReceiverObject()); - tables[BaseRelationship::DST_TABLE] = dynamic_cast(rel->getReceiverTable()->getReceiverObject()); - mandatory[BaseRelationship::SRC_TABLE] = rel->isReferenceTableMandatory(); - mandatory[BaseRelationship::DST_TABLE] = rel->isReceiverTableMandatory(); + tables[BaseRelationship::SrcTable] = dynamic_cast(rel->getReferenceTable()->getOverlyingObject()); + tables[BaseRelationship::DstTable] = dynamic_cast(rel->getReceiverTable()->getOverlyingObject()); + mandatory[BaseRelationship::SrcTable] = rel->isReferenceTableMandatory(); + mandatory[BaseRelationship::DstTable] = rel->isReceiverTableMandatory(); /* There's a special case for one-to-one relationships that will cause the crow's foot * descriptors to be positioned in the oposite sides when compared to other relationships. * This because pgModeler switches automatically the receiver table to be the destination one * when the mandatory table of the relationship is the destination. So we use and auxiliary (signal inverter) * variable to alter the descriptors position */ - if(mandatory[BaseRelationship::SRC_TABLE] && rel_type == BaseRelationship::RELATIONSHIP_11 && - rel->getTable(BaseRelationship::DST_TABLE) == rel->getReferenceTable()) + if(mandatory[BaseRelationship::SrcTable] && rel_type == BaseRelationship::Relationship11 && + rel->getTable(BaseRelationship::DstTable) == rel->getReferenceTable()) signal = -1; } //Allocatting all objects related to the crow's foot descriptors - if(cf_descriptors[BaseRelationship::SRC_TABLE] == nullptr) + if(cf_descriptors[BaseRelationship::SrcTable] == nullptr) { int src_zvalue = lines.front()->zValue() + 1, dst_zvalue = lines.back()->zValue() + 1; @@ -1483,17 +1511,17 @@ void RelationshipView::configureCrowsFootDescriptors(void) { line_item = new QGraphicsLineItem; src_cf_lines.push_back(line_item); - cf_descriptors[BaseRelationship::SRC_TABLE]->setZValue(src_zvalue); + cf_descriptors[BaseRelationship::SrcTable]->setZValue(src_zvalue); line_item = new QGraphicsLineItem; dst_cf_lines.push_back(line_item); - cf_descriptors[BaseRelationship::DST_TABLE]->setZValue(dst_zvalue); + cf_descriptors[BaseRelationship::DstTable]->setZValue(dst_zvalue); } } else { - cf_descriptors[BaseRelationship::SRC_TABLE]->setVisible(true); - cf_descriptors[BaseRelationship::DST_TABLE]->setVisible(true); + cf_descriptors[BaseRelationship::SrcTable]->setVisible(true); + cf_descriptors[BaseRelationship::DstTable]->setVisible(true); } QPointF pi; @@ -1506,7 +1534,7 @@ void RelationshipView::configureCrowsFootDescriptors(void) unsigned lin_idx = 0; double px = 0, py = 0, min_x = 0, max_x = 0, min_y = 0, max_y = 0; - for(unsigned tab_id = BaseRelationship::SRC_TABLE; tab_id <= BaseRelationship::DST_TABLE; tab_id++) + for(unsigned tab_id = BaseRelationship::SrcTable; tab_id <= BaseRelationship::DstTable; tab_id++) { cf_descriptors[tab_id]->setRotation(0); @@ -1518,11 +1546,11 @@ void RelationshipView::configureCrowsFootDescriptors(void) } //Configuring the minimum cardinality descriptor - if((tab_id == BaseRelationship::SRC_TABLE && - rel_type != BaseRelationship::RELATIONSHIP_NN && rel_type != BaseRelationship::RELATIONSHIP_FK) || + if((tab_id == BaseRelationship::SrcTable && + rel_type != BaseRelationship::RelationshipNn && rel_type != BaseRelationship::RelationshipFk) || - (tab_id == BaseRelationship::DST_TABLE && - (rel_type == BaseRelationship::RELATIONSHIP_11 || rel_type == BaseRelationship::RELATIONSHIP_FK))) + (tab_id == BaseRelationship::DstTable && + (rel_type == BaseRelationship::Relationship11 || rel_type == BaseRelationship::RelationshipFk))) { line_item = cf_lines[tab_id]->at(lin_idx++); @@ -1530,14 +1558,14 @@ void RelationshipView::configureCrowsFootDescriptors(void) line_item->setVisible(true); line_item->setLine(QLineF(QPointF(0, -8 * factor), QPointF(0, 8 * factor))); - line_item->setPos((10 * signal) * (tab_id == BaseRelationship::DST_TABLE ? -1 : 1), 0); + line_item->setPos((10 * signal) * (tab_id == BaseRelationship::DstTable ? -1 : 1), 0); line_item->setPen(pens[tab_id]); } else { //Configuring the crow's foot descriptor - if(tab_id == BaseRelationship::SRC_TABLE) + if(tab_id == BaseRelationship::SrcTable) { px = 0; line = QLineF(QPointF(14, 0), QPointF(0, - 10 * factor)); @@ -1571,38 +1599,38 @@ void RelationshipView::configureCrowsFootDescriptors(void) round_cf_descriptors[tab_id]->setVisible(false); //Configuring the maximum cardinality descriptor - if((tab_id == BaseRelationship::SRC_TABLE && mandatory[tab_id]) || rel_type == BaseRelationship::RELATIONSHIP_NN) + if((tab_id == BaseRelationship::SrcTable && mandatory[tab_id]) || rel_type == BaseRelationship::RelationshipNn) { line_item = cf_lines[tab_id]->at(lin_idx++); cf_descriptors[tab_id]->addToGroup(line_item); line_item->setVisible(true); line_item->setLine(QLineF(QPointF(0, -8 * factor), QPointF(0, 8 * factor))); - line_item->setPos(15 * signal * (tab_id == BaseRelationship::DST_TABLE ? -1 : 1), 0); + line_item->setPos(15 * signal * (tab_id == BaseRelationship::DstTable ? -1 : 1), 0); line_item->setPen(pens[tab_id]); } else if(!mandatory[tab_id] && - ((rel_type != BaseRelationship::RELATIONSHIP_FK) || - (tab_id == BaseRelationship::SRC_TABLE && rel_type == BaseRelationship::RELATIONSHIP_FK))) + ((rel_type != BaseRelationship::RelationshipFk) || + (tab_id == BaseRelationship::SrcTable && rel_type == BaseRelationship::RelationshipFk))) { //Configuring the circle which describes the optional cardinality circle_item = round_cf_descriptors[tab_id]; cf_descriptors[tab_id]->addToGroup(circle_item); circle_item->setVisible(true); - circle_item->setRect(QRectF(0, 0, GRAPHIC_PNT_RADIUS * 2.20 * factor, GRAPHIC_PNT_RADIUS * 2.20 * factor)); + circle_item->setRect(QRectF(0, 0, GraphicPointRadius * 2.20 * factor, GraphicPointRadius * 2.20 * factor)); py = -(circle_item->boundingRect().height()/2.20); - if(tab_id == BaseRelationship::SRC_TABLE) + if(tab_id == BaseRelationship::SrcTable) { - if(base_rel->isSelfRelationship() || rel_type != BaseRelationship::RELATIONSHIP_NN) + if(base_rel->isSelfRelationship() || rel_type != BaseRelationship::RelationshipNn) px = 15; else px = 11; } else { - if(rel_type == BaseRelationship::RELATIONSHIP_11) + if(rel_type == BaseRelationship::Relationship11) { if(signal < 0) px = 15; @@ -1615,7 +1643,7 @@ void RelationshipView::configureCrowsFootDescriptors(void) pen = pens[tab_id]; - if(rel_type == BaseRelationship::RELATIONSHIP_FK) + if(rel_type == BaseRelationship::RelationshipFk) pen.setStyle(Qt::DashLine); circle_item->setPos(px, py); @@ -1648,9 +1676,9 @@ void RelationshipView::configureCrowsFootDescriptors(void) * is between one of the coordinates of the relationship line used in the operation. * * If it matches we'll use the use one of the extremes of the relationship line in the matching coordinate */ - min_x = qMin(rel_lines[tab_id].p1().x(), rel_lines[tab_id].p2().x()), - max_x = qMax(rel_lines[tab_id].p1().x(), rel_lines[tab_id].p2().x()), - min_y = qMin(rel_lines[tab_id].p1().y(), rel_lines[tab_id].p2().y()), + min_x = qMin(rel_lines[tab_id].p1().x(), rel_lines[tab_id].p2().x()); + max_x = qMax(rel_lines[tab_id].p1().x(), rel_lines[tab_id].p2().x()); + min_y = qMin(rel_lines[tab_id].p1().y(), rel_lines[tab_id].p2().y()); max_y = qMax(rel_lines[tab_id].p1().y(), rel_lines[tab_id].p2().y()); if(pi.x() >= min_x && pi.x() <= max_x) @@ -1665,7 +1693,7 @@ void RelationshipView::configureCrowsFootDescriptors(void) void RelationshipView::configureAttributes(void) { - Relationship *rel=dynamic_cast(this->getSourceObject()); + Relationship *rel=dynamic_cast(this->getUnderlyingObject()); if(rel) { @@ -1683,11 +1711,11 @@ void RelationshipView::configureAttributes(void) QRectF rect; QPolygonF pol; double py, px, - factor=font_config[ParsersAttributes::GLOBAL].font().pointSizeF()/DEFAULT_FONT_SIZE; + factor=font_config[Attributes::Global].font().pointSizeF()/DefaultFontSize; - fmt=font_config[ParsersAttributes::ATTRIBUTE]; + fmt=font_config[Attributes::Attribute]; font=fmt.font(); - font.setPointSizeF(font.pointSizeF() * 0.80f); + font.setPointSizeF(font.pointSizeF() * 0.80); //Configures the rectangle used as base for creation of attribute descriptor rect.setTopLeft(QPointF(0,0)); @@ -1695,8 +1723,8 @@ void RelationshipView::configureAttributes(void) //Calculates the first attribute position based upon the attribute count and descriptor size count=rel->getAttributeCount(); - px=descriptor->pos().x() + descriptor->boundingRect().width() + ((3 * HORIZ_SPACING) * factor); - py=descriptor->pos().y() - (count * rect.height()/(4.0f * factor)); + px=descriptor->pos().x() + descriptor->boundingRect().width() + ((3 * HorizSpacing) * factor); + py=descriptor->pos().y() - (count * rect.height()/(4.0 * factor)); for(i=0; i < count; i++) { @@ -1740,32 +1768,32 @@ void RelationshipView::configureAttributes(void) } desc->setRect(rect); - desc->setPen(BaseObjectView::getBorderStyle(ParsersAttributes::ATTRIBUTE)); - desc->setBrush(BaseObjectView::getFillStyle(ParsersAttributes::ATTRIBUTE)); + desc->setPen(BaseObjectView::getBorderStyle(Attributes::Attribute)); + desc->setBrush(BaseObjectView::getFillStyle(Attributes::Attribute)); lin->setPen(descriptor->pen()); text->setBrush(fmt.foreground()); text->setFont(font); - sel_attrib->setPen(BaseObjectView::getBorderStyle(ParsersAttributes::OBJ_SELECTION)); - sel_attrib->setBrush(BaseObjectView::getFillStyle(ParsersAttributes::OBJ_SELECTION)); + sel_attrib->setPen(BaseObjectView::getBorderStyle(Attributes::ObjSelection)); + sel_attrib->setBrush(BaseObjectView::getFillStyle(Attributes::ObjSelection)); attrib->setPos(px, py); - text->setText(col->getName()); - text->setPos(QPointF(desc->pos().x() + desc->boundingRect().width() + (HORIZ_SPACING * factor), 0)); - desc->setPos(0, VERT_SPACING * factor); + text->setText(compact_view && !col->getAlias().isEmpty() ? col->getAlias() : col->getName()); + text->setPos(QPointF(desc->pos().x() + desc->boundingRect().width() + (HorizSpacing * factor), 0)); + desc->setPos(0, VertSpacing * factor); pol.clear(); pol.append(text->boundingRect().topLeft()); - pol.append(text->boundingRect().topRight() + QPointF(desc->boundingRect().width() + (HORIZ_SPACING * factor), 0)); - pol.append(text->boundingRect().bottomRight() + QPointF(desc->boundingRect().width() + (HORIZ_SPACING * factor), 0)); + pol.append(text->boundingRect().topRight() + QPointF(desc->boundingRect().width() + (HorizSpacing * factor), 0)); + pol.append(text->boundingRect().bottomRight() + QPointF(desc->boundingRect().width() + (HorizSpacing * factor), 0)); pol.append(text->boundingRect().bottomLeft()); sel_attrib->setPolygon(pol); - p_aux=this->mapToItem(attrib, descriptor->pos().x() + (descriptor->boundingRect().width()/2.0f), - descriptor->pos().y() + (descriptor->boundingRect().height()/2.0f)); + p_aux=this->mapToItem(attrib, descriptor->pos().x() + (descriptor->boundingRect().width()/2.0), + descriptor->pos().y() + (descriptor->boundingRect().height()/2.0)); lin->setLine(QLineF(p_aux, desc->boundingRect().center())); - py+=desc->boundingRect().height() + (2 * VERT_SPACING); + py+=desc->boundingRect().height() + (2 * VertSpacing); } i=attributes.size()-1; @@ -1784,61 +1812,78 @@ void RelationshipView::configureLabels(void) { double x=0,y=0; QPointF pnt; - BaseRelationship *base_rel=this->getSourceObject(); + BaseRelationship *base_rel=this->getUnderlyingObject(); unsigned rel_type=base_rel->getRelationshipType(); QPointF label_dist; - label_dist=base_rel->getLabelDistance(BaseRelationship::REL_NAME_LABEL); + label_dist=base_rel->getLabelDistance(BaseRelationship::RelNameLabel); pnt=descriptor->pos(); x=pnt.x() - - ((labels[BaseRelationship::REL_NAME_LABEL]->boundingRect().width() - - descriptor->boundingRect().width())/2.0f); + ((labels[BaseRelationship::RelNameLabel]->boundingRect().width() - + descriptor->boundingRect().width())/2.0); if(base_rel->isSelfRelationship()) - y=pnt.y() - labels[BaseRelationship::REL_NAME_LABEL]->boundingRect().height() - (2 * VERT_SPACING); + y=pnt.y() - labels[BaseRelationship::RelNameLabel]->boundingRect().height() - (2 * VertSpacing); else - y=pnt.y() + descriptor->boundingRect().height() + VERT_SPACING; + y=pnt.y() + descriptor->boundingRect().height() + VertSpacing; + + labels[BaseRelationship::RelNameLabel]->setVisible(!hide_name_label); + configureLabelPosition(BaseRelationship::RelNameLabel, x, y); - labels[BaseRelationship::REL_NAME_LABEL]->setVisible(!hide_name_label); - configureLabelPosition(BaseRelationship::REL_NAME_LABEL, x, y); + if(!hide_name_label) + { + Textbox *txtbox = dynamic_cast(labels[BaseRelationship::RelNameLabel]->getUnderlyingObject()); + + if(compact_view && !base_rel->getAlias().isEmpty()) + { + txtbox->setComment(base_rel->getAlias()); + txtbox->setModified(true); + } + else if(txtbox->getComment() != base_rel->getName(true)) + { + txtbox->setComment(base_rel->getName(true)); + txtbox->setModified(true); + } + } //Hides the cardinality labels when crow's feet is enabled - if(labels[BaseRelationship::SRC_CARD_LABEL] && labels[BaseRelationship::DST_CARD_LABEL]) + if(labels[BaseRelationship::SrcCardLabel] && labels[BaseRelationship::DstCardLabel]) { - labels[BaseRelationship::SRC_CARD_LABEL]->setVisible(!use_crows_foot); - labels[BaseRelationship::DST_CARD_LABEL]->setVisible(!use_crows_foot); + labels[BaseRelationship::SrcCardLabel]->setVisible(!use_crows_foot); + labels[BaseRelationship::DstCardLabel]->setVisible(!use_crows_foot); } if(!use_crows_foot && - rel_type!=BaseRelationship::RELATIONSHIP_GEN && - rel_type!=BaseRelationship::RELATIONSHIP_DEP) + rel_type!=BaseRelationship::RelationshipGen && + rel_type!=BaseRelationship::RelationshipDep && + rel_type!=BaseRelationship::RelationshipPart) { QPointF pi, pf, p_int, pos; unsigned idx, i1; - double dl, da, factor, v_space=VERT_SPACING * 2.5, h_space=HORIZ_SPACING * 2.5; + double dl, da, factor, v_space=VertSpacing * 2.5, h_space=HorizSpacing * 2.5; QLineF lins[2], borders[2][4]; QRectF tab_rect, rect; - unsigned label_ids[2]={ BaseRelationship::SRC_CARD_LABEL, - BaseRelationship::DST_CARD_LABEL }; + unsigned label_ids[2]={ BaseRelationship::SrcCardLabel, + BaseRelationship::DstCardLabel }; if(!base_rel->isSelfRelationship() && - line_conn_mode==CONNECT_FK_TO_PK && rel_type!=BaseRelationship::RELATIONSHIP_NN) + line_conn_mode==ConnectFkToPk && rel_type!=BaseRelationship::RelationshipNn) { for(idx=0; idx < 2; idx++) { pos=conn_points[idx]; - da=labels[idx]->boundingRect().height()/2.0f; + da=labels[idx]->boundingRect().height()/2.0; - if((rel_type!=BaseRelationship::RELATIONSHIP_FK && pos.x() < tables[idx]->pos().x()) || - (rel_type==BaseRelationship::RELATIONSHIP_FK && pos.x() >= tables[idx]->pos().x())) + if((rel_type!=BaseRelationship::RelationshipFk && pos.x() < tables[idx]->pos().x()) || + (rel_type==BaseRelationship::RelationshipFk && pos.x() >= tables[idx]->pos().x())) { - factor=(rel_type==BaseRelationship::RELATIONSHIP_FK ? 0.80 : 0.55); + factor=(rel_type==BaseRelationship::RelationshipFk ? 0.80 : 0.55); x=pos.x() - (labels[idx]->boundingRect().width() * factor); } else { - factor=(rel_type==BaseRelationship::RELATIONSHIP_FK ? 0.05 : 0.45); + factor=(rel_type==BaseRelationship::RelationshipFk ? 0.05 : 0.45); x=pos.x() - (labels[idx]->boundingRect().width() * factor); } @@ -1893,8 +1938,8 @@ void RelationshipView::configureLabels(void) pf=lins[idx].p1(); } - dl=labels[label_ids[idx]]->boundingRect().width()/2.0f; - da=labels[label_ids[idx]]->boundingRect().height()/2.0f; + dl=labels[label_ids[idx]]->boundingRect().width()/2.0; + da=labels[label_ids[idx]]->boundingRect().height()/2.0; x=pi.x() - dl; y=pi.y() - da; @@ -1934,12 +1979,12 @@ void RelationshipView::configureLabels(void) void RelationshipView::configureLabelPosition(unsigned label_id, double x, double y) { - if(label_id > BaseRelationship::REL_NAME_LABEL) - throw Exception(ERR_REF_OBJ_INV_INDEX ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(label_id > BaseRelationship::RelNameLabel) + throw Exception(ErrorCode::RefObjectInvalidIndex ,__PRETTY_FUNCTION__,__FILE__,__LINE__); if(labels[label_id]) { - BaseRelationship *base_rel=this->getSourceObject(); + BaseRelationship *base_rel=this->getUnderlyingObject(); QTextCharFormat char_fmt; QPointF label_dist; @@ -1955,12 +2000,12 @@ void RelationshipView::configureLabelPosition(unsigned label_id, double x, doubl labels[label_id]->setPos(x,y); labels[label_id]->setToolTip(this->toolTip()); - char_fmt=BaseObjectView::getFontStyle(ParsersAttributes::LABEL); + char_fmt=BaseObjectView::getFontStyle(Attributes::Label); char_fmt.setFontPointSize(char_fmt.fontPointSize() * 0.90); labels[label_id]->setFontStyle(char_fmt); - labels[label_id]->setColorStyle(BaseObjectView::getFillStyle(ParsersAttributes::LABEL), - BaseObjectView::getBorderStyle(ParsersAttributes::LABEL)); - dynamic_cast(labels[label_id]->getSourceObject())->setModified(true); + labels[label_id]->setColorStyle(BaseObjectView::getFillStyle(Attributes::Label), + BaseObjectView::getBorderStyle(Attributes::Label)); + dynamic_cast(labels[label_id]->getUnderlyingObject())->setModified(true); } } @@ -1970,7 +2015,7 @@ QRectF RelationshipView::__boundingRect(void) unsigned i, count; QPointF p; QRectF rect; - vector points=dynamic_cast(this->getSourceObject())->getPoints(); + vector points=dynamic_cast(this->getUnderlyingObject())->getPoints(); //The reference size will be the relationship descriptor dimension x1=descriptor->pos().x(); @@ -1983,10 +2028,10 @@ QRectF RelationshipView::__boundingRect(void) for(i=0; i < count; i++) { p=points[i]; - if(x1 > p.x()) x1=p.x() - GRAPHIC_PNT_RADIUS; - if(y1 > p.y()) y1=p.y() - GRAPHIC_PNT_RADIUS; - if(x2 < p.x()) x2=p.x() + GRAPHIC_PNT_RADIUS; - if(y2 < p.y()) y2=p.y() + GRAPHIC_PNT_RADIUS; + if(x1 > p.x()) x1=p.x() - GraphicPointRadius; + if(y1 > p.y()) y1=p.y() - GraphicPointRadius; + if(x2 < p.x()) x2=p.x() + GraphicPointRadius; + if(y2 < p.y()) y2=p.y() + GraphicPointRadius; } //Checks if some label is out of reference dimension diff --git a/libobjrenderer/src/relationshipview.h b/libobjrenderer/src/relationshipview.h index 624403c5d4..eae957c5b4 100644 --- a/libobjrenderer/src/relationshipview.h +++ b/libobjrenderer/src/relationshipview.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -35,10 +35,10 @@ class RelationshipView: public BaseObjectView { Q_OBJECT //! \brief Graphical point radius - static constexpr double GRAPHIC_PNT_RADIUS=6.0f; + static constexpr double GraphicPointRadius=6.0; //! \brief Length of the lines linked to fk/pk columns - static constexpr double CONN_LINE_LENGTH=20.0f; + static constexpr double ConnLineLength=20.0; //! \brief Indicates that the relationship labels must be hidden static bool hide_name_label; @@ -158,9 +158,9 @@ class RelationshipView: public BaseObjectView { void configureObject(void); public: - static const unsigned CONNECT_CENTER_PNTS=0, - CONNECT_FK_TO_PK=1, - CONNECT_TABLE_EGDES=2; + static constexpr unsigned ConnectCenterPoints=0, + ConnectFkToPk=1, + ConnectTableEdges=2; RelationshipView(BaseRelationship *rel); ~RelationshipView(void); @@ -169,7 +169,7 @@ class RelationshipView: public BaseObjectView { QRectF __boundingRect(void); //! \brief Returns the relationship that generates the graphical representation - BaseRelationship *getSourceObject(void); + BaseRelationship *getUnderlyingObject(void); //! \brief Hides the relationship's name label. This applies to all relationship instances static void setHideNameLabel(bool value); @@ -203,6 +203,9 @@ class RelationshipView: public BaseObjectView { line connection mode used. */ QPointF getConnectionPoint(unsigned table_idx); + void configureObjectShadow(void) = delete; + void configureObjectSelection(void) = delete; + signals: void s_relationshipModified(BaseGraphicObject *rel); diff --git a/libobjrenderer/src/roundedrectitem.cpp b/libobjrenderer/src/roundedrectitem.cpp index 538527b758..3ccf34ad6f 100644 --- a/libobjrenderer/src/roundedrectitem.cpp +++ b/libobjrenderer/src/roundedrectitem.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -21,7 +21,7 @@ RoundedRectItem::RoundedRectItem(QGraphicsItem *parent) : QGraphicsRectItem(parent) { radius=5; - corners=ALL_CORNERS; + corners=AllCorners; } void RoundedRectItem::setBorderRadius(double radius) @@ -37,8 +37,8 @@ double RoundedRectItem::getBorderRadius(void) void RoundedRectItem::setRoundedCorners(unsigned corners) { - if(corners > ALL_CORNERS) - corners=ALL_CORNERS; + if(corners > AllCorners) + corners=AllCorners; this->corners=corners; createPolygon(); @@ -65,9 +65,9 @@ void RoundedRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, painter->setPen(this->pen()); painter->setBrush(this->brush()); - if(corners==NO_CORNERS) + if(corners==NoCorners) painter->drawRect(this->rect()); - else if(corners==ALL_CORNERS) + else if(corners==AllCorners) painter->drawRoundedRect(this->rect(), radius, radius); else painter->drawPolygon(polygon); @@ -77,26 +77,26 @@ void RoundedRectItem::createPolygon(void) { polygon.clear(); - if(corners!=NO_CORNERS && corners!=ALL_CORNERS && this->rect().isValid()) + if(corners!=NoCorners && corners!=AllCorners && this->rect().isValid()) { QRectF rect=this->rect(); - if(isCornerRounded(TOPLEFT_CORNER)) + if(isCornerRounded(TopLeftCorner)) polygon << calculatePoints(rect.topLeft() + QPointF(radius, radius), 180, 90); else polygon.append(this->rect().topLeft()); - if(isCornerRounded(TOPRIGHT_CORNER)) + if(isCornerRounded(TopRightCorner)) polygon << calculatePoints(this->rect().topRight() + QPointF(-radius, radius), 90, 0); else polygon.append(this->rect().topRight()); - if(isCornerRounded(BOTTOMRIGHT_CORNER)) + if(isCornerRounded(BottomRightCorner)) polygon << calculatePoints(this->rect().bottomRight() + QPointF(-radius, -radius), 360, 270); else polygon.append(this->rect().bottomRight()); - if(isCornerRounded(BOTTOMLEFT_CORNER)) + if(isCornerRounded(BottomLeftCorner)) polygon << calculatePoints(this->rect().bottomLeft() + QPointF(radius, -radius), 270, 180); else polygon.append(this->rect().bottomLeft()); diff --git a/libobjrenderer/src/roundedrectitem.h b/libobjrenderer/src/roundedrectitem.h index 7c51cf9198..9ff36a9ccc 100644 --- a/libobjrenderer/src/roundedrectitem.h +++ b/libobjrenderer/src/roundedrectitem.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -51,22 +51,22 @@ class RoundedRectItem: public QGraphicsRectItem { public: //! \brief Implies a normal rectangle (no rounded corner) - static const unsigned NO_CORNERS=0, + static constexpr unsigned NoCorners=0, //! \brief The top-left corner will be rounded - TOPLEFT_CORNER=2, + TopLeftCorner=2, //! \brief The top-right corner will be rounded - TOPRIGHT_CORNER=4, + TopRightCorner=4, //! \brief The Bottom-left corner will be rounded - BOTTOMLEFT_CORNER=8, + BottomLeftCorner=8, //! \brief The Bottom-right corner will be rounded - BOTTOMRIGHT_CORNER=16, + BottomRightCorner=16, //! \brief All corners will be rounded - ALL_CORNERS=32; + AllCorners=32; explicit RoundedRectItem(QGraphicsItem *parent = 0); diff --git a/libobjrenderer/src/schemaview.cpp b/libobjrenderer/src/schemaview.cpp index cc065fcc35..0752db0267 100644 --- a/libobjrenderer/src/schemaview.cpp +++ b/libobjrenderer/src/schemaview.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -17,6 +17,7 @@ */ #include "schemaview.h" +#include "objectsscene.h" SchemaView::SchemaView(Schema *schema) : BaseObjectView(schema) { @@ -72,19 +73,19 @@ void SchemaView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) void SchemaView::fetchChildren(void) { - Schema *schema=dynamic_cast(this->getSourceObject()); + Schema *schema=dynamic_cast(this->getUnderlyingObject()); DatabaseModel *model=dynamic_cast(schema->getDatabase()); vector objs, objs1; //Gets all tables and views that belongs to the schema - objs=model->getObjects(OBJ_TABLE, schema); - objs1=model->getObjects(OBJ_VIEW, schema); + objs=model->getObjects(ObjectType::Table, schema); + objs1=model->getObjects(ObjectType::View, schema); objs.insert(objs.end(), objs1.begin(), objs1.end()); children.clear(); while(!objs.empty()) { - children.push_front(dynamic_cast(dynamic_cast(objs.back())->getReceiverObject())); + children.push_front(dynamic_cast(dynamic_cast(objs.back())->getOverlyingObject())); objs.pop_back(); } } @@ -165,8 +166,7 @@ void SchemaView::moveTo(QPointF new_pos) void SchemaView::configureObject(void) { - Schema *schema=dynamic_cast(this->getSourceObject()); - + Schema *schema=dynamic_cast(this->getUnderlyingObject()); this->fetchChildren(); /* Only configures the schema view if the rectangle is visible and there are @@ -200,19 +200,19 @@ void SchemaView::configureObject(void) } //Configures the schema name at the top - sch_name->setText(schema->getName()); - font=BaseObjectView::getFontStyle(ParsersAttributes::GLOBAL).font(); + sch_name->setText(compact_view && !schema->getAlias().isEmpty() ? schema->getAlias() : schema->getName()); + font=BaseObjectView::getFontStyle(Attributes::Global).font(); font.setItalic(true); font.setBold(true); - font.setPointSizeF(font.pointSizeF() * 1.3f); + font.setPointSizeF(font.pointSizeF() * 1.3); sch_name->setFont(font); - sch_name->setPos(HORIZ_SPACING, VERT_SPACING); - txt_h=sch_name->boundingRect().height() + (2 * VERT_SPACING); + sch_name->setPos(HorizSpacing, VertSpacing); + txt_h=sch_name->boundingRect().height() + (2 * VertSpacing); //Configures the box with the points calculated above - sp_h=(3 * HORIZ_SPACING); - sp_v=(3 * VERT_SPACING) + txt_h; + sp_h=(3 * HorizSpacing); + sp_v=(3 * VertSpacing) + txt_h; width=(x2-x1) + 1; @@ -233,20 +233,24 @@ void SchemaView::configureObject(void) this->setFlag(ItemSendsGeometryChanges, true); color=schema->getFillColor(); - color.setAlpha(OBJ_ALPHA_CHANNEL * 0.80); + color.setAlpha(ObjectAlphaChannel * 0.80); box->setBrush(color); color=QColor(color.red()/3,color.green()/3,color.blue()/3, 80); box->setPen(QPen(color, 1, Qt::SolidLine)); this->bounding_rect=rect; - this->setVisible(true); - this->setToolTip(schema->getName(true) + QString(" (") + schema->getTypeName() + QString(")")); + ObjectsScene *scene = dynamic_cast(this->scene()); + this->setVisible(scene && scene->isLayerActive(schema->getLayer())); + + this->setToolTip(schema->getName(true) + + QString(" (") + schema->getTypeName() + QString(")") + + QString("\nId: %1").arg(schema->getObjectId())); sch_name->setToolTip(this->toolTip()); this->protected_icon->setPos(QPointF( sch_name->boundingRect().width() + sp_h, - sch_name->pos().y() + VERT_SPACING )); + sch_name->pos().y() + VertSpacing )); this->configureObjectSelection(); this->configureProtectedIcon(); diff --git a/libobjrenderer/src/schemaview.h b/libobjrenderer/src/schemaview.h index f80b591a63..66b18728b5 100644 --- a/libobjrenderer/src/schemaview.h +++ b/libobjrenderer/src/schemaview.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libobjrenderer/src/styledtextboxview.cpp b/libobjrenderer/src/styledtextboxview.cpp index 5bc60051ac..fcb3cfce69 100644 --- a/libobjrenderer/src/styledtextboxview.cpp +++ b/libobjrenderer/src/styledtextboxview.cpp @@ -9,9 +9,9 @@ StyledTextboxView::StyledTextboxView(Textbox *txtbox, bool override_style) : Tex pol.append(QPointF(0,20)); fold=new QGraphicsPolygonItem; - this->addToGroup(fold); fold->setPolygon(pol); + this->addToGroup(fold); this->configureObject(); } @@ -28,26 +28,28 @@ void StyledTextboxView::configureObject(void) QPointF pnt; this->__configureObject(); - fold->setBrush(box->brush()); - fold->setPen(box->pen()); + fold->setBrush(text_item->brush()); + fold->setPen(text_item->pen()); - rect=box->boundingRect(); - pol=box->polygon(); + rect = text_item->boundingRect(); + pol = text_item->polygon(); if(rect.height() < fold->boundingRect().height()) - rect.setHeight(fold->boundingRect().height() + (2 * VERT_SPACING)); + rect.setHeight(fold->boundingRect().height() + (2 * VertSpacing)); - this->resizePolygon(pol, rect.width() + fold->boundingRect().width(), rect.height()); + TextPolygonItem::resizePolygon(pol, rect.width() + fold->boundingRect().width(), rect.height()); pnt=pol.at(2); pol.remove(2); - pol.insert(2, QPointF(pnt.x(), roundf(pnt.y() - fold->boundingRect().height()))); - pol.insert(3, QPointF(roundf(pnt.x() - fold->boundingRect().width()), pnt.y())); - box->setPolygon(pol); + pol.insert(2, QPointF(pnt.x(), round(pnt.y() - fold->boundingRect().height()))); + pol.insert(3, QPointF(round(pnt.x() - fold->boundingRect().width()), pnt.y())); - rect=box->boundingRect(); + text_item->setPolygon(pol); + rect = text_item->boundingRect(); fold->setPos(rect.width() - fold->boundingRect().width(), - rect.height() - fold->boundingRect().height()); + rect.height() - fold->boundingRect().height()); + + bounding_rect = text_item->boundingRect(); this->configureObjectShadow(); this->configureObjectSelection(); diff --git a/libobjrenderer/src/styledtextboxview.h b/libobjrenderer/src/styledtextboxview.h index c368486745..65b8972e30 100644 --- a/libobjrenderer/src/styledtextboxview.h +++ b/libobjrenderer/src/styledtextboxview.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libobjrenderer/src/tableobjectview.cpp b/libobjrenderer/src/tableobjectview.cpp index 383a499a82..7a018ea68a 100644 --- a/libobjrenderer/src/tableobjectview.cpp +++ b/libobjrenderer/src/tableobjectview.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,60 +18,58 @@ #include "tableobjectview.h" -const QString TableObjectView::TYPE_SEPARATOR=QString(" "); -const QString TableObjectView::CONSTR_SEPARATOR=QString(" "); -const QString TableObjectView::TXT_UNIQUE=QString("uq"); -const QString TableObjectView::TXT_EXCLUDE=QString("ex"); -const QString TableObjectView::TXT_CHECK=QString("ck"); -const QString TableObjectView::TXT_PRIMARY_KEY=QString("pk"); -const QString TableObjectView::TXT_FOREIGN_KEY=QString("fk"); -const QString TableObjectView::TXT_NOT_NULL=QString("nn"); -const QString TableObjectView::CONSTR_DELIM_START=QString("«"); -const QString TableObjectView::CONSTR_DELIM_END=QString("»"); +const QString TableObjectView::TypeSeparator=QString(" "); +const QString TableObjectView::ConstrSeparator=QString(" "); +const QString TableObjectView::TextUnique=QString("uq"); +const QString TableObjectView::TextExclude=QString("ex"); +const QString TableObjectView::TextCheck=QString("ck"); +const QString TableObjectView::TextPrimaryKey=QString("pk"); +const QString TableObjectView::TextForeignKey=QString("fk"); +const QString TableObjectView::TextNotNull=QString("nn"); +const QString TableObjectView::ConstrDelimStart=QString("«"); +const QString TableObjectView::ConstrDelimEnd=QString("»"); TableObjectView::TableObjectView(TableObject *object) : BaseObjectView(object) { descriptor=nullptr; + fake_selection=false; for(unsigned i=0; i < 3; i++) - { lables[i]=new QGraphicsSimpleTextItem; - this->addToGroup(lables[i]); - } + + if(obj_selection) + delete(obj_selection); } TableObjectView::~TableObjectView(void) { - this->removeFromGroup(descriptor); delete(descriptor); for(unsigned i=0; i < 3; i++) - { - this->removeFromGroup(lables[i]); delete(lables[i]); - } + + delete(obj_selection); } void TableObjectView::configureDescriptor(ConstraintType constr_type) { - ObjectType obj_type=BASE_OBJECT; - Column *column=dynamic_cast(this->getSourceObject()); + ObjectType obj_type=ObjectType::BaseObject; + Column *column=dynamic_cast(this->getUnderlyingObject()); bool ellipse_desc=false; - double factor=(font_config[ParsersAttributes::GLOBAL].font().pointSizeF()/DEFAULT_FONT_SIZE) * BaseObjectView::getScreenDpiFactor(); + double factor=(font_config[Attributes::Global].font().pointSizeF()/DefaultFontSize) * BaseObjectView::getScreenDpiFactor(); QPen pen; //Based upon the source object type the descriptor is allocated - if(this->getSourceObject()) - obj_type=this->getSourceObject()->getObjectType(); + if(this->getUnderlyingObject()) + obj_type=this->getUnderlyingObject()->getObjectType(); /* Elliptical descriptor is used to columns (with or without not-null constraint), for other object types, polygonal descriptor is usded */ - ellipse_desc=((column && constr_type==BaseType::null) || (!TableObject::isTableObject(obj_type))); + ellipse_desc=((column && constr_type==BaseType::Null) || (!TableObject::isTableObject(obj_type))); if(descriptor && ((ellipse_desc && !dynamic_cast(descriptor)) || (!ellipse_desc && dynamic_cast(descriptor)))) { - this->removeFromGroup(descriptor); delete(descriptor); descriptor=nullptr; } @@ -82,8 +80,6 @@ void TableObjectView::configureDescriptor(ConstraintType constr_type) descriptor=new QGraphicsEllipseItem; else descriptor=new QGraphicsPolygonItem; - - this->addToGroup(descriptor); } if(column) @@ -91,116 +87,112 @@ void TableObjectView::configureDescriptor(ConstraintType constr_type) QString attrib; QPolygonF pol; - if(constr_type==BaseType::null) + if(constr_type==BaseType::Null) { QGraphicsEllipseItem *desc=dynamic_cast(descriptor); - desc->setRect(QRectF(QPointF(0,0), QSizeF(9.0f * factor, 9.0f * factor))); + desc->setRect(QRectF(QPointF(0,0), QSizeF(9.0 * factor, 9.0 * factor))); if(column->isNotNull()) - attrib=ParsersAttributes::NN_COLUMN; + attrib=Attributes::NnColumn; else - attrib=ParsersAttributes::COLUMN; + attrib=Attributes::Column; desc->setBrush(this->getFillStyle(attrib)); pen = this->getBorderStyle(attrib); - pen.setWidthF(OBJ_BORDER_WIDTH * 1.15f); + pen.setWidthF(ObjectBorderWidth * 1.15); desc->setPen(pen); } else { QGraphicsPolygonItem *desc=dynamic_cast(descriptor); - if(constr_type==ConstraintType::primary_key) + if(constr_type==ConstraintType::PrimaryKey) { - attrib=ParsersAttributes::PK_COLUMN; + attrib=Attributes::PkColumn; pol.append(QPointF(2,0)); pol.append(QPointF(0,2)); pol.append(QPointF(0,7)); pol.append(QPointF(2,9)); pol.append(QPointF(3,8)); pol.append(QPointF(3,6)); pol.append(QPointF(4,6)); pol.append(QPointF(5,7)); pol.append(QPointF(6,6)); pol.append(QPointF(7,5)); pol.append(QPointF(9,7)); pol.append(QPointF(9,3)); pol.append(QPointF(3,3)); pol.append(QPointF(3,1)); } - else if(constr_type==ConstraintType::foreign_key) + else if(constr_type==ConstraintType::ForeignKey) { - attrib=ParsersAttributes::FK_COLUMN; + attrib=Attributes::FkColumn; pol.append(QPointF(0,3)); pol.append(QPointF(0,6)); pol.append(QPointF(4,6)); pol.append(QPointF(4,9)); pol.append(QPointF(5,9)); pol.append(QPointF(9,5)); pol.append(QPointF(9,4)); pol.append(QPointF(5,0)); pol.append(QPointF(4,0)); pol.append(QPointF(4,3)); } - else if(constr_type==ConstraintType::unique) + else if(constr_type==ConstraintType::Unique) { - attrib=ParsersAttributes::UQ_COLUMN; + attrib=Attributes::UqColumn; pol.append(QPointF(4,0)); pol.append(QPointF(0,4)); pol.append(QPointF(0,5)); pol.append(QPointF(4,9)); pol.append(QPointF(5,9)); pol.append(QPointF(9,5)); pol.append(QPointF(9,4)); pol.append(QPointF(5,0)); } - if(factor!=1.0f) - this->resizePolygon(pol, - pol.boundingRect().width() * factor, - pol.boundingRect().height() * factor); + if(factor!=1.0) + TextPolygonItem::resizePolygon(pol, pol.boundingRect().width() * factor, + pol.boundingRect().height() * factor); desc->setPolygon(pol); desc->setBrush(this->getFillStyle(attrib)); pen = this->getBorderStyle(attrib); - pen.setWidthF(OBJ_BORDER_WIDTH * 1.15f); + pen.setWidthF(ObjectBorderWidth * 1.15); desc->setPen(pen); } } - else if(obj_type==OBJ_INDEX || obj_type==OBJ_RULE || - obj_type==OBJ_TRIGGER || obj_type==OBJ_CONSTRAINT) + else if(obj_type != ObjectType::BaseObject) { - TableObject *tab_obj=dynamic_cast(this->getSourceObject()); + TableObject *tab_obj=dynamic_cast(this->getUnderlyingObject()); QGraphicsPolygonItem *desc=dynamic_cast(descriptor); QPolygonF pol; pol.append(QPointF(5,0)); pol.append(QPointF(0,5)); pol.append(QPointF(4,9)); pol.append(QPointF(9,9)); pol.append(QPointF(9,4)); - if(factor!=1.0f) - this->resizePolygon(pol, - pol.boundingRect().width() * factor , - pol.boundingRect().height() * factor); + if(factor!=1.0) + TextPolygonItem::resizePolygon(pol, pol.boundingRect().width() * factor , pol.boundingRect().height() * factor); desc->setPolygon(pol); desc->setBrush(this->getFillStyle(tab_obj->getSchemaName())); pen = this->getBorderStyle(tab_obj->getSchemaName()); - pen.setWidthF(OBJ_BORDER_WIDTH * 1.15f); + pen.setWidthF(ObjectBorderWidth * 1.15); desc->setPen(pen); } else { QGraphicsEllipseItem *desc=dynamic_cast(descriptor); - desc->setRect(QRectF(QPointF(0,0), - QSizeF(9.0f * factor, 9.0f * factor))); - desc->setBrush(this->getFillStyle(ParsersAttributes::REFERENCE)); + desc->setRect(QRectF(QPointF(0,0), QSizeF(9.0 * factor, 9.0 * factor))); + desc->setBrush(this->getFillStyle(Attributes::Reference)); - pen = this->getBorderStyle(ParsersAttributes::REFERENCE); - pen.setWidthF(OBJ_BORDER_WIDTH * 1.15f); + pen = this->getBorderStyle(Attributes::Reference); + pen.setWidthF(ObjectBorderWidth * 1.15); desc->setPen(pen); } } void TableObjectView::configureObject(void) { - if(this->getSourceObject()) + if(this->getUnderlyingObject()) { QTextCharFormat fmt; - double px; + double px = 0; QString str_constr, tooltip, atribs_tip; - TableObject *tab_obj=dynamic_cast(this->getSourceObject()); + TableObject *tab_obj=dynamic_cast(this->getUnderlyingObject()); Column *column=dynamic_cast(tab_obj); - ConstraintType constr_type=ConstraintType::null; + ConstraintType constr_type=ConstraintType::Null; bool sql_disabled=false; tooltip=tab_obj->getName() + QString(" (") + tab_obj->getTypeName() + QString(")"); tooltip+=QString("\nId: %1").arg(tab_obj->getObjectId()); sql_disabled=tab_obj->isSQLDisabled(); + fake_selection=false; if(column) { @@ -209,65 +201,63 @@ void TableObjectView::configureObject(void) str_constr=this->getConstraintString(column); - if(str_constr.indexOf(TXT_PRIMARY_KEY)>=0) + if(str_constr.indexOf(TextPrimaryKey)>=0) { - fmt=font_config[ParsersAttributes::PK_COLUMN]; - constr_type=ConstraintType::primary_key; + fmt=font_config[Attributes::PkColumn]; + constr_type=ConstraintType::PrimaryKey; } - else if(str_constr.indexOf(TXT_FOREIGN_KEY)>=0) + else if(str_constr.indexOf(TextForeignKey)>=0) { - fmt=font_config[ParsersAttributes::FK_COLUMN]; - constr_type=ConstraintType::foreign_key; + fmt=font_config[Attributes::FkColumn]; + constr_type=ConstraintType::ForeignKey; } - else if(str_constr.indexOf(TXT_UNIQUE)>=0) + else if(str_constr.indexOf(TextUnique)>=0) { - fmt=font_config[ParsersAttributes::UQ_COLUMN]; - constr_type=ConstraintType::unique; + fmt=font_config[Attributes::UqColumn]; + constr_type=ConstraintType::Unique; } - else if(str_constr.indexOf(TXT_NOT_NULL)>=0) - fmt=font_config[ParsersAttributes::NN_COLUMN]; + else if(str_constr.indexOf(TextNotNull)>=0) + fmt=font_config[Attributes::NnColumn]; else - fmt=font_config[ParsersAttributes::COLUMN]; + fmt=font_config[Attributes::Column]; if(column->isAddedByRelationship()) - fmt=font_config[ParsersAttributes::INH_COLUMN]; + fmt=font_config[Attributes::InhColumn]; else if(column->isProtected()) - fmt=font_config[ParsersAttributes::PROT_COLUMN]; + fmt=font_config[Attributes::ProtColumn]; - if(str_constr.indexOf(TXT_PRIMARY_KEY)>=0) - atribs_tip+=(~ConstraintType(ConstraintType::primary_key)).toLower() + QString(", "); + if(str_constr.indexOf(TextPrimaryKey)>=0) + atribs_tip+=(~ConstraintType(ConstraintType::PrimaryKey)).toLower() + QString(", "); - if(str_constr.indexOf(TXT_FOREIGN_KEY)>=0) - atribs_tip+=(~ConstraintType(ConstraintType::foreign_key)).toLower() + QString(", "); + if(str_constr.indexOf(TextForeignKey)>=0) + atribs_tip+=(~ConstraintType(ConstraintType::ForeignKey)).toLower() + QString(", "); - if(str_constr.indexOf(TXT_UNIQUE)>=0) - atribs_tip+=(~ConstraintType(ConstraintType::unique)).toLower() + QString(", "); + if(str_constr.indexOf(TextUnique)>=0) + atribs_tip+=(~ConstraintType(ConstraintType::Unique)).toLower() + QString(", "); - if(str_constr.indexOf(TXT_EXCLUDE)>=0) - atribs_tip+=(~ConstraintType(ConstraintType::exclude)).toLower() + QString(", "); + if(str_constr.indexOf(TextExclude)>=0) + atribs_tip+=(~ConstraintType(ConstraintType::Exclude)).toLower() + QString(", "); - if(str_constr.indexOf(TXT_NOT_NULL)>=0) + if(str_constr.indexOf(TextNotNull)>=0) atribs_tip+=QString("not null"); } else { if(tab_obj->isAddedByRelationship()) - fmt=font_config[ParsersAttributes::INH_COLUMN]; + fmt=font_config[Attributes::InhColumn]; else if(tab_obj->isProtected()) - fmt=font_config[ParsersAttributes::PROT_COLUMN]; + fmt=font_config[Attributes::ProtColumn]; else fmt=font_config[tab_obj->getSchemaName()]; } configureDescriptor(constr_type); - //Set the descriptor position as the first item on the view - descriptor->setPos(HORIZ_SPACING, 1); - px=descriptor->pos().x() + descriptor->boundingRect().width() + (2 * HORIZ_SPACING); + descriptor->setPos(HorizSpacing, 0); + px=HorizSpacing + descriptor->boundingRect().width() + (2 * HorizSpacing); //Configuring the labels as follow: [object name] [type] [constraints] - //Configuring tha name label - lables[0]->setText(tab_obj->getName()); + lables[0]->setText(compact_view && !tab_obj->getAlias().isEmpty() ? tab_obj->getAlias() : tab_obj->getName()); //Strikeout the column name when its SQL is disabled QFont font=fmt.font(); @@ -280,34 +270,43 @@ void TableObjectView::configureObject(void) px+=lables[0]->boundingRect().width(); //Configuring the type label - fmt=font_config[ParsersAttributes::OBJECT_TYPE]; - if(column) - lables[1]->setText(TYPE_SEPARATOR + (*column->getType())); + fmt=font_config[Attributes::ObjectType]; + + if(compact_view) + lables[1]->setText(QString()); else - lables[1]->setText(TYPE_SEPARATOR + tab_obj->getSchemaName()); + { + if(column) + lables[1]->setText(TypeSeparator + (*column->getType())); + else + lables[1]->setText(TypeSeparator + tab_obj->getSchemaName()); + } lables[1]->setFont(fmt.font()); lables[1]->setBrush(fmt.foreground()); lables[1]->setPos(px, 0); - px+=lables[1]->boundingRect().width() + (3 * HORIZ_SPACING); + px+=lables[1]->boundingRect().width() + (3 * HorizSpacing); //Configuring the constraints label - fmt=font_config[ParsersAttributes::CONSTRAINTS]; - if(column) - lables[2]->setText(str_constr); + fmt=font_config[Attributes::Constraints]; + if(compact_view) + lables[2]->setText(QString()); + else if(column) + lables[2]->setText(!str_constr.isEmpty() ? str_constr : QString(" ")); else { Rule *rule=dynamic_cast(tab_obj); Trigger *trigger=dynamic_cast(tab_obj); Index *index=dynamic_cast(tab_obj); Constraint *constr=dynamic_cast(tab_obj); + Policy *policy = dynamic_cast(tab_obj); if(rule) { str_constr+=(~rule->getExecutionType()).mid(0,1); atribs_tip+=(~rule->getExecutionType()).toLower() + QString(", "); - str_constr+=CONSTR_SEPARATOR; + str_constr+=ConstrSeparator; str_constr+=(~rule->getEventType()).mid(3,1); atribs_tip+=(~rule->getEventType()).toLower(); @@ -316,11 +315,11 @@ void TableObjectView::configureObject(void) else if(trigger) { str_constr+=(~trigger->getFiringType()).mid(0,1); - str_constr+=CONSTR_SEPARATOR; + str_constr+=ConstrSeparator; atribs_tip+=(~trigger->getFiringType()).toLower() + QString(", "); - for(unsigned i=EventType::on_insert; i <= EventType::on_truncate; i++) + for(unsigned i=EventType::OnInsert; i <= EventType::OnTruncate; i++) { if(trigger->isExecuteOnEvent(EventType(i))) { @@ -332,25 +331,25 @@ void TableObjectView::configureObject(void) } else if(index) { - if(index->getIndexAttribute(Index::UNIQUE)) + if(index->getIndexAttribute(Index::Unique)) { str_constr+=QString("u"); atribs_tip += QString("unique") + QString(", "); } - if(index->getIndexAttribute(Index::CONCURRENT)) + if(index->getIndexAttribute(Index::Concurrent)) { str_constr+=QString("c"); atribs_tip += QString("concurrent") + QString(", "); } - if(index->getIndexAttribute(Index::FAST_UPDATE)) + if(index->getIndexAttribute(Index::FastUpdate)) { str_constr+=QString("f"); atribs_tip += QString("fast updated"); } - if(index->getIndexAttribute(Index::BUFFERING)) + if(index->getIndexAttribute(Index::Buffering)) { str_constr+=QString("b"); atribs_tip += QString("buffering"); @@ -360,20 +359,43 @@ void TableObjectView::configureObject(void) { ConstraintType type = constr->getConstraintType(); - if(type == ConstraintType::primary_key) - str_constr = TXT_PRIMARY_KEY; - else if(type == ConstraintType::foreign_key) - str_constr = TXT_FOREIGN_KEY; - else if(type == ConstraintType::unique) - str_constr = TXT_UNIQUE; - else if(type == ConstraintType::exclude) - str_constr = TXT_EXCLUDE; + if(type == ConstraintType::PrimaryKey) + str_constr = TextPrimaryKey; + else if(type == ConstraintType::ForeignKey) + str_constr = TextForeignKey; + else if(type == ConstraintType::Unique) + str_constr = TextUnique; + else if(type == ConstraintType::Exclude) + str_constr = TextExclude; + else if(type == ConstraintType::Check) + str_constr = TextCheck; + + atribs_tip = (~type).toLower(); + } + else if(policy) + { + if(policy->isPermissive()) + { + str_constr += QString("p"); + atribs_tip += QString("permissive"); + } + else + { + str_constr += QString("r"); + atribs_tip += QString("restrictive"); + } + + atribs_tip += QString(", "); + str_constr += (~policy->getPolicyCommand()).toLower().at(0); + atribs_tip += (~policy->getPolicyCommand()).toLower(); } if(!str_constr.isEmpty()) - lables[2]->setText(CONSTR_DELIM_START + QString(" ") + + lables[2]->setText(ConstrDelimStart + QString(" ") + str_constr + QString(" ") + - CONSTR_DELIM_END); + ConstrDelimEnd); + else + lables[2]->setText(QString()); } if(!atribs_tip.isEmpty()) @@ -381,24 +403,19 @@ void TableObjectView::configureObject(void) if(atribs_tip.at(atribs_tip.length()-1)==' ') atribs_tip.remove(atribs_tip.length()-2, 2); - atribs_tip=QString("\n") + CONSTR_DELIM_START + - QString(" ") + atribs_tip + QString(" ") + CONSTR_DELIM_END; + atribs_tip=QString("\n") + ConstrDelimStart + + QString(" ") + atribs_tip + QString(" ") + ConstrDelimEnd; + } + if(!tab_obj->getComment().isEmpty()) + atribs_tip += QString("\n---\n%1").arg(tab_obj->getComment()); + lables[2]->setFont(fmt.font()); lables[2]->setBrush(fmt.foreground()); lables[2]->setPos(px, 0); - //Calculating the object bounding rect that is composed by the join of the all object's child dimensions - descriptor->setPos(HORIZ_SPACING, lables[0]->boundingRect().center().y() - descriptor->boundingRect().center().y()); - bounding_rect.setTopLeft(QPointF(descriptor->boundingRect().left(), lables[0]->boundingRect().top())); - - //Special case: when the constraint label has no text use the type label dimension - if(lables[2]->boundingRect().width()==0) - bounding_rect.setBottomRight(QPointF(lables[1]->boundingRect().right(), lables[0]->boundingRect().bottom())); - else - bounding_rect.setBottomRight(QPointF(lables[2]->boundingRect().right(), lables[0]->boundingRect().bottom())); - + calculateBoundingRect(); this->setToolTip(tooltip + atribs_tip); } } @@ -410,24 +427,34 @@ void TableObjectView::configureObject(Reference reference) QString str_aux; configureDescriptor(); - descriptor->setPos(HORIZ_SPACING, 1); - px=descriptor->pos().x() + descriptor->boundingRect().width() + (2 * HORIZ_SPACING); + descriptor->setPos(HorizSpacing, 0); + px=descriptor->pos().x() + descriptor->boundingRect().width() + (2 * HorizSpacing); - if(reference.getReferenceType()==Reference::REFER_COLUMN) + if(reference.getReferenceType()==Reference::ReferColumn) { //Configures the name label as: [table].[column] - fmt=font_config[ParsersAttributes::REF_TABLE]; - lables[0]->setText(reference.getTable()->getName() + "."); + fmt=font_config[Attributes::RefTable]; + + if(compact_view && !reference.getReferenceAlias().isEmpty()) + lables[0]->setText(reference.getReferenceAlias()); + else + lables[0]->setText(reference.getTable()->getName() + "."); + lables[0]->setFont(fmt.font()); lables[0]->setBrush(fmt.foreground()); lables[0]->setPos(px, 0); px+=lables[0]->boundingRect().width(); - fmt=font_config[ParsersAttributes::REF_COLUMN]; - if(reference.getColumn()) - lables[1]->setText(reference.getColumn()->getName()); + fmt=font_config[Attributes::RefColumn]; + if(compact_view && !reference.getReferenceAlias().isEmpty()) + lables[1]->setText(QString()); else - lables[1]->setText("*"); + { + if(reference.getColumn()) + lables[1]->setText(reference.getColumn()->getName()); + else + lables[1]->setText("*"); + } lables[1]->setFont(fmt.font()); lables[1]->setBrush(fmt.foreground()); @@ -436,11 +463,15 @@ void TableObjectView::configureObject(Reference reference) } else { - fmt=font_config[ParsersAttributes::REF_TABLE]; + fmt=font_config[Attributes::RefTable]; + str_aux = compact_view && !reference.getReferenceAlias().isEmpty() ? reference.getReferenceAlias() : QString(); - str_aux=reference.getExpression().simplified().mid(0,25); - if(reference.getExpression().size() > 25) str_aux+=QString("..."); - str_aux.replace(QString("\n"), QString(" ")); + if(str_aux.isEmpty()) + { + str_aux=reference.getExpression().simplified().mid(0,25); + if(reference.getExpression().size() > 25) str_aux+=QString("..."); + str_aux.replace(QString("\n"), QString(" ")); + } lables[0]->setText(str_aux); lables[0]->setFont(fmt.font()); @@ -451,51 +482,117 @@ void TableObjectView::configureObject(Reference reference) } //Configures a label for the alias (if there is one) - if((reference.getColumn() && !reference.getColumnAlias().isEmpty()) || - (!reference.getAlias().isEmpty() && reference.getReferenceType()==Reference::REFER_EXPRESSION)) + if(!compact_view && + ((reference.getColumn() && !reference.getColumnAlias().isEmpty()) || + (!reference.getAlias().isEmpty() && reference.getReferenceType()==Reference::ReferExpression))) { - if(reference.getReferenceType()==Reference::REFER_EXPRESSION) + if(reference.getReferenceType()==Reference::ReferExpression) str_aux=reference.getAlias(); else str_aux=reference.getColumnAlias(); str_aux=QString(" (") + str_aux + QString(") "); - fmt=font_config[ParsersAttributes::ALIAS]; + fmt=font_config[Attributes::Alias]; lables[2]->setText(str_aux); lables[2]->setFont(fmt.font()); lables[2]->setBrush(fmt.foreground()); lables[2]->setPos(px, 0); } + else + lables[2]->setText(QString()); - descriptor->setPos(HORIZ_SPACING, lables[0]->boundingRect().center().y() - descriptor->boundingRect().center().y()); - bounding_rect.setTopLeft(QPointF(descriptor->pos().x(), lables[0]->pos().y())); + calculateBoundingRect(); +} - if(lables[2]->text().isEmpty()) - bounding_rect.setBottomRight(QPointF(lables[1]->boundingRect().right(), lables[0]->boundingRect().bottom())); +void TableObjectView::configureObject(const SimpleColumn &col) +{ + QTextCharFormat fmt; + double px; + + configureDescriptor(); + descriptor->setPos(HorizSpacing, 0); + px=descriptor->pos().x() + descriptor->boundingRect().width() + (2 * HorizSpacing); + + fmt = font_config[Attributes::Column]; + + if(compact_view && !col.alias.isEmpty()) + lables[0]->setText(col.alias); else - bounding_rect.setBottomRight(QPointF(lables[2]->boundingRect().right(), lables[0]->boundingRect().bottom())); + lables[0]->setText(col.name); + + lables[0]->setFont(fmt.font()); + lables[0]->setBrush(fmt.foreground()); + lables[0]->setPos(px, 0); + px+=lables[0]->boundingRect().width() + (4 * HorizSpacing); + + if(!compact_view && !col.type.isEmpty()) + { + fmt=font_config[Attributes::ObjectType]; + lables[1]->setText(col.type); + lables[1]->setFont(fmt.font()); + lables[1]->setBrush(fmt.foreground()); + lables[1]->setPos(px, 0); + px+=lables[1]->boundingRect().width() + (4 * HorizSpacing); + } + else + lables[1]->setText(QString()); + + lables[2]->setText(QString()); + calculateBoundingRect(); } void TableObjectView::setChildObjectXPos(unsigned obj_idx, double px) { if(obj_idx >= 4) - throw Exception(ERR_REF_OBJ_INV_INDEX, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex, __PRETTY_FUNCTION__, __FILE__, __LINE__); if(obj_idx==0) descriptor->setPos(px, descriptor->pos().y()); else lables[obj_idx-1]->setPos(px, lables[obj_idx-1]->pos().y()); + + calculateBoundingRect(); +} + +void TableObjectView::calculateBoundingRect(void) +{ + double width = 0, height = 0, curr_w = 0, py = 0; + + width = descriptor->pos().x() + descriptor->boundingRect().width(); + height = lables[0]->boundingRect().height(); + + for(int i = 0; i < 3; i++) + { + if(lables[i]->text().isEmpty()) + continue; + + curr_w = lables[i]->pos().x() + lables[i]->boundingRect().width(); + + if(width < curr_w) + width = lables[i]->pos().x() + lables[i]->boundingRect().width(); + } + + bounding_rect = QRectF(QPointF(0,0), QSizeF(width + (4 * HorizSpacing), height + VertSpacing * 0.80)); + + //Adjusting the Y position of the objects in order to center them on the new bouding rect + descriptor->setPos(descriptor->pos().x(), + (bounding_rect.height() - descriptor->boundingRect().height() + (VertSpacing * 0.4))/2); + + py = (bounding_rect.height() - lables[0]->boundingRect().height())/2; + + for(unsigned i = 0; i < 3; i++) + lables[i]->setPos(lables[i]->pos().x(), py); } QGraphicsItem *TableObjectView::getChildObject(unsigned obj_idx) { - if(obj_idx >= 4) - throw Exception(ERR_REF_OBJ_INV_INDEX, __PRETTY_FUNCTION__, __FILE__, __LINE__); + if(obj_idx > ConstrAliasLabel) + throw Exception(ErrorCode::RefObjectInvalidIndex, __PRETTY_FUNCTION__, __FILE__, __LINE__); - if(obj_idx==0) + if(obj_idx == ObjDescriptor) return(descriptor); else - return(lables[obj_idx-1]); + return(lables[obj_idx - 1]); } QString TableObjectView::getConstraintString(Column *column) @@ -508,8 +605,8 @@ QString TableObjectView::getConstraintString(Column *column) vector::iterator itr,itr_end; ConstraintType constr_type; - itr=table->getObjectList(OBJ_CONSTRAINT)->begin(); - itr_end=table->getObjectList(OBJ_CONSTRAINT)->end(); + itr=table->getObjectList(ObjectType::Constraint)->begin(); + itr_end=table->getObjectList(ObjectType::Constraint)->end(); while(itr!=itr_end) { @@ -517,35 +614,117 @@ QString TableObjectView::getConstraintString(Column *column) itr++; //Check if the column is referecend by the constraint - if((constr->getConstraintType()!=ConstraintType::exclude && constr->isColumnExists(column, Constraint::SOURCE_COLS)) || - (constr->getConstraintType()==ConstraintType::exclude && constr->isColumnReferenced(column, false))) + if((constr->getConstraintType()!=ConstraintType::Exclude && constr->isColumnExists(column, Constraint::SourceCols)) || + (constr->getConstraintType()==ConstraintType::Exclude && constr->isColumnReferenced(column, false))) { constr_type=constr->getConstraintType(); - if(constr_type==ConstraintType::primary_key) - str_constr=TXT_PRIMARY_KEY + CONSTR_SEPARATOR + str_constr; + if(constr_type==ConstraintType::PrimaryKey) + str_constr=TextPrimaryKey + ConstrSeparator + str_constr; - if(constr_type==ConstraintType::foreign_key && str_constr.indexOf(TXT_FOREIGN_KEY) < 0) - str_constr+=TXT_FOREIGN_KEY + CONSTR_SEPARATOR; + if(constr_type==ConstraintType::ForeignKey && str_constr.indexOf(TextForeignKey) < 0) + str_constr+=TextForeignKey + ConstrSeparator; - if(constr_type==ConstraintType::unique && str_constr.indexOf(TXT_UNIQUE) < 0) - str_constr+=TXT_UNIQUE + CONSTR_SEPARATOR; + if(constr_type==ConstraintType::Unique && str_constr.indexOf(TextUnique) < 0) + str_constr+=TextUnique + ConstrSeparator; - if(constr_type==ConstraintType::exclude && str_constr.indexOf(TXT_EXCLUDE) < 0) - str_constr+=TXT_EXCLUDE + CONSTR_SEPARATOR; + if(constr_type==ConstraintType::Exclude && str_constr.indexOf(TextExclude) < 0) + str_constr+=TextExclude + ConstrSeparator; } } - if(column->isNotNull() && !str_constr.contains(TXT_PRIMARY_KEY)) - str_constr+=TXT_NOT_NULL + CONSTR_SEPARATOR; + if(column->isNotNull() && !str_constr.contains(TextPrimaryKey)) + str_constr+=TextNotNull + ConstrSeparator; if(!str_constr.isEmpty()) - str_constr= CONSTR_DELIM_START + - CONSTR_SEPARATOR + str_constr + - CONSTR_DELIM_END; + str_constr= ConstrDelimStart + ConstrSeparator + str_constr + ConstrDelimEnd; return(str_constr); } else return(QString()); } +void TableObjectView::setFakeSelection(bool value) +{ + // Fake selection is used only by instances that own and underlying object (column, constratin, trigger,etc) + if(!this->getUnderlyingObject()) + return; + + fake_selection = value; + + if(value) + { + configureObjectSelection(); + sel_order=++BaseObjectView::global_sel_order; + } + else + sel_order = 0; + + update(); +} + +bool TableObjectView::hasFakeSelection(void) +{ + return(fake_selection); +} + +void TableObjectView::configureObjectSelection(void) +{ + QGraphicsItem *parent = this->parentItem(); + RoundedRectItem *rect_item=nullptr; + QRectF rect = this->boundingRect(); + + /* In order to avoid unnecessary memory usage by items that eventually will + * get selection we allocate the object selection rectangle only if the object + * itself is selected by the user, and it'll be allocated until the object's destruction */ + if(!obj_selection) + obj_selection=new RoundedRectItem; + + rect_item = dynamic_cast(obj_selection); + rect.setX(0); + rect.setY(0); + rect.setHeight(rect.height() - VertSpacing); + + // An small hack to capture the width of the table in which the item is child of + if(parent->parentItem()) + rect.setWidth(parent->parentItem()->boundingRect().width() - (2.5 * HorizSpacing)); + else + rect.setWidth(rect.width() - (3.5 * HorizSpacing)); + + rect_item->setBorderRadius(2); + rect_item->setRect(rect); + rect_item->setPos(0, VertSpacing/2); + rect_item->setBrush(this->getFillStyle(Attributes::ObjSelection)); + rect_item->setPen(this->getBorderStyle(Attributes::ObjSelection)); +} + +void TableObjectView::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + painter->save(); + painter->translate(descriptor->pos()); + descriptor->paint(painter, option, widget); + painter->restore(); + + for(int i = 0 ; i < 3; i++) + { + if(lables[i]->text().isEmpty()) + continue; + + painter->save(); + painter->translate(lables[i]->pos()); + lables[i]->paint(painter, option, widget); + painter->restore(); + } + + if(fake_selection) + { + painter->translate(obj_selection->pos()); + obj_selection->paint(painter, option, widget); + } +} + +QRectF TableObjectView::boundingRect(void) const +{ + return(bounding_rect); +} + diff --git a/libobjrenderer/src/tableobjectview.h b/libobjrenderer/src/tableobjectview.h index c4838a520f..4077462b02 100644 --- a/libobjrenderer/src/tableobjectview.h +++ b/libobjrenderer/src/tableobjectview.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -37,6 +37,8 @@ class TableObjectView: public BaseObjectView //! \brief Table object descriptor QGraphicsItem *descriptor; + bool fake_selection; + //! \brief Labels used to show objects informatoni (name, type, constraints/aliases) QGraphicsSimpleTextItem *lables[3]; @@ -44,24 +46,31 @@ class TableObjectView: public BaseObjectView The constraint type parameter is only used when the source object is a column and is used to format the descriptor indication that the column has a constraint */ - void configureDescriptor(ConstraintType constr_type=BaseType::null); + void configureDescriptor(ConstraintType constr_type=BaseType::Null); QVariant itemChange(GraphicsItemChange, const QVariant &value) { return(value); } + void calculateBoundingRect(void); + public: - static const QString CONSTR_DELIM_END, - CONSTR_DELIM_START, - TYPE_SEPARATOR, - CONSTR_SEPARATOR, - TXT_FOREIGN_KEY, - TXT_NOT_NULL, - TXT_PRIMARY_KEY, - TXT_UNIQUE, - TXT_CHECK, - TXT_EXCLUDE; + static const QString ConstrDelimEnd, + ConstrDelimStart, + TypeSeparator, + ConstrSeparator, + TextForeignKey, + TextNotNull, + TextPrimaryKey, + TextUnique, + TextCheck, + TextExclude; + + static constexpr unsigned ObjDescriptor = 0, + NameLabel = 1, + TypeLabel = 2, + ConstrAliasLabel = 3; TableObjectView(TableObject *object=nullptr); ~TableObjectView(void); @@ -69,6 +78,9 @@ class TableObjectView: public BaseObjectView //! \brief Configures the object as a view reference void configureObject(Reference reference); + //! \brief Configures a item from a SimpleColumn instance + void configureObject(const SimpleColumn &col); + //! \brief Configures the object as a table object void configureObject(void); @@ -81,6 +93,15 @@ class TableObjectView: public BaseObjectView /*! \brief Returns a formatted string containing the keywords indicating the constraints that is applyed to the passed column */ static QString getConstraintString(Column *column); + + void setFakeSelection(bool value); + bool hasFakeSelection(void); + + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr); + + virtual QRectF boundingRect(void) const; + virtual void configureObjectSelection(void); + void configureObjectShadow(void) = delete; }; #endif diff --git a/libobjrenderer/src/tabletitleview.cpp b/libobjrenderer/src/tabletitleview.cpp index ed7e1c71dc..533eef5cad 100644 --- a/libobjrenderer/src/tabletitleview.cpp +++ b/libobjrenderer/src/tabletitleview.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -26,21 +26,13 @@ TableTitleView::TableTitleView(void) : BaseObjectView(nullptr) obj_name=new QGraphicsSimpleTextItem; obj_name->setZValue(1); - //box=new QGraphicsPolygonItem; box=new RoundedRectItem; - box->setRoundedCorners(RoundedRectItem::TOPLEFT_CORNER | RoundedRectItem::TOPRIGHT_CORNER); + box->setRoundedCorners(RoundedRectItem::TopLeftCorner | RoundedRectItem::TopRightCorner); box->setZValue(0); - - this->addToGroup(box); - this->addToGroup(schema_name); - this->addToGroup(obj_name); } TableTitleView::~TableTitleView(void) { - this->removeFromGroup(schema_name); - this->removeFromGroup(obj_name); - this->removeFromGroup(box); delete(schema_name); delete(obj_name); delete(box); @@ -51,32 +43,35 @@ void TableTitleView::configureObject(BaseGraphicObject *object) QTextCharFormat fmt; QString name_attrib, schema_name_attrib, title_color_attrib; QPen pen; - Schema *schema=dynamic_cast(object->getSchema()); + Schema *schema=nullptr; QFont font; - Tag *tag=dynamic_cast(object)->getTag(); + Tag *tag=nullptr; + Table *table = dynamic_cast
(object); //Raises an error if the object related to the title is not allocated if(!object) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject, __PRETTY_FUNCTION__, __FILE__, __LINE__); //Raises an error if the object is invalid - else if(object->getObjectType()!=OBJ_TABLE && - object->getObjectType()!=OBJ_VIEW) - throw Exception(ERR_OPR_OBJ_INV_TYPE, __PRETTY_FUNCTION__, __FILE__, __LINE__); + else if(object->getObjectType()!=ObjectType::Table && + object->getObjectType()!=ObjectType::View) + throw Exception(ErrorCode::OprObjectInvalidType, __PRETTY_FUNCTION__, __FILE__, __LINE__); + + schema=dynamic_cast(object->getSchema()); + tag=dynamic_cast(object)->getTag(); - if(object->getObjectType()==OBJ_VIEW && !tag) + if(object->getObjectType()==ObjectType::View && !tag) { - name_attrib=ParsersAttributes::VIEW_NAME; - schema_name_attrib=ParsersAttributes::VIEW_SCHEMA_NAME; - title_color_attrib=ParsersAttributes::VIEW_TITLE; + name_attrib=Attributes::ViewName; + schema_name_attrib=Attributes::ViewSchemaName; + title_color_attrib=Attributes::ViewTitle; } else { - name_attrib=ParsersAttributes::TABLE_NAME; - schema_name_attrib=ParsersAttributes::TABLE_SCHEMA_NAME; - title_color_attrib=ParsersAttributes::TABLE_TITLE; + name_attrib=Attributes::TableName; + schema_name_attrib=Attributes::TableSchemaName; + title_color_attrib=Attributes::TableTitle; } - //Strike out the table name when its sql is disabled fmt=font_config[schema_name_attrib]; font=fmt.font(); schema_name->setFont(font); @@ -84,18 +79,23 @@ void TableTitleView::configureObject(BaseGraphicObject *object) if(!tag) schema_name->setBrush(fmt.foreground()); else - schema_name->setBrush(tag->getElementColor(schema_name_attrib, Tag::FILL_COLOR1)); + schema_name->setBrush(tag->getElementColor(schema_name_attrib, Tag::FillColor1)); if(schema->isRectVisible()) schema_name->setText(QString(" ")); else - schema_name->setText(schema->getName() + QString(".")); + { + if(compact_view && !schema->getAlias().isEmpty()) + schema_name->setText(schema->getAlias() + QString(".")); + else + schema_name->setText(schema->getName() + QString(".")); + } fmt=font_config[name_attrib]; font=fmt.font(); obj_name->setFont(font); - obj_name->setText(object->getName()); + obj_name->setText(compact_view && !object->getAlias().isEmpty() ? object->getAlias() : object->getName()); if(!tag) { @@ -104,42 +104,55 @@ void TableTitleView::configureObject(BaseGraphicObject *object) } else { - obj_name->setBrush(tag->getElementColor(name_attrib, Tag::FILL_COLOR1)); + obj_name->setBrush(tag->getElementColor(name_attrib, Tag::FillColor1)); box->setBrush(tag->getFillStyle(title_color_attrib)); } pen=this->getBorderStyle(title_color_attrib); if(tag) - pen.setColor(tag->getElementColor(title_color_attrib, Tag::BORDER_COLOR)); + pen.setColor(tag->getElementColor(title_color_attrib, Tag::BorderColor)); - if(object->getObjectType()==OBJ_VIEW) + if(object->getObjectType()==ObjectType::View || (table && table->isPartition())) pen.setStyle(Qt::DashLine); box->setPen(pen); if(schema->isRectVisible()) - this->resizeTitle(obj_name->boundingRect().width() + (2 * HORIZ_SPACING), - obj_name->boundingRect().height() + (2 * VERT_SPACING)); + this->resizeTitle(obj_name->boundingRect().width() + (2 * HorizSpacing), + obj_name->boundingRect().height() + (2 * VertSpacing)); else - this->resizeTitle(obj_name->boundingRect().width() + schema_name->boundingRect().width() + (2 * HORIZ_SPACING), - schema_name->boundingRect().height() + (2 * VERT_SPACING)); + this->resizeTitle(obj_name->boundingRect().width() + schema_name->boundingRect().width() + (2 * HorizSpacing), + schema_name->boundingRect().height() + (2 * VertSpacing)); } void TableTitleView::resizeTitle(double width, double height) { + double py = height / 1.5; + + box->setPos(0,0); box->setRect(QRectF(0,0, width, height)); if(schema_name->text()==QString(" ")) - obj_name->setPos((box->boundingRect().width() - obj_name->boundingRect().width())/2.0f, VERT_SPACING); + obj_name->setPos((box->boundingRect().width() - obj_name->boundingRect().width())/2.0, py); else { - schema_name->setPos((box->boundingRect().width() - (schema_name->boundingRect().width() + obj_name->boundingRect().width()))/2.0f, VERT_SPACING); - obj_name->setPos(schema_name->pos().x() + schema_name->boundingRect().width(), VERT_SPACING); - obj_name->setPos(schema_name->pos().x() + schema_name->boundingRect().width(), VERT_SPACING); + schema_name->setPos((box->boundingRect().width() - (schema_name->boundingRect().width() + obj_name->boundingRect().width()))/2.0, py); + obj_name->setPos(schema_name->pos().x() + schema_name->boundingRect().width(), py); } - this->bounding_rect.setTopLeft(this->pos()); this->bounding_rect.setSize(QSizeF(box->boundingRect().width(), box->boundingRect().height())); } +void TableTitleView::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + box->paint(painter, option, widget); + + painter->setFont(schema_name->font()); + painter->setPen(schema_name->brush().color()); + painter->drawText(schema_name->pos(), schema_name->text()); + + painter->setFont(obj_name->font()); + painter->setPen(obj_name->brush().color()); + painter->drawText(obj_name->pos(), obj_name->text()); +} diff --git a/libobjrenderer/src/tabletitleview.h b/libobjrenderer/src/tabletitleview.h index dbcdb00514..e2891e918e 100644 --- a/libobjrenderer/src/tabletitleview.h +++ b/libobjrenderer/src/tabletitleview.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -36,8 +36,7 @@ class TableTitleView: public BaseObjectView private: Q_OBJECT - //! \brief Polygonal object that defines the title border - //QGraphicsPolygonItem *box; + //! \brief Rounded rectangle object that defines the title border RoundedRectItem *box; //! \brief Graphical texts that is used to store the object name and schema name @@ -52,6 +51,8 @@ class TableTitleView: public BaseObjectView void configureObject(BaseGraphicObject *object); void resizeTitle(double width, double height); + + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr); }; #endif diff --git a/libobjrenderer/src/tableview.cpp b/libobjrenderer/src/tableview.cpp index 8385f31e29..2b6e1119d9 100644 --- a/libobjrenderer/src/tableview.cpp +++ b/libobjrenderer/src/tableview.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -26,9 +26,19 @@ TableView::TableView(Table *table) : BaseTableView(table) void TableView::configureObject(void) { - Table *table=dynamic_cast
(this->getSourceObject()); + /* If the table isn't visible we abort the current configuration + * and mark its geometry update as pending so in the next call to + * setVisible(true) the geometry can be updated (see BaseObjectView::itemChange()) */ + if(!this->isVisible()) + { + pending_geom_update = true; + return; + } + + Table *table=dynamic_cast
(this->getUnderlyingObject()); int i, count, obj_idx; double width=0, px=0, cy=0, old_width=0, old_height=0; + unsigned start_col = 0, end_col = 0, start_ext = 0, end_ext = 0; QPen pen; TableObjectView *col_item=nullptr; QList subitems; @@ -36,14 +46,43 @@ void TableView::configureObject(void) TableObject *tab_obj=nullptr; QGraphicsItemGroup *groups[]={ columns, ext_attribs }; RoundedRectItem *bodies[]={ body, ext_attribs_body }; - vector tab_objs; - QString atribs[]={ ParsersAttributes::TABLE_BODY, ParsersAttributes::TABLE_EXT_BODY }; + vector tab_objs, columns, ext_tab_objs; + QString atribs[]={ Attributes::TableBody, Attributes::TableExtBody }; Tag *tag=table->getTag(); + CollapseMode collapse_mode = table->getCollapseMode(); + ObjectType ext_types[5] = { ObjectType::Constraint, + ObjectType::Trigger, ObjectType::Index, + ObjectType::Rule, ObjectType::Policy }; + bool has_col_pag = false, has_ext_pag = false; + + + // Clear the selected children objects vector since we'll (re)configure the whole table + sel_child_objs.clear(); //Configures the table title title->configureObject(table); - px=0; + // We store the columns in a separated vector in order to paginate them (if enabled) + columns.assign(table->getObjectList(ObjectType::Column)->begin(), + table->getObjectList(ObjectType::Column)->end()); + + // We store the extended attributes in a separated vector in order to paginate them (if enabled) + for(unsigned idx = 0; idx < 5; idx++) + { + ext_tab_objs.insert(ext_tab_objs.end(), + table->getObjectList(ext_types[idx])->begin(), + table->getObjectList(ext_types[idx])->end()); + } + + has_col_pag = configurePaginationParams(BaseTable::AttribsSection, columns.size(), start_col, end_col); + + has_ext_pag = configurePaginationParams(BaseTable::ExtAttribsSection, + collapse_mode != CollapseMode::ExtAttribsCollapsed ? ext_tab_objs.size() : 0, + start_ext, end_ext); + + attribs_toggler->setHasExtAttributes(!hide_ext_attribs && !ext_tab_objs.empty()); + + px=0; old_width=this->bounding_rect.width(); old_height=this->bounding_rect.height(); @@ -53,36 +92,32 @@ void TableView::configureObject(void) if(obj_idx==0) { - tab_objs.assign(table->getObjectList(OBJ_COLUMN)->begin(), - table->getObjectList(OBJ_COLUMN)->end()); + if(collapse_mode != CollapseMode::AllAttribsCollapsed) + { + if(table->isPaginationEnabled() && has_col_pag) + tab_objs.assign(columns.begin() + start_col, columns.begin() + end_col); + else + tab_objs.assign(columns.begin(), columns.end()); + } } else { - tab_objs.assign(table->getObjectList(OBJ_CONSTRAINT)->begin(), - table->getObjectList(OBJ_CONSTRAINT)->end()); - tab_objs.insert(tab_objs.end(), - table->getObjectList(OBJ_TRIGGER)->begin(), - table->getObjectList(OBJ_TRIGGER)->end()); - tab_objs.insert(tab_objs.end(), - table->getObjectList(OBJ_INDEX)->begin(), - table->getObjectList(OBJ_INDEX)->end()); - tab_objs.insert(tab_objs.end(), - table->getObjectList(OBJ_RULE)->begin(), - table->getObjectList(OBJ_RULE)->end()); + if(!hide_ext_attribs && collapse_mode == CollapseMode::NotCollapsed) + { + if(table->isPaginationEnabled() && has_ext_pag) + tab_objs.assign(ext_tab_objs.begin() + start_ext, ext_tab_objs.begin() + end_ext); + else + tab_objs.assign(ext_tab_objs.begin(), ext_tab_objs.end()); + } } //Gets the subitems of the current group subitems=groups[obj_idx]->childItems(); groups[obj_idx]->moveBy(-groups[obj_idx]->scenePos().x(), - -groups[obj_idx]->scenePos().y()); + -groups[obj_idx]->scenePos().y()); count=tab_objs.size(); - - //Special case: if there is no item on extended attributes, the extended body is hidden - if(obj_idx==1) - { - groups[obj_idx]->setVisible(count > 0 && !hide_ext_attribs); - bodies[obj_idx]->setVisible(count > 0 && !hide_ext_attribs); - } + groups[obj_idx]->setVisible(count > 0); + bodies[obj_idx]->setVisible(count > 0); for(i=0; i < count; i++) { @@ -94,20 +129,19 @@ void TableView::configureObject(void) col_item=dynamic_cast(subitems[i]); col_item->setSourceObject(tab_obj); col_item->configureObject(); - col_item->moveBy(-col_item->scenePos().x(), - -col_item->scenePos().y()); + col_item->moveBy(-col_item->scenePos().x(),-col_item->scenePos().y()); } else col_item=new TableObjectView(tab_obj); //Configures the item and set its position col_item->configureObject(); - col_item->moveBy(HORIZ_SPACING, (i * col_item->boundingRect().height()) + VERT_SPACING); + col_item->moveBy(HorizSpacing, (i * col_item->boundingRect().height()) + VertSpacing); /* Calculates the width of the name + type of the object. This is used to align all the constraint labels on table */ - width=col_item->getChildObject(0)->boundingRect().width() + - col_item->getChildObject(1)->boundingRect().width() + (6 * HORIZ_SPACING); + width=col_item->getChildObject(TableObjectView::ObjDescriptor)->boundingRect().width() + + col_item->getChildObject(TableObjectView::NameLabel)->boundingRect().width() + (5 * HorizSpacing); if(px < width) px=width; @@ -133,12 +167,11 @@ void TableView::configureObject(void) col_items.pop_front(); //Positioning the type label - col_item->setChildObjectXPos(2, px); + col_item->setChildObjectXPos(TableObjectView::TypeLabel, px); //Positioning the constraints label - col_item->setChildObjectXPos(3, px + - ((col_item->getChildObject(2)->boundingRect().width() + - col_item->getChildObject(3)->boundingRect().width()) * 0.90)); + col_item->setChildObjectXPos(TableObjectView::ConstrAliasLabel, + px + (col_item->getChildObject(TableObjectView::TypeLabel)->boundingRect().width() * 1.05)); groups[obj_idx]->addToGroup(col_item); } @@ -152,14 +185,17 @@ void TableView::configureObject(void) //Resizes the columns/extended attributes using the new width for(obj_idx=0; obj_idx < 2; obj_idx++) { - bodies[obj_idx]->setRect(QRectF(0,0, width, groups[obj_idx]->boundingRect().height() + (2 * VERT_SPACING))); + bodies[obj_idx]->setRect(QRectF(0,0, width, groups[obj_idx]->boundingRect().height() + (2 * VertSpacing))); pen=this->getBorderStyle(atribs[obj_idx]); + if(table->isPartition()) + pen.setStyle(Qt::DashLine); + if(!tag) bodies[obj_idx]->setBrush(this->getFillStyle(atribs[obj_idx])); else { - pen.setColor(tag->getElementColor(atribs[obj_idx], Tag::BORDER_COLOR)); + pen.setColor(tag->getElementColor(atribs[obj_idx], Tag::BorderColor)); bodies[obj_idx]->setBrush(tag->getFillStyle(atribs[obj_idx])); } @@ -168,9 +204,15 @@ void TableView::configureObject(void) if(obj_idx==0) bodies[obj_idx]->setPos(title->pos().x(), title->boundingRect().height()-1); else - bodies[obj_idx]->setPos(title->pos().x(), - title->boundingRect().height() + - bodies[0]->boundingRect().height() - 2); + { + if(bodies[0]->isVisible()) + bodies[obj_idx]->setPos(title->pos().x(), + title->boundingRect().height() + + bodies[0]->boundingRect().height() - 2); + else + bodies[obj_idx]->setPos(title->pos().x(), title->boundingRect().height()-1); + } + groups[obj_idx]->setPos(bodies[obj_idx]->pos()); subitems=groups[obj_idx]->childItems(); @@ -178,26 +220,36 @@ void TableView::configureObject(void) { col_item=dynamic_cast(subitems.front()); subitems.pop_front(); - col_item->setChildObjectXPos(3, width - - col_item->boundingRect().width() - (2 * HORIZ_SPACING) - 1); - + col_item->setChildObjectXPos(TableObjectView::ConstrAliasLabel, + width - col_item->getChildObject(TableObjectView::ConstrAliasLabel)->boundingRect().width() - (2 * HorizSpacing) - 1); //Generating the connection points of the columns if(obj_idx==0) { - tab_obj=dynamic_cast(col_item->getSourceObject()); + tab_obj=dynamic_cast(col_item->getUnderlyingObject()); cy=title->boundingRect().height() + col_item->pos().y() + (col_item->boundingRect().height()/2); conn_points[tab_obj].resize(2); - conn_points[tab_obj][LEFT_CONN_POINT]=QPointF(col_item->pos().x() - 1.5f, cy); - conn_points[tab_obj][RIGHT_CONN_POINT]=QPointF(col_item->pos().x() + width - 1.5f , cy); + conn_points[tab_obj][LeftConnPoint]=QPointF(col_item->pos().x() - 1.5, cy); + conn_points[tab_obj][RightConnPoint]=QPointF(col_item->pos().x() + width - 1.5 , cy); } } } BaseTableView::__configureObject(width); + + if(table->isPartitioned()) + table_tooltip += QString("\n%1 (%2)").arg(trUtf8("Partitioned")).arg(~table->getPartitioningType()); + + if(table->isPartition()) + table_tooltip += QString("\n%1 of %2").arg(trUtf8("Partition")).arg(table->getPartitionedTable()->getSignature(true)); + + if(!table->getAlias().isEmpty()) + table_tooltip += QString("\nAlias: %1").arg(table->getAlias()); + + if(!table->getComment().isEmpty()) + table_tooltip += QString("\n---\n%1").arg(table->getComment()); + BaseObjectView::__configureObject(); - BaseObjectView::configureObjectShadow(); - BaseObjectView::configureObjectSelection(); configureTag(); configureSQLDisabledInfo(); @@ -211,9 +263,9 @@ void TableView::configureObject(void) QPointF TableView::getConnectionPoints(TableObject *tab_obj, unsigned pnt_type) { if(!tab_obj) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); - else if(pnt_type > RIGHT_CONN_POINT) - throw Exception(ERR_REF_ELEM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(pnt_type > RightConnPoint) + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(conn_points.count(tab_obj)==0) //Returns the center point in case of the connection point of the table object wasn't calculated already return(this->getCenter()); diff --git a/libobjrenderer/src/tableview.h b/libobjrenderer/src/tableview.h index 3825896c14..6e6c400b3e 100644 --- a/libobjrenderer/src/tableview.h +++ b/libobjrenderer/src/tableview.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libobjrenderer/src/textboxview.cpp b/libobjrenderer/src/textboxview.cpp index 4b707fa9f7..4032a18a42 100644 --- a/libobjrenderer/src/textboxview.cpp +++ b/libobjrenderer/src/textboxview.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -26,8 +26,8 @@ TextboxView::TextboxView(Textbox *txtbox, bool override_style) : BaseObjectView( box=new QGraphicsPolygonItem; text=new QGraphicsSimpleTextItem; - box->setZValue(0); - text->setZValue(1); + text_item = new TextPolygonItem; + this->addToGroup(text_item); obj_shadow=new QGraphicsPolygonItem; obj_shadow->setZValue(-1); @@ -39,25 +39,21 @@ TextboxView::TextboxView(Textbox *txtbox, bool override_style) : BaseObjectView( this->addToGroup(obj_selection); this->override_style=override_style; - this->addToGroup(text); - this->addToGroup(box); this->configureObject(); } TextboxView::~TextboxView(void) { - this->removeFromGroup(box); - this->removeFromGroup(text); - delete(box); - delete(text); + this->removeFromGroup(text_item); + delete(text_item); } void TextboxView::setColorStyle(const QBrush &fill_style, const QPen &border_style) { if(override_style) { - box->setBrush(fill_style); - box->setPen(border_style); + text_item->setBrush(fill_style); + text_item->setPen(border_style); } } @@ -65,80 +61,63 @@ void TextboxView::setFontStyle(const QTextCharFormat &fmt) { if(override_style) { - text->setFont(fmt.font()); - text->setBrush(fmt.foreground()); + text_item->setFont(fmt.font()); + text_item->setTextBrush(fmt.foreground()); } } -/*void TextboxView::togglePlaceholder(bool visible) +void TextboxView::setToolTip(const QString &tooltip) { - if(use_placeholder && this->scene()) - { - if(!placeholder_pol->scene()) - this->scene()->addItem(placeholder_pol); - - if(visible) - { - QPen pen=BaseObjectView::getBorderStyle(ParsersAttributes::PLACEHOLDER); - pen.setStyle(Qt::DashLine); - - placeholder_pol->setBrush(BaseObjectView::getFillStyle(ParsersAttributes::PLACEHOLDER)); - placeholder_pol->setPen(pen); - placeholder_pol->setPolygon(box->polygon()); - placeholder_pol->setPos(this->mapToScene(this->bounding_rect.topLeft())); - } - - placeholder_pol->setVisible(visible); - } -}*/ + txtbox_tooltip = tooltip; +} void TextboxView::__configureObject(void) { - Textbox *txtbox=dynamic_cast(this->getSourceObject()); - QTextCharFormat fmt=font_config[ParsersAttributes::GLOBAL]; + Textbox *txtbox=dynamic_cast(this->getUnderlyingObject()); + QTextCharFormat fmt=font_config[Attributes::Global]; QPolygonF polygon; - polygon.append(QPointF(0.0f,0.0f)); - polygon.append(QPointF(1.0f,0.0f)); - polygon.append(QPointF(1.0f,1.0f)); - polygon.append(QPointF(0.0f,1.0f)); + polygon.append(QPointF(0.0,0.0)); + polygon.append(QPointF(1.0,0.0)); + polygon.append(QPointF(1.0,1.0)); + polygon.append(QPointF(0.0,1.0)); if(!override_style) { QFont font; - box->setBrush(this->getFillStyle(BaseObject::getSchemaName(OBJ_TEXTBOX))); - box->setPen(this->getBorderStyle(BaseObject::getSchemaName(OBJ_TEXTBOX))); + + text_item->setBrush(this->getFillStyle(BaseObject::getSchemaName(ObjectType::Textbox))); + text_item->setPen(this->getBorderStyle(BaseObject::getSchemaName(ObjectType::Textbox))); font=fmt.font(); - font.setItalic(txtbox->getTextAttribute(Textbox::ITALIC_TXT)); - font.setBold(txtbox->getTextAttribute(Textbox::BOLD_TXT)); - font.setUnderline(txtbox->getTextAttribute(Textbox::UNDERLINE_TXT)); + font.setItalic(txtbox->getTextAttribute(Textbox::ItalicText)); + font.setBold(txtbox->getTextAttribute(Textbox::BoldText)); + font.setUnderline(txtbox->getTextAttribute(Textbox::UnderlineText)); font.setPointSizeF(txtbox->getFontSize()); - text->setFont(font); - text->setBrush(txtbox->getTextColor()); + text_item->setFont(font); + text_item->setTextBrush(txtbox->getTextColor()); } - text->setText(txtbox->getComment()); + text_item->setText(txtbox->getComment()); + text_item->setTextPos(HorizSpacing * 2, VertSpacing * (text_item->getFont().italic() ? 0.90 : 0.50)); - if(text->font().italic()) - text->setPos(HORIZ_SPACING * 1.5, VERT_SPACING * 0.90); - else - text->setPos(HORIZ_SPACING, VERT_SPACING); + TextPolygonItem::resizePolygon(polygon, round(text_item->getTextBoundingRect().width() + (2.5 * HorizSpacing)), + round(text_item->getTextBoundingRect().height() + (1.5 * VertSpacing))); - this->resizePolygon(polygon, roundf(text->boundingRect().width() + (2.5 * HORIZ_SPACING)), - roundf(text->boundingRect().height() + (1.5 * VERT_SPACING))); + text_item->setPos(0,0); + text_item->setPolygon(polygon); - box->setPos(0,0); - box->setPolygon(polygon); + protected_icon->setPos(text_item->boundingRect().width() + 2 * HorizSpacing, + text_item->boundingRect().height() * 0.70); - protected_icon->setPos(box->boundingRect().right() - (protected_icon->boundingRect().width() + 2 * HORIZ_SPACING), - box->boundingRect().bottom()- (protected_icon->boundingRect().height() + 2 * VERT_SPACING)); - - this->bounding_rect.setTopLeft(box->boundingRect().topLeft()); - this->bounding_rect.setBottomRight(box->boundingRect().bottomRight()); + this->bounding_rect.setTopLeft(text_item->boundingRect().topLeft()); + this->bounding_rect.setBottomRight(text_item->boundingRect().bottomRight()); BaseObjectView::__configureObject(); + + if(!txtbox_tooltip.isEmpty()) + this->BaseObjectView::setToolTip(txtbox_tooltip); } void TextboxView::configureObject(void) @@ -154,7 +133,7 @@ void TextboxView::configureObjectShadow(void) pol_item->setPen(Qt::NoPen); pol_item->setBrush(QColor(50,50,50,60)); - pol_item->setPolygon(box->polygon()); + pol_item->setPolygon(text_item->polygon()); pol_item->setPos(3.5,3.5); } @@ -162,8 +141,8 @@ void TextboxView::configureObjectSelection(void) { QGraphicsPolygonItem *pol_item=dynamic_cast(obj_selection); - pol_item->setPolygon(box->polygon()); + pol_item->setPolygon(text_item->polygon()); pol_item->setPos(0,0); - pol_item->setBrush(this->getFillStyle(ParsersAttributes::OBJ_SELECTION)); - pol_item->setPen(this->getBorderStyle(ParsersAttributes::OBJ_SELECTION)); + pol_item->setBrush(this->getFillStyle(Attributes::ObjSelection)); + pol_item->setPen(this->getBorderStyle(Attributes::ObjSelection)); } diff --git a/libobjrenderer/src/textboxview.h b/libobjrenderer/src/textboxview.h index 2cfa29d7c5..be40509e13 100644 --- a/libobjrenderer/src/textboxview.h +++ b/libobjrenderer/src/textboxview.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -28,6 +28,7 @@ #include "textbox.h" #include "baseobjectview.h" #include "roundedrectitem.h" +#include "textpolygonitem.h" class TextboxView: public BaseObjectView { private: @@ -36,6 +37,8 @@ class TextboxView: public BaseObjectView { //! \brief Indicates the the font / color styles will be overriden (need to call setColorStyle, setFontStyle) bool override_style; + QString txtbox_tooltip; + protected: //! \brief Graphical item that represent the box QGraphicsPolygonItem *box; @@ -43,6 +46,8 @@ class TextboxView: public BaseObjectView { //! \brief Graphical item that represent the text QGraphicsSimpleTextItem *text; + TextPolygonItem *text_item; + //! \brief Configures the shadow for the textbox void configureObjectShadow(void); @@ -64,6 +69,8 @@ class TextboxView: public BaseObjectView { the style can be overriden (via constructor) */ void setFontStyle(const QTextCharFormat &fmt); + void setToolTip(const QString &tooltip); + protected slots: virtual void configureObject(void); }; diff --git a/libobjrenderer/src/textpolygonitem.cpp b/libobjrenderer/src/textpolygonitem.cpp new file mode 100644 index 0000000000..3723fb250d --- /dev/null +++ b/libobjrenderer/src/textpolygonitem.cpp @@ -0,0 +1,98 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "textpolygonitem.h" + +TextPolygonItem::TextPolygonItem(QGraphicsItem *parent) : QGraphicsPolygonItem(parent) +{ + text_item = new QGraphicsSimpleTextItem; +} + +TextPolygonItem::~TextPolygonItem(void) +{ + delete(text_item); +} + +void TextPolygonItem::setText(const QString &text) +{ + text_item->setText(text); +} + +void TextPolygonItem::setTextPen(const QPen &pen) +{ + text_item->setPen(pen); +} + +void TextPolygonItem::setTextBrush(const QBrush &brush) +{ + text_item->setBrush(brush); +} + +QRectF TextPolygonItem::getTextBoundingRect(void) +{ + return(text_item->boundingRect()); +} + +void TextPolygonItem::setTextPos(const QPointF &pos) +{ + text_item->setPos(pos); +} + +void TextPolygonItem::setTextPos(double x, double y) +{ + text_item->setPos(x, y); +} + +void TextPolygonItem::setFont(const QFont &fnt) +{ + text_item->setFont(fnt); +} + +QFont TextPolygonItem::getFont() +{ + return(text_item->font()); +} + +void TextPolygonItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + QGraphicsPolygonItem::paint(painter, option, widget); + + painter->translate(text_item->pos()); + text_item->paint(painter, option, widget); +} + +void TextPolygonItem::resizePolygon(QPolygonF &pol, double width, double height) +{ + QVector::iterator itr,itr_end; + double coef_a, coef_b; + + itr=pol.begin(); + itr_end=pol.end(); + + //Calculates the resize factor + coef_a=width / pol.boundingRect().width(); + coef_b=height / pol.boundingRect().height(); + + //Applies the resize factor to all the polygon points + while(itr!=itr_end) + { + itr->setX(itr->x() * coef_a); + itr->setY(itr->y() * coef_b); + itr++; + } +} diff --git a/libobjrenderer/src/textpolygonitem.h b/libobjrenderer/src/textpolygonitem.h new file mode 100644 index 0000000000..859b96c9cc --- /dev/null +++ b/libobjrenderer/src/textpolygonitem.h @@ -0,0 +1,68 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +/** +\ingroup libobjrenderer +\class TextPolygonItem +\brief This specialization of QGraphicsPolygonItem allows a text to be drawn over a polygonal element +*/ + +#ifndef TEXT_POLYGON_ITEM_H +#define TEXT_POLYGON_ITEM_H + +#include +#include +#include +#include + +class TextPolygonItem : public QGraphicsPolygonItem { + private: + QGraphicsSimpleTextItem *text_item; + + public: + TextPolygonItem(QGraphicsItem *parent = nullptr); + ~TextPolygonItem(void); + + //! \brief Defines the text displayed by the item + void setText(const QString &text); + + //! \brief Defines the position of the text element (in local coordinate) + void setTextPos(const QPointF &pos); + void setTextPos(double x, double y); + + //! \brief Defines the pen used by the text element + void setTextPen(const QPen &pen); + + //! \brief Defines the brush used by the text element + void setTextBrush(const QBrush &brush); + + //! \brief Returns the bounding rect of the text item + QRectF getTextBoundingRect(void); + + //! \brief Sets the font used by the text item + void setFont(const QFont &fnt); + + QFont getFont(void); + + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr); + + //! \brief Resizes to the specified dimension the passed polygon + static void resizePolygon(QPolygonF &pol, double width, double height); +}; + +#endif diff --git a/libparsers/libparsers.pro b/libparsers/libparsers.pro index c79ab53714..0a1d08891d 100644 --- a/libparsers/libparsers.pro +++ b/libparsers/libparsers.pro @@ -16,11 +16,11 @@ windows: DESTDIR = $$PWD HEADERS += src/schemaparser.h \ src/xmlparser.h \ src/attribsmap.h \ - src/parsersattributes.h + src/attributes.h SOURCES += src/schemaparser.cpp \ src/xmlparser.cpp \ - src/parsersattributes.cpp + src/attributes.cpp unix|windows: LIBS += -L$$OUT_PWD/../libutils/ -lutils $$XML_LIB diff --git a/libparsers/src/attribsmap.h b/libparsers/src/attribsmap.h index 39c05b51a7..88e104dd07 100644 --- a/libparsers/src/attribsmap.h +++ b/libparsers/src/attribsmap.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -28,5 +28,5 @@ to store objects attributes and used by SchemaParser, XMLParser and several othe #include #include -typedef std::map attribs_map; +using attribs_map = std::map; #endif diff --git a/libparsers/src/attributes.cpp b/libparsers/src/attributes.cpp new file mode 100644 index 0000000000..ff678d39cc --- /dev/null +++ b/libparsers/src/attributes.cpp @@ -0,0 +1,613 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful), +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also), you can get the complete GNU General Public License at +*/ + +#include "attributes.h" + +namespace Attributes { + const QString + False=QString("false"), + File=QString("file"), + LcCollate=QString("lc-collate"), + LcCtype=QString("lc-ctype"), + True=QString("true"), + ActiveLayers=QString("active-layers"), + AdminOption=QString("admin-option"), + AdminRoles=QString("admin-roles"), + Alias=QString("alias"), + Alignment=QString("alignment"), + AlignObjsToGrid=QString("align-objs-to-grid"), + AlterCmds=QString("alter-cmds"), + AllowConns=QString("allow-conns"), + AnalyzeFunc=QString("analyze"), + AncestorTable=QString("ancestor-table"), + AppendAtEod=QString("append-at-eod"), + AppendedSql=QString("appended-sql"), + Application=QString("application"), + ArgCount=QString("arg-count"), + ArgDefCount=QString("arg-def-count"), + ArgDefaults=QString("arg-defaults"), + ArgModes=QString("arg-modes"), + ArgNames=QString("arg-names"), + ArgTypes=QString("arg-types"), + Arguments=QString("arguments"), + AscOrder=QString("asc-order"), + Assignment=QString("assignment"), + Attribute=QString("attribute"), + AttribsPage=QString("attribs-page"), + AttribsPerPage=QString("attribs-per-page"), + AutoBrowseDb=QString("auto-browse-db"), + AutoSaveInterval=QString("autosave-interval"), + BackgroundColor=QString("background-color"), + BaseType=QString("base"), + Before=QString("before"), + BehaviorType=QString("behavior-type"), + Bold=QString("bold"), + BorderColor=QString("border-color"), + Bottom=QString("bottom"), + Buffering=QString("buffering"), + ByValue=QString("by-value"), + BypassRls=QString("bypassrls"), + Cache=QString("cache"), + CanonicalFunc=QString("canonical"), + CanvasCornerMove=QString("canvas-corner-move"), + Cascade=QString("cascade"), + CaseSensitive=QString("case-sensitive"), + CastType=QString("cast-type"), + Category=QString("category"), + Change=QString("change"), + Changelog=QString("changelog"), + CheckExp=QString("check-exp"), + CheckUpdate=QString("check-update"), + CkConstr=QString("ck-constr"), + ClientEncoding=QString("client-encoding"), + CodeCompletion=QString("code-completion"), + CodeFontSize=QString("code-font-size"), + CodeFont=QString("code-font"), + CodeTabWidth=QString("code-tab-width"), + ColIndexes=QString("col-indexes"), + CollapseMode=QString("collapse-mode"), + Collatable=QString("collatable"), + Collation=QString("collation"), + Collations=QString("collations"), + Color=QString("color"), + Colors=QString("colors"), + ColsComment=QString("cols-comment"), + ColIsIdentity=QString("col-is-identity"), + ColumnAlias=QString("column-alias"), + Column=QString("column"), + Columns=QString("columns"), + Command=QString("command"), + Commands=QString("commands"), + Comment=QString("comment"), + CommutatorOp=QString("commutator-op"), + ComparisonType=QString("comparison-type"), + CompactView=QString("compact-view"), + CompletionTrigger=QString("completion-trigger"), + CompositeType=QString("composite"), + Concurrent=QString("concurrent"), + Condition=QString("condition"), + ConfigFile=QString("config-file"), + Configuration=QString("configuration"), + ConfirmValidation=QString("confirm-validation"), + ConnLimit=QString("connlimit"), + ConnectCenterPnts=QString("center-pnts"), + ConnectFkToPk=QString("fk-to-pk"), + ConnectTableEdges=QString("table-edges"), + ConnectPriv=QString("connect"), + Connection=QString("connection"), + Connections=QString("connections"), + ConnectionTimeout=QString("connection-timeout"), + ConstrIndexes=QString("constr-indexes"), + ConstrSqlDisabled=QString("constr-sql-disabled"), + Constraint=QString("constraint"), + Constraints=QString("constraints"), + ConstrDefs=QString("constr-defs"), + Contents=QString("contents"), + CopyMode=QString("copy-mode"), + CopyOptions=QString("copy-options"), + CopyTable=QString("copy-table"), + CreateCmds=QString("create-cmds"), + CreatePriv=QString("create"), + Create=QString("create"), + CreateDb=QString("createdb"), + CreateRole=QString("createrole"), + CrowsFoot=QString("crows-foot"), + CteExpression=QString("cte-exp"), + CurVersion=QString("cur-version"), + CurIdentityType=QString("cur-identity-type"), + CustomColor=QString("custom-color"), + CustomFilter=QString("custom-filter"), + CustomIdxs=QString("customidxs"), + Cycle=QString("cycle"), + DataDirectory=QString("data-directory"), + Date=QString("date"), + Database=QString("database"), + DbModel=QString("dbmodel"), + DdlEndToken=QString("-- ddl-end --"), + DeadRowsAmount=QString("dead-rows-amount"), + DeclInTable=QString("decl-in-table"), + Declaration=QString("declaration"), + DefaultCollation=QString("default-collation"), + DefaultForOps=QString("default-for-ops"), + DefaultOwner=QString("default-owner"), + DefaultSchema=QString("default-schema"), + DefaultTablespace=QString("default-tablespace"), + DefaultValue=QString("default-value"), + Default=QString("default"), + DeferType=QString("defer-type"), + Deferrable=QString("deferrable"), + Definition=QString("definition"), + DelAction=QString("del-action"), + DelEvent=QString("del-event"), + DeletePriv=QString("delete"), + Delimiter=QString("delimiter"), + DestType=QString("destiny-type"), + DstType=QString("dst-type"), + Diff=QString("diff"), + Dimension=QString("dimension"), + Directory=QString("directory"), + DisableSmoothness=QString("disable-smoothness"), + DisplayLineNumbers=QString("display-line-numbers"), + DomConstraint=QString("domconstraint"), + DockWidgets=QString("dock-widgets"), + DropCmds=QString("drop-cmds"), + Drop=QString("drop"), + DstColPattern=QString("dst-col-pattern"), + DstColumns=QString("dst-columns"), + DstEncoding=QString("dst-encoding"), + DstFkPattern=QString("dst-fk-pattern"), + DstLabel=QString("dst-label"), + DstRequired=QString("dst-required"), + DstTable=QString("dst-table"), + DynamicLibraryPath=QString("dynamic-library-path"), + DynamicSharedMemory=QString("dynamic-shared-memory-type"), + EndExp=QString("end-exp"), + Element=QString("element"), + Elements=QString("elements"), + Encoding=QString("encoding"), + Encrypted=QString("encrypted"), + EnumType=QString("enumeration"), + Enumerations=QString("enumerations"), + EventType=QString("event-type"), + Event=QString("event"), + Events=QString("events"), + ExConstr=QString("ex-constr"), + ExactMatch=QString("exact-match"), + ExcBuiltinArrays=QString("exc-builtin-arrays"), + ExcludeElement=QString("excelement"), + ExecType=QString("exec-type"), + ExecutPriv=QString("execute"), + ExecutionCost=QString("execution-cost"), + ExistingValue=QString("existing-value"), + Explicit=QString("explicit"), + Export=QString("export"), + ExportToFile=QString("export-to-file"), + Expression=QString("expression"), + Expressions=QString("expressions"), + ExtAttribsPage=QString("ext-attribs-page"), + ExtAttribsPerPage=QString("ext-attribs-per-page"), + ExtObjOids=QString("ext-obj-oids"), + Factor=QString("factor"), + FadeInObjects=QString("fadein-objects"), + FadedOut=QString("faded-out"), + Family=QString("family"), + FastUpdate=QString("fast-update"), + Fdw=QString("fdw"), + FileAssociated=QString("file-associated"), + FillColor=QString("fill-color"), + FilterOids=QString("filter-oids"), + FilterTableTypes=QString("filter-tab-types"), + Filter=QString("filter"), + FinalFunc=QString("final"), + FiringType=QString("firing-type"), + FkColumn=QString("fk-column"), + FkConstr=QString("fk-constr"), + FkDefs=QString("fk-defs"), + FontSize=QString("font-size"), + Font=QString("font"), + ForegroundColor=QString("foreground-color"), + ForeignKeys=QString("foreign-keys"), + FormatName=QString("format-name"), + FromExp=QString("from-exp"), + FunctionType=QString("function-type"), + Function=QString("function"), + General=QString("general"), + GenAlterCmds=QString("gen-alter-cmds"), + Global=QString("global"), + GrantOp=QString("grant-op"), + GridSize=QString("grid-size"), + Group=QString("group"), + HandlerFunc=QString("handler"), + HandlesType=QString("handles-type"), + HasChanges=QString("has-changes"), + Hashes=QString("hashes"), + HbaFile=QString("hba-file"), + Height=QString("height"), + HideExtAttribs=QString("hide-ext-attribs"), + HideRelName=QString("hide-rel-name"), + HideTableTags=QString("hide-table-tags"), + HighlightLines=QString("highlight-lines"), + HighlightOrder=QString("highlight-order"), + HistoryMaxLength=QString("history-max-length"), + Icon=QString("icon"), + Id=QString("id"), + Identifier=QString("identifier"), + IdentityType=QString("identity-type"), + IdentFile=QString("ident-file"), + IgnoredChars=QString("ignored-chars"), + Implicit=QString("implicit"), + Import=QString("import"), + Increment=QString("increment"), + IndexElement=QString("idxelement"), + IndexType=QString("index-type"), + Index=QString("index"), + Indexes=QString("indexes"), + Info=QString("info"), + InhColumn=QString("inh-column"), + InhColumns=QString("inh-columns"), + Inherit=QString("inherit"), + Inherited=QString("inherited"), + InitialCond=QString("initial-cond"), + InitialData=QString("initial-data"), + InitialExp=QString("initial-exp"), + InlineFunc=QString("inline"), + InputFunc=QString("input"), + InsEvent=QString("ins-event"), + InsertPriv=QString("insert"), + InternalLength=QString("internal-length"), + IntervalType=QString("interval-type"), + InvertRangeSelTrigger=QString("invert-rangesel-trigger"), + IsTemplate=QString("is-template"), + IsPartitioned=QString("is-partitioned"), + IoCast=QString("io-cast"), + Italic=QString("italic"), + JoinFunc=QString("join"), + Label=QString("label"), + LabelsPos=QString("labels-pos"), + Landscape=QString("landscape"), + Language=QString("language"), + LastPosition=QString("last-position"), + LastSysOid=QString("last-sys-oid"), + LastValue=QString("last-value"), + LastZoom=QString("last-zoom"), + LastAnalyze=QString("last-analyze"), + LastAutovacuum=QString("last-autovacuum"), + LastVacuum=QString("last-vacuum"), + LeakProof=QString("leakproof"), + Layer=QString("layer"), + Layers=QString("layers"), + LeftType=QString("left-type"), + Left=QString("left"), + Length=QString("length"), + Library=QString("library"), + LikeType=QString("like-type"), + Line=QString("line"), + LineNumbersColor=QString("line-numbers-color"), + LineNumbersBgColor=QString("line-numbers-bg-color"), + LineHighlightColor=QString("line-highlight-color"), + ListenAddresses=QString("listen-addresses"), + Locale=QString("locale"), + LockerArc=QString("locker-arc"), + LockerBody=QString("locker-body"), + Login=QString("login"), + LookaheadChar=QString("lookahead-char"), + LowVerbosity=QString("low-verbosity"), + Materialized=QString("materialized"), + MaxConnections=QString("max-connections"), + MaxObjCount=QString("max-obj-count"), + MaxValue=QString("max-value"), + Maximized=QString("maximized"), + MemberRoles=QString("member-roles"), + Member=QString("member"), + Merges=QString("merges"), + Metadata=QString("metadata"), + MinObjectOpacity=QString("min-object-opacity"), + MinValue=QString("min-value"), + Mode=QString("mode"), + ModelAuthor=QString("author"), + NameLabel=QString("name-label"), + NamePatterns=QString("name-patterns"), + Name=QString("name"), + Names=QString("names"), + NegatorOp=QString("negator-op"), + NewName=QString("new-name"), + NewTableName=QString("new-table-name"), + NewIdentityType=QString("new-identity-type"), + NewVersion=QString("new-version"), + NnColumn=QString("nn-column"), + NoInherit=QString("no-inherit"), + None=QString("none"), + NotExtObject=QString("not-ext-object"), + NotNull=QString("not-null"), + NullsFirst=QString("nulls-first"), + ObjSelection=QString("obj-selection"), + ObjectId=QString("object-id"), + ObjectFinder=QString("objectfinder"), + ObjectType=QString("object-type"), + Object=QString("object"), + Objects=QString("objects"), + OidFilterOp=QString("oid-filter-op"), + Oid=QString("oid"), + Oids=QString("oids"), + OldName=QString("old-name"), + OldTableName=QString("old-table-name"), + OldVersion=QString("old-version"), + OpClass=QString("opclass"), + OpClasses=QString("opclasses"), + OpFamily=QString("opfamily"), + OpListSize=QString("op-list-size"), + OperatorFunc=QString("operfunc"), + Operator=QString("operator"), + Operators=QString("operators"), + Options=QString("options"), + OriginalPk=QString("original-pk"), + OutputFunc=QString("output"), + OwnerColumn=QString("owner-col"), + Owner=QString("owner"), + Pagination=QString("pagination"), + PaperCustomSize=QString("paper-custom-size"), + PaperMargin=QString("paper-margin"), + PaperOrientation=QString("paper-orientation"), + PaperType=QString("paper-type"), + ParamIn=QString("in"), + ParamOut=QString("out"), + ParamVariadic=QString("variadic"), + Parameter=QString("parameter"), + Parameters=QString("parameters"), + Parent=QString("parent"), + Parents=QString("parents"), + Parsable=QString("parsable"), + PartialMatch=QString("partial-match"), + PartitionKey=QString("partitionkey"), + PartitionBoundExpr=QString("partition-bound-expr"), + PartitionedTable=QString("partitioned-table"), + Partitioning=QString("partitioning"), + PartKeyCols=QString("part-key-cols"), + PartKeyColls=QString("part-key-colls"), + PartKeyOpCls=QString("part-key-opcls"), + PartKeyExprs=QString("part-key-exprs"), + Password=QString("password"), + PasswordEncryption=QString("password-encryption"), + Path=QString("path"), + Patterns=QString("patterns"), + PerRow=QString("per-line"), + Permission=QString("permission"), + Permissive=QString("permissive"), + PgModelerVersion=QString("pgmodeler-ver"), + PgSqlBaseType=QString("basetype"), + PgSqlVersion=QString("pgsql-ver"), + Placeholder=QString("placeholder"), + Placeholders=QString("placeholders"), + PkColPattern=QString("pk-col-pattern"), + PkColumn=QString("pk-column"), + PkConstr=QString("pk-constr"), + PkPattern=QString("pk-pattern"), + Points=QString("points"), + Port=QString("port"), + Portrait=QString("portrait"), + PositionInfo=QString("pos-info"), + Position=QString("position"), + Precision=QString("precision"), + Predicate=QString("predicate"), + Preferred=QString("preferred"), + PrependAtBod=QString("prepend-at-bod"), + PrependedSql=QString("prepended-sql"), + PrintGrid=QString("print-grid"), + PrintPgNum=QString("print-pg-num"), + PrivilegesGop=QString("privileges-gop"), + Privileges=QString("privileges"), + ProtColumn=QString("prot-column"), + Protected=QString("protected"), + RangeAttribs=QString("range-attribs"), + RangeType=QString("range"), + RecentModels=QString("recent-models"), + Recent=QString("recent"), + RectVisible=QString("rect-visible"), + Recursive=QString("recursive"), + RecvFunc=QString("receive"), + ReducedForm=QString("reduced-form"), + RefAlias=QString("ref-alias"), + RefName=QString("ref-name"), + RefColumn=QString("ref-column"), + RefRoles=QString("ref-roles"), + RefTable=QString("ref-table"), + RefTables=QString("ref-tables"), + RefTableTag=QString("reftable"), + RefType=QString("ref-type"), + Refer=QString("refer"), + Reference=QString("reference"), + ReferenceFk=QString("reference-fk"), + ReferencesPriv=QString("references"), + References=QString("references"), + Referrers=QString("referrers"), + RegularExp=QString("regexp"), + RelationshipTabView=QString("reltv"), + Relationship11=QString("rel11"), + Relationship1n=QString("rel1n"), + RelationshipDep=QString("reldep"), + RelationshipFk=QString("relfk"), + RelationshipGen=QString("relgen"), + RelationshipNn=QString("relnn"), + RelationshipPart=QString("relpart"), + Relationship=QString("relationship"), + Rename=QString("rename"), + Replication=QString("replication"), + RestrictionFunc=QString("restriction"), + RestartSeq=QString("restart-seq"), + ReturnTable=QString("return-table"), + ReturnType=QString("return-type"), + ReturnsSetOf=QString("returns-setof"), + Revoke=QString("revoke"), + RightType=QString("right-type"), + Right=QString("right"), + RlsEnabled=QString("rls-enabled"), + RlsForced=QString("rls-forced"), + RoleType=QString("role-type"), + Role=QString("role"), + ROLE_CURRENT_USER=QString("CURRENT_USER"), + ROLE_SESSION_USER=QString("SESSION_USER"), + ROLE_PUBLIC=QString("PUBLIC"), + Roles=QString("roles"), + RowAmount=QString("row-amount"), + Rules=QString("rules"), + SaveLastPosition=QString("save-last-position"), + SaveRestoreGeometry=QString("save-restore-geometry"), + Schema=QString("schema"), + SchemaOid=QString("schema-oid"), + SearchPath=QString("search-path"), + SecurityType=QString("security-type"), + SelectExp=QString("select-exp"), + SelectPriv=QString("select"), + SelectObjects=QString("select-objects"), + SendFunc=QString("send"), + Sequence=QString("sequence"), + Server=QString("server"), + ServerEncoding=QString("server-encoding"), + ServerVersion=QString("server-version"), + ServerPid=QString("server-pid"), + ServerProtocol=QString("server-protocol"), + SetPerms=QString("set-perms"), + SharedObj=QString("shared-obj"), + ShellTypes=QString("shell-types"), + ShowCanvasGrid=QString("show-canvas-grid"), + ShowPageDelimiters=QString("show-page-delimiters"), + ShowAttributesGrid=QString("show-attributes-grid"), + ShowSourcePane=QString("show-source-pane"), + ShowMainMenu=QString("show-main-menu"), + Signature=QString("signature"), + SimpleExp=QString("simple-exp"), + SimplifiedObjCreation=QString("simplified-obj-creation"), + SinglePkColumn=QString("single-pk-col"), + Size=QString("size"), + Snippet=QString("snippet"), + SortOp=QString("sort-op"), + SourceEditorApp=QString("source-editor-app"), + SourceEditorArgs=QString("source-editor-args"), + SourceType=QString("source-type"), + SrcType=QString("src-type"), + SpatialType=QString("spatial-type"), + SpecialPkCols=QString("special-pk-cols"), + SqlDisabled=QString("sql-disabled"), + SqlObject=QString("sql-object"), + SqlValidation=QString("sql-validation"), + SqlTool=QString("sqltool"), + SrcColPattern=QString("src-col-pattern"), + SrcColumns=QString("src-columns"), + SrcEncoding=QString("src-encoding"), + SrcFkPattern=QString("src-fk-pattern"), + SrcLabel=QString("src-label"), + SrcRequired=QString("src-required"), + SrcTable=QString("src-table"), + Srid=QString("srid"), + Ssl=QString("ssl"), + SslCaFile=QString("ssl-ca-file"), + SslCertFile=QString("ssl-cert-file"), + SslCrlFile=QString("ssl-crl-file"), + SslKeyFile=QString("ssl-key-file"), + Start=QString("start"), + StateType=QString("state-type"), + StorageParams=QString("stg-params"), + Storage=QString("storage"), + StrategyNum=QString("stg-number"), + Style=QString("style"), + Styles=QString("styles"), + SubtypeDiffFunc=QString("subtypediff"), + Subtype=QString("subtype"), + Superuser=QString("superuser"), + Symbol=QString("symbol"), + TableBody=QString("table-body"), + TableExtBody=QString("table-ext-body"), + TableName=QString("table-name"), + TableObject=QString("table-obj"), + TableSchemaName=QString("table-schema-name"), + TableTitle=QString("table-title"), + TableType=QString("table-type"), + Table=QString("table"), + Tablespace=QString("tablespace"), + Tag=QString("tag"), + TemplateDb=QString("template"), + TemporaryPriv=QString("temporary"), + Top=QString("top"), + TpmodInFunc=QString("tpmodin"), + TpmodOutFunc=QString("tpmodout"), + TransitionFunc=QString("transition"), + TriggerFunc=QString("trigger-func"), + TriggerPriv=QString("trigger"), + Triggers=QString("triggers"), + TruncEvent=QString("trunc-event"), + TruncateCmds=QString("truncate-cmds"), + TruncatePriv=QString("truncate"), + Truncate=QString("truncate"), + Trusted=QString("trusted"), + TuplesDel=QString("tuples-del"), + TyplesUpd=QString("tuples-upd"), + TuplesIns=QString("tuples-ins"), + TypeAttribute=QString("typeattrib"), + TypeOid=QString("type-oid"), + Type=QString("type"), + Types=QString("types"), + TypeClass=QString("type-class"), + UiLanguage=QString("ui-language"), + Underline=QString("underline"), + Unique=QString("unique"), + Unlogged=QString("unlogged"), + UnsetPerms=QString("unset-perms"), + Unset=QString("unset"), + UpdAction=QString("upd-action"), + UpdEvent=QString("upd-event"), + UpdatePriv=QString("update"), + UqColumn=QString("uq-column"), + UqConstr=QString("uq-constr"), + UqPattern=QString("uq-pattern"), + UsagePriv=QString("usage"), + UseCurvedLines=QString("use-curved-lines"), + UseSignature=QString("use-signature"), + UsePlaceholders=QString("use-placeholders"), + UseSorting=QString("use-sorting"), + UseUniqueNames=QString("use-unique-names"), + UsingExp=QString("using-exp"), + ValidatorFunc=QString("validator"), + Validator=QString("validator"), + Validity=QString("validity"), + Validation=QString("validation"), + Value=QString("value"), + Values=QString("values"), + Variable=QString("variable"), + Variation=QString("variation"), + Version=QString("version"), + ViewBody=QString("view-body"), + ViewExtBody=QString("view-ext-body"), + ViewName=QString("view-name"), + ViewSchemaName=QString("view-schema-name"), + ViewTitle=QString("view-title"), + Visible=QString("visible"), + Widget=QString("widget"), + WidgetsGeometry=QString("widgets-geometry"), + Width=QString("width"), + Wildcard=QString("wildcard"), + WindowFunc=QString("window-func"), + WithNoData=QString("with-no-data"), + WithTimezone=QString("with-timezone"), + WithoutOids=QString("without-oids"), + WordDelimiters=QString("word-delimiters"), + WordSeparators=QString("word-separators"), + WorkingDir=QString("working-dir"), + XPos=QString("x"), + YPos=QString("y"); +} + diff --git a/libparsers/src/attributes.h b/libparsers/src/attributes.h new file mode 100644 index 0000000000..2d0f8a6cf1 --- /dev/null +++ b/libparsers/src/attributes.h @@ -0,0 +1,626 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful), +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also), you can get the complete GNU General Public License at +*/ + +/** +\ingroup libparsers +\namespace Attributes +\brief Definition of parsers attributes namespace which stores a series of static strings constants used + to reference the attributes of objects in SQL/XML generation methods. + Each string stores the name of the attribute used in the schema file "sch" of the respective objects. +\note Creation date: 23/09/2008 +*/ + +#ifndef ATTRIBUTES_H +#define ATTRIBUTES_H + +/* Including QByteArray due to 'QByteArray has no toStdString()' + error on Qt 5.4 (Windows only) */ +#include +#include + +namespace Attributes { + extern const QString + False, + File, + LcCollate, + LcCtype, + True, + ActiveLayers, + AdminOption, + AdminRoles, + Alias, + Alignment, + AlignObjsToGrid, + AlterCmds, + AllowConns, + AnalyzeFunc, + AncestorTable, + AppendAtEod, + AppendedSql, + Application, + ArgCount, + ArgDefCount, + ArgDefaults, + ArgModes, + ArgNames, + ArgTypes, + Arguments, + AscOrder, + Assignment, + Attribute, + AttribsPage, + AttribsPerPage, + AutoBrowseDb, + AutoSaveInterval, + BackgroundColor, + BaseType, + Before, + BehaviorType, + Bold, + BorderColor, + Bottom, + Buffering, + ByValue, + BypassRls, + Cache, + CanonicalFunc, + CanvasCornerMove, + Cascade, + CaseSensitive, + CastType, + Category, + Change, + Changelog, + CheckExp, + CheckUpdate, + CkConstr, + ClientEncoding, + CodeCompletion, + CodeFontSize, + CodeFont, + CodeTabWidth, + ColIndexes, + CollapseMode, + Collatable, + Collation, + Collations, + Color, + Colors, + ColsComment, + ColIsIdentity, + ColumnAlias, + Column, + Columns, + Command, + Commands, + Comment, + CommutatorOp, + ComparisonType, + CompactView, + CompletionTrigger, + CompositeType, + Concurrent, + Condition, + Configuration, + ConfigFile, + ConfirmValidation, + ConnLimit, + ConnectCenterPnts, + ConnectFkToPk, + ConnectTableEdges, + ConnectPriv, + Connection, + Connections, + ConnectionTimeout, + ConstrDefs, + ConstrIndexes, + ConstrSqlDisabled, + Constraint, + Constraints, + Contents, + CopyMode, + CopyOptions, + CopyTable, + CreateCmds, + CreatePriv, + Create, + CreateDb, + CreateRole, + CrowsFoot, + CteExpression, + CurVersion, + CurIdentityType, + CustomColor, + CustomFilter, + CustomIdxs, + Cycle, + Database, + DataDirectory, + Date, + DbModel, + DdlEndToken, + DeadRowsAmount, + DeclInTable, + Declaration, + DefaultCollation, + DefaultForOps, + DefaultOwner, + DefaultSchema, + DefaultTablespace, + DefaultValue, + Default, + DeferType, + Deferrable, + Definition, + DelAction, + DelEvent, + DeletePriv, + Delimiter, + DestType, + DstType, + Diff, + Dimension, + Directory, + DisableSmoothness, + DisplayLineNumbers, + DomConstraint, + DockWidgets, + DropCmds, + Drop, + DstColPattern, + DstColumns, + DstEncoding, + DstFkPattern, + DstLabel, + DstRequired, + DstTable, + DynamicLibraryPath, + DynamicSharedMemory, + Element, + Elements, + Encoding, + Encrypted, + EndExp, + EnumType, + Enumerations, + EventType, + Event, + Events, + ExConstr, + ExactMatch, + ExcBuiltinArrays, + ExcludeElement, + ExecType, + ExecutPriv, + ExecutionCost, + ExistingValue, + Explicit, + Export, + ExportToFile, + Expression, + Expressions, + ExtAttribsPage, + ExtAttribsPerPage, + ExtObjOids, + Factor, + FadeInObjects, + FadedOut, + Family, + FastUpdate, + Fdw, + FileAssociated, + FillColor, + FilterOids, + FilterTableTypes, + Filter, + FinalFunc, + FiringType, + FkColumn, + FkConstr, + FkDefs, + FontSize, + Font, + ForegroundColor, + ForeignKeys, + FormatName, + FromExp, + FunctionType, + Function, + General, + GenAlterCmds, + Global, + GrantOp, + GridSize, + Group, + HandlerFunc, + HandlesType, + HasChanges, + Hashes, + HbaFile, + Height, + HideExtAttribs, + HideRelName, + HideTableTags, + HighlightLines, + HighlightOrder, + HistoryMaxLength, + Icon, + Id, + Identifier, + IdentityType, + IgnoredChars, + Implicit, + Import, + Increment, + IdentFile, + IndexElement, + IndexType, + Index, + Indexes, + Info, + InhColumn, + InhColumns, + Inherit, + Inherited, + InitialCond, + InitialData, + InitialExp, + InlineFunc, + InputFunc, + InsEvent, + InsertPriv, + InternalLength, + IntervalType, + InvertRangeSelTrigger, + IoCast, + IsTemplate, + IsPartitioned, + Italic, + JoinFunc, + Label, + LabelsPos, + Landscape, + Language, + LastPosition, + LastSysOid, + LastValue, + LastZoom, + Layer, + Layers, + LeakProof, + LeftType, + Left, + Length, + Library, + LikeType, + Line, + LineNumbersColor, + LineNumbersBgColor, + LineHighlightColor, + ListenAddresses, + Locale, + LockerArc, + LockerBody, + Login, + LookaheadChar, + LowVerbosity, + Materialized, + MaxConnections, + MaxObjCount, + MaxValue, + Maximized, + MemberRoles, + Member, + Merges, + Metadata, + MinObjectOpacity, + MinValue, + Mode, + ModelAuthor, + NameLabel, + NamePatterns, + Name, + Names, + NegatorOp, + NewName, + NewTableName, + NewIdentityType, + NewVersion, + NnColumn, + NoInherit, + None, + NotExtObject, + NotNull, + NullsFirst, + ObjSelection, + ObjectId, + ObjectFinder, + ObjectType, + Object, + Objects, + OidFilterOp, + Oid, + Oids, + OldName, + OldTableName, + OldVersion, + OpClass, + OpClasses, + OpFamily, + OpListSize, + OperatorFunc, + Operator, + Operators, + Options, + OriginalPk, + OutputFunc, + OwnerColumn, + Owner, + Pagination, + PaperCustomSize, + PaperMargin, + PaperOrientation, + PaperType, + ParamIn, + ParamOut, + ParamVariadic, + Parameter, + Parameters, + Parent, + Parents, + Parsable, + PartialMatch, + PartitionKey, + PartitionedTable, + PartitionBoundExpr, + Partitioning, + PartKeyCols, + PartKeyColls, + PartKeyOpCls, + PartKeyExprs, + Password, + PasswordEncryption, + Path, + Patterns, + PerRow, + Permission, + Permissive, + PgModelerVersion, + PgSqlBaseType, + PgSqlVersion, + Placeholder, + Placeholders, + PkColPattern, + PkColumn, + PkConstr, + PkPattern, + Points, + Port, + Portrait, + PositionInfo, + Position, + Precision, + Predicate, + Preferred, + PrependAtBod, + PrependedSql, + PrintGrid, + PrintPgNum, + PrivilegesGop, + Privileges, + ProtColumn, + Protected, + RangeAttribs, + RangeType, + RecentModels, + Recent, + RectVisible, + Recursive, + RecvFunc, + ReducedForm, + RefAlias, + RefName, + RefColumn, + RefRoles, + RefTable, + RefTables, + RefTableTag, + RefType, + Refer, + Reference, + ReferenceFk, + ReferencesPriv, + References, + Referrers, + RegularExp, + RelationshipTabView, + Relationship11, + Relationship1n, + RelationshipDep, + RelationshipFk, + RelationshipGen, + RelationshipNn, + RelationshipPart, + Relationship, + Rename, + Replication, + RestartSeq, + RestrictionFunc, + ReturnTable, + ReturnType, + ReturnsSetOf, + Revoke, + RightType, + Right, + RlsEnabled, + RlsForced, + RoleType, + Role, + Roles, + RowAmount, + Rules, + SaveLastPosition, + SaveRestoreGeometry, + Schema, + SchemaOid, + SearchPath, + SecurityType, + SelectExp, + SelectPriv, + SelectObjects, + SendFunc, + Sequence, + Server, + ServerEncoding, + ServerVersion, + ServerPid, + ServerProtocol, + SetPerms, + SharedObj, + ShellTypes, + ShowCanvasGrid, + ShowPageDelimiters, + ShowAttributesGrid, + ShowSourcePane, + ShowMainMenu, + Signature, + SimpleExp, + SimplifiedObjCreation, + SinglePkColumn, + Size, + Snippet, + SortOp, + SourceEditorApp, + SourceEditorArgs, + SourceType, + SrcType, + SpatialType, + SpecialPkCols, + SqlDisabled, + SqlObject, + SqlValidation, + SqlTool, + SrcColPattern, + SrcColumns, + SrcEncoding, + SrcFkPattern, + SrcLabel, + SrcRequired, + SrcTable, + Srid, + Ssl, + SslCaFile, + SslCertFile, + SslCrlFile, + SslKeyFile, + Start, + StateType, + StorageParams, + Storage, + StrategyNum, + Style, + Styles, + SubtypeDiffFunc, + Subtype, + Superuser, + Symbol, + TableBody, + TableExtBody, + TableName, + TableObject, + TableSchemaName, + TableTitle, + Table, + TableType, + Tablespace, + Tag, + TemplateDb, + TemporaryPriv, + Top, + TpmodInFunc, + TpmodOutFunc, + TransitionFunc, + TriggerFunc, + TriggerPriv, + Triggers, + TruncEvent, + TruncateCmds, + TruncatePriv, + Truncate, + Trusted, + TypeAttribute, + TypeOid, + Type, + Types, + TypeClass, + UiLanguage, + Underline, + Unique, + Unlogged, + UnsetPerms, + Unset, + UpdAction, + UpdEvent, + UpdatePriv, + UqColumn, + UqConstr, + UqPattern, + UsagePriv, + UseCurvedLines, + UsePlaceholders, + UseSignature, + UseSorting, + UseUniqueNames, + UsingExp, + ValidatorFunc, + Validator, + Validity, + Validation, + Value, + Values, + Variable, + Variation, + Version, + ViewBody, + ViewExtBody, + ViewName, + ViewSchemaName, + ViewTitle, + Visible, + Widget, + WidgetsGeometry, + Width, + Wildcard, + WindowFunc, + WithNoData, + WithTimezone, + WithoutOids, + WordDelimiters, + WordSeparators, + WorkingDir, + XPos, + YPos, + LastAnalyze, + LastAutovacuum, + LastVacuum, + TuplesDel, + TyplesUpd, + TuplesIns; +} + +#endif diff --git a/libparsers/src/parsersattributes.cpp b/libparsers/src/parsersattributes.cpp deleted file mode 100644 index dd0f7709ba..0000000000 --- a/libparsers/src/parsersattributes.cpp +++ /dev/null @@ -1,564 +0,0 @@ -/* -# PostgreSQL Database Modeler (pgModeler) -# -# Copyright 2006-2018 - Raphael Araújo e Silva -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation version 3. -# -# This program is distributed in the hope that it will be useful), -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# The complete text of GPLv3 is at LICENSE file on source code root directory. -# Also), you can get the complete GNU General Public License at -*/ - -#include "parsersattributes.h" - -namespace ParsersAttributes { - const QString - _FALSE_=QString("false"), - _FILE_=QString("file"), - _LC_COLLATE_=QString("lc-collate"), - _LC_CTYPE_=QString("lc-ctype"), - _TRUE_=QString("true"), - ADMIN_OPTION=QString("admin-option"), - ADMIN_ROLES=QString("admin-roles"), - ALIAS=QString("alias"), - ALIGNMENT=QString("alignment"), - ALIGN_OBJS_TO_GRID=QString("align-objs-to-grid"), - ALTER_CMDS=QString("alter-cmds"), - ALLOW_CONNS=QString("allow-conns"), - ANALYZE_FUNC=QString("analyze"), - ANCESTOR_TABLE=QString("ancestor-table"), - APPEND_AT_EOD=QString("append-at-eod"), - APPENDED_SQL=QString("appended-sql"), - APPLICATION=QString("application"), - ARG_COUNT=QString("arg-count"), - ARG_DEF_COUNT=QString("arg-def-count"), - ARG_DEFAULTS=QString("arg-defaults"), - ARG_MODES=QString("arg-modes"), - ARG_NAMES=QString("arg-names"), - ARG_TYPES=QString("arg-types"), - ARGUMENTS=QString("arguments"), - ASC_ORDER=QString("asc-order"), - ASSIGNMENT=QString("assignment"), - ATTRIBUTE=QString("attribute"), - AUTO_BROWSE_DB=QString("auto-browse-db"), - AUTOSAVE_INTERVAL=QString("autosave-interval"), - BACKGROUND_COLOR=QString("background-color"), - BASE_TYPE=QString("base"), - BEFORE=QString("before"), - BEHAVIOR_TYPE=QString("behavior-type"), - BOLD=QString("bold"), - BORDER_COLOR=QString("border-color"), - BOTTOM=QString("bottom"), - BUFFERING=QString("buffering"), - BY_VALUE=QString("by-value"), - BYPASSRLS=QString("bypassrls"), - CACHE=QString("cache"), - CANONICAL_FUNC=QString("canonical"), - CANVAS_CORNER_MOVE=QString("canvas-corner-move"), - CASCADE=QString("cascade"), - CASE_SENSITIVE=QString("case-sensitive"), - CAST_TYPE=QString("cast-type"), - CATEGORY=QString("category"), - CHANGE=QString("change"), - CHANGELOG=QString("changelog"), - CHECK_EXP=QString("check-exp"), - CHECK_UPDATE=QString("check-update"), - CK_CONSTR=QString("ck-constr"), - CLIENT_ENCODING=QString("client-encoding"), - CODE_COMPLETION=QString("code-completion"), - CODE_FONT_SIZE=QString("code-font-size"), - CODE_FONT=QString("code-font"), - CODE_TAB_WIDTH=QString("code-tab-width"), - COL_INDEXES=QString("col-indexes"), - COLLATABLE=QString("collatable"), - COLLATION=QString("collation"), - COLLATIONS=QString("collations"), - COLOR=QString("color"), - COLORS=QString("colors"), - COLS_COMMENT=QString("cols-comment"), - COL_IS_IDENTITY=QString("col-is-identity"), - COLUMN_ALIAS=QString("column-alias"), - COLUMN=QString("column"), - COLUMNS=QString("columns"), - COMMAND=QString("command"), - COMMANDS=QString("commands"), - COMMENT=QString("comment"), - COMMUTATOR_OP=QString("commutator-op"), - COMPARISON_TYPE=QString("comparison-type"), - COMPLETION_TRIGGER=QString("completion-trigger"), - COMPOSITE_TYPE=QString("composite"), - CONCURRENT=QString("concurrent"), - CONDITION=QString("condition"), - CONFIG_FILE=QString("config-file"), - CONFIGURATION=QString("configuration"), - CONFIRM_VALIDATION=QString("confirm-validation"), - CONN_LIMIT=QString("connlimit"), - CONNECT_CENTER_PNTS=QString("center-pnts"), - CONNECT_FK_TO_PK=QString("fk-to-pk"), - CONNECT_TABLE_EDGES=QString("table-edges"), - CONNECT_PRIV=QString("connect"), - CONNECTION=QString("connection"), - CONNECTIONS=QString("connections"), - CONNECTION_TIMEOUT=QString("connection-timeout"), - CONSTR_INDEXES=QString("constr-indexes"), - CONSTR_SQL_DISABLED=QString("constr-sql-disabled"), - CONSTRAINT=QString("constraint"), - CONSTRAINTS=QString("constraints"), - CONSTR_DEFS=QString("constr-defs"), - CONTENTS=QString("contents"), - COPY_MODE=QString("copy-mode"), - COPY_OPTIONS=QString("copy-options"), - COPY_TABLE=QString("copy-table"), - CREATE_CMDS=QString("create-cmds"), - CREATE_PRIV=QString("create"), - CREATE=QString("create"), - CREATEDB=QString("createdb"), - CREATEROLE=QString("createrole"), - CROWS_FOOT=QString("crows-foot"), - CTE_EXPRESSION=QString("cte-exp"), - CUR_VERSION=QString("cur-version"), - CUSTOM_COLOR=QString("custom-color"), - CUSTOM_FILTER=QString("custom-filter"), - CUSTOMIDXS=QString("customidxs"), - CYCLE=QString("cycle"), - DATA_DIRECTORY=QString("data-directory"), - DATE=QString("date"), - DATABASE=QString("database"), - DB_MODEL=QString("dbmodel"), - DDL_END_TOKEN=QString("-- ddl-end --"), - DECL_IN_TABLE=QString("decl-in-table"), - DECLARATION=QString("declaration"), - DEFAULT_COLLATION=QString("default-collation"), - DEFAULT_FOR_OPS=QString("default-for-ops"), - DEFAULT_OWNER=QString("default-owner"), - DEFAULT_SCHEMA=QString("default-schema"), - DEFAULT_TABLESPACE=QString("default-tablespace"), - DEFAULT_VALUE=QString("default-value"), - DEFAULT=QString("default"), - DEFER_TYPE=QString("defer-type"), - DEFERRABLE=QString("deferrable"), - DEFINITION=QString("definition"), - DEL_ACTION=QString("del-action"), - DEL_EVENT=QString("del-event"), - DELETE_PRIV=QString("delete"), - DELIMITER=QString("delimiter"), - DEST_TYPE=QString("destiny-type"), - DST_TYPE=QString("dst-type"), - DIFF=QString("diff"), - DIMENSION=QString("dimension"), - DIRECTORY=QString("directory"), - DISABLE_SMOOTHNESS=QString("disable-smoothness"), - DISPLAY_LINE_NUMBERS=QString("display-line-numbers"), - DOM_CONSTRAINT=QString("domconstraint"), - DOCK_WIDGETS=QString("dock-widgets"), - DROP_CMDS=QString("drop-cmds"), - DROP=QString("drop"), - DST_COL_PATTERN=QString("dst-col-pattern"), - DST_COLUMNS=QString("dst-columns"), - DST_ENCODING=QString("dst-encoding"), - DST_FK_PATTERN=QString("dst-fk-pattern"), - DST_LABEL=QString("dst-label"), - DST_REQUIRED=QString("dst-required"), - DST_TABLE=QString("dst-table"), - DYNAMIC_LIBRARY_PATH=QString("dynamic-library-path"), - DYNAMIC_SHARED_MEMORY=QString("dynamic-shared-memory-type"), - END_EXP=QString("end-exp"), - ELEMENT=QString("element"), - ELEMENTS=QString("elements"), - ENCODING=QString("encoding"), - ENCRYPTED=QString("encrypted"), - ENUM_TYPE=QString("enumeration"), - ENUMERATIONS=QString("enumerations"), - EVENT_TYPE=QString("event-type"), - EVENT=QString("event"), - EVENTS=QString("events"), - EX_CONSTR=QString("ex-constr"), - EXACT_MATCH=QString("exact-match"), - EXC_BUILTIN_ARRAYS=QString("exc-builtin-arrays"), - EXCLUDE_ELEMENT=QString("excelement"), - EXEC_TYPE=QString("exec-type"), - EXECUTE_PRIV=QString("execute"), - EXECUTION_COST=QString("execution-cost"), - EXISTING_VALUE=QString("existing-value"), - EXPLICIT=QString("explicit"), - EXPORT=QString("export"), - EXPORT_TO_FILE=QString("export-to-file"), - EXPRESSION=QString("expression"), - EXPRESSIONS=QString("expressions"), - EXT_OBJ_OIDS=QString("ext-obj-oids"), - FACTOR=QString("factor"), - FADEIN_OBJECTS=QString("fadein-objects"), - FADED_OUT=QString("faded-out"), - FAMILY=QString("family"), - FAST_UPDATE=QString("fast-update"), - FILE_ASSOCIATED=QString("file-associated"), - FILL_COLOR=QString("fill-color"), - FILTER_OIDS=QString("filter-oids"), - FILTER_TABLE_TYPES=QString("filter-tab-types"), - FILTER=QString("filter"), - FINAL_FUNC=QString("final"), - FIRING_TYPE=QString("firing-type"), - FK_COLUMN=QString("fk-column"), - FK_CONSTR=QString("fk-constr"), - FK_DEFS=QString("fk-defs"), - FONT_SIZE=QString("font-size"), - FONT=QString("font"), - FOREGROUND_COLOR=QString("foreground-color"), - FOREIGN_KEYS=QString("foreign-keys"), - FROM_EXP=QString("from-exp"), - FUNCTION_TYPE=QString("function-type"), - FUNCTION=QString("function"), - GENERAL=QString("general"), - GEN_ALTER_CMDS=QString("gen-alter-cmds"), - GLOBAL=QString("global"), - GRANT_OP=QString("grant-op"), - GRID_SIZE=QString("grid-size"), - GROUP=QString("group"), - HANDLER_FUNC=QString("handler"), - HANDLES_TYPE=QString("handles-type"), - HAS_CHANGES=QString("has-changes"), - HASHES=QString("hashes"), - HBA_FILE=QString("hba-file"), - HIDE_EXT_ATTRIBS=QString("hide-ext-attribs"), - HIDE_REL_NAME=QString("hide-rel-name"), - HIDE_TABLE_TAGS=QString("hide-table-tags"), - HIGHLIGHT_LINES=QString("highlight-lines"), - HIGHLIGHT_ORDER=QString("highlight-order"), - HISTORY_MAX_LENGTH=QString("history-max-length"), - ICON=QString("icon"), - ID=QString("id"), - IDENTIFIER=QString("identifier"), - IDENTITY_TYPE=QString("identity-type"), - IDENT_FILE=QString("ident-file"), - IGNORED_CHARS=QString("ignored-chars"), - IMPLICIT=QString("implicit"), - IMPORT=QString("import"), - INCREMENT=QString("increment"), - INDEX_ELEMENT=QString("idxelement"), - INDEX_TYPE=QString("index-type"), - INDEX=QString("index"), - INDEXES=QString("indexes"), - INFO=QString("info"), - INH_COLUMN=QString("inh-column"), - INH_COLUMNS=QString("inh-columns"), - INHERIT=QString("inherit"), - INHERITED=QString("inherited"), - INITIAL_COND=QString("initial-cond"), - INITIAL_DATA=QString("initial-data"), - INITIAL_EXP=QString("initial-exp"), - INLINE_FUNC=QString("inline"), - INPUT_FUNC=QString("input"), - INS_EVENT=QString("ins-event"), - INSERT_PRIV=QString("insert"), - INTERNAL_LENGTH=QString("internal-length"), - INTERVAL_TYPE=QString("interval-type"), - INVERT_RANGESEL_TRIGGER=QString("invert-rangesel-trigger"), - IS_TEMPLATE=QString("is-template"), - IO_CAST=QString("io-cast"), - ITALIC=QString("italic"), - JOIN_FUNC=QString("join"), - LABEL=QString("label"), - LABELS_POS=QString("labels-pos"), - LANDSCAPE=QString("landscape"), - LANGUAGE=QString("language"), - LAST_POSITION=QString("last-position"), - LAST_SYS_OID=QString("last-sys-oid"), - LAST_VALUE=QString("last-value"), - LAST_ZOOM=QString("last-zoom"), - LEAKPROOF=QString("leakproof"), - LEFT_TYPE=QString("left-type"), - LEFT=QString("left"), - LENGTH=QString("length"), - LIBRARY=QString("library"), - LIKE_TYPE=QString("like-type"), - LINE=QString("line"), - LINE_NUMBERS_COLOR=QString("line-numbers-color"), - LINE_NUMBERS_BG_COLOR=QString("line-numbers-bg-color"), - LINE_HIGHLIGHT_COLOR=QString("line-highlight-color"), - LISTEN_ADDRESSES=QString("listen-addresses"), - LOCALE=QString("locale"), - LOCKER_ARC=QString("locker-arc"), - LOCKER_BODY=QString("locker-body"), - LOGIN=QString("login"), - LOOKAHEAD_CHAR=QString("lookahead-char"), - MATERIALIZED=QString("materialized"), - MAX_CONNECTIONS=QString("max-connections"), - MAX_VALUE=QString("max-value"), - MAX_RESULT_ROWS=QString("max-result-rows"), - MEMBER_ROLES=QString("member-roles"), - MEMBER=QString("member"), - MERGES=QString("merges"), - METADATA=QString("metadata"), - MIN_OBJECT_OPACITY=QString("min-object-opacity"), - MIN_VALUE=QString("min-value"), - MODE=QString("mode"), - MODEL_AUTHOR=QString("author"), - NAME_LABEL=QString("name-label"), - NAME_PATTERNS=QString("name-patterns"), - NAME=QString("name"), - NAMES=QString("names"), - NEGATOR_OP=QString("negator-op"), - NEW_NAME=QString("new-name"), - NEW_IDENTITY_TYPE=QString("new-identity-type"), - NEW_VERSION=QString("new-version"), - NN_COLUMN=QString("nn-column"), - NO_INHERIT=QString("no-inherit"), - NONE=QString("none"), - NOT_EXT_OBJECT=QString("not-ext-object"), - NOT_NULL=QString("not-null"), - NULLS_FIRST=QString("nulls-first"), - OBJ_SELECTION=QString("obj-selection"), - OBJECT_ID=QString("object-id"), - OBJECT_FINDER=QString("objectfinder"), - OBJECT_TYPE=QString("object-type"), - OBJECT=QString("object"), - OBJECTS=QString("objects"), - OID_FILTER_OP=QString("oid-filter-op"), - OID=QString("oid"), - OIDS=QString("oids"), - OLD_NAME=QString("old-name"), - OLD_VERSION=QString("old-version"), - OP_CLASS=QString("opclass"), - OP_CLASSES=QString("opclasses"), - OP_FAMILY=QString("opfamily"), - OP_LIST_SIZE=QString("op-list-size"), - OPERATOR_FUNC=QString("operfunc"), - OPERATOR=QString("operator"), - OPERATORS=QString("operators"), - OUTPUT_FUNC=QString("output"), - OWNER_COLUMN=QString("owner-col"), - OWNER=QString("owner"), - PAPER_CUSTOM_SIZE=QString("paper-custom-size"), - PAPER_MARGIN=QString("paper-margin"), - PAPER_ORIENTATION=QString("paper-orientation"), - PAPER_TYPE=QString("paper-type"), - PARAM_IN=QString("in"), - PARAM_OUT=QString("out"), - PARAM_VARIADIC=QString("variadic"), - PARAMETER=QString("parameter"), - PARAMETERS=QString("parameters"), - PARENT=QString("parent"), - PARENTS=QString("parents"), - PARSABLE=QString("parsable"), - PARTIAL_MATCH=QString("partial-match"), - PASSWORD=QString("password"), - PASSWORD_ENCRYPTION=QString("password-encryption"), - PATH=QString("path"), - PATTERNS=QString("patterns"), - PER_ROW=QString("per-line"), - PERMISSION=QString("permission"), - PERMISSIVE=QString("permissive"), - PGMODELER_VERSION=QString("pgmodeler-ver"), - PGSQL_BASE_TYPE=QString("basetype"), - PGSQL_VERSION=QString("pgsql-ver"), - PLACEHOLDER=QString("placeholder"), - PLACEHOLDERS=QString("placeholders"), - PK_COL_PATTERN=QString("pk-col-pattern"), - PK_COLUMN=QString("pk-column"), - PK_CONSTR=QString("pk-constr"), - PK_PATTERN=QString("pk-pattern"), - POINTS=QString("points"), - PORT=QString("port"), - PORTRAIT=QString("portrait"), - POSITION_INFO=QString("pos-info"), - POSITION=QString("position"), - PRECISION=QString("precision"), - PREDICATE=QString("predicate"), - PREFERRED=QString("preferred"), - PREPEND_AT_BOD=QString("prepend-at-bod"), - PREPENDED_SQL=QString("prepended-sql"), - PRINT_GRID=QString("print-grid"), - PRINT_PG_NUM=QString("print-pg-num"), - PRIVILEGES_GOP=QString("privileges-gop"), - PRIVILEGES=QString("privileges"), - PROT_COLUMN=QString("prot-column"), - PROTECTED=QString("protected"), - RANGE_ATTRIBS=QString("range-attribs"), - RANGE_TYPE=QString("range"), - RECENT_MODELS=QString("recent-models"), - RECENT=QString("recent"), - RECT_VISIBLE=QString("rect-visible"), - RECURSIVE=QString("recursive"), - RECV_FUNC=QString("receive"), - REDUCED_FORM=QString("reduced-form"), - REF_COLUMN=QString("ref-column"), - REF_ROLES=QString("ref-roles"), - REF_TABLE=QString("ref-table"), - REF_TYPE=QString("ref-type"), - REFER=QString("refer"), - REFERENCE=QString("reference"), - REFERENCE_FK=QString("reference-fk"), - REFERENCES_PRIV=QString("references"), - REFERENCES=QString("references"), - REFERRERS=QString("referrers"), - REGULAR_EXP=QString("regexp"), - RELATION_TAB_VIEW=QString("reltv"), - RELATIONSHIP_11=QString("rel11"), - RELATIONSHIP_1N=QString("rel1n"), - RELATIONSHIP_DEP=QString("reldep"), - RELATIONSHIP_FK=QString("relfk"), - RELATIONSHIP_GEN=QString("relgen"), - RELATIONSHIP_NN=QString("relnn"), - RELATIONSHIP=QString("relationship"), - RENAME=QString("rename"), - REPLICATION=QString("replication"), - RESTRICTION_FUNC=QString("restriction"), - RETURN_TABLE=QString("return-table"), - RETURN_TYPE=QString("return-type"), - RETURNS_SETOF=QString("returns-setof"), - REVOKE=QString("revoke"), - RIGHT_TYPE=QString("right-type"), - RIGHT=QString("right"), - RLS_ENABLED=QString("rls-enabled"), - RLS_FORCED=QString("rls-forced"), - ROLE_TYPE=QString("role-type"), - ROLE=QString("role"), - ROLE_CURRENT_USER=QString("CURRENT_USER"), - ROLE_SESSION_USER=QString("SESSION_USER"), - ROLE_PUBLIC=QString("PUBLIC"), - ROLES=QString("roles"), - ROW_AMOUNT=QString("row-amount"), - RULES=QString("rules"), - SAVE_LAST_POSITION=QString("save-last-position"), - SCHEMA=QString("schema"), - SEARCH_PATH=QString("search-path"), - SECURITY_TYPE=QString("security-type"), - SELECT_EXP=QString("select-exp"), - SELECT_PRIV=QString("select"), - SELECT_OBJECTS=QString("select-objects"), - SEND_FUNC=QString("send"), - SEQUENCE=QString("sequence"), - SERVER_ENCODING=QString("server-encoding"), - SERVER_VERSION=QString("server-version"), - SERVER_PID=QString("server-pid"), - SERVER_PROTOCOL=QString("server-protocol"), - SET_PERMS=QString("set-perms"), - SHARED_OBJ=QString("shared-obj"), - SHELL_TYPES=QString("shell-types"), - SHOW_CANVAS_GRID=QString("show-canvas-grid"), - SHOW_PAGE_DELIMITERS=QString("show-page-delimiters"), - SHOW_ATTRIBUTES_GRID=QString("show-attributes-grid"), - SHOW_SOURCE_PANE=QString("show-source-pane"), - SHOW_MAIN_MENU=QString("show-main-menu"), - SIGNATURE=QString("signature"), - SIMPLE_EXP=QString("simple-exp"), - SIMPLIFIED_OBJ_CREATION=QString("simplified-obj-creation"), - SINGLE_PK_COLUMN=QString("single-pk-col"), - SIZE=QString("size"), - SNIPPET=QString("snippet"), - SORT_OP=QString("sort-op"), - SOURCE_EDITOR_APP=QString("source-editor-app"), - SOURCE_EDITOR_ARGS=QString("source-editor-args"), - SOURCE_TYPE=QString("source-type"), - SRC_TYPE=QString("src-type"), - SPATIAL_TYPE=QString("spatial-type"), - SPECIAL_PK_COLS=QString("special-pk-cols"), - SQL_DISABLED=QString("sql-disabled"), - SQL_OBJECT=QString("sql-object"), - SQL_VALIDATION=QString("sql-validation"), - SQL_TOOL=QString("sqltool"), - SRC_COL_PATTERN=QString("src-col-pattern"), - SRC_COLUMNS=QString("src-columns"), - SRC_ENCODING=QString("src-encoding"), - SRC_FK_PATTERN=QString("src-fk-pattern"), - SRC_LABEL=QString("src-label"), - SRC_REQUIRED=QString("src-required"), - SRC_TABLE=QString("src-table"), - SRID=QString("srid"), - SSL=QString("ssl"), - SSL_CA_FILE=QString("ssl-ca-file"), - SSL_CERT_FILE=QString("ssl-cert-file"), - SSL_CRL_FILE=QString("ssl-crl-file"), - SSL_KEY_FILE=QString("ssl-key-file"), - START=QString("start"), - STATE_TYPE=QString("state-type"), - STORAGE_PARAMS=QString("stg-params"), - STORAGE=QString("storage"), - STRATEGY_NUM=QString("stg-number"), - STYLE=QString("style"), - STYLES=QString("styles"), - SUBTYPE_DIFF_FUNC=QString("subtypediff"), - SUBTYPE=QString("subtype"), - SUPERUSER=QString("superuser"), - SYMBOL=QString("symbol"), - TABLE_BODY=QString("table-body"), - TABLE_EXT_BODY=QString("table-ext-body"), - TABLE_NAME=QString("table-name"), - TABLE_OBJECT=QString("table-obj"), - TABLE_SCHEMA_NAME=QString("table-schema-name"), - TABLE_TITLE=QString("table-title"), - TABLE_TYPE=QString("table-type"), - TABLE=QString("table"), - TABLESPACE=QString("tablespace"), - TAG=QString("tag"), - TEMPLATE_DB=QString("template"), - TEMPORARY_PRIV=QString("temporary"), - TOP=QString("top"), - TPMOD_IN_FUNC=QString("tpmodin"), - TPMOD_OUT_FUNC=QString("tpmodout"), - TRANSITION_FUNC=QString("transition"), - TRIGGER_FUNC=QString("trigger-func"), - TRIGGER_PRIV=QString("trigger"), - TRIGGERS=QString("triggers"), - TRUNC_EVENT=QString("trunc-event"), - TRUNCATE_CMDS=QString("truncate-cmds"), - TRUNCATE_PRIV=QString("truncate"), - TRUNCATE=QString("truncate"), - TRUSTED=QString("trusted"), - TYPE_ATTRIBUTE=QString("typeattrib"), - TYPE_OID=QString("type-oid"), - TYPE=QString("type"), - TYPES=QString("types"), - TYPE_CLASS=QString("type-class"), - UI_LANGUAGE=QString("ui-language"), - UNDERLINE=QString("underline"), - UNIQUE=QString("unique"), - UNLOGGED=QString("unlogged"), - UNSET_PERMS=QString("unset-perms"), - UNSET=QString("unset"), - UPD_ACTION=QString("upd-action"), - UPD_EVENT=QString("upd-event"), - UPDATE_PRIV=QString("update"), - UQ_COLUMN=QString("uq-column"), - UQ_CONSTR=QString("uq-constr"), - UQ_PATTERN=QString("uq-pattern"), - USAGE_PRIV=QString("usage"), - USE_CURVED_LINES=QString("use-curved-lines"), - USE_PLACEHOLDERS=QString("use-placeholders"), - USE_SORTING=QString("use-sorting"), - USE_UNIQUE_NAMES=QString("use-unique-names"), - USING_EXP=QString("using-exp"), - VALIDATOR_FUNC=QString("validator"), - VALIDATOR=QString("validator"), - VALIDITY=QString("validity"), - VALIDATION=QString("validation"), - VALUE=QString("value"), - VALUES=QString("values"), - VARIABLE=QString("variable"), - VARIATION=QString("variation"), - VIEW_BODY=QString("view-body"), - VIEW_EXT_BODY=QString("view-ext-body"), - VIEW_NAME=QString("view-name"), - VIEW_SCHEMA_NAME=QString("view-schema-name"), - VIEW_TITLE=QString("view-title"), - VISIBLE=QString("visible"), - WIDGET=QString("widget"), - WILDCARD=QString("wildcard"), - WINDOW_FUNC=QString("window-func"), - WITH_NO_DATA=QString("with-no-data"), - WITH_TIMEZONE=QString("with-timezone"), - WITHOUT_OIDS=QString("without-oids"), - WORD_DELIMITERS=QString("word-delimiters"), - WORD_SEPARATORS=QString("word-separators"), - WORKING_DIR=QString("working-dir"), - X_POS=QString("x"), - Y_POS=QString("y"); -} - diff --git a/libparsers/src/parsersattributes.h b/libparsers/src/parsersattributes.h deleted file mode 100644 index d06ce98284..0000000000 --- a/libparsers/src/parsersattributes.h +++ /dev/null @@ -1,577 +0,0 @@ -/* -# PostgreSQL Database Modeler (pgModeler) -# -# Copyright 2006-2018 - Raphael Araújo e Silva -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation version 3. -# -# This program is distributed in the hope that it will be useful), -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# The complete text of GPLv3 is at LICENSE file on source code root directory. -# Also), you can get the complete GNU General Public License at -*/ - -/** -\ingroup libparsers -\namespace ParsersAttributes -\brief Definition of parsers attributes namespace which stores a series of static strings constants used - to reference the attributes of objects in SQL/XML generation methods. - Each string stores the name of the attribute used in the schema file "sch" of the respective objects. -\note Creation date: 23/09/2008 -*/ - -#ifndef PARSERS_ATTRIBUTES_H -#define PARSERS_ATTRIBUTES_H - -/* Including QByteArray due to 'QByteArray has no toStdString()' - error on Qt 5.4 (Windows only) */ -#include -#include - -namespace ParsersAttributes { - extern const QString - _FALSE_, - _FILE_, - _LC_COLLATE_, - _LC_CTYPE_, - _TRUE_, - ADMIN_OPTION, - ADMIN_ROLES, - ALIAS, - ALIGNMENT, - ALIGN_OBJS_TO_GRID, - ALTER_CMDS, - ALLOW_CONNS, - ANALYZE_FUNC, - ANCESTOR_TABLE, - APPEND_AT_EOD, - APPENDED_SQL, - APPLICATION, - ARG_COUNT, - ARG_DEF_COUNT, - ARG_DEFAULTS, - ARG_MODES, - ARG_NAMES, - ARG_TYPES, - ARGUMENTS, - ASC_ORDER, - ASSIGNMENT, - ATTRIBUTE, - AUTO_BROWSE_DB, - AUTOSAVE_INTERVAL, - BACKGROUND_COLOR, - BASE_TYPE, - BEFORE, - BEHAVIOR_TYPE, - BOLD, - BORDER_COLOR, - BOTTOM, - BUFFERING, - BY_VALUE, - BYPASSRLS, - CACHE, - CANONICAL_FUNC, - CANVAS_CORNER_MOVE, - CASCADE, - CASE_SENSITIVE, - CAST_TYPE, - CATEGORY, - CHANGE, - CHANGELOG, - CHECK_EXP, - CHECK_UPDATE, - CK_CONSTR, - CLIENT_ENCODING, - CODE_COMPLETION, - CODE_FONT_SIZE, - CODE_FONT, - CODE_TAB_WIDTH, - COL_INDEXES, - COLLATABLE, - COLLATION, - COLLATIONS, - COLOR, - COLORS, - COLS_COMMENT, - COL_IS_IDENTITY, - COLUMN_ALIAS, - COLUMN, - COLUMNS, - COMMAND, - COMMANDS, - COMMENT, - COMMUTATOR_OP, - COMPARISON_TYPE, - COMPLETION_TRIGGER, - COMPOSITE_TYPE, - CONCURRENT, - CONDITION, - CONFIGURATION, - CONFIG_FILE, - CONFIRM_VALIDATION, - CONN_LIMIT, - CONNECT_CENTER_PNTS, - CONNECT_FK_TO_PK, - CONNECT_TABLE_EDGES, - CONNECT_PRIV, - CONNECTION, - CONNECTIONS, - CONNECTION_TIMEOUT, - CONSTR_DEFS, - CONSTR_INDEXES, - CONSTR_SQL_DISABLED, - CONSTRAINT, - CONSTRAINTS, - CONTENTS, - COPY_MODE, - COPY_OPTIONS, - COPY_TABLE, - CREATE_CMDS, - CREATE_PRIV, - CREATE, - CREATEDB, - CREATEROLE, - CROWS_FOOT, - CTE_EXPRESSION, - CUR_VERSION, - CUSTOM_COLOR, - CUSTOM_FILTER, - CUSTOMIDXS, - CYCLE, - DATABASE, - DATA_DIRECTORY, - DATE, - DB_MODEL, - DDL_END_TOKEN, - DECL_IN_TABLE, - DECLARATION, - DEFAULT_COLLATION, - DEFAULT_FOR_OPS, - DEFAULT_OWNER, - DEFAULT_SCHEMA, - DEFAULT_TABLESPACE, - DEFAULT_VALUE, - DEFAULT, - DEFER_TYPE, - DEFERRABLE, - DEFINITION, - DEL_ACTION, - DEL_EVENT, - DELETE_PRIV, - DELIMITER, - DEST_TYPE, - DST_TYPE, - DIFF, - DIMENSION, - DIRECTORY, - DISABLE_SMOOTHNESS, - DISPLAY_LINE_NUMBERS, - DOM_CONSTRAINT, - DOCK_WIDGETS, - DROP_CMDS, - DROP, - DST_COL_PATTERN, - DST_COLUMNS, - DST_ENCODING, - DST_FK_PATTERN, - DST_LABEL, - DST_REQUIRED, - DST_TABLE, - DYNAMIC_LIBRARY_PATH, - DYNAMIC_SHARED_MEMORY, - ELEMENT, - ELEMENTS, - ENCODING, - ENCRYPTED, - END_EXP, - ENUM_TYPE, - ENUMERATIONS, - EVENT_TYPE, - EVENT, - EVENTS, - EX_CONSTR, - EXACT_MATCH, - EXC_BUILTIN_ARRAYS, - EXCLUDE_ELEMENT, - EXEC_TYPE, - EXECUTE_PRIV, - EXECUTION_COST, - EXISTING_VALUE, - EXPLICIT, - EXPORT, - EXPORT_TO_FILE, - EXPRESSION, - EXPRESSIONS, - EXT_OBJ_OIDS, - FACTOR, - FADEIN_OBJECTS, - FADED_OUT, - FAMILY, - FAST_UPDATE, - FILE_ASSOCIATED, - FILL_COLOR, - FILTER_OIDS, - FILTER_TABLE_TYPES, - FILTER, - FINAL_FUNC, - FIRING_TYPE, - FK_COLUMN, - FK_CONSTR, - FK_DEFS, - FONT_SIZE, - FONT, - FOREGROUND_COLOR, - FOREIGN_KEYS, - FROM_EXP, - FUNCTION_TYPE, - FUNCTION, - GENERAL, - GEN_ALTER_CMDS, - GLOBAL, - GRANT_OP, - GRID_SIZE, - GROUP, - HANDLER_FUNC, - HANDLES_TYPE, - HAS_CHANGES, - HASHES, - HBA_FILE, - HIDE_EXT_ATTRIBS, - HIDE_REL_NAME, - HIDE_TABLE_TAGS, - HIGHLIGHT_LINES, - HIGHLIGHT_ORDER, - HISTORY_MAX_LENGTH, - ICON, - ID, - IDENTIFIER, - IDENTITY_TYPE, - IGNORED_CHARS, - IMPLICIT, - IMPORT, - INCREMENT, - IDENT_FILE, - INDEX_ELEMENT, - INDEX_TYPE, - INDEX, - INDEXES, - INFO, - INH_COLUMN, - INH_COLUMNS, - INHERIT, - INHERITED, - INITIAL_COND, - INITIAL_DATA, - INITIAL_EXP, - INLINE_FUNC, - INPUT_FUNC, - INS_EVENT, - INSERT_PRIV, - INTERNAL_LENGTH, - INTERVAL_TYPE, - INVERT_RANGESEL_TRIGGER, - IO_CAST, - IS_TEMPLATE, - ITALIC, - JOIN_FUNC, - LABEL, - LABELS_POS, - LANDSCAPE, - LANGUAGE, - LAST_POSITION, - LAST_SYS_OID, - LAST_VALUE, - LAST_ZOOM, - LEAKPROOF, - LEFT_TYPE, - LEFT, - LENGTH, - LIBRARY, - LIKE_TYPE, - LINE, - LINE_NUMBERS_COLOR, - LINE_NUMBERS_BG_COLOR, - LINE_HIGHLIGHT_COLOR, - LISTEN_ADDRESSES, - LOCALE, - LOCKER_ARC, - LOCKER_BODY, - LOGIN, - LOOKAHEAD_CHAR, - MATERIALIZED, - MAX_CONNECTIONS, - MAX_VALUE, - MAX_RESULT_ROWS, - MEMBER_ROLES, - MEMBER, - MERGES, - METADATA, - MIN_OBJECT_OPACITY, - MIN_VALUE, - MODE, - MODEL_AUTHOR, - NAME_LABEL, - NAME_PATTERNS, - NAME, - NAMES, - NEGATOR_OP, - NEW_NAME, - NEW_IDENTITY_TYPE, - NEW_VERSION, - NN_COLUMN, - NO_INHERIT, - NONE, - NOT_EXT_OBJECT, - NOT_NULL, - NULLS_FIRST, - OBJ_SELECTION, - OBJECT_ID, - OBJECT_FINDER, - OBJECT_TYPE, - OBJECT, - OBJECTS, - OID_FILTER_OP, - OID, - OIDS, - OLD_NAME, - OLD_VERSION, - OP_CLASS, - OP_CLASSES, - OP_FAMILY, - OP_LIST_SIZE, - OPERATOR_FUNC, - OPERATOR, - OPERATORS, - OUTPUT_FUNC, - OWNER_COLUMN, - OWNER, - PAPER_CUSTOM_SIZE, - PAPER_MARGIN, - PAPER_ORIENTATION, - PAPER_TYPE, - PARAM_IN, - PARAM_OUT, - PARAM_VARIADIC, - PARAMETER, - PARAMETERS, - PARENT, - PARENTS, - PARSABLE, - PARTIAL_MATCH, - PASSWORD, - PASSWORD_ENCRYPTION, - PATH, - PATTERNS, - PER_ROW, - PERMISSION, - PERMISSIVE, - PGMODELER_VERSION, - PGSQL_BASE_TYPE, - PGSQL_VERSION, - PLACEHOLDER, - PLACEHOLDERS, - PK_COL_PATTERN, - PK_COLUMN, - PK_CONSTR, - PK_PATTERN, - POINTS, - PORT, - PORTRAIT, - POSITION_INFO, - POSITION, - PRECISION, - PREDICATE, - PREFERRED, - PREPEND_AT_BOD, - PREPENDED_SQL, - PRINT_GRID, - PRINT_PG_NUM, - PRIVILEGES_GOP, - PRIVILEGES, - PROT_COLUMN, - PROTECTED, - RANGE_ATTRIBS, - RANGE_TYPE, - RECENT_MODELS, - RECENT, - RECT_VISIBLE, - RECURSIVE, - RECV_FUNC, - REDUCED_FORM, - REF_COLUMN, - REF_ROLES, - REF_TABLE, - REF_TYPE, - REFER, - REFERENCE, - REFERENCE_FK, - REFERENCES_PRIV, - REFERENCES, - REFERRERS, - REGULAR_EXP, - RELATION_TAB_VIEW, - RELATIONSHIP_11, - RELATIONSHIP_1N, - RELATIONSHIP_DEP, - RELATIONSHIP_FK, - RELATIONSHIP_GEN, - RELATIONSHIP_NN, - RELATIONSHIP, - RENAME, - REPLICATION, - RESTRICTION_FUNC, - RETURN_TABLE, - RETURN_TYPE, - RETURNS_SETOF, - REVOKE, - RIGHT_TYPE, - RIGHT, - RLS_ENABLED, - RLS_FORCED, - ROLE_TYPE, - ROLE, - ROLES, - ROW_AMOUNT, - RULES, - SAVE_LAST_POSITION, - SCHEMA, - SEARCH_PATH, - SECURITY_TYPE, - SELECT_EXP, - SELECT_PRIV, - SELECT_OBJECTS, - SEND_FUNC, - SEQUENCE, - SERVER_ENCODING, - SERVER_VERSION, - SERVER_PID, - SERVER_PROTOCOL, - SET_PERMS, - SHARED_OBJ, - SHELL_TYPES, - SHOW_CANVAS_GRID, - SHOW_PAGE_DELIMITERS, - SHOW_ATTRIBUTES_GRID, - SHOW_SOURCE_PANE, - SHOW_MAIN_MENU, - SIGNATURE, - SIMPLE_EXP, - SIMPLIFIED_OBJ_CREATION, - SINGLE_PK_COLUMN, - SIZE, - SNIPPET, - SORT_OP, - SOURCE_EDITOR_APP, - SOURCE_EDITOR_ARGS, - SOURCE_TYPE, - SRC_TYPE, - SPATIAL_TYPE, - SPECIAL_PK_COLS, - SQL_DISABLED, - SQL_OBJECT, - SQL_VALIDATION, - SQL_TOOL, - SRC_COL_PATTERN, - SRC_COLUMNS, - SRC_ENCODING, - SRC_FK_PATTERN, - SRC_LABEL, - SRC_REQUIRED, - SRC_TABLE, - SRID, - SSL, - SSL_CA_FILE, - SSL_CERT_FILE, - SSL_CRL_FILE, - SSL_KEY_FILE, - START, - STATE_TYPE, - STORAGE_PARAMS, - STORAGE, - STRATEGY_NUM, - STYLE, - STYLES, - SUBTYPE_DIFF_FUNC, - SUBTYPE, - SUPERUSER, - SYMBOL, - TABLE_BODY, - TABLE_EXT_BODY, - TABLE_NAME, - TABLE_OBJECT, - TABLE_SCHEMA_NAME, - TABLE_TITLE, - TABLE, - TABLE_TYPE, - TABLESPACE, - TAG, - TEMPLATE_DB, - TEMPORARY_PRIV, - TOP, - TPMOD_IN_FUNC, - TPMOD_OUT_FUNC, - TRANSITION_FUNC, - TRIGGER_FUNC, - TRIGGER_PRIV, - TRIGGERS, - TRUNC_EVENT, - TRUNCATE_CMDS, - TRUNCATE_PRIV, - TRUNCATE, - TRUSTED, - TYPE_ATTRIBUTE, - TYPE_OID, - TYPE, - TYPES, - TYPE_CLASS, - UI_LANGUAGE, - UNDERLINE, - UNIQUE, - UNLOGGED, - UNSET_PERMS, - UNSET, - UPD_ACTION, - UPD_EVENT, - UPDATE_PRIV, - UQ_COLUMN, - UQ_CONSTR, - UQ_PATTERN, - USAGE_PRIV, - USE_CURVED_LINES, - USE_PLACEHOLDERS, - USE_SORTING, - USE_UNIQUE_NAMES, - USING_EXP, - VALIDATOR_FUNC, - VALIDATOR, - VALIDITY, - VALIDATION, - VALUE, - VALUES, - VARIABLE, - VARIATION, - VIEW_BODY, - VIEW_EXT_BODY, - VIEW_NAME, - VIEW_SCHEMA_NAME, - VIEW_TITLE, - VISIBLE, - WIDGET, - WILDCARD, - WINDOW_FUNC, - WITH_NO_DATA, - WITH_TIMEZONE, - WITHOUT_OIDS, - WORD_DELIMITERS, - WORD_SEPARATORS, - WORKING_DIR, - X_POS, - Y_POS; -} - -#endif diff --git a/libparsers/src/schemaparser.cpp b/libparsers/src/schemaparser.cpp index 3bb7248e9e..c8763556fa 100644 --- a/libparsers/src/schemaparser.cpp +++ b/libparsers/src/schemaparser.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -17,74 +17,74 @@ */ #include "schemaparser.h" -#include "parsersattributes.h" - -const char SchemaParser::CHR_COMMENT='#'; -const char SchemaParser::CHR_LINE_END='\n'; -const char SchemaParser::CHR_TABULATION='\t'; -const char SchemaParser::CHR_SPACE=' '; -const char SchemaParser::CHR_INI_ATTRIB='{'; -const char SchemaParser::CHR_END_ATTRIB='}'; -const char SchemaParser::CHR_INI_CONDITIONAL='%'; -const char SchemaParser::CHR_INI_METACHAR='$'; -const char SchemaParser::CHR_INI_PURETEXT='['; -const char SchemaParser::CHR_END_PURETEXT=']'; -const char SchemaParser::CHR_INI_CEXPR='('; -const char SchemaParser::CHR_END_CEXPR=')'; -const char SchemaParser::CHR_VAL_DELIM='"'; -const char SchemaParser::CHR_VALUE_OF='@'; - -const QString SchemaParser::TOKEN_IF=QString("if"); -const QString SchemaParser::TOKEN_THEN=QString("then"); -const QString SchemaParser::TOKEN_ELSE=QString("else"); -const QString SchemaParser::TOKEN_END=QString("end"); -const QString SchemaParser::TOKEN_OR=QString("or"); -const QString SchemaParser::TOKEN_AND=QString("and"); -const QString SchemaParser::TOKEN_NOT=QString("not"); -const QString SchemaParser::TOKEN_SET=QString("set"); -const QString SchemaParser::TOKEN_UNSET=QString("unset"); - -const QString SchemaParser::TOKEN_META_SP=QString("sp"); -const QString SchemaParser::TOKEN_META_BR=QString("br"); -const QString SchemaParser::TOKEN_META_TB=QString("tb"); -const QString SchemaParser::TOKEN_META_OB=QString("ob"); -const QString SchemaParser::TOKEN_META_CB=QString("cb"); -const QString SchemaParser::TOKEN_META_OC=QString("oc"); -const QString SchemaParser::TOKEN_META_CC=QString("cc"); - -const QString SchemaParser::TOKEN_EQ_OP=QString("=="); -const QString SchemaParser::TOKEN_NE_OP=QString("!="); -const QString SchemaParser::TOKEN_GT_OP=QString(">"); -const QString SchemaParser::TOKEN_LT_OP=QString("<"); -const QString SchemaParser::TOKEN_GT_EQ_OP=QString(">="); -const QString SchemaParser::TOKEN_LT_EQ_OP=QString("<="); - -const QRegExp SchemaParser::ATTR_REGEXP=QRegExp("^([a-z])([a-z]*|(\\d)*|(\\-)*|(_)*)+", Qt::CaseInsensitive); +#include "attributes.h" + +const char SchemaParser::CharComment='#'; +const char SchemaParser::CharLineEnd='\n'; +const char SchemaParser::CharTabulation='\t'; +const char SchemaParser::CharSpace=' '; +const char SchemaParser::CharIniAttribute='{'; +const char SchemaParser::CharEndAttribute='}'; +const char SchemaParser::CharIniConditional='%'; +const char SchemaParser::CharIniMetachar='$'; +const char SchemaParser::CharIniPlainText='['; +const char SchemaParser::CharEndPlainText=']'; +const char SchemaParser::CharIniCompExpr='('; +const char SchemaParser::CharEndCompExpr=')'; +const char SchemaParser::CharValueDelim='"'; +const char SchemaParser::CharValueOf='@'; + +const QString SchemaParser::TokenIf=QString("if"); +const QString SchemaParser::TokenThen=QString("then"); +const QString SchemaParser::TokenElse=QString("else"); +const QString SchemaParser::TokenEnd=QString("end"); +const QString SchemaParser::TokenOr=QString("or"); +const QString SchemaParser::TokenAnd=QString("and"); +const QString SchemaParser::TokenNot=QString("not"); +const QString SchemaParser::TokenSet=QString("set"); +const QString SchemaParser::TokenUnset=QString("unset"); + +const QString SchemaParser::TokenMetaSp=QString("sp"); +const QString SchemaParser::TokenMetaBr=QString("br"); +const QString SchemaParser::TokenMetaTb=QString("tb"); +const QString SchemaParser::TokenMetaOb=QString("ob"); +const QString SchemaParser::TokenMetaCb=QString("cb"); +const QString SchemaParser::TokenMetaOc=QString("oc"); +const QString SchemaParser::TokenMetaCc=QString("cc"); + +const QString SchemaParser::TokenEqOper=QString("=="); +const QString SchemaParser::TokenNeOper=QString("!="); +const QString SchemaParser::TokenGtOper=QString(">"); +const QString SchemaParser::TokenLtOper=QString("<"); +const QString SchemaParser::TokenGtEqOper=QString(">="); +const QString SchemaParser::TokenLtEqOper=QString("<="); + +const QRegExp SchemaParser::AttribRegExp=QRegExp("^([a-z])([a-z]*|(\\d)*|(\\-)*|(_)*)+", Qt::CaseInsensitive); SchemaParser::SchemaParser(void) { line=column=comment_count=0; ignore_unk_atribs=ignore_empty_atribs=false; - pgsql_version=PgSQLVersions::DEFAULT_VERSION; + pgsql_version=PgSqlVersions::DefaulVersion; } void SchemaParser::setPgSQLVersion(const QString &pgsql_ver) { unsigned curr_ver = QString(pgsql_ver).remove('.').toUInt(), - version90 = QString(PgSQLVersions::PGSQL_VERSION_90).remove('.').toUInt(), - default_ver = QString(PgSQLVersions::DEFAULT_VERSION).remove('.').toUInt(); + version90 = QString(PgSqlVersions::PgSqlVersion90).remove('.').toUInt(), + default_ver = QString(PgSqlVersions::DefaulVersion).remove('.').toUInt(); if(curr_ver != 0 && (curr_ver < version90)) - throw Exception(Exception::getErrorMessage(ERR_INV_POSTGRESQL_VERSION) + throw Exception(Exception::getErrorMessage(ErrorCode::InvPostgreSQLVersion) .arg(pgsql_ver) - .arg(PgSQLVersions::PGSQL_VERSION_90) - .arg(PgSQLVersions::DEFAULT_VERSION), - ERR_INV_POSTGRESQL_VERSION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(PgSqlVersions::PgSqlVersion90) + .arg(PgSqlVersions::DefaulVersion), + ErrorCode::InvPostgreSQLVersion,__PRETTY_FUNCTION__,__FILE__,__LINE__); if(curr_ver > 0 && curr_ver <= default_ver) pgsql_version=pgsql_ver; else - pgsql_version=PgSQLVersions::DEFAULT_VERSION; + pgsql_version=PgSqlVersions::DefaulVersion; } QString SchemaParser::getPgSQLVersion(void) @@ -100,17 +100,17 @@ QStringList SchemaParser::extractAttributes(void) for(QString line : buffer) { //Find the first occurrence of '{' in the line - start=line.indexOf(CHR_INI_ATTRIB, start); + start=line.indexOf(CharIniAttribute, start); while(start >= 0 && start < line.size()) { - end=line.indexOf(CHR_END_ATTRIB, start); + end=line.indexOf(CharEndAttribute, start); if(end >= 0) { //Extract the name between {} and push it into the list attribs.push_back(line.mid(start + 1, end - start -1)); //Start searching new attribute start now from the last position - start=line.indexOf(CHR_INI_ATTRIB, end); + start=line.indexOf(CharIniAttribute, end); } else break; @@ -151,13 +151,13 @@ void SchemaParser::loadBuffer(const QString &buf) /* Since the method getline discards the \n when the line was just a line break its needed to treat it in order to not lost it */ - if(lin.isEmpty()) lin+=CHR_LINE_END; + if(lin.isEmpty()) lin+=CharLineEnd; //If the entire line is commented out increases the comment lines counter - if(lin[0]==CHR_COMMENT) comment_count++; + if(lin[0]==CharComment) comment_count++; //Looking for the position of other comment characters for deletion - pos=lin.indexOf(CHR_COMMENT); + pos=lin.indexOf(CharComment); //Removes the characters from the found position if(pos >= 0) @@ -166,8 +166,8 @@ void SchemaParser::loadBuffer(const QString &buf) if(!lin.isEmpty()) { //Add a line break in case the last character is not - if(lin[lin.size()-1]!=CHR_LINE_END) - lin+=CHR_LINE_END; + if(lin[lin.size()-1]!=CharLineEnd) + lin+=CharLineEnd; //Add the treated line in the buffer buffer.push_back(lin); @@ -187,8 +187,8 @@ void SchemaParser::loadFile(const QString &filename) input.open(QFile::ReadOnly); if(!input.isOpen()) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED).arg(filename), - ERR_FILE_DIR_NOT_ACCESSED,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed).arg(filename), + ErrorCode::FileDirectoryNotAccessed,__PRETTY_FUNCTION__,__FILE__,__LINE__); buf=input.readAll(); input.close(); @@ -209,7 +209,7 @@ QString SchemaParser::getAttribute(void) /* Only start extracting an attribute if it starts with a { even if the current character is an attribute delimiter */ - if(current_line[column]!=CHR_INI_ATTRIB) + if(current_line[column]!=CharIniAttribute) error=true; else { @@ -223,14 +223,14 @@ QString SchemaParser::getAttribute(void) /* Attempt to extract an attribute until a space, end of line or attribute is encountered */ - while(current_line[column]!=CHR_LINE_END && - current_line[column]!=CHR_SPACE && - current_line[column]!=CHR_TABULATION && + while(current_line[column]!=CharLineEnd && + current_line[column]!=CharSpace && + current_line[column]!=CharTabulation && !end_attrib && !error) { - if(current_line[column]!=CHR_END_ATTRIB) + if(current_line[column]!=CharEndAttribute) atrib+=current_line[column]; - else if(current_line[column]==CHR_END_ATTRIB && !atrib.isEmpty()) + else if(current_line[column]==CharEndAttribute && !atrib.isEmpty()) end_attrib=true; else error=true; @@ -245,15 +245,15 @@ QString SchemaParser::getAttribute(void) if(error) { - throw Exception(QString(Exception::getErrorMessage(ERR_INV_SYNTAX)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidSyntax) .arg(filename).arg((line + comment_count + 1)).arg((column+1)), - ERR_INV_SYNTAX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidSyntax,__PRETTY_FUNCTION__,__FILE__,__LINE__); } - else if(!ATTR_REGEXP.exactMatch(atrib)) + else if(!AttribRegExp.exactMatch(atrib)) { - throw Exception(QString(Exception::getErrorMessage(ERR_INV_ATTRIBUTE)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidAttribute) .arg(atrib).arg(filename).arg((line + comment_count + 1)).arg((column+1)), - ERR_INV_ATTRIBUTE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidAttribute,__PRETTY_FUNCTION__,__FILE__,__LINE__); } return(atrib); @@ -272,10 +272,10 @@ QString SchemaParser::getWord(void) { /* Extract the word while it is not end of line, space or special character */ - while(current_line[column]!=CHR_LINE_END && + while(current_line[column]!=CharLineEnd && !isSpecialCharacter(current_line[column].toLatin1()) && - current_line[column]!=CHR_SPACE && - current_line[column]!=CHR_TABULATION) + current_line[column]!=CharSpace && + current_line[column]!=CharTabulation) { word+=current_line[column]; column++; @@ -293,23 +293,23 @@ QString SchemaParser::getPureText(void) current_line=buffer[line]; //Attempt to extract a pure text if the first character is a [ - if(current_line[column]==CHR_INI_PURETEXT) + if(current_line[column]==CharIniPlainText) { //Moves to the next character that contains the beginning of the text column++; /* Extracts the text while the end of pure text (]), end of buffer or beginning of other pure text ([) is reached */ - while(current_line[column]!=CHR_END_PURETEXT && + while(current_line[column]!=CharEndPlainText && line < buffer.size() && - current_line[column]!=CHR_INI_PURETEXT) + current_line[column]!=CharIniPlainText) { text+=current_line[column]; /* Special case to end of line. Unlike other elements of language, a pure text can be extracted until the end of the buffer, thus, this method also controls the lines transitions */ - if(current_line[column]==CHR_LINE_END) + if(current_line[column]==CharLineEnd) { //Step to the next line line++; @@ -321,7 +321,7 @@ QString SchemaParser::getPureText(void) else column++; } - if(current_line[column]==CHR_END_PURETEXT) + if(current_line[column]==CharEndPlainText) column++; else error=true; @@ -330,9 +330,9 @@ QString SchemaParser::getPureText(void) if(error) { - throw Exception(QString(Exception::getErrorMessage(ERR_INV_SYNTAX)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidSyntax) .arg(filename).arg((line + comment_count + 1)).arg((column+1)), - ERR_INV_SYNTAX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidSyntax,__PRETTY_FUNCTION__,__FILE__,__LINE__); } return(text); @@ -346,7 +346,7 @@ QString SchemaParser::getConditional(void) current_line=buffer[line]; //Will initiate extraction if a % is found - if(current_line[column]==CHR_INI_CONDITIONAL) + if(current_line[column]==CharIniConditional) { /* Passa para o próximo caractere que é o início do do nome da palavra condicional */ @@ -354,9 +354,9 @@ QString SchemaParser::getConditional(void) /* Moves to the next character that is the beginning of the name of the conditional word */ - while(current_line[column]!=CHR_LINE_END && - current_line[column]!=CHR_SPACE && - current_line[column]!=CHR_TABULATION) + while(current_line[column]!=CharLineEnd && + current_line[column]!=CharSpace && + current_line[column]!=CharTabulation) { conditional+=current_line[column]; column++; @@ -369,9 +369,9 @@ QString SchemaParser::getConditional(void) if(error) { - throw Exception(QString(Exception::getErrorMessage(ERR_INV_SYNTAX)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidSyntax) .arg(filename).arg(line + comment_count + 1).arg(column+1), - ERR_INV_SYNTAX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidSyntax,__PRETTY_FUNCTION__,__FILE__,__LINE__); } return(conditional); @@ -385,15 +385,15 @@ QString SchemaParser::getMetaCharacter(void) current_line=buffer[line]; //Begins the extraction in case of a $ is found - if(current_line[column]==CHR_INI_METACHAR) + if(current_line[column]==CharIniMetachar) { //Moves to the next character that is the beginning of the metacharacter column++; //Extracts the metacharacter until doesn't finds a space or end of line - while(current_line[column]!=CHR_LINE_END && - current_line[column]!=CHR_SPACE && - current_line[column]!=CHR_TABULATION) + while(current_line[column]!=CharLineEnd && + current_line[column]!=CharSpace && + current_line[column]!=CharTabulation) { meta+=current_line[column]; column++; @@ -406,9 +406,9 @@ QString SchemaParser::getMetaCharacter(void) if(error) { - throw Exception(QString(Exception::getErrorMessage(ERR_INV_SYNTAX)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidSyntax) .arg(filename).arg(line + comment_count + 1).arg(column+1), - ERR_INV_SYNTAX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidSyntax,__PRETTY_FUNCTION__,__FILE__,__LINE__); } return(meta); @@ -416,17 +416,17 @@ QString SchemaParser::getMetaCharacter(void) bool SchemaParser::isSpecialCharacter(char chr) { - return(chr==CHR_INI_ATTRIB || chr==CHR_END_ATTRIB || - chr==CHR_INI_CONDITIONAL || chr==CHR_INI_METACHAR || - chr==CHR_INI_PURETEXT || chr==CHR_END_PURETEXT); + return(chr==CharIniAttribute || chr==CharEndAttribute || + chr==CharIniConditional || chr==CharIniMetachar || + chr==CharIniPlainText || chr==CharEndPlainText); } bool SchemaParser::evaluateComparisonExpr(void) { QString curr_line, attrib, value, oper, valid_op_chrs="=!<>fi"; bool error=false, end_eval=false, expr_is_true=true; - static QStringList opers = { TOKEN_EQ_OP, TOKEN_NE_OP, TOKEN_GT_OP, - TOKEN_LT_OP, TOKEN_GT_EQ_OP, TOKEN_LT_EQ_OP }; + static QStringList opers = { TokenEqOper, TokenNeOper, TokenGtOper, + TokenLtOper, TokenGtEqOper, TokenLtEqOper }; try { @@ -439,12 +439,12 @@ bool SchemaParser::evaluateComparisonExpr(void) /* If the scan reached the end of the line and the expression was not closed raises an syntax error Comparison expr must start and end in the same line */ - if(curr_line[column]==CHR_LINE_END && !end_eval) + if(curr_line[column]==CharLineEnd && !end_eval) error=true; switch(curr_line[column].toLatin1()) { - case CHR_INI_ATTRIB: + case CharIniAttribute: /* Extract the attribute (the first element in the expression) only if the comparison operator and values aren't extracted */ if(attrib.isEmpty() && oper.isEmpty() && value.isEmpty()) @@ -453,7 +453,7 @@ bool SchemaParser::evaluateComparisonExpr(void) error=true; break; - case CHR_VAL_DELIM: + case CharValueDelim: /* Extract the value (the last element in the expression) only if the attribute and operator were extracted */ if(value.isEmpty() && !attrib.isEmpty() && !oper.isEmpty()) @@ -464,9 +464,9 @@ bool SchemaParser::evaluateComparisonExpr(void) { value+=curr_line[column++]; - if(curr_line[column]==CHR_VAL_DELIM) + if(curr_line[column]==CharValueDelim) { - value+=CHR_VAL_DELIM; + value+=CharValueDelim; column++; break; } @@ -477,7 +477,7 @@ bool SchemaParser::evaluateComparisonExpr(void) break; - case CHR_END_CEXPR: + case CharEndCompExpr: column++; //If one of the elements are missing, raise an syntax error @@ -485,20 +485,20 @@ bool SchemaParser::evaluateComparisonExpr(void) error=true; else if(!opers.contains(QString(oper).remove('f').remove('i'))) { - throw Exception(QString(Exception::getErrorMessage(ERR_INV_OPERATOR_IN_EXPR)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidOperatorInExpression) .arg(oper).arg(filename).arg((line + comment_count + 1)).arg((column+1)), - ERR_INV_OPERATOR_IN_EXPR,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidOperatorInExpression,__PRETTY_FUNCTION__,__FILE__,__LINE__); } else if(attributes.count(attrib)==0 && !ignore_unk_atribs) { - throw Exception(Exception::getErrorMessage(ERR_UNK_ATTRIBUTE) + throw Exception(Exception::getErrorMessage(ErrorCode::UnkownAttribute) .arg(attrib).arg(filename).arg((line + comment_count +1)).arg((column+1)), - ERR_UNK_ATTRIBUTE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::UnkownAttribute,__PRETTY_FUNCTION__,__FILE__,__LINE__); } else { QVariant left_val, right_val; - value.remove(CHR_VAL_DELIM); + value.remove(CharValueDelim); //Evaluating the attribute value against the one captured on the expression without casting if(oper.endsWith('f')) @@ -519,12 +519,12 @@ bool SchemaParser::evaluateComparisonExpr(void) right_val = QVariant(value); } - expr_is_true=((oper==TOKEN_EQ_OP && (left_val == right_val)) || - (oper==TOKEN_NE_OP && (left_val != right_val)) || - (oper==TOKEN_GT_OP && (left_val > right_val)) || - (oper==TOKEN_LT_OP && (left_val < right_val)) || - (oper==TOKEN_GT_EQ_OP && (left_val >= right_val)) || - (oper==TOKEN_LT_EQ_OP && (left_val <= right_val))); + expr_is_true=((oper==TokenEqOper && (left_val == right_val)) || + (oper==TokenNeOper && (left_val != right_val)) || + (oper==TokenGtOper && (left_val > right_val)) || + (oper==TokenLtOper && (left_val < right_val)) || + (oper==TokenGtEqOper && (left_val >= right_val)) || + (oper==TokenLtEqOper && (left_val <= right_val))); end_eval=true; } @@ -550,13 +550,13 @@ bool SchemaParser::evaluateComparisonExpr(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } if(error) - throw Exception(QString(Exception::getErrorMessage(ERR_INV_SYNTAX)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidSyntax) .arg(filename).arg((line + comment_count + 1)).arg((column+1)), - ERR_INV_SYNTAX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidSyntax,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(expr_is_true); } @@ -576,11 +576,11 @@ void SchemaParser::defineAttribute(void) switch(curr_line[column].toLatin1()) { - case CHR_LINE_END: + case CharLineEnd: end_def=true; break; - case CHR_VALUE_OF: + case CharValueOf: if(!use_val_as_name) { use_val_as_name=true; @@ -591,11 +591,11 @@ void SchemaParser::defineAttribute(void) error=true; break; - case CHR_INI_CONDITIONAL: + case CharIniConditional: error=true; break; - case CHR_INI_ATTRIB: + case CharIniAttribute: if(new_attrib.isEmpty()) new_attrib=getAttribute(); else @@ -605,20 +605,20 @@ void SchemaParser::defineAttribute(void) if(attributes.count(attrib)==0 && !ignore_unk_atribs) { - throw Exception(Exception::getErrorMessage(ERR_UNK_ATTRIBUTE) + throw Exception(Exception::getErrorMessage(ErrorCode::UnkownAttribute) .arg(attrib).arg(filename).arg((line + comment_count +1)).arg((column+1)), - ERR_UNK_ATTRIBUTE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::UnkownAttribute,__PRETTY_FUNCTION__,__FILE__,__LINE__); } value+=attributes[attrib]; } break; - case CHR_INI_PURETEXT: + case CharIniPlainText: value+=getPureText(); break; - case CHR_INI_METACHAR: + case CharIniMetachar: value+=translateMetaCharacter(getMetaCharacter()); break; @@ -634,7 +634,7 @@ void SchemaParser::defineAttribute(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } if(!error) @@ -642,11 +642,11 @@ void SchemaParser::defineAttribute(void) attrib=(use_val_as_name ? attributes[new_attrib] : new_attrib); //Checking if the attribute has a valid name - if(!ATTR_REGEXP.exactMatch(attrib)) + if(!AttribRegExp.exactMatch(attrib)) { - throw Exception(QString(Exception::getErrorMessage(ERR_INV_ATTRIBUTE)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidAttribute) .arg(attrib).arg(filename).arg((line + comment_count + 1)).arg((column+1)), - ERR_INV_ATTRIBUTE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidAttribute,__PRETTY_FUNCTION__,__FILE__,__LINE__); } /* Creates the attribute in the attribute map of the schema, making the attribute @@ -655,9 +655,9 @@ void SchemaParser::defineAttribute(void) attributes[attrib]=value; } else - throw Exception(QString(Exception::getErrorMessage(ERR_INV_SYNTAX)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidSyntax) .arg(filename).arg((line + comment_count + 1)).arg((column+1)), - ERR_INV_SYNTAX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidSyntax,__PRETTY_FUNCTION__,__FILE__,__LINE__); } void SchemaParser::unsetAttribute(void) @@ -675,40 +675,39 @@ void SchemaParser::unsetAttribute(void) switch(curr_line[column].toLatin1()) { - case CHR_LINE_END: + case CharLineEnd: end_def=true; break; - case CHR_INI_ATTRIB: + case CharIniAttribute: attrib=getAttribute(); if(attributes.count(attrib)==0 && !ignore_unk_atribs) { - throw Exception(Exception::getErrorMessage(ERR_UNK_ATTRIBUTE) + throw Exception(Exception::getErrorMessage(ErrorCode::UnkownAttribute) .arg(attrib).arg(filename).arg((line + comment_count +1)).arg((column+1)), - ERR_UNK_ATTRIBUTE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::UnkownAttribute,__PRETTY_FUNCTION__,__FILE__,__LINE__); } - else if(!ATTR_REGEXP.exactMatch(attrib)) + else if(!AttribRegExp.exactMatch(attrib)) { - throw Exception(QString(Exception::getErrorMessage(ERR_INV_ATTRIBUTE)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidAttribute) .arg(attrib).arg(filename).arg((line + comment_count + 1)).arg((column+1)), - ERR_INV_ATTRIBUTE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidAttribute,__PRETTY_FUNCTION__,__FILE__,__LINE__); } attributes[attrib]=QString(); break; default: - throw Exception(QString(Exception::getErrorMessage(ERR_INV_SYNTAX)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidSyntax) .arg(filename).arg((line + comment_count + 1)).arg((column+1)), - ERR_INV_SYNTAX,__PRETTY_FUNCTION__,__FILE__,__LINE__); - break; + ErrorCode::InvalidSyntax,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } bool SchemaParser::evaluateExpression(void) @@ -725,7 +724,7 @@ bool SchemaParser::evaluateExpression(void) { ignoreBlankChars(current_line); - if(current_line[column]==CHR_LINE_END) + if(current_line[column]==CharLineEnd) { line++; if(line < buffer.size()) @@ -741,20 +740,20 @@ bool SchemaParser::evaluateExpression(void) switch(current_line[column].toLatin1()) { //Extract the next conditional token - case CHR_INI_CONDITIONAL: + case CharIniConditional: prev_cond=cond; cond=getConditional(); //Error 1: %if {a} %or %or %then error=(cond==prev_cond || //Error 2: %if {a} %and %or %then - (cond==TOKEN_AND && prev_cond==TOKEN_OR) || + (cond==TokenAnd && prev_cond==TokenOr) || //Error 3: %if {a} %or %and %then - (cond==TOKEN_OR && prev_cond==TOKEN_AND) || + (cond==TokenOr && prev_cond==TokenAnd) || //Error 4: %if %and {a} %then - (attrib_count==0 && (cond==TOKEN_AND || cond==TOKEN_OR))); + (attrib_count==0 && (cond==TokenAnd || cond==TokenOr))); - if(cond==TOKEN_THEN) + if(cond==TokenThen) { /* Returns the parser to the token %then because additional operations is done whe this token is found */ @@ -762,31 +761,31 @@ bool SchemaParser::evaluateExpression(void) end_eval=true; //Error 1: %if {a} %not %then - error=(prev_cond==TOKEN_NOT || + error=(prev_cond==TokenNot || //Error 2: %if %then attrib_count==0 || //Error 3: %if {a} %and %then (and_or_count!=attrib_count-1)); } - else if(cond==TOKEN_OR || cond==TOKEN_AND) + else if(cond==TokenOr || cond==TokenAnd) and_or_count++; break; - case CHR_INI_ATTRIB: + case CharIniAttribute: attrib=getAttribute(); //Raises an error if the attribute does is unknown if(attributes.count(attrib)==0 && !ignore_unk_atribs) { - throw Exception(Exception::getErrorMessage(ERR_UNK_ATTRIBUTE) + throw Exception(Exception::getErrorMessage(ErrorCode::UnkownAttribute) .arg(attrib).arg(filename).arg((line + comment_count +1)).arg((column+1)), - ERR_UNK_ATTRIBUTE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::UnkownAttribute,__PRETTY_FUNCTION__,__FILE__,__LINE__); } //Error 1: A conditional token other than %or %not %and if found on conditional expression - error=(!cond.isEmpty() && cond!=TOKEN_OR && cond!=TOKEN_AND && cond!=TOKEN_NOT) || + error=(!cond.isEmpty() && cond!=TokenOr && cond!=TokenAnd && cond!=TokenNot) || //Error 2: A %not token if found after an attribute: %if {a} %not %then - (attrib_count > 0 && cond==TOKEN_NOT && prev_cond.isEmpty()) || + (attrib_count > 0 && cond==TokenNot && prev_cond.isEmpty()) || //Error 3: Two attributes not separated by any conditional token: %if {a} {b} %then (attrib_count > 0 && cond.isEmpty()); @@ -796,12 +795,12 @@ bool SchemaParser::evaluateExpression(void) if(!error) { //Appliyng the NOT operator if found - attrib_true=(cond==TOKEN_NOT ? attributes[attrib].isEmpty() : !attributes[attrib].isEmpty()); + attrib_true=(cond==TokenNot ? attributes[attrib].isEmpty() : !attributes[attrib].isEmpty()); //Executing the AND operation if the token is found - if(cond==TOKEN_AND || prev_cond==TOKEN_AND) + if(cond==TokenAnd || prev_cond==TokenAnd) expr_is_true=(expr_is_true && attrib_true); - else if(cond==TOKEN_OR || prev_cond==TOKEN_OR) + else if(cond==TokenOr || prev_cond==TokenOr) expr_is_true=(expr_is_true || attrib_true); else expr_is_true=attrib_true; @@ -811,16 +810,16 @@ bool SchemaParser::evaluateExpression(void) } break; - case CHR_INI_CEXPR: + case CharIniCompExpr: comp_true=evaluateComparisonExpr(); //Appliyng the NOT operator if found - if(cond==TOKEN_NOT) comp_true=!comp_true; + if(cond==TokenNot) comp_true=!comp_true; //Executing the AND operation if the token is found - if(cond==TOKEN_AND || prev_cond==TOKEN_AND) + if(cond==TokenAnd || prev_cond==TokenAnd) expr_is_true=(expr_is_true && comp_true); - else if(cond==TOKEN_OR || prev_cond==TOKEN_OR) + else if(cond==TokenOr || prev_cond==TokenOr) expr_is_true=(expr_is_true || comp_true); else expr_is_true=comp_true; @@ -839,14 +838,14 @@ bool SchemaParser::evaluateExpression(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } if(error) { - throw Exception(QString(Exception::getErrorMessage(ERR_INV_SYNTAX)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidSyntax) .arg(filename).arg((line + comment_count + 1)).arg((column+1)), - ERR_INV_SYNTAX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidSyntax,__PRETTY_FUNCTION__,__FILE__,__LINE__); } return(expr_is_true); @@ -855,25 +854,25 @@ bool SchemaParser::evaluateExpression(void) void SchemaParser::ignoreBlankChars(const QString &line) { while(column < line.size() && - (line[column]==CHR_SPACE || - line[column]==CHR_TABULATION)) column++; + (line[column]==CharSpace || + line[column]==CharTabulation)) column++; } char SchemaParser::translateMetaCharacter(const QString &meta) { - static map metas={{ TOKEN_META_SP, CHR_SPACE }, - { TOKEN_META_TB, CHR_TABULATION }, - { TOKEN_META_BR, CHR_LINE_END }, - { TOKEN_META_OB, CHR_INI_PURETEXT }, - { TOKEN_META_CB, CHR_END_PURETEXT }, - { TOKEN_META_OC, CHR_INI_ATTRIB }, - { TOKEN_META_CC, CHR_END_ATTRIB }}; + static map metas={{ TokenMetaSp, CharSpace }, + { TokenMetaTb, CharTabulation }, + { TokenMetaBr, CharLineEnd }, + { TokenMetaOb, CharIniPlainText }, + { TokenMetaCb, CharEndPlainText }, + { TokenMetaOc, CharIniAttribute }, + { TokenMetaCc, CharEndAttribute }}; if(metas.count(meta)==0) { - throw Exception(QString(Exception::getErrorMessage(ERR_INV_METACHARACTER)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidMetacharacter) .arg(meta).arg(filename).arg(line + comment_count +1).arg(column+1), - ERR_INV_METACHARACTER,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidMetacharacter,__PRETTY_FUNCTION__,__FILE__,__LINE__); } return(metas.at(meta)); @@ -885,29 +884,29 @@ QString SchemaParser::getCodeDefinition(const QString & obj_name, attribs_map &a { QString filename; - if(def_type==SQL_DEFINITION) + if(def_type==SqlDefinition) { //Formats the filename - filename=GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::SQL_SCHEMA_DIR + GlobalAttributes::DIR_SEPARATOR + obj_name + GlobalAttributes::SCHEMA_EXT; + filename=GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + GlobalAttributes::SQLSchemaDir + GlobalAttributes::DirSeparator + obj_name + GlobalAttributes::SchemaExt; - attribs[ParsersAttributes::PGSQL_VERSION]=pgsql_version; + attribs[Attributes::PgSqlVersion]=pgsql_version; //Try to get the object definitin from the specified path return(getCodeDefinition(filename, attribs)); } else { - filename=GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::XML_SCHEMA_DIR + GlobalAttributes::DIR_SEPARATOR + obj_name + - GlobalAttributes::SCHEMA_EXT; + filename=GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + GlobalAttributes::XMLSchemaDir + GlobalAttributes::DirSeparator + obj_name + + GlobalAttributes::SchemaExt; return(convertCharsToXMLEntities(getCodeDefinition(filename, attribs))); } } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(), __PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -979,14 +978,14 @@ QString SchemaParser::convertCharsToXMLEntities(QString buf) if(str_aux.contains(QRegExp("(&|\\<|\\>|\")"))) { //Replaces the char by the XML entities - if(!str_aux.contains(XMLParser::CHAR_QUOT) && !str_aux.contains(XMLParser::CHAR_LT) && - !str_aux.contains(XMLParser::CHAR_GT) && !str_aux.contains(XMLParser::CHAR_AMP) && - !str_aux.contains(XMLParser::CHAR_APOS) && str_aux.contains('&')) - str_aux.replace('&', XMLParser::CHAR_AMP); + if(!str_aux.contains(XmlParser::CharQuot) && !str_aux.contains(XmlParser::CharLt) && + !str_aux.contains(XmlParser::CharGt) && !str_aux.contains(XmlParser::CharAmp) && + !str_aux.contains(XmlParser::CharApos) && str_aux.contains('&')) + str_aux.replace('&', XmlParser::CharAmp); - str_aux.replace('"',XMLParser::CHAR_QUOT); - str_aux.replace('<',XMLParser::CHAR_LT); - str_aux.replace('>',XMLParser::CHAR_GT); + str_aux.replace('"',XmlParser::CharQuot); + str_aux.replace('<',XmlParser::CharLt); + str_aux.replace('>',XmlParser::CharGt); //Puts on the original XML definition the modified string lin.replace(attr_start, count, str_aux); @@ -1043,28 +1042,28 @@ QString SchemaParser::getCodeDefinition(attribs_map &attribs) { /* Increments the number of rows causing the parser to get the next line buffer for analysis */ - case CHR_LINE_END: + case CharLineEnd: line++; column=0; break; - case CHR_TABULATION: - case CHR_SPACE: + case CharTabulation: + case CharSpace: //The parser will ignore the spaces that are not within pure texts - while(buffer[line][column]==CHR_SPACE || - buffer[line][column]==CHR_TABULATION) column++; + while(buffer[line][column]==CharSpace || + buffer[line][column]==CharTabulation) column++; break; //Metacharacter extraction - case CHR_INI_METACHAR: + case CharIniMetachar: meta=getMetaCharacter(); //Checks whether the metacharacter is part of the 'if' expression (this is an error) if(if_level>=0 && vet_tk_if[if_level] && !vet_tk_then[if_level]) { - throw Exception(QString(Exception::getErrorMessage(ERR_INV_SYNTAX)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidSyntax) .arg(filename).arg(line + comment_count +1).arg(column+1), - ERR_INV_SYNTAX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidSyntax,__PRETTY_FUNCTION__,__FILE__,__LINE__); } else { @@ -1097,8 +1096,8 @@ QString SchemaParser::getCodeDefinition(attribs_map &attribs) break; //Attribute extraction - case CHR_INI_ATTRIB: - case CHR_END_ATTRIB: + case CharIniAttribute: + case CharEndAttribute: atrib=getAttribute(); //Checks if the attribute extracted belongs to the passed list of attributes @@ -1106,9 +1105,9 @@ QString SchemaParser::getCodeDefinition(attribs_map &attribs) { if(!ignore_unk_atribs) { - throw Exception(QString(Exception::getErrorMessage(ERR_UNK_ATTRIBUTE)) + throw Exception(Exception::getErrorMessage(ErrorCode::UnkownAttribute) .arg(atrib).arg(filename).arg((line + comment_count +1)).arg((column+1)), - ERR_UNK_ATTRIBUTE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::UnkownAttribute,__PRETTY_FUNCTION__,__FILE__,__LINE__); } else attributes[atrib]=QString(); @@ -1122,9 +1121,9 @@ QString SchemaParser::getCodeDefinition(attribs_map &attribs) { word=atrib; atrib=QString(); - atrib+=CHR_INI_ATTRIB; + atrib+=CharIniAttribute; atrib+=word; - atrib+=CHR_END_ATTRIB; + atrib+=CharEndAttribute; //If the parser is in the 'if' section if(vet_tk_if[if_level] && @@ -1143,9 +1142,9 @@ QString SchemaParser::getCodeDefinition(attribs_map &attribs) raises an exception */ if(attributes[atrib].isEmpty() && !ignore_empty_atribs) { - throw Exception(QString(Exception::getErrorMessage(ERR_UNDEF_ATTRIB_VALUE)) + throw Exception(Exception::getErrorMessage(ErrorCode::UndefinedAttributeValue) .arg(atrib).arg(filename).arg(line + comment_count +1).arg(column+1), - ERR_UNDEF_ATTRIB_VALUE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::UndefinedAttributeValue,__PRETTY_FUNCTION__,__FILE__,__LINE__); } /* If the parser is not in an if / else, concatenates the value of the attribute @@ -1155,22 +1154,22 @@ QString SchemaParser::getCodeDefinition(attribs_map &attribs) break; //Conditional instruction extraction - case CHR_INI_CONDITIONAL: + case CharIniConditional: prev_cond=cond; cond=getConditional(); //Checks whether the extracted token is a valid conditional - if(cond!=TOKEN_IF && cond!=TOKEN_ELSE && - cond!=TOKEN_THEN && cond!=TOKEN_END && - cond!=TOKEN_OR && cond!=TOKEN_NOT && - cond!=TOKEN_AND && cond!=TOKEN_SET && - cond!=TOKEN_UNSET) + if(cond!=TokenIf && cond!=TokenElse && + cond!=TokenThen && cond!=TokenEnd && + cond!=TokenOr && cond!=TokenNot && + cond!=TokenAnd && cond!=TokenSet && + cond!=TokenUnset) { - throw Exception(QString(Exception::getErrorMessage(ERR_INV_INSTRUCTION)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidInstruction) .arg(cond).arg(filename).arg(line + comment_count +1).arg(column+1), - ERR_INV_INSTRUCTION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidInstruction,__PRETTY_FUNCTION__,__FILE__,__LINE__); } - else if(cond==TOKEN_SET || cond==TOKEN_UNSET) + else if(cond==TokenSet || cond==TokenUnset) { bool extract=false; @@ -1182,20 +1181,23 @@ QString SchemaParser::getCodeDefinition(attribs_map &attribs) if(!extract && if_level >= 0) { //If in 'else' the related 'if' is false, extracts the attribute - if(prev_cond==TOKEN_ELSE && !vet_expif[if_level]) + if(prev_cond == TokenElse && !vet_expif[if_level]) extract=true; - else if(prev_cond!=TOKEN_ELSE) + else if(prev_cond != TokenElse) { //If in the 'if' part all the previous ifs until the current must be true extract=true; for(int i=0; i <= if_level && extract; i++) - extract=vet_expif[i]; + { + extract=(vet_expif[i] && !vet_tk_else[i]) || + (!vet_expif[i] && vet_tk_else[i]); + } } } if(extract) { - if(cond==TOKEN_SET) + if(cond==TokenSet) defineAttribute(); else unsetAttribute(); @@ -1209,7 +1211,7 @@ QString SchemaParser::getCodeDefinition(attribs_map &attribs) else { //If the toke is an 'if' - if(cond==TOKEN_IF) + if(cond==TokenIf) { //Evaluates the if expression storing the result on the vector if_expr=true; @@ -1232,7 +1234,7 @@ QString SchemaParser::getCodeDefinition(attribs_map &attribs) if_cnt++; } //If the parser is in 'if / else' and one 'then' token is found - else if(cond==TOKEN_THEN && if_level>=0) + else if(cond==TokenThen && if_level>=0) { //Marks the then token flag of the current 'if' vet_tk_then[if_level]=true; @@ -1243,11 +1245,11 @@ QString SchemaParser::getCodeDefinition(attribs_map &attribs) if_expr=false; } //If the parser is in 'if / else' and a 'else' token is found - else if(cond==TOKEN_ELSE && if_level>=0) + else if(cond==TokenElse && if_level>=0) //Mark the o flag do token else do if atual vet_tk_else[if_level]=true; //Case the parser is in 'if/else' and a 'end' token was found - else if(cond==TOKEN_END && if_level>=0) + else if(cond==TokenEnd && if_level>=0) { //Increments the number of 'end' tokes found end_cnt++; @@ -1304,7 +1306,7 @@ QString SchemaParser::getCodeDefinition(attribs_map &attribs) word=(*itr); //Check if the word is not an attribute - if(!word.isEmpty() && word.startsWith(CHR_INI_ATTRIB) && word.endsWith(CHR_END_ATTRIB)) + if(!word.isEmpty() && word.startsWith(CharIniAttribute) && word.endsWith(CharEndAttribute)) { //If its an attribute, extracts the name between { } and checks if the same has empty value atrib=word.mid(1, word.size()-2); @@ -1314,9 +1316,9 @@ QString SchemaParser::getCodeDefinition(attribs_map &attribs) raises an exception */ if(word.isEmpty() && !ignore_empty_atribs) { - throw Exception(QString(Exception::getErrorMessage(ERR_UNDEF_ATTRIB_VALUE)) + throw Exception(Exception::getErrorMessage(ErrorCode::UndefinedAttributeValue) .arg(atrib).arg(filename).arg(line + comment_count +1).arg(column+1), - ERR_UNDEF_ATTRIB_VALUE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::UndefinedAttributeValue,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } @@ -1356,25 +1358,25 @@ QString SchemaParser::getCodeDefinition(attribs_map &attribs) /* Verifying that the conditional words appear in a valid order if not the parser generates an error. Correct order means IF before THEN, ELSE after IF and before END */ - if((prev_cond==TOKEN_IF && cond!=TOKEN_THEN) || - (prev_cond==TOKEN_ELSE && cond!=TOKEN_IF && cond!=TOKEN_END) || - (prev_cond==TOKEN_THEN && cond==TOKEN_THEN)) + if((prev_cond==TokenIf && cond!=TokenThen) || + (prev_cond==TokenElse && cond!=TokenIf && cond!=TokenEnd) || + (prev_cond==TokenThen && cond==TokenThen)) error=true; } if(error) { - throw Exception(QString(Exception::getErrorMessage(ERR_INV_SYNTAX)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidSyntax) .arg(filename).arg(line + comment_count +1).arg(column+1), - ERR_INV_SYNTAX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidSyntax,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } break; //Extraction of pure text or simple words default: - if(chr==CHR_INI_PURETEXT || - chr==CHR_END_PURETEXT) + if(chr==CharIniPlainText || + chr==CharEndPlainText) word=getPureText(); else word=getWord(); @@ -1386,9 +1388,9 @@ QString SchemaParser::getCodeDefinition(attribs_map &attribs) because only an attribute must be on the 'if' expression */ if(vet_tk_if[if_level] && !vet_tk_then[if_level]) { - throw Exception(QString(Exception::getErrorMessage(ERR_INV_SYNTAX)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidSyntax) .arg(filename).arg(line + comment_count +1).arg(column+1), - ERR_INV_SYNTAX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidSyntax,__PRETTY_FUNCTION__,__FILE__,__LINE__); } //Case the parser is in 'if' section else if(vet_tk_if[if_level] && @@ -1411,9 +1413,9 @@ QString SchemaParser::getCodeDefinition(attribs_map &attribs) was not closed thus the parser returns an error */ if(if_cnt!=end_cnt) { - throw Exception(QString(Exception::getErrorMessage(ERR_INV_SYNTAX)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidSyntax) .arg(filename).arg(line + comment_count +1).arg(column+1), - ERR_INV_SYNTAX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvalidSyntax,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } @@ -1428,11 +1430,11 @@ QString SchemaParser::getCodeDefinition(const QString &filename, attribs_map &at try { loadFile(filename); - attribs[ParsersAttributes::PGSQL_VERSION]=pgsql_version; + attribs[Attributes::PgSqlVersion]=pgsql_version; return(getCodeDefinition(attribs)); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libparsers/src/schemaparser.h b/libparsers/src/schemaparser.h index 13a2c1da91..b3f1b74026 100644 --- a/libparsers/src/schemaparser.h +++ b/libparsers/src/schemaparser.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -45,53 +45,8 @@ class SchemaParser { attributes avoiding raising exceptions */ bool ignore_empty_atribs; - static const char CHR_COMMENT, //! \brief Character that starts a comment - CHR_LINE_END, //! \brief Character that indicates end of line - CHR_SPACE, //! \brief Character that indicates spacing - CHR_TABULATION, //! \brief Character that indicates tabulation - CHR_INI_ATTRIB, //! \brief Character that indicates a reference to an attribute - CHR_END_ATTRIB, //! \brief Character that delimits on the right the attribute name - CHR_INI_CONDITIONAL,//! \brief Character that starts a conditional instruction - CHR_INI_METACHAR, //! \brief Character that starts a metacharacter - CHR_INI_PURETEXT, //! \brief Character that starts a puretext - CHR_END_PURETEXT, //! \brief Character that ends a puretext - CHR_INI_CEXPR, //! \brief Character that starts a comparison expression - CHR_END_CEXPR, //! \brief Character that ends a comparison expression - CHR_VAL_DELIM, //! \brief Character that delimiters a value (string) - CHR_VALUE_OF; /*! \brief Character that is used on %set instructions to - create an attribute name based upon another attribute value */ - - //! \brief Tokens related to conditional instructions and operators - static const QString TOKEN_IF, // %if - TOKEN_THEN,// %then - TOKEN_ELSE,// %else - TOKEN_END, // %end - TOKEN_OR, // %or - TOKEN_NOT, // %not - TOKEN_AND, // %and - TOKEN_SET, //%set - TOKEN_UNSET; //%unset - - - //! \brief Tokens related to metacharacters - static const QString TOKEN_META_SP,// $sp (space) - TOKEN_META_BR,// $br (line break) - TOKEN_META_TB,// $tb (tabulation) - TOKEN_META_OB,// $ob (open square bracket '[') - TOKEN_META_CB,// $cb (close square bracket ']') - TOKEN_META_OC,// $ob (open curly bracket '{') - TOKEN_META_CC;// $cb (close curly bracket '}') - - //! \brief Tokens related to comparison expressions - static const QString TOKEN_EQ_OP,// == (equal) - TOKEN_NE_OP,// != (not equal) - TOKEN_GT_OP,// > (greater than) - TOKEN_LT_OP,// < (less than) - TOKEN_GT_EQ_OP,// >= (greater or equal to) - TOKEN_LT_EQ_OP;// <= (less or equal to) - //! \brief RegExp used to validate attribute names - static const QRegExp ATTR_REGEXP; + static const QRegExp AttribRegExp; //! \brief Get an attribute name from the buffer on the current position QString getAttribute(void); @@ -186,9 +141,53 @@ class SchemaParser { QString pgsql_version; public: + static const char CharComment, //! \brief Character that starts a comment + CharLineEnd, //! \brief Character that indicates end of line + CharSpace, //! \brief Character that indicates spacing + CharTabulation, //! \brief Character that indicates tabulation + CharIniAttribute, //! \brief Character that indicates a reference to an attribute + CharEndAttribute, //! \brief Character that delimits on the right the attribute name + CharIniConditional, //! \brief Character that starts a conditional instruction + CharIniMetachar, //! \brief Character that starts a metacharacter + CharIniPlainText, //! \brief Character that starts a plain text + CharEndPlainText, //! \brief Character that ends a plain text + CharIniCompExpr, //! \brief Character that starts a comparison expression + CharEndCompExpr, //! \brief Character that ends a comparison expression + CharValueDelim, //! \brief Character that delimiters a value (string) + CharValueOf; /*! \brief Character that is used on %set instructions to + create an attribute name based upon another attribute value */ + + //! \brief Tokens related to conditional instructions and operators + static const QString TokenIf, // %if + TokenThen,// %then + TokenElse,// %else + TokenEnd, // %end + TokenOr, // %or + TokenNot, // %not + TokenAnd, // %and + TokenSet, //%set + TokenUnset; //%unset + + //! \brief Tokens related to metacharacters + static const QString TokenMetaSp,// $sp (space) + TokenMetaBr,// $br (line break) + TokenMetaTb,// $tb (tabulation) + TokenMetaOb,// $ob (open square bracket '[') + TokenMetaCb,// $cb (close square bracket ']') + TokenMetaOc,// $ob (open curly bracket '{') + TokenMetaCc;// $cb (close curly bracket '}') + + //! \brief Tokens related to comparison expressions + static const QString TokenEqOper,// == (equal) + TokenNeOper,// != (not equal) + TokenGtOper,// > (greater than) + TokenLtOper,// < (less than) + TokenGtEqOper,// >= (greater or equal to) + TokenLtEqOper;// <= (less or equal to) + //! \brief Constants used to get a specific object definition - static const unsigned SQL_DEFINITION=0, - XML_DEFINITION=1; + static constexpr unsigned SqlDefinition=0, + XmlDefinition=1; SchemaParser(void); @@ -235,7 +234,7 @@ class SchemaParser { QStringList extractAttributes(void); /*! \brief Converts any chars (operators) < > " to the respective XML entities. This method is only - called when generating XML code and only tag attributes are treated.*/ + * called when generating XML code and only tag attributes are treated.*/ static QString convertCharsToXMLEntities(QString buf); }; diff --git a/libparsers/src/xmlparser.cpp b/libparsers/src/xmlparser.cpp index cb78d0f51e..1c4d65e956 100644 --- a/libparsers/src/xmlparser.cpp +++ b/libparsers/src/xmlparser.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -19,27 +19,28 @@ #include "xmlparser.h" #include -const QString XMLParser::CHAR_AMP=QString("&"); -const QString XMLParser::CHAR_LT=QString("<"); -const QString XMLParser::CHAR_GT=QString(">"); -const QString XMLParser::CHAR_QUOT=QString("""); -const QString XMLParser::CHAR_APOS=QString("'"); +const QString XmlParser::CharAmp=QString("&"); +const QString XmlParser::CharLt=QString("<"); +const QString XmlParser::CharGt=QString(">"); +const QString XmlParser::CharQuot=QString("""); +const QString XmlParser::CharApos=QString("'"); -XMLParser::XMLParser(void) +XmlParser::XmlParser(void) { root_elem=nullptr; curr_elem=nullptr; xml_doc=nullptr; + curr_line = 0; xmlInitParser(); } -XMLParser::~XMLParser(void) +XmlParser::~XmlParser(void) { restartParser(); xmlCleanupParser(); } -void XMLParser::removeDTD(void) +void XmlParser::removeDTD(void) { int pos1=-1, pos2=-1, pos3=-1, len; @@ -59,7 +60,7 @@ void XMLParser::removeDTD(void) } } -void XMLParser::loadXMLFile(const QString &filename) +void XmlParser::loadXMLFile(const QString &filename) { try { @@ -75,8 +76,8 @@ void XMLParser::loadXMLFile(const QString &filename) //Case the file opening was not sucessful if(!input.isOpen()) { - throw Exception(QString(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED)).arg(filename), - ERR_FILE_DIR_NOT_ACCESSED,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed).arg(filename), + ErrorCode::FileDirectoryNotAccessed,__PRETTY_FUNCTION__,__FILE__,__LINE__); } buffer=input.readAll(); @@ -88,18 +89,18 @@ void XMLParser::loadXMLFile(const QString &filename) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } -void XMLParser::loadXMLBuffer(const QString &xml_buf) +void XmlParser::loadXMLBuffer(const QString &xml_buf) { try { int pos1=-1, pos2=-1, tam=0; if(xml_buf.isEmpty()) - throw Exception(ERR_ASG_EMPTY_XML_BUFFER,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgEmptyXMLBuffer,__PRETTY_FUNCTION__,__FILE__,__LINE__); pos1=xml_buf.indexOf(QLatin1String("")); @@ -119,19 +120,19 @@ void XMLParser::loadXMLBuffer(const QString &xml_buf) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } -void XMLParser::setDTDFile(const QString &dtd_file, const QString &dtd_name) +void XmlParser::setDTDFile(const QString &dtd_file, const QString &dtd_name) { QString fmt_dtd_file; if(dtd_file.isEmpty()) - throw Exception(ERR_ASG_EMPTY_DTD_FILE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgEmptyDTDFile,__PRETTY_FUNCTION__,__FILE__,__LINE__); if(dtd_name.isEmpty()) - throw Exception(ERR_ASG_EMPTY_DTD_NAME,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgEmptyDTDName,__PRETTY_FUNCTION__,__FILE__,__LINE__); #ifndef Q_OS_WIN fmt_dtd_file=QString("file://"); @@ -147,7 +148,7 @@ void XMLParser::setDTDFile(const QString &dtd_file, const QString &dtd_name) fmt_dtd_file + QString("\">\n"); } -void XMLParser::readBuffer(void) +void XmlParser::readBuffer(void) { QByteArray buffer; QString msg, file; @@ -160,7 +161,7 @@ void XMLParser::readBuffer(void) buffer+=xml_decl; //Configures the parser, initially, to not validate the document against the dtd - parser_opt=( XML_PARSE_NOBLANKS | XML_PARSE_NONET | XML_PARSE_NOENT ); + parser_opt=( XML_PARSE_NOBLANKS | XML_PARSE_NONET | XML_PARSE_NOENT | XML_PARSE_BIG_LINES); //If the dtd declarions is setup if(!dtd_decl.isEmpty()) @@ -193,9 +194,9 @@ void XMLParser::readBuffer(void) if(xml_doc) restartParser(); //Raise an exception with the error massege from the parser xml - throw Exception(QString(Exception::getErrorMessage(ERR_LIBXMLERR)) + throw Exception(Exception::getErrorMessage(ErrorCode::LibXMLError) .arg(xml_error->line).arg(xml_error->int2).arg(msg).arg(file), - ERR_LIBXMLERR,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::LibXMLError,__PRETTY_FUNCTION__,__FILE__,__LINE__); } //Gets the referênce to the root element on the document @@ -203,18 +204,18 @@ void XMLParser::readBuffer(void) } } -void XMLParser::savePosition(void) +void XmlParser::savePosition(void) { if(!root_elem) - throw Exception(ERR_OPR_NOT_ALOC_ELEM_TREE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedElementTree,__PRETTY_FUNCTION__,__FILE__,__LINE__); elems_stack.push(curr_elem); } -void XMLParser::restorePosition(void) +void XmlParser::restorePosition(void) { if(!root_elem) - throw Exception(ERR_OPR_NOT_ALOC_ELEM_TREE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedElementTree,__PRETTY_FUNCTION__,__FILE__,__LINE__); if(elems_stack.empty()) curr_elem=root_elem; @@ -225,21 +226,21 @@ void XMLParser::restorePosition(void) } } -void XMLParser::restorePosition(const xmlNode *elem) +void XmlParser::restorePosition(const xmlNode *elem) { if(!elem) - throw Exception(ERR_OPR_NOT_ALOC_ELEMENT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedElement,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(elem->doc!=xml_doc) - throw Exception(ERR_OPR_INEXIST_ELEMENT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprInexistentElement,__PRETTY_FUNCTION__,__FILE__,__LINE__); restartNavigation(); curr_elem=const_cast(elem); } -void XMLParser::restartNavigation(void) +void XmlParser::restartNavigation(void) { if(!root_elem) - throw Exception(ERR_OPR_NOT_ALOC_ELEM_TREE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedElementTree,__PRETTY_FUNCTION__,__FILE__,__LINE__); curr_elem=root_elem; @@ -247,9 +248,10 @@ void XMLParser::restartNavigation(void) elems_stack.pop(); } -void XMLParser::restartParser(void) +void XmlParser::restartParser(void) { root_elem=curr_elem=nullptr; + curr_line = 0; if(xml_doc) { @@ -265,18 +267,18 @@ void XMLParser::restartParser(void) xmlResetLastError(); } -bool XMLParser::accessElement(unsigned elem_type) +bool XmlParser::accessElement(unsigned elem_type) { bool has_elem; xmlNode *elems[4]; if(!root_elem) - throw Exception(ERR_OPR_NOT_ALOC_ELEM_TREE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedElementTree,__PRETTY_FUNCTION__,__FILE__,__LINE__); - elems[ROOT_ELEMENT]=curr_elem->parent; - elems[CHILD_ELEMENT]=curr_elem->children; - elems[NEXT_ELEMENT]=curr_elem->next; - elems[PREVIOUS_ELEMENT]=curr_elem->prev; + elems[RootElement]=curr_elem->parent; + elems[ChildElement]=curr_elem->children; + elems[NextElement]=curr_elem->next; + elems[PreviousElement]=curr_elem->prev; /* Checks whether the current element has the element that is to be accessed. The flag 'has_elem' is also used @@ -285,27 +287,45 @@ bool XMLParser::accessElement(unsigned elem_type) has_elem=hasElement(elem_type); if(has_elem) + { curr_elem=elems[elem_type]; + /* NOTE: Due to XML2 implementation big line numbers are stored in the psvi + * attribute so we need to convert the void* to char and convert it back to integer value */ + if(curr_elem->line == 65535 && curr_elem->next && curr_elem->next->psvi != nullptr) + { + char hex_value[10] = ""; + int aux_line = 0; + + sprintf(hex_value, "%p", curr_elem->next->psvi); + aux_line = static_cast(strtol(hex_value, nullptr, 16)); + + if(curr_line < aux_line) + curr_line = aux_line; + } + else if(curr_elem->line > curr_line) + curr_line = curr_elem->line; + } + return(has_elem); } -bool XMLParser::hasElement(unsigned elem_type, xmlElementType xml_node_type) +bool XmlParser::hasElement(unsigned elem_type, xmlElementType xml_node_type) { if(!root_elem) - throw Exception(ERR_OPR_NOT_ALOC_ELEM_TREE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedElementTree,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(elem_type==ROOT_ELEMENT) + if(elem_type==RootElement) /* Returns the verification if the current element has a parent. The element must be different from the root, because the root element is not connected to a parent */ return(curr_elem!=root_elem && curr_elem->parent!=nullptr && (xml_node_type==0 || (xml_node_type!=0 && curr_elem->parent->type==xml_node_type))); - else if(elem_type==CHILD_ELEMENT) + else if(elem_type==ChildElement) //Returns the verification if the current element has children return(curr_elem->children!=nullptr && (xml_node_type==0 || (xml_node_type!=0 && curr_elem->children->type==xml_node_type))); - else if(elem_type==NEXT_ELEMENT) + else if(elem_type==NextElement) return(curr_elem->next!=nullptr && (xml_node_type==0 || (xml_node_type!=0 && curr_elem->next->type==xml_node_type))); else @@ -315,18 +335,18 @@ bool XMLParser::hasElement(unsigned elem_type, xmlElementType xml_node_type) (xml_node_type==0 || (xml_node_type!=0 && curr_elem->prev->type==xml_node_type))); } -bool XMLParser::hasAttributes(void) +bool XmlParser::hasAttributes(void) { if(!root_elem) - throw Exception(ERR_OPR_NOT_ALOC_ELEM_TREE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedElementTree,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(curr_elem->properties!=nullptr); } -QString XMLParser::getElementContent(void) +QString XmlParser::getElementContent(void) { if(!root_elem) - throw Exception(ERR_OPR_NOT_ALOC_ELEM_TREE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedElementTree,__PRETTY_FUNCTION__,__FILE__,__LINE__); /* If the current element has node returns the content of the CDATA instead of return the content of the element itself */ @@ -337,34 +357,34 @@ QString XMLParser::getElementContent(void) return(QString(reinterpret_cast(curr_elem->content))); } -QString XMLParser::getElementName(void) +QString XmlParser::getElementName(void) { if(!root_elem) - throw Exception(ERR_OPR_NOT_ALOC_ELEM_TREE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedElementTree,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(QString(reinterpret_cast(curr_elem->name))); } -xmlElementType XMLParser::getElementType(void) +xmlElementType XmlParser::getElementType(void) { if(!root_elem) - throw Exception(ERR_OPR_NOT_ALOC_ELEM_TREE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedElementTree,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(curr_elem->type); } -const xmlNode *XMLParser::getCurrentElement(void) +const xmlNode *XmlParser::getCurrentElement(void) { return(curr_elem); } -void XMLParser::getElementAttributes(attribs_map &attributes) +void XmlParser::getElementAttributes(attribs_map &attributes) { xmlAttr *elem_attribs=nullptr; QString attrib, value; if(!root_elem) - throw Exception(ERR_OPR_NOT_ALOC_ELEM_TREE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedElementTree,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Always clears the passed attributes maps attributes.clear(); @@ -388,31 +408,43 @@ void XMLParser::getElementAttributes(attribs_map &attributes) } } -QString XMLParser::getLoadedFilename(void) +QString XmlParser::getLoadedFilename(void) { return(xml_doc_filename); } -QString XMLParser::getXMLBuffer(void) +QString XmlParser::getXMLBuffer(void) { return(xml_buffer); } -int XMLParser::getCurrentBufferLine(void) +int XmlParser::getCurrentBufferLine(void) { if(curr_elem) - return(curr_elem->line); + return(curr_line); else return(0); } -int XMLParser::getBufferLineCount(void) +int XmlParser::getBufferLineCount(void) { if(xml_doc) + { /* To get the very last line of the document is necessary to call the last element of the last because xml_doc->last->line stores the - last line of the root element */ + last line of the root element. + + NOTE: Due to XML2 implementation big line numbers are stored in the psvi + attribute so we need to convert the void* to char and convert it back to integer value */ + if(xml_doc->last->last->line == 65535 && xml_doc->last->last->psvi != nullptr) + { + char hex_value[10] = ""; + sprintf(hex_value, "%p", xml_doc->last->last->psvi); + return(static_cast(strtol(hex_value, nullptr, 16))); + } + return(xml_doc->last->last->line); + } else return(0); } diff --git a/libparsers/src/xmlparser.h b/libparsers/src/xmlparser.h index fae7432727..16b77d8357 100644 --- a/libparsers/src/xmlparser.h +++ b/libparsers/src/xmlparser.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -34,7 +34,7 @@ #include #include "attribsmap.h" -class XMLParser { +class XmlParser { private: /*! \brief Stores the name of the file that generated the xml buffer when loadXMLFile() method is called */ @@ -43,8 +43,12 @@ class XMLParser { //! \brief Stores the xml document (element tree) generated after the buffer reading xmlDoc *xml_doc; + //! \brief Stores the approximated line position on the current parsed buffer + int curr_line; + //! \brief Stores the reference to the root element of the element tree xmlNode *root_elem, + //! \brief Stores the current element that parser is analyzing *curr_elem; @@ -74,19 +78,19 @@ class XMLParser { public: //! \brief Constants used to referência the elements on the element tree - static const unsigned ROOT_ELEMENT=0, - CHILD_ELEMENT=1, - NEXT_ELEMENT=2, - PREVIOUS_ELEMENT=3; - - static const QString CHAR_AMP; //! \brief & = & - static const QString CHAR_LT; //! \brief < = < - static const QString CHAR_GT; //! \brief < = > - static const QString CHAR_QUOT; //! \brief < = " - static const QString CHAR_APOS; //! \brief < = ' - - XMLParser(void); - ~XMLParser(void); + static constexpr unsigned RootElement=0, + ChildElement=1, + NextElement=2, + PreviousElement=3; + + static const QString CharAmp, //! \brief & = & + CharLt, //! \brief < = < + CharGt, //! \brief < = > + CharQuot, //! \brief < = " + CharApos; //! \brief < = ' + + XmlParser(void); + ~XmlParser(void); //! \brief Loads the XML buffer from a file void loadXMLFile(const QString &filename); diff --git a/libpgconnector/src/catalog.cpp b/libpgconnector/src/catalog.cpp index 28b95fc865..d5c98c71cb 100644 --- a/libpgconnector/src/catalog.cpp +++ b/libpgconnector/src/catalog.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -17,55 +17,56 @@ */ #include "catalog.h" -const QString Catalog::QUERY_LIST=QString("list"); -const QString Catalog::QUERY_ATTRIBS=QString("attribs"); -const QString Catalog::CATALOG_SCH_DIR=QString("catalog"); -const QString Catalog::PGSQL_TRUE=QString("t"); -const QString Catalog::PGSQL_FALSE=QString("f"); -const QString Catalog::BOOL_FIELD=QString("_bool"); -const QString Catalog::ARRAY_PATTERN=QString("((\\[)[0-9]+(\\:)[0-9]+(\\])=)?(\\{)((.)+(,)*)*(\\})$"); -const QString Catalog::GET_EXT_OBJS_SQL=QString("SELECT objid AS oid FROM pg_depend WHERE objid > 0 AND refobjid > 0 AND deptype='e'"); -const QString Catalog::PGMODELER_TEMP_DB_OBJ=QString("__pgmodeler_tmp"); - -bool Catalog::use_cached_queries=false; +const QString Catalog::QueryList=QString("list"); +const QString Catalog::QueryAttribs=QString("attribs"); +const QString Catalog::CatalogSchemasDir=QString("catalog"); +const QString Catalog::PgSqlTrue=QString("t"); +const QString Catalog::PgSqlFalse=QString("f"); +const QString Catalog::BoolField=QString("_bool"); +const QString Catalog::ArrayPattern=QString("((\\[)[0-9]+(\\:)[0-9]+(\\])=)?(\\{)((.)+(,)*)*(\\})$"); +const QString Catalog::GetExtensionObjsSql=QString("SELECT objid AS oid FROM pg_depend WHERE objid > 0 AND refobjid > 0 AND deptype='e'"); +const QString Catalog::PgModelerTempDbObj=QString("__pgmodeler_tmp"); + attribs_map Catalog::catalog_queries; map Catalog::oid_fields= -{ {OBJ_DATABASE, "oid"}, {OBJ_ROLE, "oid"}, {OBJ_SCHEMA,"oid"}, - {OBJ_LANGUAGE, "oid"}, {OBJ_TABLESPACE, "oid"}, {OBJ_EXTENSION, "ex.oid"}, - {OBJ_FUNCTION, "pr.oid"}, {OBJ_AGGREGATE, "pr.oid"}, {OBJ_OPERATOR, "op.oid"}, - {OBJ_OPCLASS, "op.oid"}, {OBJ_OPFAMILY, "op.oid"}, {OBJ_COLLATION, "cl.oid"}, - {OBJ_CONVERSION, "cn.oid"}, {OBJ_CAST, "cs.oid"}, {OBJ_VIEW, "vw.oid"}, - {OBJ_SEQUENCE, "sq.oid"}, {OBJ_DOMAIN, "dm.oid"}, {OBJ_TYPE, "tp.oid"}, - {OBJ_TABLE, "tb.oid"}, {OBJ_COLUMN, "cl.oid"}, {OBJ_CONSTRAINT, "cs.oid"}, - {OBJ_RULE, "rl.oid"}, {OBJ_TRIGGER, "tg.oid"}, {OBJ_INDEX, "id.indexrelid"}, - {OBJ_EVENT_TRIGGER, "et.oid"}, {OBJ_POLICY, "pl.oid"} +{ {ObjectType::Database, "oid"}, {ObjectType::Role, "oid"}, {ObjectType::Schema,"oid"}, + {ObjectType::Language, "oid"}, {ObjectType::Tablespace, "oid"}, {ObjectType::Extension, "ex.oid"}, + {ObjectType::Function, "pr.oid"}, {ObjectType::Aggregate, "pr.oid"}, {ObjectType::Operator, "op.oid"}, + {ObjectType::OpClass, "op.oid"}, {ObjectType::OpFamily, "op.oid"}, {ObjectType::Collation, "cl.oid"}, + {ObjectType::Conversion, "cn.oid"}, {ObjectType::Cast, "cs.oid"}, {ObjectType::View, "vw.oid"}, + {ObjectType::Sequence, "sq.oid"}, {ObjectType::Domain, "dm.oid"}, {ObjectType::Type, "tp.oid"}, + {ObjectType::Table, "tb.oid"}, {ObjectType::Column, "cl.oid"}, {ObjectType::Constraint, "cs.oid"}, + {ObjectType::Rule, "rl.oid"}, {ObjectType::Trigger, "tg.oid"}, {ObjectType::Index, "id.indexrelid"}, + {ObjectType::EventTrigger, "et.oid"}, {ObjectType::Policy, "pl.oid"}, {ObjectType::ForeignDataWrapper, "fw.oid"}, + {ObjectType::ForeignServer, "sv.oid"}, {ObjectType::UserMapping, "um.umid"} }; map Catalog::ext_oid_fields={ - {OBJ_CONSTRAINT, "cs.conrelid"}, - {OBJ_INDEX, "id.indexrelid"}, - {OBJ_TRIGGER, "tg.tgrelid"}, - {OBJ_RULE, "rl.ev_class"}, - {OBJ_POLICY, "pl.polrelid"} + {ObjectType::Constraint, "cs.conrelid"}, + {ObjectType::Index, "id.indexrelid"}, + {ObjectType::Trigger, "tg.tgrelid"}, + {ObjectType::Rule, "rl.ev_class"}, + {ObjectType::Policy, "pl.polrelid"} }; map Catalog::name_fields= -{ {OBJ_DATABASE, "datname"}, {OBJ_ROLE, "rolname"}, {OBJ_SCHEMA,"nspname"}, - {OBJ_LANGUAGE, "lanname"}, {OBJ_TABLESPACE, "spcname"}, {OBJ_EXTENSION, "extname"}, - {OBJ_FUNCTION, "proname"}, {OBJ_AGGREGATE, "proname"}, {OBJ_OPERATOR, "oprname"}, - {OBJ_OPCLASS, "opcname"}, {OBJ_OPFAMILY, "opfname"}, {OBJ_COLLATION, "collname"}, - {OBJ_CONVERSION, "conname"}, {OBJ_CAST, ""}, {OBJ_VIEW, "relname"}, - {OBJ_SEQUENCE, "relname"}, {OBJ_DOMAIN, "typname"}, {OBJ_TYPE, "typname"}, - {OBJ_TABLE, "relname"}, {OBJ_COLUMN, "attname"}, {OBJ_CONSTRAINT, "conname"}, - {OBJ_RULE, "rulename"}, {OBJ_TRIGGER, "tgname"}, {OBJ_INDEX, "relname"}, - {OBJ_EVENT_TRIGGER, "evtname"}, {OBJ_POLICY, "polname"} +{ {ObjectType::Database, "datname"}, {ObjectType::Role, "rolname"}, {ObjectType::Schema,"nspname"}, + {ObjectType::Language, "lanname"}, {ObjectType::Tablespace, "spcname"}, {ObjectType::Extension, "extname"}, + {ObjectType::Function, "proname"}, {ObjectType::Aggregate, "proname"}, {ObjectType::Operator, "oprname"}, + {ObjectType::OpClass, "opcname"}, {ObjectType::OpFamily, "opfname"}, {ObjectType::Collation, "collname"}, + {ObjectType::Conversion, "conname"}, {ObjectType::Cast, ""}, {ObjectType::View, "relname"}, + {ObjectType::Sequence, "relname"}, {ObjectType::Domain, "typname"}, {ObjectType::Type, "typname"}, + {ObjectType::Table, "relname"}, {ObjectType::Column, "attname"}, {ObjectType::Constraint, "conname"}, + {ObjectType::Rule, "rulename"}, {ObjectType::Trigger, "tgname"}, {ObjectType::Index, "relname"}, + {ObjectType::EventTrigger, "evtname"}, {ObjectType::Policy, "polname"}, {ObjectType::ForeignDataWrapper, "fdwname"}, + {ObjectType::ForeignServer, "srvname"} }; Catalog::Catalog(void) { last_sys_oid=0; - setFilter(EXCL_EXTENSION_OBJS | EXCL_SYSTEM_OBJS); + setFilter(ExclExtensionObjs | ExclSystemObjs); } Catalog::Catalog(const Catalog &catalog) @@ -85,31 +86,31 @@ void Catalog::setConnection(Connection &conn) connection.connect(); //Retrieving the last system oid - executeCatalogQuery(QUERY_LIST, OBJ_DATABASE, res, true, - {{ParsersAttributes::NAME, conn.getConnectionParam(Connection::PARAM_DB_NAME)}}); + executeCatalogQuery(QueryList, ObjectType::Database, res, true, + {{Attributes::Name, conn.getConnectionParam(Connection::ParamDbName)}}); - if(res.accessTuple(ResultSet::FIRST_TUPLE)) + if(res.accessTuple(ResultSet::FirstTuple)) { attribs_map attribs=changeAttributeNames(res.getTupleValues()); - last_sys_oid=attribs[ParsersAttributes::LAST_SYS_OID].toUInt(); + last_sys_oid=attribs[Attributes::LastSysOid].toUInt(); } //Retrieving the list of objects created by extensions - this->connection.executeDMLCommand(GET_EXT_OBJS_SQL, res); - if(res.accessTuple(ResultSet::FIRST_TUPLE)) + this->connection.executeDMLCommand(GetExtensionObjsSql, res); + if(res.accessTuple(ResultSet::FirstTuple)) { do { ext_obj.push_back(res.getColumnValue(QString("oid"))); } - while(res.accessTuple(ResultSet::NEXT_TUPLE)); + while(res.accessTuple(ResultSet::NextTuple)); ext_obj_oids=ext_obj.join(','); } } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -120,17 +121,17 @@ void Catalog::closeConnection(void) void Catalog::setFilter(unsigned filter) { - bool list_all=(LIST_ALL_OBJS & filter) == LIST_ALL_OBJS; + bool list_all=(ListAllObjects & filter) == ListAllObjects; this->filter=filter; list_only_sys_objs=false; - exclude_array_types=(EXCL_BUILTIN_ARRAY_TYPES & filter) == EXCL_BUILTIN_ARRAY_TYPES; - exclude_ext_objs=(EXCL_EXTENSION_OBJS & filter) == EXCL_EXTENSION_OBJS; - exclude_sys_objs=(EXCL_SYSTEM_OBJS & filter) == EXCL_SYSTEM_OBJS; + exclude_array_types=(ExclBuiltinArrayTypes & filter) == ExclBuiltinArrayTypes; + exclude_ext_objs=(ExclExtensionObjs & filter) == ExclExtensionObjs; + exclude_sys_objs=(ExclSystemObjs & filter) == ExclSystemObjs; if(!list_all) { - list_only_sys_objs=(LIST_ONLY_SYS_OBJS & filter) == LIST_ONLY_SYS_OBJS; + list_only_sys_objs=(ListOnlySystemObjs & filter) == ListOnlySystemObjs; if(list_only_sys_objs) { @@ -157,17 +158,16 @@ bool Catalog::isExtensionObject(unsigned oid) void Catalog::loadCatalogQuery(const QString &qry_id) { - if((!use_cached_queries) || - (use_cached_queries && catalog_queries.count(qry_id)==0)) + if(catalog_queries.count(qry_id)==0) { QFile input; - input.setFileName(GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - CATALOG_SCH_DIR + GlobalAttributes::DIR_SEPARATOR + - qry_id + GlobalAttributes::SCHEMA_EXT); + input.setFileName(GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + CatalogSchemasDir + GlobalAttributes::DirSeparator + + qry_id + GlobalAttributes::SchemaExt); if(!input.open(QFile::ReadOnly)) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED).arg(input.fileName()), - ERR_FILE_DIR_NOT_ACCESSED,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed).arg(input.fileName()), + ErrorCode::FileDirectoryNotAccessed,__PRETTY_FUNCTION__,__FILE__,__LINE__); catalog_queries[qry_id]=QString(input.readAll()); input.close(); @@ -184,44 +184,44 @@ QString Catalog::getCatalogQuery(const QString &qry_type, ObjectType obj_type, b * due to support to this char in the middle of objects' names */ for(auto &attr : attribs) { - if(attr.first != ParsersAttributes::CUSTOM_FILTER && attr.second.contains(QChar('\''))) + if(attr.first != Attributes::CustomFilter && attr.second.contains(QChar('\''))) attr.second.replace(QChar('\''), QString("''")); } schparser.setPgSQLVersion(connection.getPgSQLVersion(true)); - attribs[qry_type]=ParsersAttributes::_TRUE_; + attribs[qry_type]=Attributes::True; if(exclude_sys_objs || list_only_sys_objs) - attribs[ParsersAttributes::LAST_SYS_OID]=QString("%1").arg(last_sys_oid); + attribs[Attributes::LastSysOid]=QString("%1").arg(last_sys_oid); if(list_only_sys_objs) - attribs[ParsersAttributes::OID_FILTER_OP]=QString("<="); + attribs[Attributes::OidFilterOp]=QString("<="); else - attribs[ParsersAttributes::OID_FILTER_OP]=QString(">"); + attribs[Attributes::OidFilterOp]=QString(">"); - if(obj_type==OBJ_TYPE && exclude_array_types) - attribs[ParsersAttributes::EXC_BUILTIN_ARRAYS]=ParsersAttributes::_TRUE_; + if(obj_type==ObjectType::Type && exclude_array_types) + attribs[Attributes::ExcBuiltinArrays]=Attributes::True; //Checking if the custom filter expression is present - if(attribs.count(ParsersAttributes::CUSTOM_FILTER)) + if(attribs.count(Attributes::CustomFilter)) { - custom_filter=attribs[ParsersAttributes::CUSTOM_FILTER]; - attribs.erase(ParsersAttributes::CUSTOM_FILTER); + custom_filter=attribs[Attributes::CustomFilter]; + attribs.erase(Attributes::CustomFilter); } - if(exclude_ext_objs && obj_type!=OBJ_DATABASE && obj_type!=OBJ_ROLE && obj_type!=OBJ_TABLESPACE && obj_type!=OBJ_EXTENSION) + if(exclude_ext_objs && obj_type!=ObjectType::Database && obj_type!=ObjectType::Role && obj_type!=ObjectType::Tablespace && obj_type!=ObjectType::Extension) { if(ext_oid_fields.count(obj_type)==0) - attribs[ParsersAttributes::NOT_EXT_OBJECT]=getNotExtObjectQuery(oid_fields[obj_type]); + attribs[Attributes::NotExtObject]=getNotExtObjectQuery(oid_fields[obj_type]); else - attribs[ParsersAttributes::NOT_EXT_OBJECT]=getNotExtObjectQuery(ext_oid_fields[obj_type]); + attribs[Attributes::NotExtObject]=getNotExtObjectQuery(ext_oid_fields[obj_type]); } loadCatalogQuery(BaseObject::getSchemaName(obj_type)); schparser.ignoreUnkownAttributes(true); schparser.ignoreEmptyAttributes(true); - attribs[ParsersAttributes::PGSQL_VERSION]=schparser.getPgSQLVersion(); + attribs[Attributes::PgSqlVersion]=schparser.getPgSQLVersion(); sql=schparser.getCodeDefinition(attribs).simplified(); //Appeding the custom filter to the whole catalog query @@ -256,7 +256,7 @@ void Catalog::executeCatalogQuery(const QString &qry_type, ObjectType obj_type, } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, QString("catalog: %1").arg(BaseObject::getSchemaName(obj_type))); } } @@ -267,16 +267,16 @@ unsigned Catalog::getObjectCount(ObjectType obj_type, const QString &sch_name, c { ResultSet res; - extra_attribs[ParsersAttributes::SCHEMA]=sch_name; - extra_attribs[ParsersAttributes::TABLE]=tab_name; + extra_attribs[Attributes::Schema]=sch_name; + extra_attribs[Attributes::Table]=tab_name; - executeCatalogQuery(QUERY_LIST, obj_type, res, false, extra_attribs); - res.accessTuple(ResultSet::FIRST_TUPLE); + executeCatalogQuery(QueryList, obj_type, res, false, extra_attribs); + res.accessTuple(ResultSet::FirstTuple); return(res.getTupleCount()); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -289,9 +289,9 @@ void Catalog::getObjectsOIDs(map > &obj_oids, map types=BaseObject::getObjectTypes(true, { OBJ_DATABASE, OBJ_RELATIONSHIP, BASE_RELATIONSHIP, - OBJ_TEXTBOX, OBJ_TAG, OBJ_COLUMN, OBJ_PERMISSION, - OBJ_GENERIC_SQL }); + vector types=BaseObject::getObjectTypes(true, { ObjectType::Database, ObjectType::Relationship, ObjectType::BaseRelationship, + ObjectType::Textbox, ObjectType::Tag, ObjectType::Column, ObjectType::Permission, + ObjectType::GenericSql }); attribs_map attribs, col_attribs, sch_names; vector tab_attribs; unsigned tab_oid=0; @@ -305,16 +305,16 @@ void Catalog::getObjectsOIDs(map > &obj_oids, map > &obj_oids, map Catalog::getObjectsNames(vector obj_types, const QStringList queries; attribs_map attribs; - extra_attribs[ParsersAttributes::SCHEMA]=sch_name; - extra_attribs[ParsersAttributes::TABLE]=tab_name; + extra_attribs[Attributes::Schema]=sch_name; + extra_attribs[Attributes::Table]=tab_name; for(ObjectType obj_type : obj_types) { //Build the catalog query for the specified object type - sql=getCatalogQuery(QUERY_LIST, obj_type, false, extra_attribs); + sql=getCatalogQuery(QueryList, obj_type, false, extra_attribs); /* For certain objects the catalog query will be empty due to the absence of that kind of element in the version of the database. @@ -381,7 +381,7 @@ vector Catalog::getObjectsNames(vector obj_types, const { //Injecting the object type integer code in order to sort the final result sql.replace(sql.indexOf(select_kw), select_kw.size(), - QString("%1 %2 AS object_type, ").arg(select_kw).arg(obj_type)); + QString("%1 %2 AS object_type, ").arg(select_kw).arg(enum_cast(obj_type))); sql+=QChar('\n'); queries.push_back(sql); @@ -396,24 +396,24 @@ vector Catalog::getObjectsNames(vector obj_types, const connection.executeDMLCommand(sql, res); - if(res.accessTuple(ResultSet::FIRST_TUPLE)) + if(res.accessTuple(ResultSet::FirstTuple)) { do { - attribs[ParsersAttributes::OID]=res.getColumnValue(ParsersAttributes::OID); - attribs[ParsersAttributes::NAME]=res.getColumnValue(ParsersAttributes::NAME); - attribs[ParsersAttributes::OBJECT_TYPE]=res.getColumnValue(QString("object_type")); + attribs[Attributes::Oid]=res.getColumnValue(Attributes::Oid); + attribs[Attributes::Name]=res.getColumnValue(Attributes::Name); + attribs[Attributes::ObjectType]=res.getColumnValue(QString("object_type")); objects.push_back(attribs); attribs.clear(); } - while(res.accessTuple(ResultSet::NEXT_TUPLE)); + while(res.accessTuple(ResultSet::NextTuple)); } return(objects); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -425,21 +425,21 @@ attribs_map Catalog::getAttributes(const QString &obj_name, ObjectType obj_type, attribs_map obj_attribs; //Add the name of the object as extra attrib in order to retrieve the data only for it - extra_attribs[ParsersAttributes::NAME]=obj_name; - executeCatalogQuery(QUERY_ATTRIBS, obj_type, res, true, extra_attribs); + extra_attribs[Attributes::Name]=obj_name; + executeCatalogQuery(QueryAttribs, obj_type, res, true, extra_attribs); - if(res.accessTuple(ResultSet::FIRST_TUPLE)) + if(res.accessTuple(ResultSet::FirstTuple)) obj_attribs=changeAttributeNames(res.getTupleValues()); /* Insert the object type as an attribute of the query result to facilitate the import process on the classes that uses the Catalog */ - obj_attribs[ParsersAttributes::OBJECT_TYPE]=QString("%1").arg(obj_type); + obj_attribs[Attributes::ObjectType]=QString("%1").arg(enum_cast(obj_type)); return(obj_attribs); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -451,8 +451,8 @@ vector Catalog::getMultipleAttributes(ObjectType obj_type, attribs_ attribs_map tuple; vector obj_attribs; - executeCatalogQuery(QUERY_ATTRIBS, obj_type, res, false, extra_attribs); - if(res.accessTuple(ResultSet::FIRST_TUPLE)) + executeCatalogQuery(QueryAttribs, obj_type, res, false, extra_attribs); + if(res.accessTuple(ResultSet::FirstTuple)) { do { @@ -460,37 +460,71 @@ vector Catalog::getMultipleAttributes(ObjectType obj_type, attribs_ /* Insert the object type as an attribute of the query result to facilitate the import process on the classes that uses the Catalog */ - tuple[ParsersAttributes::OBJECT_TYPE]=QString("%1").arg(obj_type); + tuple[Attributes::ObjectType]=QString("%1").arg(enum_cast(obj_type)); + + obj_attribs.push_back(tuple); + tuple.clear(); + } + while(res.accessTuple(ResultSet::NextTuple)); + } + + return(obj_attribs); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +vector Catalog::getMultipleAttributes(const QString &catalog_sch, attribs_map attribs) +{ + try + { + ResultSet res; + attribs_map tuple; + vector obj_attribs; + + loadCatalogQuery(catalog_sch); + schparser.ignoreUnkownAttributes(true); + schparser.ignoreEmptyAttributes(true); + + attribs[Attributes::PgSqlVersion]=schparser.getPgSQLVersion(); + connection.executeDMLCommand(schparser.getCodeDefinition(attribs).simplified(), res); + if(res.accessTuple(ResultSet::FirstTuple)) + { + do + { + tuple=changeAttributeNames(res.getTupleValues()); obj_attribs.push_back(tuple); tuple.clear(); } - while(res.accessTuple(ResultSet::NEXT_TUPLE)); + while(res.accessTuple(ResultSet::NextTuple)); } return(obj_attribs); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } QString Catalog::getCommentQuery(const QString &oid_field, bool is_shared_obj) { - QString query_id=ParsersAttributes::COMMENT; + QString query_id=Attributes::Comment; try { - attribs_map attribs={{ParsersAttributes::OID, oid_field}, - {ParsersAttributes::SHARED_OBJ, (is_shared_obj ? ParsersAttributes::_TRUE_ : QString())}}; + attribs_map attribs={{Attributes::Oid, oid_field}, + {Attributes::SharedObj, (is_shared_obj ? Attributes::True : QString())}}; loadCatalogQuery(query_id); return(schparser.getCodeDefinition(attribs).simplified()); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, QString("catalog: %1").arg(query_id)); } } @@ -501,8 +535,8 @@ QString Catalog::getNotExtObjectQuery(const QString &oid_field) try { - attribs_map attribs={{ParsersAttributes::OID, oid_field}, - {ParsersAttributes::EXT_OBJ_OIDS, ext_obj_oids}}; + attribs_map attribs={{Attributes::Oid, oid_field}, + {Attributes::ExtObjOids, ext_obj_oids}}; loadCatalogQuery(query_id); @@ -510,7 +544,7 @@ QString Catalog::getNotExtObjectQuery(const QString &oid_field) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, QString("catalog: %1").arg(query_id)); } } @@ -526,11 +560,11 @@ attribs_map Catalog::changeAttributeNames(const attribs_map &attribs) attr_name=itr->first; value=itr->second; - if(attr_name.endsWith(BOOL_FIELD)) + if(attr_name.endsWith(BoolField)) { - attr_name.remove(BOOL_FIELD); - if(value==PGSQL_FALSE) value.clear(); - else value=ParsersAttributes::_TRUE_; + attr_name.remove(BoolField); + if(value==PgSqlFalse) value.clear(); + else value=Attributes::True; } attr_name.replace('_','-'); @@ -558,24 +592,24 @@ vector Catalog::getObjectsAttributes(ObjectType obj_type, const QSt { try { - bool is_shared_obj=(obj_type==OBJ_DATABASE || obj_type==OBJ_ROLE || obj_type==OBJ_TABLESPACE || - obj_type==OBJ_LANGUAGE || obj_type==OBJ_CAST); + bool is_shared_obj=(obj_type==ObjectType::Database || obj_type==ObjectType::Role || obj_type==ObjectType::Tablespace || + obj_type==ObjectType::Language || obj_type==ObjectType::Cast); - extra_attribs[ParsersAttributes::SCHEMA]=schema; - extra_attribs[ParsersAttributes::TABLE]=table; + extra_attribs[Attributes::Schema]=schema; + extra_attribs[Attributes::Table]=table; if(!filter_oids.empty()) - extra_attribs[ParsersAttributes::FILTER_OIDS]=createOidFilter(filter_oids); + extra_attribs[Attributes::FilterOids]=createOidFilter(filter_oids); //Retrieve the comment catalog query. Only columns need to retreive comments in their own catalog query file - if(obj_type != OBJ_COLUMN) - extra_attribs[ParsersAttributes::COMMENT]=getCommentQuery(oid_fields[obj_type], is_shared_obj); + if(obj_type != ObjectType::Column) + extra_attribs[Attributes::Comment]=getCommentQuery(oid_fields[obj_type], is_shared_obj); return(getMultipleAttributes(obj_type, extra_attribs)); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, QApplication::translate("Catalog","Object type: %1","", -1).arg(BaseObject::getSchemaName(obj_type))); } } @@ -589,7 +623,7 @@ attribs_map Catalog::getObjectAttributes(ObjectType obj_type, unsigned oid, cons } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, QApplication::translate("Catalog","Object type: %1","", -1).arg(BaseObject::getSchemaName(obj_type))); } } @@ -601,26 +635,26 @@ QString Catalog::getObjectOID(const QString &name, ObjectType obj_type, const QS attribs_map attribs; ResultSet res; - attribs[ParsersAttributes::CUSTOM_FILTER] = QString("%1 = E'%2'").arg(name_fields[obj_type]).arg(name); - attribs[ParsersAttributes::SCHEMA] = schema; - attribs[ParsersAttributes::TABLE] = table; - executeCatalogQuery(QUERY_LIST, obj_type, res, false, attribs); + attribs[Attributes::CustomFilter] = QString("%1 = E'%2'").arg(name_fields[obj_type]).arg(name); + attribs[Attributes::Schema] = schema; + attribs[Attributes::Table] = table; + executeCatalogQuery(QueryList, obj_type, res, false, attribs); if(res.getTupleCount() > 1) throw Exception(QApplication::translate("Catalog","The catalog query returned more than one OID!","", -1), - ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(res.isEmpty()) return("0"); else { - res.accessTuple(ResultSet::FIRST_TUPLE); - return(res.getColumnValue(ParsersAttributes::OID)); + res.accessTuple(ResultSet::FirstTuple); + return(res.getColumnValue(Attributes::Oid)); } } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, QApplication::translate("Catalog","Object type: %1","", -1).arg(BaseObject::getSchemaName(obj_type))); } } @@ -641,25 +675,25 @@ attribs_map Catalog::getServerAttributes(void) sql = schparser.getCodeDefinition(attribs).simplified(); connection.executeDMLCommand(sql, res); - if(res.accessTuple(ResultSet::FIRST_TUPLE)) + if(res.accessTuple(ResultSet::FirstTuple)) { do { tuple=res.getTupleValues(); - attr_name = tuple[ParsersAttributes::ATTRIBUTE]; + attr_name = tuple[Attributes::Attribute]; attr_name.replace('_','-'); - attribs[attr_name]=tuple[ParsersAttributes::VALUE]; + attribs[attr_name]=tuple[Attributes::Value]; } - while(res.accessTuple(ResultSet::NEXT_TUPLE)); + while(res.accessTuple(ResultSet::NextTuple)); - attribs[ParsersAttributes::CONNECTION] = connection.getConnectionId(); + attribs[Attributes::Connection] = connection.getConnectionId(); attribs_aux = connection.getServerInfo(); attribs.insert(attribs_aux.begin(), attribs_aux.end()) ; } } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, QApplication::translate("Catalog","Object type: server","", -1)); } @@ -670,7 +704,7 @@ QStringList Catalog::parseArrayValues(const QString &array_val) { QStringList list; - if(QRegExp(ARRAY_PATTERN).exactMatch(array_val)) + if(QRegExp(ArrayPattern).exactMatch(array_val)) { //Detecting the position of { and } int start=array_val.indexOf('{')+1, @@ -752,14 +786,49 @@ QStringList Catalog::parseRuleCommands(const QString &cmds) return(cmds.mid(start,(end - start) + 1).split(';', QString::SkipEmptyParts)); } -void Catalog::enableCachedQueries(bool value) +QStringList Catalog::parseIndexExpressions(const QString &expr) { - use_cached_queries=value; -} + int open_paren = 0, close_paren = 0, pos = 0; + QStringList expressions; + QChar chr; + QString word; + bool open_apos = false; -bool Catalog::isCachedQueriesEnabled(void) -{ - return(use_cached_queries); + if(!expr.isEmpty()) + { + while(pos < expr.length()) + { + chr = expr[pos++]; + word += chr; + + if(chr == QChar('\'')) + open_apos = !open_apos; + + if(!open_apos && chr == QChar('(')) + open_paren++; + else if(!open_apos && chr == QChar(')')) + close_paren++; + + if(chr == QChar(',') || pos == expr.length()) + { + if(open_paren == close_paren) + { + if(word.endsWith(QChar(','))) + word.remove(word.length() - 1, 1); + + if(word.contains('(') && word.contains(')')) + expressions.push_back(word.trimmed()); + else + expressions.push_back(word); + + word.clear(); + open_paren = close_paren = 0; + } + } + } + } + + return(expressions); } void Catalog::operator = (const Catalog &catalog) @@ -778,6 +847,6 @@ void Catalog::operator = (const Catalog &catalog) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } diff --git a/libpgconnector/src/catalog.h b/libpgconnector/src/catalog.h index 4b45018906..8b588f1b33 100644 --- a/libpgconnector/src/catalog.h +++ b/libpgconnector/src/catalog.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -36,18 +36,18 @@ class Catalog { private: SchemaParser schparser; - static const QString QUERY_LIST, //! \brief Executes a list command on catalog - QUERY_ATTRIBS, //! \brief Executes a attribute retrieving command on catalog - CATALOG_SCH_DIR, //! \brief Default catalog schemas directory - PGSQL_TRUE, //! \brief Replacement for true 't' boolean value - PGSQL_FALSE, //! \brief Replacement for false 'f' boolean value - BOOL_FIELD, //! \brief Suffix for boolean fields. + static const QString QueryList, //! \brief Executes a list command on catalog + QueryAttribs, //! \brief Executes a attribute retrieving command on catalog + CatalogSchemasDir, //! \brief Default catalog schemas directory + PgSqlTrue, //! \brief Replacement for true 't' boolean value + PgSqlFalse, //! \brief Replacement for false 'f' boolean value + BoolField, //! \brief Suffix for boolean fields. //! \brief Query used to retrieve extension objects. - GET_EXT_OBJS_SQL, + GetExtensionObjsSql, //! \brief This pattern matches the PostgreSQL array values in format [n:n]={a,b,c,d,...} or {a,b,c,d,...} - ARRAY_PATTERN; + ArrayPattern; /*! \brief Stores in comma seperated way the oids of all objects created by extensions. This attribute is use when filtering objects that are created by extensions */ @@ -65,10 +65,7 @@ class Catalog { there are different fields that tells if the object (or its parent) is part of extension. */ static map ext_oid_fields; - //! \brief Indicates is the use of cached catalog queries is enabled - static bool use_cached_queries; - - //! \brief Store the cached catalog queries (only when use_cached_queries=true) + //! \brief Store the cached catalog queries static attribs_map catalog_queries; //! \brief Connection used to query the pg_catalog @@ -129,23 +126,23 @@ class Catalog { Catalog(const Catalog &catalog); //! \brief Stores the prefix of any temp object (in pg_temp) created during catalog reading by pgModeler - static const QString PGMODELER_TEMP_DB_OBJ; + static const QString PgModelerTempDbObj; //! \brief Excludes the system objects from listing - static const unsigned EXCL_SYSTEM_OBJS=1, + static constexpr unsigned ExclSystemObjs=1, //! \brief Excludes the extension generated objects from listing - EXCL_EXTENSION_OBJS=2, + ExclExtensionObjs=2, //! \brief Excludes the builtin array types. - EXCL_BUILTIN_ARRAY_TYPES=4, + ExclBuiltinArrayTypes=4, /*! \brief Shows only system objects. Using this filter will disable the other two filters. Using this filter implies the listing of extension objects */ - LIST_ONLY_SYS_OBJS=8, + ListOnlySystemObjs=8, //! \brief Shows all objects including system objects and extension object. - LIST_ALL_OBJS=16; + ListAllObjects=16; //! \brief Changes the current connection used by the catalog void setConnection(Connection &conn); @@ -188,6 +185,12 @@ class Catalog { //! \brief Returns a set of multiple attributes (several tuples) for the specified object type vector getMultipleAttributes(ObjectType obj_type, attribs_map extra_attribs=attribs_map()); + /*! \brief Returns a set of multiple attributes (several tuples) for the specified catalog schema file. + * This version of the method differs from the one in which the user need to provide the object type. + * This one, the user is responsible to provide all attributes that will be parsed together with the + * catalog file. */ + vector getMultipleAttributes(const QString &catalog_sch, attribs_map attribs=attribs_map()); + /*! \brief Retrieve all available objects attributes for the specified type. Internally this method calls the get method for the specified type. User can filter items by oids (except for table child objects), by schema (in the object type is suitable to accept schema) and by table name (only when retriving child objects for a specific table) */ @@ -215,6 +218,10 @@ class Catalog { //! \brief Parse the raw commands of a rule retrieved by the catalog and returns only the relevant parts static QStringList parseRuleCommands(const QString &cmd); + /*! \brief Parse a set of expressions related to an index returned by the pg_get_expr(oid) and separates + * them as a string list. */ + static QStringList parseIndexExpressions(const QString &expr); + /*! \brief Enable/disable the use of cached catalog queries. When enabled, the schema files read for the first are stored in memory so in the next time the same catalog query must be used it'll be read right from the memory and not from the disk anymore */ static void enableCachedQueries(bool value); diff --git a/libpgconnector/src/connection.cpp b/libpgconnector/src/connection.cpp index c284c83acc..2a6ee04f7b 100644 --- a/libpgconnector/src/connection.cpp +++ b/libpgconnector/src/connection.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -19,34 +19,34 @@ #include "connection.h" #include #include -#include "parsersattributes.h" - -const QString Connection::SSL_DESABLE=QString("disable"); -const QString Connection::SSL_ALLOW=QString("allow"); -const QString Connection::SSL_PREFER=QString("prefer"); -const QString Connection::SSL_REQUIRE=QString("require"); -const QString Connection::SSL_CA_VERIF=QString("verify-ca"); -const QString Connection::SSL_FULL_VERIF=QString("verify-full"); -const QString Connection::PARAM_ALIAS=QString("alias"); -const QString Connection::PARAM_SERVER_FQDN=QString("host"); -const QString Connection::PARAM_SERVER_IP=QString("hostaddr"); -const QString Connection::PARAM_PORT=QString("port"); -const QString Connection::PARAM_DB_NAME=QString("dbname"); -const QString Connection::PARAM_USER=QString("user"); -const QString Connection::PARAM_PASSWORD=QString("password"); -const QString Connection::PARAM_CONN_TIMEOUT=QString("connect_timeout"); -const QString Connection::PARAM_OTHERS=QString("options"); -const QString Connection::PARAM_SSL_MODE=QString("sslmode"); -const QString Connection::PARAM_SSL_CERT=QString("sslcert"); -const QString Connection::PARAM_SSL_KEY=QString("sslkey"); -const QString Connection::PARAM_SSL_ROOT_CERT=QString("sslrootcert"); -const QString Connection::PARAM_SSL_CRL=QString("sslcrl"); -const QString Connection::PARAM_KERBEROS_SERVER=QString("krbsrvname"); -const QString Connection::PARAM_LIB_GSSAPI=QString("gsslib"); - -const QString Connection::SERVER_PID=QString("server-pid"); -const QString Connection::SERVER_PROTOCOL=QString("server-protocol"); -const QString Connection::SERVER_VERSION=QString("server-version"); +#include "attributes.h" + +const QString Connection::SslDisable=QString("disable"); +const QString Connection::SslAllow=QString("allow"); +const QString Connection::SslPrefer=QString("prefer"); +const QString Connection::SslRequire=QString("require"); +const QString Connection::SslCaVerify=QString("verify-ca"); +const QString Connection::SslFullVerify=QString("verify-full"); +const QString Connection::ParamAlias=QString("alias"); +const QString Connection::ParamServerFqdn=QString("host"); +const QString Connection::ParamServerIp=QString("hostaddr"); +const QString Connection::ParamPort=QString("port"); +const QString Connection::ParamDbName=QString("dbname"); +const QString Connection::ParamUser=QString("user"); +const QString Connection::ParamPassword=QString("password"); +const QString Connection::ParamConnTimeout=QString("connect_timeout"); +const QString Connection::ParamOthers=QString("options"); +const QString Connection::ParamSslMode=QString("sslmode"); +const QString Connection::ParamSslCert=QString("sslcert"); +const QString Connection::ParamSslKey=QString("sslkey"); +const QString Connection::ParamSslRootCert=QString("sslrootcert"); +const QString Connection::ParamSslCrl=QString("sslcrl"); +const QString Connection::ParamKerberosServer=QString("krbsrvname"); +const QString Connection::ParamLibGssapi=QString("gsslib"); + +const QString Connection::ServerPid=QString("server-pid"); +const QString Connection::ServerProtocol=QString("server-protocol"); +const QString Connection::ServerVersion=QString("server-version"); bool Connection::notice_enabled=false; bool Connection::print_sql=false; @@ -59,7 +59,7 @@ Connection::Connection(void) auto_browse_db=false; cmd_exec_timeout=0; - for(unsigned idx=OP_VALIDATION; idx <= OP_DIFF; idx++) + for(unsigned idx=OpValidation; idx <= OpDiff; idx++) default_for_oper[idx]=false; } @@ -89,16 +89,16 @@ void Connection::setConnectionParam(const QString ¶m, const QString &value) //Raise an error in case the param name is empty if(param.isEmpty()) - throw Exception(ERR_ASG_INV_CONN_PARAM, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::AsgInvalidConnParameter, __PRETTY_FUNCTION__, __FILE__, __LINE__); /* Set the value to the specified param on the map. One special case is treated here, if user use the parameter SERVER_FQDN and the value is a IP address, the method will assign the value to the SERVER_IP parameter */ - if(param==PARAM_SERVER_FQDN && ip_regexp.exactMatch(value)) + if(param==ParamServerFqdn && ip_regexp.exactMatch(value)) { - connection_params[Connection::PARAM_SERVER_IP]=value; - connection_params[Connection::PARAM_SERVER_FQDN]=QString(); + connection_params[Connection::ParamServerIp]=value; + connection_params[Connection::ParamServerFqdn]=QString(); } else connection_params[param]=value; @@ -127,21 +127,21 @@ void Connection::generateConnectionString(void) for(auto &itr : connection_params) { - if(itr.first!=PARAM_ALIAS) + if(itr.first!=ParamAlias) { value=itr.second; value.replace("\\","\\\\"); value.replace("'","\\'"); - if(itr.first==PARAM_PASSWORD && (value.contains(' ') || value.isEmpty())) + if(itr.first==ParamPassword && (value.contains(' ') || value.isEmpty())) value=QString("'%1'").arg(value); if(!value.isEmpty()) { - if(itr.first==PARAM_DB_NAME) + if(itr.first==ParamDbName) connection_str.prepend(param_str.arg(itr.first).arg(value)); - else if(itr.first!=PARAM_OTHERS) + else if(itr.first!=ParamOthers) connection_str+=param_str.arg(itr.first).arg(value); else connection_str+=value; @@ -149,9 +149,9 @@ void Connection::generateConnectionString(void) } } - if(!connection_str.contains(PARAM_DB_NAME) || - (!connection_str.contains(PARAM_SERVER_FQDN) && - !connection_str.contains(PARAM_SERVER_IP))) + if(!connection_str.contains(ParamDbName) || + (!connection_str.contains(ParamServerFqdn) && + !connection_str.contains(ParamServerIp))) connection_str.clear(); } @@ -170,15 +170,15 @@ void Connection::validateConnectionStatus(void) if(dt >= cmd_exec_timeout) { close(); - throw Exception(ERR_CONNECTION_TIMEOUT, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::ConnectionTimeout, __PRETTY_FUNCTION__, __FILE__, __LINE__); } } if(PQstatus(connection)==CONNECTION_BAD) - throw Exception(Exception::getErrorMessage(ERR_CONNECTION_BROKEN) - .arg(connection_params[PARAM_SERVER_FQDN].isEmpty() ? connection_params[PARAM_SERVER_IP] : connection_params[PARAM_SERVER_FQDN]) - .arg(connection_params[PARAM_PORT]), - ERR_CONNECTION_BROKEN, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::ConnectionBroken) + .arg(connection_params[ParamServerFqdn].isEmpty() ? connection_params[ParamServerIp] : connection_params[ParamServerFqdn]) + .arg(connection_params[ParamPort]), + ErrorCode::ConnectionBroken, __PRETTY_FUNCTION__, __FILE__, __LINE__); } void Connection::setNoticeEnabled(bool value) @@ -217,11 +217,11 @@ void Connection::connect(void) is trying to connect without configuring connection parameters, thus an error is raised */ if(connection_str.isEmpty()) - throw Exception(ERR_CONNECTION_NOT_CONFIGURED, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::ConnectionNotConfigured, __PRETTY_FUNCTION__, __FILE__, __LINE__); else if(connection) { if(!silence_conn_err) - throw Exception(ERR_CONNECTION_ALREADY_STABLISHED, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::ConnectionAlreadyStablished, __PRETTY_FUNCTION__, __FILE__, __LINE__); else { QTextStream err(stderr); @@ -240,8 +240,8 @@ void Connection::connect(void) if(connection==nullptr || PQstatus(connection)==CONNECTION_BAD) { //Raise the error generated by the DBMS - throw Exception(QString(Exception::getErrorMessage(ERR_CONNECTION_NOT_STABLISHED)) - .arg(PQerrorMessage(connection)), ERR_CONNECTION_NOT_STABLISHED, + throw Exception(Exception::getErrorMessage(ErrorCode::ConnectionNotStablished) + .arg(PQerrorMessage(connection)), ErrorCode::ConnectionNotStablished, __PRETTY_FUNCTION__, __FILE__, __LINE__); } @@ -272,7 +272,7 @@ void Connection::reset(void) { //Raise an erro in case the user try to reset a not opened connection if(!connection) - throw Exception(ERR_OPR_NOT_ALOC_CONN, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::OprNotAllocatedConnection, __PRETTY_FUNCTION__, __FILE__, __LINE__); //Reinicia a conexão PQreset(connection); @@ -293,11 +293,11 @@ attribs_map Connection::getServerInfo(void) attribs_map info; if(!connection) - throw Exception(ERR_OPR_NOT_ALOC_CONN,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedConnection,__PRETTY_FUNCTION__,__FILE__,__LINE__); - info[SERVER_PID]=QString::number(PQbackendPID(connection)); - info[SERVER_VERSION]=getPgSQLVersion(); - info[SERVER_PROTOCOL]=QString::number(PQprotocolVersion(connection)); + info[ServerPid]=QString::number(PQbackendPID(connection)); + info[ServerVersion]=getPgSQLVersion(); + info[ServerProtocol]=QString::number(PQprotocolVersion(connection)); return(info); } @@ -314,21 +314,21 @@ QString Connection::getConnectionId(bool host_port_only, bool incl_db_name) if(!isConfigured()) return(QString()); - if(!connection_params[PARAM_SERVER_FQDN].isEmpty()) - addr=connection_params[PARAM_SERVER_FQDN]; + if(!connection_params[ParamServerFqdn].isEmpty()) + addr=connection_params[ParamServerFqdn]; else - addr=connection_params[PARAM_SERVER_IP]; + addr=connection_params[ParamServerIp]; - if(!connection_params[PARAM_PORT].isEmpty()) - port = QString(":%1").arg(connection_params[PARAM_PORT]); + if(!connection_params[ParamPort].isEmpty()) + port = QString(":%1").arg(connection_params[ParamPort]); if(incl_db_name) - db_name = QString("%1@").arg(connection_params[PARAM_DB_NAME]); + db_name = QString("%1@").arg(connection_params[ParamDbName]); if(host_port_only) return(QString("%1%2%3").arg(db_name, addr, port)); else - return(QString("%1%2 (%3%4)").arg(db_name, connection_params[PARAM_ALIAS], addr, port)); + return(QString("%1%2 (%3%4)").arg(db_name, connection_params[ParamAlias], addr, port)); } bool Connection::isStablished(void) @@ -351,7 +351,7 @@ QString Connection::getPgSQLVersion(bool major_only) QString raw_ver, fmt_ver; if(!connection) - throw Exception(ERR_OPR_NOT_ALOC_CONN, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::OprNotAllocatedConnection, __PRETTY_FUNCTION__, __FILE__, __LINE__); raw_ver=QString("%1").arg(PQserverVersion(connection)); @@ -392,7 +392,7 @@ void Connection::executeDMLCommand(const QString &sql, ResultSet &result) //Raise an error in case the user try to close a not opened connection if(!connection) - throw Exception(ERR_OPR_NOT_ALOC_CONN, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::OprNotAllocatedConnection, __PRETTY_FUNCTION__, __FILE__, __LINE__); validateConnectionStatus(); notices.clear(); @@ -410,9 +410,9 @@ void Connection::executeDMLCommand(const QString &sql, ResultSet &result) //Raise an error in case the command sql execution is not sucessful if(strlen(PQerrorMessage(connection))>0) { - throw Exception(QString(Exception::getErrorMessage(ERR_CMD_SQL_NOT_EXECUTED)) + throw Exception(Exception::getErrorMessage(ErrorCode::SQLCommandNotExecuted) .arg(PQerrorMessage(connection)), - ERR_CMD_SQL_NOT_EXECUTED, __PRETTY_FUNCTION__, __FILE__, __LINE__, nullptr, + ErrorCode::SQLCommandNotExecuted, __PRETTY_FUNCTION__, __FILE__, __LINE__, nullptr, QString(PQresultErrorField(sql_res, PG_DIAG_SQLSTATE))); } @@ -433,7 +433,7 @@ void Connection::executeDDLCommand(const QString &sql) //Raise an error in case the user try to close a not opened connection if(!connection) - throw Exception(ERR_OPR_NOT_ALOC_CONN, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::OprNotAllocatedConnection, __PRETTY_FUNCTION__, __FILE__, __LINE__); validateConnectionStatus(); notices.clear(); @@ -453,9 +453,9 @@ void Connection::executeDDLCommand(const QString &sql) PQclear(sql_res); - throw Exception(QString(Exception::getErrorMessage(ERR_CMD_SQL_NOT_EXECUTED)) + throw Exception(Exception::getErrorMessage(ErrorCode::SQLCommandNotExecuted) .arg(PQerrorMessage(connection)), - ERR_CMD_SQL_NOT_EXECUTED, __PRETTY_FUNCTION__, __FILE__, __LINE__, nullptr, field); + ErrorCode::SQLCommandNotExecuted, __PRETTY_FUNCTION__, __FILE__, __LINE__, nullptr, field); } PQclear(sql_res); @@ -463,17 +463,17 @@ void Connection::executeDDLCommand(const QString &sql) void Connection::setDefaultForOperation(unsigned op_id, bool value) { - if(op_id > OP_NONE) - throw Exception(ERR_REF_ELEM_INV_INDEX, __PRETTY_FUNCTION__, __FILE__, __LINE__); - else if(op_id!=OP_NONE) + if(op_id > OpNone) + throw Exception(ErrorCode::RefElementInvalidIndex, __PRETTY_FUNCTION__, __FILE__, __LINE__); + else if(op_id!=OpNone) default_for_oper[op_id]=value; } bool Connection::isDefaultForOperation(unsigned op_id) { - if(op_id > OP_NONE) - throw Exception(ERR_REF_ELEM_INV_INDEX, __PRETTY_FUNCTION__, __FILE__, __LINE__); - else if(op_id==OP_NONE) + if(op_id > OpNone) + throw Exception(ErrorCode::RefElementInvalidIndex, __PRETTY_FUNCTION__, __FILE__, __LINE__); + else if(op_id==OpNone) return(false); return(default_for_oper[op_id]); @@ -481,7 +481,7 @@ bool Connection::isDefaultForOperation(unsigned op_id) void Connection::switchToDatabase(const QString &dbname) { - QString prev_dbname=connection_params[PARAM_DB_NAME]; + QString prev_dbname=connection_params[ParamDbName]; try { @@ -490,7 +490,7 @@ void Connection::switchToDatabase(const QString &dbname) close(); //Change the database name and reconfigure the connection string - connection_params[PARAM_DB_NAME]=dbname; + connection_params[ParamDbName]=dbname; generateConnectionString(); //Reopen connection @@ -498,10 +498,10 @@ void Connection::switchToDatabase(const QString &dbname) } catch(Exception &e) { - connection_params[PARAM_DB_NAME]=prev_dbname; + connection_params[ParamDbName]=prev_dbname; connect(); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -515,7 +515,14 @@ void Connection::operator = (const Connection &conn) this->connection_str=conn.connection_str; this->connection=nullptr; - for(unsigned idx=OP_VALIDATION; idx <= OP_DIFF; idx++) + for(unsigned idx=OpValidation; idx <= OpDiff; idx++) default_for_oper[idx]=conn.default_for_oper[idx]; } +void Connection::requestCancel(void) +{ + if(!connection) + throw Exception(ErrorCode::OprNotAllocatedConnection, __PRETTY_FUNCTION__, __FILE__, __LINE__); + + PQrequestCancel(connection); +} diff --git a/libpgconnector/src/connection.h b/libpgconnector/src/connection.h index 40016e2359..d9b44c23f5 100644 --- a/libpgconnector/src/connection.h +++ b/libpgconnector/src/connection.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -95,40 +95,40 @@ class Connection { public: //! \brief Constants used to reference the connections parameters - static const QString PARAM_ALIAS, - PARAM_SERVER_FQDN, - PARAM_SERVER_IP, - PARAM_PORT, - PARAM_DB_NAME, - PARAM_USER, - PARAM_PASSWORD, - PARAM_CONN_TIMEOUT, - PARAM_OTHERS, - PARAM_SSL_MODE, - PARAM_SSL_CERT, - PARAM_SSL_KEY, - PARAM_SSL_ROOT_CERT, - PARAM_SSL_CRL, - PARAM_KERBEROS_SERVER, - PARAM_LIB_GSSAPI, - SSL_DESABLE, - SSL_ALLOW, - SSL_PREFER, - SSL_REQUIRE, - SSL_CA_VERIF, - SSL_FULL_VERIF; + static const QString ParamAlias, + ParamServerFqdn, + ParamServerIp, + ParamPort, + ParamDbName, + ParamUser, + ParamPassword, + ParamConnTimeout, + ParamOthers, + ParamSslMode, + ParamSslCert, + ParamSslKey, + ParamSslRootCert, + ParamSslCrl, + ParamKerberosServer, + ParamLibGssapi, + SslDisable, + SslAllow, + SslPrefer, + SslRequire, + SslCaVerify, + SslFullVerify; //! \brief Constants used to reference the server info details (see getServerInfo()) - static const QString SERVER_VERSION, - SERVER_PROTOCOL, - SERVER_PID; + static const QString ServerVersion, + ServerProtocol, + ServerPid; //! \brief Constants used to reference the default usage in model operations (see setDefaultForOperation()) - static const unsigned OP_VALIDATION=0, - OP_EXPORT=1, - OP_IMPORT=2, - OP_DIFF=3, - OP_NONE=4; + static constexpr unsigned OpValidation=0, + OpExport=1, + OpImport=2, + OpDiff=3, + OpNone=4; Connection(void); Connection(const attribs_map ¶ms); @@ -168,7 +168,7 @@ class Connection { //! \brief Set if the database configured on the connection is auto browseable when using the SQLTool manage database void setAutoBrowseDB(bool value); - //! \brief Open the connection to the database + //! \brief Open the connection to the database. void connect(void); //! \brief Resets the database connection @@ -177,6 +177,9 @@ class Connection { //! \brief Close the opened connection void close(void); + //! \brief Request the cancel of the running command on a opened connection + void requestCancel(void); + //! \brief Returns the value of specified parameter name QString getConnectionParam(const QString ¶m); diff --git a/libpgconnector/src/resultset.cpp b/libpgconnector/src/resultset.cpp index 81dac934cc..567ca21653 100644 --- a/libpgconnector/src/resultset.cpp +++ b/libpgconnector/src/resultset.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -32,7 +32,7 @@ ResultSet::ResultSet(PGresult *sql_result) int res_state; if(!sql_result) - throw Exception(ERR_ASG_SQL_RESULT_NOT_ALOC, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::AsgNotAllocatedSQLResult, __PRETTY_FUNCTION__, __FILE__, __LINE__); this->sql_result=sql_result; res_state=PQresultStatus(this->sql_result); @@ -42,23 +42,22 @@ ResultSet::ResultSet(PGresult *sql_result) { //Generating an error in case the server returns an incomprehensible response case PGRES_BAD_RESPONSE: - throw Exception(ERR_INCOMPREHENSIBLE_DBMS_RESP, __PRETTY_FUNCTION__, __FILE__, __LINE__); - break; + throw Exception(ErrorCode::IncomprehensibleDBMSResponse, __PRETTY_FUNCTION__, __FILE__, __LINE__); //Generating an error in case the server returns a fatal error case PGRES_FATAL_ERROR: - str_aux=QString(Exception::getErrorMessage(ERR_DBMS_FATAL_ERROR)) + str_aux=Exception::getErrorMessage(ErrorCode::DBMSFatalError) .arg(PQresultErrorMessage(sql_result)); - throw Exception(str_aux,ERR_DBMS_FATAL_ERROR, __PRETTY_FUNCTION__, __FILE__, __LINE__); - break; + throw Exception(str_aux,ErrorCode::DBMSFatalError, __PRETTY_FUNCTION__, __FILE__, __LINE__); //In case of sucess states the result will be created case PGRES_COMMAND_OK: case PGRES_TUPLES_OK: + case PGRES_SINGLE_TUPLE: case PGRES_COPY_OUT: case PGRES_COPY_IN: default: - empty_result=(res_state!=PGRES_TUPLES_OK && res_state!=PGRES_EMPTY_QUERY); + empty_result=(res_state!=PGRES_TUPLES_OK && res_state!=PGRES_SINGLE_TUPLE && res_state!=PGRES_EMPTY_QUERY); current_tuple=-1; is_res_copied=false; break; @@ -67,10 +66,10 @@ ResultSet::ResultSet(PGresult *sql_result) ResultSet::~ResultSet(void) { - destroyResultSet(); + clearResultSet(); } -void ResultSet::destroyResultSet(void) +void ResultSet::clearResultSet(void) { /* Destroy the resultset of the object if it was not copied to another class instance (see 'operator =') */ @@ -88,7 +87,7 @@ QString ResultSet::getColumnName(int column_idx) { //Throws an error in case the column index is invalid if(column_idx < 0 || column_idx >= getColumnCount()) - throw Exception(ERR_REF_TUPLE_COL_INV_INDEX, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::RefTupleColumnInvalidIndex, __PRETTY_FUNCTION__, __FILE__, __LINE__); //Returns the column name on the specified index return(QString(PQfname(sql_result, column_idx))); @@ -98,7 +97,7 @@ unsigned ResultSet::getColumnTypeId(int column_idx) { //Throws an error in case the column index is invalid if(column_idx < 0 || column_idx >= getColumnCount()) - throw Exception(ERR_REF_TUPLE_COL_INV_INDEX, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::RefTupleColumnInvalidIndex, __PRETTY_FUNCTION__, __FILE__, __LINE__); //Returns the column type id on the specified index return(static_cast(PQftype(sql_result, column_idx))); @@ -114,7 +113,7 @@ int ResultSet::getColumnIndex(const QString &column_name) /* In case the index is negative indicates that the column doesn't exists in the tuple thus an error will be raised */ if(col_idx < 0) - throw Exception(ERR_REF_TUPLE_COL_INV_NAME, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::RefTupleColumnInvalidName, __PRETTY_FUNCTION__, __FILE__, __LINE__); return(col_idx); } @@ -127,9 +126,9 @@ int ResultSet::validateColumnName(const QString &column_name) a tuple of an empty result or generated from an INSERT, DELETE, UPDATE, that is, which command do not return lines but only do updates or removal */ if(getTupleCount()==0 || empty_result) - throw Exception(ERR_REF_TUPLE_INEXISTENT, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::RefInvalidTuple, __PRETTY_FUNCTION__, __FILE__, __LINE__); else if(current_tuple < 0 || current_tuple >= getTupleCount()) - throw Exception(ERR_REF_INV_TUPLE_COLUMN, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::RefInvalidTupleColumn, __PRETTY_FUNCTION__, __FILE__, __LINE__); //Get the column index through its name return (getColumnIndex(column_name)); @@ -137,7 +136,7 @@ int ResultSet::validateColumnName(const QString &column_name) catch(Exception &e) { //Capture and redirect any generated exception - throw Exception(e.getErrorMessage(), e.getErrorType(), __PRETTY_FUNCTION__, __FILE__, __LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__, __FILE__, __LINE__, &e); } } @@ -151,14 +150,14 @@ void ResultSet::validateColumnIndex(int column_idx) { //Raise an error in case the column index is invalid if(column_idx < 0 || column_idx >= getColumnCount()) - throw Exception(ERR_REF_TUPLE_COL_INV_INDEX, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::RefTupleColumnInvalidIndex, __PRETTY_FUNCTION__, __FILE__, __LINE__); /* Raises an error if the user try to get the value of a column in a tuple of an empty result or generated from an INSERT, DELETE, UPDATE, that is, which command do not return lines but only do updates or removal */ else if(getTupleCount()==0 || empty_result) - throw Exception(ERR_REF_TUPLE_INEXISTENT, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::RefInvalidTuple, __PRETTY_FUNCTION__, __FILE__, __LINE__); else if(current_tuple < 0 || current_tuple >= getTupleCount()) - throw Exception(ERR_REF_INV_TUPLE_COLUMN, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::RefInvalidTupleColumn, __PRETTY_FUNCTION__, __FILE__, __LINE__); } char *ResultSet::getColumnValue(int column_idx) @@ -193,9 +192,9 @@ int ResultSet::getColumnSize(int column_idx) { //Raise an error in case the column index is invalid if(column_idx < 0 || column_idx >= getColumnCount()) - throw Exception(ERR_REF_TUPLE_COL_INV_INDEX, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::RefTupleColumnInvalidIndex, __PRETTY_FUNCTION__, __FILE__, __LINE__); else if(current_tuple < 0 || current_tuple >= getTupleCount()) - throw Exception(ERR_REF_INV_TUPLE_COLUMN, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::RefInvalidTupleColumn, __PRETTY_FUNCTION__, __FILE__, __LINE__); //Retorns the column value length on the current tuple return(PQgetlength(sql_result, current_tuple, column_idx)); @@ -206,7 +205,7 @@ attribs_map ResultSet::getTupleValues(void) attribs_map tup_vals; if(current_tuple < 0 || current_tuple >= getTupleCount()) - throw Exception(ERR_REF_TUPLE_INEXISTENT, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::RefInvalidTuple, __PRETTY_FUNCTION__, __FILE__, __LINE__); for(int col=0; col < getColumnCount(); col++) tup_vals[getColumnName(col)]=getColumnValue(col); @@ -246,7 +245,7 @@ bool ResultSet::isColumnBinaryFormat(const QString &column_name) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(), __PRETTY_FUNCTION__, __FILE__, __LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__, __FILE__, __LINE__, &e); } /* Returns the column format in the current tuple. @@ -259,7 +258,7 @@ bool ResultSet::isColumnBinaryFormat(int column_idx) { //Raise an error in case the column index is invalid if(column_idx < 0 || column_idx >= getColumnCount()) - throw Exception(ERR_REF_TUPLE_COL_INV_INDEX, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(ErrorCode::RefTupleColumnInvalidIndex, __PRETTY_FUNCTION__, __FILE__, __LINE__); /* Returns the column format in the current tuple. According to libpq documentation, value = 0, indicates column text format, @@ -277,8 +276,8 @@ bool ResultSet::accessTuple(unsigned tuple_type) is derived from a command which affects only rows or The tuple type to be accessed is invalid, out of set defined by the class */ - if(empty_result || tuple_type > NEXT_TUPLE) - throw Exception(ERR_REF_TUPLE_INEXISTENT, __PRETTY_FUNCTION__, __FILE__, __LINE__); + if(empty_result || tuple_type > NextTuple) + throw Exception(ErrorCode::RefInvalidTuple, __PRETTY_FUNCTION__, __FILE__, __LINE__); if(tuple_count==0) return(false); @@ -288,20 +287,20 @@ bool ResultSet::accessTuple(unsigned tuple_type) switch(tuple_type) { - case FIRST_TUPLE: + case FirstTuple: current_tuple=0; break; - case LAST_TUPLE: + case LastTuple: current_tuple=tuple_count-1; break; - case PREVIOUS_TUPLE: + case PreviousTuple: accessed=(current_tuple > 0); if(accessed) current_tuple--; break; - case NEXT_TUPLE: + case NextTuple: accessed=(current_tuple < (tuple_count-1)); if(accessed) current_tuple++; break; @@ -316,6 +315,11 @@ bool ResultSet::isEmpty(void) return(empty_result); } +bool ResultSet::isValid(void) +{ + return(sql_result != nullptr); +} + void ResultSet::operator = (ResultSet &res) { /* Mark the result parameter as copied, avoiding @@ -324,7 +328,7 @@ void ResultSet::operator = (ResultSet &res) /* If the resultset 'this' is allocated, it will be deallocated to avoid memory leaks */ - destroyResultSet(); + clearResultSet(); //Copy the parameter restulset attributes to 'this' resultset this->current_tuple=res.current_tuple; diff --git a/libpgconnector/src/resultset.h b/libpgconnector/src/resultset.h index d07ad541ec..7be97d0142 100644 --- a/libpgconnector/src/resultset.h +++ b/libpgconnector/src/resultset.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -46,8 +46,6 @@ class ResultSet { when this flag is marked as false */ bool is_res_copied; - void destroyResultSet(void); - void validateColumnIndex(int column_idx); int validateColumnName(const QString &column_name); @@ -69,10 +67,10 @@ class ResultSet { public: //! \brief Constants used to navigate through the resultset - static const unsigned FIRST_TUPLE=0, - LAST_TUPLE=1, - PREVIOUS_TUPLE=2, - NEXT_TUPLE=3; + static constexpr unsigned FirstTuple=0, + LastTuple=1, + PreviousTuple=2, + NextTuple=3; ResultSet(void); ~ResultSet(void); @@ -122,6 +120,11 @@ class ResultSet { //! \brief Returns if the result set is empty due a DML command that does not returned any data bool isEmpty(void); + //! \brief Returns if the result set is valid (created from a valid result set) + bool isValid(void); + + void clearResultSet(void); + //! \brief Make a copy between two resultsets void operator = (ResultSet &res); diff --git a/libpgmodeler/libpgmodeler.pro b/libpgmodeler/libpgmodeler.pro index 96a255a38f..22470e0355 100644 --- a/libpgmodeler/libpgmodeler.pro +++ b/libpgmodeler/libpgmodeler.pro @@ -23,7 +23,7 @@ HEADERS += src/textbox.h \ src/column.h \ src/domain.h \ src/aggregate.h \ - src/permission.h \ + src/permission.h \ src/databasemodel.h \ src/role.h \ src/constraint.h \ @@ -41,6 +41,7 @@ HEADERS += src/textbox.h \ src/basegraphicobject.h \ src/relationship.h \ src/table.h \ + src/usermapping.h \ src/view.h \ src/operatorfamily.h \ src/operatorclasselement.h \ @@ -56,11 +57,15 @@ HEADERS += src/textbox.h \ src/copyoptions.h \ src/typeattribute.h \ src/extension.h \ - src/pgmodelerns.h \ - src/tag.h \ - src/eventtrigger.h \ - src/genericsql.h \ - src/policy.h + src/pgmodelerns.h \ + src/tag.h \ + src/eventtrigger.h \ + src/genericsql.h \ + src/policy.h \ + src/partitionkey.h \ + src/foreigndatawrapper.h \ + src/foreignobject.h \ + src/foreignserver.h SOURCES += src/textbox.cpp \ src/domain.cpp \ @@ -79,10 +84,11 @@ SOURCES += src/textbox.cpp \ src/language.cpp \ src/role.cpp \ src/sequence.cpp \ + src/usermapping.cpp \ src/view.cpp \ src/conversion.cpp \ src/function.cpp \ - src/permission.cpp \ + src/permission.cpp \ src/databasemodel.cpp \ src/rule.cpp \ src/table.cpp \ @@ -105,11 +111,15 @@ SOURCES += src/textbox.cpp \ src/typeattribute.cpp \ src/extension.cpp \ src/pgmodelerns.cpp \ - src/tag.cpp \ - src/eventtrigger.cpp \ - src/operation.cpp \ - src/genericsql.cpp \ - src/policy.cpp + src/tag.cpp \ + src/eventtrigger.cpp \ + src/operation.cpp \ + src/genericsql.cpp \ + src/policy.cpp \ + src/partitionkey.cpp \ + src/foreigndatawrapper.cpp \ + src/foreignobject.cpp \ + src/foreignserver.cpp unix|windows: LIBS += -L$$OUT_PWD/../libparsers/ -lparsers \ -L$$OUT_PWD/../libutils/ -lutils diff --git a/libpgmodeler/src/aggregate.cpp b/libpgmodeler/src/aggregate.cpp index 6f8112037b..81dc0771b4 100644 --- a/libpgmodeler/src/aggregate.cpp +++ b/libpgmodeler/src/aggregate.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,30 +20,30 @@ Aggregate::Aggregate(void) { - obj_type=OBJ_AGGREGATE; + obj_type=ObjectType::Aggregate; functions[0]=functions[1]=nullptr; sort_operator=nullptr; - attributes[ParsersAttributes::TYPES]=QString(); - attributes[ParsersAttributes::TRANSITION_FUNC]=QString(); - attributes[ParsersAttributes::STATE_TYPE]=QString(); - attributes[ParsersAttributes::BASE_TYPE]=QString(); - attributes[ParsersAttributes::FINAL_FUNC]=QString(); - attributes[ParsersAttributes::INITIAL_COND]=QString(); - attributes[ParsersAttributes::SORT_OP]=QString(); + attributes[Attributes::Types]=QString(); + attributes[Attributes::TransitionFunc]=QString(); + attributes[Attributes::StateType]=QString(); + attributes[Attributes::BaseType]=QString(); + attributes[Attributes::FinalFunc]=QString(); + attributes[Attributes::InitialCond]=QString(); + attributes[Attributes::SortOp]=QString(); } void Aggregate::setFunction(unsigned func_idx, Function *func) { //Case the function index is invalid raises an error - if(func_idx!=FINAL_FUNC && func_idx!=TRANSITION_FUNC) - throw Exception(ERR_REF_FUNCTION_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(func_idx!=FinalFunc && func_idx!=TransitionFunc) + throw Exception(ErrorCode::RefFunctionInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Checks if the function is valid, if not the case raises an error if(!isValidFunction(func_idx, func)) - throw Exception(Exception::getErrorMessage(ERR_USING_INV_FUNC_CONFIG) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidConfiguration) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_AGGREGATE)), - ERR_USING_INV_FUNC_CONFIG,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Aggregate)), + ErrorCode::AsgFunctionInvalidConfiguration,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(functions[func_idx]!=func); functions[func_idx]=func; @@ -53,7 +53,7 @@ bool Aggregate::isValidFunction(unsigned func_idx, Function *func) { if(func) { - if(func_idx==FINAL_FUNC) + if(func_idx==FinalFunc) { /* According to docs the final function to be valid must have 1 parameter which type is the same as the state_type attribute. BUT when importing system aggregates some functions has @@ -97,7 +97,7 @@ bool Aggregate::isValidFunction(unsigned func_idx, Function *func) else return(true); } -void Aggregate::setStateType(PgSQLType state_type) +void Aggregate::setStateType(PgSqlType state_type) { setCodeInvalidated(this->state_type != state_type); this->state_type=state_type; @@ -121,14 +121,14 @@ void Aggregate::setSortOperator(Operator *sort_op) 1) The aggregate accepts only one data type 2) The function that defines the operator has the parameter types identical as the input data type of the aggregate */ - func=sort_op->getFunction(Operator::FUNC_OPERATOR); + func=sort_op->getFunction(Operator::FuncOperator); //Validating the condition 1 if(data_types.size()!=1) - throw Exception(ERR_ASG_INV_OPER_ARGS,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidOperatorArguments,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Validating the condition 2 else if(func->getParameter(0).getType()!=data_types[0] || (func->getParameterCount()==2 && func->getParameter(1).getType()!=data_types[0])) - throw Exception(ERR_ASG_INV_OPERATOR_TYPES,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidOperatorTypes,__PRETTY_FUNCTION__,__FILE__,__LINE__); } setCodeInvalidated(sort_operator != sort_op); @@ -143,9 +143,9 @@ void Aggregate::setTypesAttribute(unsigned def_type) count=data_types.size(); for(i=0; i < count; i++) { - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) { - str_types+=data_types[i].getCodeDefinition(SchemaParser::SQL_DEFINITION); + str_types+=data_types[i].getCodeDefinition(SchemaParser::SqlDefinition); if(i < (count-1)) str_types+=','; } else str_types+=data_types[i].getCodeDefinition(def_type); @@ -153,12 +153,12 @@ void Aggregate::setTypesAttribute(unsigned def_type) /* Case none data type is specified for the aggregate creates an aggregate that accepts any possible data '*' e.g. function(*) */ - if(def_type == SchemaParser::SQL_DEFINITION && str_types.isEmpty()) str_types='*'; + if(def_type == SchemaParser::SqlDefinition && str_types.isEmpty()) str_types='*'; - attributes[ParsersAttributes::TYPES]=str_types; + attributes[Attributes::Types]=str_types; } -void Aggregate::addDataType(PgSQLType type) +void Aggregate::addDataType(PgSqlType type) { data_types.push_back(type); setCodeInvalidated(true); @@ -168,7 +168,7 @@ void Aggregate::removeDataType(unsigned type_idx) { //Raises an exception if the type index is out of bound if(type_idx >= data_types.size()) - throw Exception(ERR_REF_TYPE_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefTypeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Removes the type at the specified position data_types.erase(data_types.begin() + type_idx); @@ -189,13 +189,13 @@ unsigned Aggregate::getDataTypeCount(void) Function *Aggregate::getFunction(unsigned func_idx) { //Raises an exception if the function index is invalid - if(func_idx!=FINAL_FUNC && func_idx!=TRANSITION_FUNC) - throw Exception(ERR_REF_FUNCTION_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(func_idx!=FinalFunc && func_idx!=TransitionFunc) + throw Exception(ErrorCode::RefFunctionInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(functions[func_idx]); } -PgSQLType Aggregate::getStateType(void) +PgSqlType Aggregate::getStateType(void) { return(state_type); } @@ -210,11 +210,11 @@ Operator *Aggregate::getSortOperator(void) return(sort_operator); } -PgSQLType Aggregate::getDataType(unsigned type_idx) +PgSqlType Aggregate::getDataType(unsigned type_idx) { //Raises an exception if the type index is out of bound if(type_idx >= data_types.size()) - throw Exception(ERR_REF_TYPE_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefTypeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(data_types[type_idx]); } @@ -226,52 +226,52 @@ QString Aggregate::getCodeDefinition(unsigned def_type) setTypesAttribute(def_type); - if(functions[TRANSITION_FUNC]) + if(functions[TransitionFunc]) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::TRANSITION_FUNC]=functions[TRANSITION_FUNC]->getSignature(); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::TransitionFunc]=functions[TransitionFunc]->getSignature(); else { - functions[TRANSITION_FUNC]->setAttribute(ParsersAttributes::REF_TYPE, - ParsersAttributes::TRANSITION_FUNC); - attributes[ParsersAttributes::TRANSITION_FUNC]=functions[TRANSITION_FUNC]->getCodeDefinition(def_type,true); + functions[TransitionFunc]->setAttribute(Attributes::RefType, + Attributes::TransitionFunc); + attributes[Attributes::TransitionFunc]=functions[TransitionFunc]->getCodeDefinition(def_type,true); } } - if(functions[FINAL_FUNC]) + if(functions[FinalFunc]) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::FINAL_FUNC]=functions[FINAL_FUNC]->getSignature(); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::FinalFunc]=functions[FinalFunc]->getSignature(); else { - functions[FINAL_FUNC]->setAttribute(ParsersAttributes::REF_TYPE, - ParsersAttributes::FINAL_FUNC); - attributes[ParsersAttributes::FINAL_FUNC]=functions[FINAL_FUNC]->getCodeDefinition(def_type,true); + functions[FinalFunc]->setAttribute(Attributes::RefType, + Attributes::FinalFunc); + attributes[Attributes::FinalFunc]=functions[FinalFunc]->getCodeDefinition(def_type,true); } } if(sort_operator) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::SORT_OP]=sort_operator->getName(true); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::SortOp]=sort_operator->getName(true); else - attributes[ParsersAttributes::SORT_OP]=sort_operator->getCodeDefinition(def_type,true); + attributes[Attributes::SortOp]=sort_operator->getCodeDefinition(def_type,true); } if(!initial_condition.isEmpty()) - attributes[ParsersAttributes::INITIAL_COND]=initial_condition; + attributes[Attributes::InitialCond]=initial_condition; - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::STATE_TYPE]=*(state_type); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::StateType]=*(state_type); else - attributes[ParsersAttributes::STATE_TYPE]=state_type.getCodeDefinition(def_type,ParsersAttributes::STATE_TYPE); + attributes[Attributes::StateType]=state_type.getCodeDefinition(def_type,Attributes::StateType); return(BaseObject::__getCodeDefinition(def_type)); } QString Aggregate::getDropDefinition(bool cascade) { - setTypesAttribute(SchemaParser::SQL_DEFINITION); + setTypesAttribute(SchemaParser::SqlDefinition); return(BaseObject::getDropDefinition(cascade)); } @@ -279,12 +279,12 @@ QString Aggregate::getAlterDefinition(BaseObject *object) { try { - setTypesAttribute(SchemaParser::SQL_DEFINITION); + setTypesAttribute(SchemaParser::SqlDefinition); return(BaseObject::getAlterDefinition(object)); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -297,9 +297,20 @@ QString Aggregate::getSignature(bool format) else { for(auto &tp : data_types) - types.push_back(tp.getCodeDefinition(SchemaParser::SQL_DEFINITION)); + types.push_back(tp.getCodeDefinition(SchemaParser::SqlDefinition)); } return(BaseObject::getSignature(format) + QString("(%1)").arg(types.join(','))); } +void Aggregate::configureSearchAttributes(void) +{ + QStringList list; + + BaseObject::configureSearchAttributes(); + + for(auto &type : data_types) + list += *type; + + search_attribs[Attributes::Type] = list.join("; "); +} diff --git a/libpgmodeler/src/aggregate.h b/libpgmodeler/src/aggregate.h index 3bb5b59a17..079acf7f7d 100644 --- a/libpgmodeler/src/aggregate.h +++ b/libpgmodeler/src/aggregate.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -41,7 +41,7 @@ class Aggregate: public BaseObject { To declare an aggregate function which works with several types in the old syntax, the only element of the list must be of type 'any' */ - vector data_types; + vector data_types; /*! \brief Function that defines the aggregate behavior 0 -> Final function @@ -49,7 +49,7 @@ class Aggregate: public BaseObject { Function *functions[2]; //! \brief Data type used as aggregate's state - PgSQLType state_type; + PgSqlType state_type; //! \brief Initial condition for the aggregate QString initial_condition; @@ -63,10 +63,13 @@ class Aggregate: public BaseObject { //! \brief Checks if the passed function is valid according to the rule of aggregate definition bool isValidFunction(unsigned func_idx, Function *func); + protected: + virtual void configureSearchAttributes(void); + public: //! \brief Constants used to reference the functions used by the aggregate - static const unsigned FINAL_FUNC=0, - TRANSITION_FUNC=1; + static constexpr unsigned FinalFunc=0, + TransitionFunc=1; Aggregate(void); @@ -74,7 +77,7 @@ class Aggregate: public BaseObject { void setFunction(unsigned func_idx, Function *func); //! \brief Defines the state data type of the aggregate - void setStateType(PgSQLType state_type); + void setStateType(PgSqlType state_type); //! \brief Defines the initial condition for the aggregate void setInitialCondition(const QString &cond); @@ -83,7 +86,7 @@ class Aggregate: public BaseObject { void setSortOperator(Operator *sort_op); //! \brief Adds a data type in the group that is accepted by the aggregate - void addDataType(PgSQLType type); + void addDataType(PgSqlType type); //! \brief Removes one aggregate accepted data type void removeDataType(unsigned type_idx); @@ -92,10 +95,10 @@ class Aggregate: public BaseObject { void removeDataTypes(void); Function *getFunction(unsigned func_idx); - PgSQLType getStateType(void); + PgSqlType getStateType(void); QString getInitialCondition(void); Operator *getSortOperator(void); - PgSQLType getDataType(unsigned type_idx); + PgSqlType getDataType(unsigned type_idx); unsigned getDataTypeCount(void); //! \brief Returns the SQL / XML code definition for the aggregate diff --git a/libpgmodeler/src/basegraphicobject.cpp b/libpgmodeler/src/basegraphicobject.cpp index ca626a5a38..a79933cc90 100644 --- a/libpgmodeler/src/basegraphicobject.cpp +++ b/libpgmodeler/src/basegraphicobject.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -22,11 +22,13 @@ BaseGraphicObject::BaseGraphicObject(void) { is_modified=true; is_faded_out=false; - attributes[ParsersAttributes::X_POS]=QString(); - attributes[ParsersAttributes::Y_POS]=QString(); - attributes[ParsersAttributes::POSITION]=QString(); - attributes[ParsersAttributes::FADED_OUT]=QString(); + attributes[Attributes::XPos]=QString(); + attributes[Attributes::YPos]=QString(); + attributes[Attributes::Position]=QString(); + attributes[Attributes::FadedOut]=QString(); + attributes[Attributes::Layer]=QString(); receiver_object=nullptr; + layer = 0; } void BaseGraphicObject::setProtected(bool value) @@ -76,14 +78,14 @@ bool BaseGraphicObject::isFadedOut(void) void BaseGraphicObject::setFadedOutAttribute(void) { - attributes[ParsersAttributes::FADED_OUT]=(is_faded_out ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::FadedOut]=(is_faded_out ? Attributes::True : QString()); } void BaseGraphicObject::setPositionAttribute(void) { - attributes[ParsersAttributes::X_POS]=QString("%1").arg(position.x()); - attributes[ParsersAttributes::Y_POS]=QString("%1").arg(position.y()); - attributes[ParsersAttributes::POSITION]=schparser.getCodeDefinition(ParsersAttributes::POSITION, attributes, SchemaParser::XML_DEFINITION); + attributes[Attributes::XPos]=QString("%1").arg(position.x()); + attributes[Attributes::YPos]=QString("%1").arg(position.y()); + attributes[Attributes::Position]=schparser.getCodeDefinition(Attributes::Position, attributes, SchemaParser::XmlDefinition); } void BaseGraphicObject::setPosition(QPointF pos) @@ -111,13 +113,24 @@ void BaseGraphicObject::setReceiverObject(QObject *obj) receiver_object=obj; } -QObject *BaseGraphicObject::getReceiverObject(void) +QObject *BaseGraphicObject::getOverlyingObject(void) { return(receiver_object); } bool BaseGraphicObject::isGraphicObject(ObjectType type) { - return(type==OBJ_TABLE || type==OBJ_VIEW || type==OBJ_RELATIONSHIP || - type==BASE_RELATIONSHIP || type==OBJ_TEXTBOX || type==OBJ_SCHEMA); + return(type==ObjectType::Table || type==ObjectType::View || type==ObjectType::Relationship || + type==ObjectType::BaseRelationship || type==ObjectType::Textbox || type==ObjectType::Schema); +} + +void BaseGraphicObject::setLayer(unsigned layer) +{ + setCodeInvalidated(this->layer != layer); + this->layer = layer; +} + +unsigned BaseGraphicObject::getLayer(void) +{ + return(layer); } diff --git a/libpgmodeler/src/basegraphicobject.h b/libpgmodeler/src/basegraphicobject.h index f0d9440fbb..3f2e991fe6 100644 --- a/libpgmodeler/src/basegraphicobject.h +++ b/libpgmodeler/src/basegraphicobject.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -56,6 +56,9 @@ class BaseGraphicObject: public QObject, public BaseObject { QObject *receiver_object; protected: + //! \brief This attributes holds the layer in which the object is visible. + unsigned layer; + /*! \brief Method that defines the objects position attributes used in generation of XML code definition */ void setPositionAttribute(void); @@ -103,8 +106,8 @@ class BaseGraphicObject: public QObject, public BaseObject { //! \brief Assigns on object to other mading the correct attribute copy void operator = (BaseGraphicObject &obj); - //! \brief Gets the current receiver object that graphically represents the 'this' object - QObject *getReceiverObject(void); + //! \brief Gets the current overlying (top object, scene object) that graphically represents the 'this' object + QObject *getOverlyingObject(void); //! \brief Returns the code definition of the object virtual QString getCodeDefinition(unsigned)=0; @@ -112,6 +115,12 @@ class BaseGraphicObject: public QObject, public BaseObject { //! \brief Returns if the passed type one that has a graphical representation (table, view, schema, relationship or textbox) static bool isGraphicObject(ObjectType type); + //! \brief Defines in which layer the object is visible + void setLayer(unsigned layer); + + //! \brief Returns the layer in which the object is visible + unsigned getLayer(void); + signals: //! \brief Signal emitted when the user calls the setModified() method void s_objectModified(void); diff --git a/libpgmodeler/src/baseobject.cpp b/libpgmodeler/src/baseobject.cpp index 62b1aa10de..39cd60f415 100644 --- a/libpgmodeler/src/baseobject.cpp +++ b/libpgmodeler/src/baseobject.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -25,19 +25,20 @@ const QByteArray BaseObject::special_chars = QByteArray("'_-.@ $:()/<>+*\\=~!#%^ /* CAUTION: If both amount and order of the enumerations are modified then the order and amount of the elements of this vector must also be modified */ -QString BaseObject::objs_schemas[OBJECT_TYPE_COUNT]={ +const QString BaseObject::objs_schemas[BaseObject::ObjectTypeCount]={ "column", "constraint", "function", "trigger", "index", "rule", "table", "view", "domain", "schema", "aggregate", "operator", "sequence", "role", "conversion", "cast", "language", "usertype", "tablespace", "opfamily", "opclass", "database","collation", - "extension", "eventtrigger", "policy", "relationship", - "textbox", "permission", "parameter", "typeattribute", - "tag", "genericsql", "relationship" + "extension", "eventtrigger", "policy", "foreigndatawrapper", + "foreignserver", "usermapping", "relationship", "textbox", + "permission", "parameter", "typeattribute", "tag", + "genericsql", "relationship" }; -QString BaseObject::obj_type_names[OBJECT_TYPE_COUNT]={ +const QString BaseObject::obj_type_names[BaseObject::ObjectTypeCount]={ QT_TR_NOOP("Column"), QT_TR_NOOP("Constraint"), QT_TR_NOOP("Function"), QT_TR_NOOP("Trigger"), QT_TR_NOOP("Index"), QT_TR_NOOP("Rule"), QT_TR_NOOP("Table"), QT_TR_NOOP("View"), QT_TR_NOOP("Domain"), @@ -46,19 +47,23 @@ QString BaseObject::obj_type_names[OBJECT_TYPE_COUNT]={ QT_TR_NOOP("Cast"), QT_TR_NOOP("Language"), QT_TR_NOOP("Type"), QT_TR_NOOP("Tablespace"), QT_TR_NOOP("Operator Family"), QT_TR_NOOP("Operator Class"), QT_TR_NOOP("Database"), QT_TR_NOOP("Collation"), QT_TR_NOOP("Extension"), - QT_TR_NOOP("Event Trigger"), QT_TR_NOOP("Policy"), QT_TR_NOOP("Relationship"), - QT_TR_NOOP("Textbox"), QT_TR_NOOP("Permission"), QT_TR_NOOP("Parameter"), QT_TR_NOOP("Type Attribute"), - QT_TR_NOOP("Tag"), QT_TR_NOOP("Generic SQL"), QT_TR_NOOP("Basic Relationship") + QT_TR_NOOP("Event Trigger"), QT_TR_NOOP("Policy"), QT_TR_NOOP("Foreign Data Wrapper"), + QT_TR_NOOP("Foreign Server"), QT_TR_NOOP("User Mapping"), QT_TR_NOOP("Relationship"), + QT_TR_NOOP("Textbox"), QT_TR_NOOP("Permission"), QT_TR_NOOP("Parameter"), + QT_TR_NOOP("Type Attribute"), QT_TR_NOOP("Tag"), QT_TR_NOOP("Generic SQL"), + QT_TR_NOOP("Basic Relationship") }; -QString BaseObject::objs_sql[OBJECT_TYPE_COUNT]={ +const QString BaseObject::objs_sql[BaseObject::ObjectTypeCount]={ QString("COLUMN"), QString("CONSTRAINT"), QString("FUNCTION"), QString("TRIGGER"), QString("INDEX"), QString("RULE"), QString("TABLE"), QString("VIEW"), QString("DOMAIN"), QString("SCHEMA"), QString("AGGREGATE"), QString("OPERATOR"), QString("SEQUENCE"), QString("ROLE"), QString("CONVERSION"), QString("CAST"), QString("LANGUAGE"), QString("TYPE"), QString("TABLESPACE"), QString("OPERATOR FAMILY"), QString("OPERATOR CLASS"), QString("DATABASE"), - QString("COLLATION"), QString("EXTENSION"), QString("EVENT TRIGGER"), QString("POLICY") + QString("COLLATION"), QString("EXTENSION"), QString("EVENT TRIGGER"), + QString("POLICY"), QString("FOREIGN DATA WRAPPER"), QString("SERVER"), + QString("USER MAPPING") }; /* Initializes the global id which is shared between instances @@ -68,7 +73,7 @@ QString BaseObject::objs_sql[OBJECT_TYPE_COUNT]={ DatabaseModel, Tag */ unsigned BaseObject::global_id=4000; -QString BaseObject::pgsql_ver=PgSQLVersions::DEFAULT_VERSION; +QString BaseObject::pgsql_ver=PgSqlVersions::DefaulVersion; bool BaseObject::use_cached_code=true; BaseObject::BaseObject(void) @@ -76,24 +81,25 @@ BaseObject::BaseObject(void) object_id=BaseObject::global_id++; is_protected=system_obj=sql_disabled=false; code_invalidated=true; - obj_type=BASE_OBJECT; + obj_type=ObjectType::BaseObject; schema=nullptr; owner=nullptr; tablespace=nullptr; database=nullptr; collation=nullptr; - attributes[ParsersAttributes::NAME]=QString(); - attributes[ParsersAttributes::COMMENT]=QString(); - attributes[ParsersAttributes::OWNER]=QString(); - attributes[ParsersAttributes::TABLESPACE]=QString(); - attributes[ParsersAttributes::SCHEMA]=QString(); - attributes[ParsersAttributes::COLLATION]=QString(); - attributes[ParsersAttributes::PROTECTED]=QString(); - attributes[ParsersAttributes::SQL_DISABLED]=QString(); - attributes[ParsersAttributes::APPENDED_SQL]=QString(); - attributes[ParsersAttributes::PREPENDED_SQL]=QString(); - attributes[ParsersAttributes::DROP]=QString(); - attributes[ParsersAttributes::SIGNATURE]=QString(); + attributes[Attributes::Name]=QString(); + attributes[Attributes::Alias]=QString(); + attributes[Attributes::Comment]=QString(); + attributes[Attributes::Owner]=QString(); + attributes[Attributes::Tablespace]=QString(); + attributes[Attributes::Schema]=QString(); + attributes[Attributes::Collation]=QString(); + attributes[Attributes::Protected]=QString(); + attributes[Attributes::SqlDisabled]=QString(); + attributes[Attributes::AppendedSql]=QString(); + attributes[Attributes::PrependedSql]=QString(); + attributes[Attributes::Drop]=QString(); + attributes[Attributes::Signature]=QString(); this->setName(QApplication::translate("BaseObject","new_object","", -1)); } @@ -104,11 +110,11 @@ unsigned BaseObject::getGlobalId(void) QString BaseObject::getTypeName(ObjectType obj_type) { - if(obj_type!=BASE_OBJECT) + if(obj_type!=ObjectType::BaseObject) /* Due to the class BaseObject not be derived from QObject the function tr() is inefficient to translate the type names thus the method called to do the translation is from the application specifying the context (BaseObject) in the ts file and the text to be translated */ - return(QApplication::translate("BaseObject",obj_type_names[obj_type].toStdString().c_str(),"", -1)); + return(QApplication::translate("BaseObject",obj_type_names[enum_cast(obj_type)].toStdString().c_str(),"", -1)); else return(QString()); } @@ -120,9 +126,9 @@ QString BaseObject::getTypeName(const QString &type_str) ObjectType BaseObject::getObjectType(const QString &type_name) { - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; - for(int i=0; i < BaseObject::OBJECT_TYPE_COUNT; i++) + for(unsigned i=0; i < BaseObject::ObjectTypeCount; i++) { if(objs_schemas[i]==type_name) { @@ -136,12 +142,12 @@ ObjectType BaseObject::getObjectType(const QString &type_name) QString BaseObject::getSchemaName(ObjectType obj_type) { - return(objs_schemas[obj_type]); + return(objs_schemas[enum_cast(obj_type)]); } QString BaseObject::getSQLName(ObjectType obj_type) { - return(objs_sql[obj_type]); + return(objs_sql[enum_cast(obj_type)]); } QString BaseObject::formatName(const QString &name, bool is_operator) @@ -214,7 +220,7 @@ QString BaseObject::formatName(const QString &name, bool is_operator) } - if(needs_fmt || PgModelerNS::isReservedKeyword(name)) + if(needs_fmt || PgModelerNs::isReservedKeyword(name)) frmt_name=QString("\"%1\"").arg(name); else frmt_name=name; @@ -239,7 +245,7 @@ bool BaseObject::isValidName(const QString &name) by PostgreSQL (currently 63 bytes) the name is invalid. In this case the starting and ending quotes are discarded from the name in order to validate the length. */ - if(name.isEmpty() || aux_name.size() > OBJECT_NAME_MAX_LENGTH) + if(name.isEmpty() || aux_name.size() > ObjectNameMaxLength) return(false); else { @@ -323,7 +329,7 @@ bool BaseObject::isValidName(const QString &name) void BaseObject::setDatabase(BaseObject *db) { - if((db && db->getObjectType()==OBJ_DATABASE) || !db) + if((db && db->getObjectType()==ObjectType::Database) || !db) this->database=db; } @@ -347,12 +353,12 @@ void BaseObject::setName(const QString &name) if(!isValidName(aux_name)) { if(aux_name.isEmpty()) - throw Exception(ERR_ASG_EMPTY_NAME_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgEmptyNameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //If the name is quoted we add 2 bytes to the maximum in order to check if it exceeds the limit - else if(aux_name.size() > (OBJECT_NAME_MAX_LENGTH + (is_quoted ? 2 : 0))) - throw Exception(ERR_ASG_LONG_NAME_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(aux_name.size() > (ObjectNameMaxLength + (is_quoted ? 2 : 0))) + throw Exception(ErrorCode::AsgLongNameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else - throw Exception(ERR_ASG_INV_NAME_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidNameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); } aux_name.remove('"'); @@ -360,6 +366,15 @@ void BaseObject::setName(const QString &name) this->obj_name=aux_name; } +void BaseObject::setAlias(const QString &alias) +{ + if(alias.size() > ObjectNameMaxLength) + throw Exception(ErrorCode::AsgLongNameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + this->alias = alias; + setCodeInvalidated(this->alias != alias); +} + void BaseObject::setComment(const QString &comment) { setCodeInvalidated(this->comment!=comment); @@ -368,13 +383,13 @@ void BaseObject::setComment(const QString &comment) bool BaseObject::acceptsSchema(ObjectType obj_type) { - return(obj_type==OBJ_FUNCTION || obj_type==OBJ_TABLE || - obj_type==OBJ_VIEW || obj_type==OBJ_DOMAIN || - obj_type==OBJ_AGGREGATE || obj_type==OBJ_OPERATOR || - obj_type==OBJ_SEQUENCE || obj_type==OBJ_CONVERSION || - obj_type==OBJ_TYPE || obj_type==OBJ_OPCLASS || - obj_type==OBJ_OPFAMILY || obj_type==OBJ_COLLATION || - obj_type==OBJ_EXTENSION); + return(obj_type==ObjectType::Function || obj_type==ObjectType::Table || + obj_type==ObjectType::View || obj_type==ObjectType::Domain || + obj_type==ObjectType::Aggregate || obj_type==ObjectType::Operator || + obj_type==ObjectType::Sequence || obj_type==ObjectType::Conversion || + obj_type==ObjectType::Type || obj_type==ObjectType::OpClass || + obj_type==ObjectType::OpFamily || obj_type==ObjectType::Collation || + obj_type==ObjectType::Extension); } bool BaseObject::acceptsSchema(void) @@ -384,15 +399,16 @@ bool BaseObject::acceptsSchema(void) bool BaseObject::acceptsOwner(ObjectType obj_type) { - return(obj_type==OBJ_FUNCTION || obj_type==OBJ_TABLE || - obj_type==OBJ_DOMAIN || obj_type==OBJ_SCHEMA || - obj_type==OBJ_AGGREGATE || obj_type==OBJ_OPERATOR || - obj_type==OBJ_CONVERSION || obj_type==OBJ_SEQUENCE || - obj_type==OBJ_LANGUAGE || obj_type==OBJ_TYPE || - obj_type==OBJ_TABLESPACE || obj_type==OBJ_DATABASE || - obj_type==OBJ_OPCLASS || obj_type==OBJ_OPFAMILY || - obj_type==OBJ_COLLATION || obj_type==OBJ_VIEW || - obj_type==OBJ_EVENT_TRIGGER); + return(obj_type==ObjectType::Function || obj_type==ObjectType::Table || + obj_type==ObjectType::Domain || obj_type==ObjectType::Schema || + obj_type==ObjectType::Aggregate || obj_type==ObjectType::Operator || + obj_type==ObjectType::Conversion || obj_type==ObjectType::Sequence || + obj_type==ObjectType::Language || obj_type==ObjectType::Type || + obj_type==ObjectType::Tablespace || obj_type==ObjectType::Database || + obj_type==ObjectType::OpClass || obj_type==ObjectType::OpFamily || + obj_type==ObjectType::Collation || obj_type==ObjectType::View || + obj_type==ObjectType::EventTrigger || obj_type==ObjectType::ForeignDataWrapper || + obj_type==ObjectType::ForeignServer || obj_type==ObjectType::UserMapping); } bool BaseObject::acceptsOwner(void) @@ -402,11 +418,11 @@ bool BaseObject::acceptsOwner(void) bool BaseObject::acceptsTablespace(ObjectType obj_type) { - return(obj_type==OBJ_INDEX || - obj_type==OBJ_TABLE || - obj_type==OBJ_VIEW || - obj_type==OBJ_CONSTRAINT || - obj_type==OBJ_DATABASE); + return(obj_type==ObjectType::Index || + obj_type==ObjectType::Table || + obj_type==ObjectType::View || + obj_type==ObjectType::Constraint || + obj_type==ObjectType::Database); } bool BaseObject::acceptsTablespace(void) @@ -416,9 +432,9 @@ bool BaseObject::acceptsTablespace(void) bool BaseObject::acceptsCollation(ObjectType obj_type) { - return(obj_type==OBJ_DOMAIN || obj_type==OBJ_COLUMN || - obj_type==OBJ_COLLATION || obj_type==OBJ_TYPE || - obj_type==OBJ_TYPE_ATTRIBUTE); + return(obj_type==ObjectType::Domain || obj_type==ObjectType::Column || + obj_type==ObjectType::Collation || obj_type==ObjectType::Type || + obj_type==ObjectType::TypeAttribute); } bool BaseObject::acceptsCollation(void) @@ -428,31 +444,42 @@ bool BaseObject::acceptsCollation(void) bool BaseObject::acceptsCustomSQL(ObjectType obj_type) { - return(obj_type!=OBJ_COLUMN && obj_type!=OBJ_CONSTRAINT && - obj_type!=OBJ_RELATIONSHIP && obj_type!=OBJ_TEXTBOX && obj_type!=OBJ_PARAMETER && - obj_type!=OBJ_TYPE_ATTRIBUTE && obj_type!=BASE_RELATIONSHIP && - obj_type!=BASE_OBJECT && obj_type!=BASE_TABLE && obj_type!=OBJ_PERMISSION && - obj_type!=OBJ_TAG && obj_type!=OBJ_GENERIC_SQL); + return(obj_type!=ObjectType::Column && obj_type!=ObjectType::Constraint && + obj_type!=ObjectType::Relationship && obj_type!=ObjectType::Textbox && obj_type!=ObjectType::Parameter && + obj_type!=ObjectType::TypeAttribute && obj_type!=ObjectType::BaseRelationship && + obj_type!=ObjectType::BaseObject && obj_type!=ObjectType::BaseTable && obj_type!=ObjectType::Permission && + obj_type!=ObjectType::Tag && obj_type!=ObjectType::GenericSql); } bool BaseObject::acceptsAlterCommand(ObjectType obj_type) { - return(obj_type==OBJ_COLLATION || obj_type==OBJ_COLUMN || - obj_type==OBJ_DOMAIN || obj_type==OBJ_EVENT_TRIGGER || - obj_type==OBJ_EXTENSION || obj_type==OBJ_FUNCTION || - obj_type==OBJ_INDEX || obj_type==OBJ_ROLE || - obj_type==OBJ_SCHEMA || obj_type==OBJ_SEQUENCE || - obj_type==OBJ_TABLE || obj_type==OBJ_TABLESPACE || - obj_type==OBJ_TYPE || obj_type==OBJ_POLICY); + return(obj_type==ObjectType::Collation || obj_type==ObjectType::Column || + obj_type==ObjectType::Domain || obj_type==ObjectType::EventTrigger || + obj_type==ObjectType::Extension || obj_type==ObjectType::Function || + obj_type==ObjectType::Index || obj_type==ObjectType::Role || + obj_type==ObjectType::Schema || obj_type==ObjectType::Sequence || + obj_type==ObjectType::Table || obj_type==ObjectType::Tablespace || + obj_type==ObjectType::Type || obj_type==ObjectType::Policy || + obj_type==ObjectType::ForeignDataWrapper || obj_type==ObjectType::ForeignServer || + obj_type==ObjectType::UserMapping); } bool BaseObject::acceptsDropCommand(ObjectType obj_type) { - return(obj_type!=OBJ_PERMISSION && obj_type!=OBJ_RELATIONSHIP && - obj_type!=OBJ_TEXTBOX && obj_type!=OBJ_TYPE_ATTRIBUTE && - obj_type!=OBJ_PARAMETER && obj_type!=BASE_OBJECT && - obj_type!=OBJ_TAG && obj_type!=BASE_RELATIONSHIP && - obj_type!=BASE_TABLE); + return(obj_type!=ObjectType::Permission && obj_type!=ObjectType::Relationship && + obj_type!=ObjectType::Textbox && obj_type!=ObjectType::TypeAttribute && + obj_type!=ObjectType::Parameter && obj_type!=ObjectType::BaseObject && + obj_type!=ObjectType::Tag && obj_type!=ObjectType::BaseRelationship && + obj_type!=ObjectType::BaseTable); +} + +bool BaseObject::acceptsAlias(ObjectType obj_type) +{ + return(obj_type==ObjectType::Relationship || obj_type==ObjectType::BaseRelationship || + obj_type==ObjectType::Table || obj_type==ObjectType::Schema || obj_type==ObjectType::View || + obj_type == ObjectType::Column || obj_type == ObjectType::Constraint || + obj_type == ObjectType::Index || obj_type == ObjectType::Rule || + obj_type == ObjectType::Trigger || obj_type == ObjectType::Policy); } bool BaseObject::acceptsCustomSQL(void) @@ -473,14 +500,14 @@ bool BaseObject::acceptsDropCommand(void) void BaseObject::setSchema(BaseObject *schema) { if(!schema) - throw Exception(Exception::getErrorMessage(ERR_ASG_NOT_ALOC_SCHEMA) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgNotAllocatedSchema) .arg(this->obj_name) .arg(this->getTypeName()), - ERR_ASG_NOT_ALOC_SCHEMA,__PRETTY_FUNCTION__,__FILE__,__LINE__); - else if(schema && schema->getObjectType()!=OBJ_SCHEMA) - throw Exception(ERR_ASG_INV_SCHEMA_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgNotAllocatedSchema,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(schema && schema->getObjectType()!=ObjectType::Schema) + throw Exception(ErrorCode::AsgInvalidSchemaObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(!acceptsSchema()) - throw Exception(ERR_ASG_INV_SCHEMA_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidSchemaObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->schema != schema); this->schema=schema; @@ -488,10 +515,10 @@ void BaseObject::setSchema(BaseObject *schema) void BaseObject::setOwner(BaseObject *owner) { - if(owner && owner->getObjectType()!=OBJ_ROLE) - throw Exception(ERR_ASG_INV_ROLE_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(owner && owner->getObjectType()!=ObjectType::Role) + throw Exception(ErrorCode::AsgInvalidRoleObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(!acceptsOwner()) - throw Exception(ERR_ASG_ROLE_OBJECT_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgRoleObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->owner != owner); this->owner=owner; @@ -499,10 +526,10 @@ void BaseObject::setOwner(BaseObject *owner) void BaseObject::setTablespace(BaseObject *tablespace) { - if(tablespace && tablespace->getObjectType()!=OBJ_TABLESPACE) - throw Exception(ERR_ASG_INV_TABLESPACE_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(tablespace && tablespace->getObjectType()!=ObjectType::Tablespace) + throw Exception(ErrorCode::AsgInvalidTablespaceObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(!acceptsTablespace()) - throw Exception(ERR_ASG_TABSPC_INV_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgTablespaceInvalidObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->tablespace != tablespace); this->tablespace=tablespace; @@ -511,9 +538,9 @@ void BaseObject::setTablespace(BaseObject *tablespace) void BaseObject::setCollation(BaseObject *collation) { if(collation && !acceptsCollation()) - throw Exception(ERR_ASG_INV_COLLATION_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(collation && collation->getObjectType()!=OBJ_COLLATION) - throw Exception(ERR_ASG_INV_COLLATION_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidCollationObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(collation && collation->getObjectType()!=ObjectType::Collation) + throw Exception(ErrorCode::AsgInvalidCollationObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->collation != collation); this->collation=collation; @@ -522,7 +549,7 @@ void BaseObject::setCollation(BaseObject *collation) void BaseObject::setAppendedSQL(const QString &sql) { if(!acceptsCustomSQL()) - throw Exception(ERR_ASG_APPSQL_OBJECT_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgCustomSQLObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->appended_sql != sql); this->appended_sql=sql; @@ -531,7 +558,7 @@ void BaseObject::setAppendedSQL(const QString &sql) void BaseObject::setPrependedSQL(const QString &sql) { if(!acceptsCustomSQL()) - throw Exception(ERR_ASG_APPSQL_OBJECT_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgCustomSQLObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->prepended_sql != sql); this->prepended_sql=sql; @@ -542,7 +569,7 @@ QString BaseObject::getName(bool format, bool prepend_schema) if(format) { QString aux_name; - aux_name=formatName(this->obj_name, (obj_type==OBJ_OPERATOR)); + aux_name=formatName(this->obj_name, (obj_type==ObjectType::Operator)); if(this->schema && prepend_schema) aux_name=formatName(this->schema->getName(format)) + QString(".") + aux_name; @@ -556,6 +583,11 @@ QString BaseObject::getName(bool format, bool prepend_schema) return(this->obj_name); } +QString BaseObject::getAlias(void) +{ + return(this->alias); +} + QString BaseObject::getSignature(bool format) { return(this->getName(format, true)); @@ -650,14 +682,17 @@ bool BaseObject::isSystemObject(void) void BaseObject::setBasicAttributes(bool format_name) { - if(attributes[ParsersAttributes::NAME].isEmpty()) - attributes[ParsersAttributes::NAME]=this->getName(format_name); + if(attributes[Attributes::Name].isEmpty()) + attributes[Attributes::Name]=this->getName(format_name); - if(attributes[ParsersAttributes::SIGNATURE].isEmpty()) - attributes[ParsersAttributes::SIGNATURE]=this->getSignature(format_name); + if(attributes[Attributes::Alias].isEmpty()) + attributes[Attributes::Alias]=this->getAlias(); - if(attributes[ParsersAttributes::SQL_OBJECT].isEmpty()) - attributes[ParsersAttributes::SQL_OBJECT]=objs_sql[this->obj_type]; + if(attributes[Attributes::Signature].isEmpty()) + attributes[Attributes::Signature]=this->getSignature(format_name); + + if(attributes[Attributes::SqlObject].isEmpty()) + attributes[Attributes::SqlObject]=objs_sql[enum_cast(this->obj_type)]; } QString BaseObject::__getCodeDefinition(unsigned def_type) @@ -669,135 +704,135 @@ QString BaseObject::getCodeDefinition(unsigned def_type, bool reduced_form) { QString code_def; - if((def_type==SchemaParser::SQL_DEFINITION && - obj_type!=BASE_OBJECT && obj_type!=BASE_RELATIONSHIP && - obj_type!=BASE_TABLE && obj_type!=OBJ_TEXTBOX) || + if((def_type==SchemaParser::SqlDefinition && + obj_type!=ObjectType::BaseObject && obj_type!=ObjectType::BaseRelationship && + obj_type!=ObjectType::BaseTable && obj_type!=ObjectType::Textbox) || - (def_type==SchemaParser::XML_DEFINITION && - obj_type!=BASE_OBJECT && obj_type!=BASE_TABLE)) + (def_type==SchemaParser::XmlDefinition && + obj_type!=ObjectType::BaseObject && obj_type!=ObjectType::BaseTable)) { bool format=false; schparser.setPgSQLVersion(BaseObject::pgsql_ver); - attributes[ParsersAttributes::SQL_DISABLED]=(sql_disabled ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::SqlDisabled]=(sql_disabled ? Attributes::True : QString()); //Formats the object's name in case the SQL definition is being generated - format=((def_type==SchemaParser::SQL_DEFINITION) || - (def_type==SchemaParser::XML_DEFINITION && reduced_form && - obj_type!=OBJ_TEXTBOX && obj_type!=OBJ_RELATIONSHIP)); + format=((def_type==SchemaParser::SqlDefinition) || + (def_type==SchemaParser::XmlDefinition && reduced_form && + obj_type!=ObjectType::Textbox && obj_type!=ObjectType::Relationship)); setBasicAttributes(format); if(schema) { - if(def_type==SchemaParser::XML_DEFINITION) - attributes[ParsersAttributes::SCHEMA]=schema->getCodeDefinition(def_type, true); + if(def_type==SchemaParser::XmlDefinition) + attributes[Attributes::Schema]=schema->getCodeDefinition(def_type, true); else - attributes[ParsersAttributes::SCHEMA]=schema->getName(format); + attributes[Attributes::Schema]=schema->getName(format); } - if(def_type==SchemaParser::XML_DEFINITION) - attributes[ParsersAttributes::PROTECTED]=(is_protected ? ParsersAttributes::_TRUE_ : QString()); + if(def_type==SchemaParser::XmlDefinition) + attributes[Attributes::Protected]=(is_protected ? Attributes::True : QString()); if(tablespace) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::TABLESPACE]=tablespace->getName(format); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Tablespace]=tablespace->getName(format); else - attributes[ParsersAttributes::TABLESPACE]=tablespace->getCodeDefinition(def_type, true); + attributes[Attributes::Tablespace]=tablespace->getCodeDefinition(def_type, true); } - if(collation && attributes[ParsersAttributes::COLLATION].isEmpty()) + if(collation && attributes[Attributes::Collation].isEmpty()) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::COLLATION]=collation->getName(format); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Collation]=collation->getName(format); else - attributes[ParsersAttributes::COLLATION]=collation->getCodeDefinition(def_type, true); + attributes[Attributes::Collation]=collation->getCodeDefinition(def_type, true); } if(owner) { - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) { - attributes[ParsersAttributes::OWNER]=owner->getName(format); + attributes[Attributes::Owner]=owner->getName(format); - /** Only tablespaces and database do not have an ALTER OWNER SET + /* Only tablespaces, database and user mapping do not have an ALTER OWNER SET because the rule says that PostgreSQL tablespaces and database should be created - with just a command line isolated from the others **/ - if(obj_type!=OBJ_TABLESPACE && obj_type!=OBJ_DATABASE) + with just a command line isolated from the others */ + if(obj_type!=ObjectType::Tablespace && obj_type!=ObjectType::Database && obj_type!=ObjectType::UserMapping) { SchemaParser sch_parser; - QString filename=GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::ALTER_SCHEMA_DIR + GlobalAttributes::DIR_SEPARATOR + - ParsersAttributes::OWNER + GlobalAttributes::SCHEMA_EXT; + QString filename=GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + GlobalAttributes::AlterSchemaDir + GlobalAttributes::DirSeparator + + Attributes::Owner + GlobalAttributes::SchemaExt; sch_parser.ignoreUnkownAttributes(true); - attributes[ParsersAttributes::OWNER]=sch_parser.getCodeDefinition(filename, attributes); + attributes[Attributes::Owner]=sch_parser.getCodeDefinition(filename, attributes); } } else - attributes[ParsersAttributes::OWNER]=owner->getCodeDefinition(def_type, true); + attributes[Attributes::Owner]=owner->getCodeDefinition(def_type, true); } if(!comment.isEmpty()) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::COMMENT]=QString(comment).replace(QString("'"), QString("''")); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Comment]=QString(comment).replace(QString("'"), QString("''")); else - attributes[ParsersAttributes::COMMENT]=comment; + attributes[Attributes::Comment]=comment; schparser.ignoreUnkownAttributes(true); - attributes[ParsersAttributes::COMMENT]= - schparser.getCodeDefinition(ParsersAttributes::COMMENT, attributes, def_type); + attributes[Attributes::Comment]= + schparser.getCodeDefinition(Attributes::Comment, attributes, def_type); } if(!appended_sql.isEmpty()) { - attributes[ParsersAttributes::APPENDED_SQL]=appended_sql; + attributes[Attributes::AppendedSql]=appended_sql; - if(def_type==SchemaParser::XML_DEFINITION) + if(def_type==SchemaParser::XmlDefinition) { schparser.ignoreUnkownAttributes(true); - attributes[ParsersAttributes::APPENDED_SQL]= - schparser.getCodeDefinition(QString(ParsersAttributes::APPENDED_SQL).remove('-'), attributes, def_type); + attributes[Attributes::AppendedSql]= + schparser.getCodeDefinition(QString(Attributes::AppendedSql).remove('-'), attributes, def_type); } else { - attributes[ParsersAttributes::APPENDED_SQL]=QString("\n-- Appended SQL commands --\n") + appended_sql; + attributes[Attributes::AppendedSql]=QString("\n-- Appended SQL commands --\n") + appended_sql; } } if(!prepended_sql.isEmpty()) { - attributes[ParsersAttributes::PREPENDED_SQL]=prepended_sql; + attributes[Attributes::PrependedSql]=prepended_sql; - if(def_type==SchemaParser::XML_DEFINITION) + if(def_type==SchemaParser::XmlDefinition) { schparser.ignoreUnkownAttributes(true); - attributes[ParsersAttributes::PREPENDED_SQL]= - schparser.getCodeDefinition(QString(ParsersAttributes::PREPENDED_SQL).remove('-'), attributes, def_type); + attributes[Attributes::PrependedSql]= + schparser.getCodeDefinition(QString(Attributes::PrependedSql).remove('-'), attributes, def_type); } else { - attributes[ParsersAttributes::PREPENDED_SQL]=QString("\n-- Prepended SQL commands --\n") + prepended_sql; + attributes[Attributes::PrependedSql]=QString("\n-- Prepended SQL commands --\n") + prepended_sql; } } - if(def_type==SchemaParser::SQL_DEFINITION && this->acceptsDropCommand()) + if(def_type==SchemaParser::SqlDefinition && this->acceptsDropCommand()) { - attributes[ParsersAttributes::DROP]=getDropDefinition(true); - attributes[ParsersAttributes::DROP].remove(ParsersAttributes::DDL_END_TOKEN + '\n'); + attributes[Attributes::Drop]=getDropDefinition(true); + attributes[Attributes::Drop].remove(Attributes::DdlEndToken + '\n'); } - attributes[ParsersAttributes::REDUCED_FORM]=(reduced_form ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::ReducedForm]=(reduced_form ? Attributes::True : QString()); try { - code_def+=schparser.getCodeDefinition(objs_schemas[obj_type], attributes, def_type); + code_def+=schparser.getCodeDefinition(objs_schemas[enum_cast(obj_type)], attributes, def_type); //Internally disabling the SQL definition - if(sql_disabled && def_type==SchemaParser::SQL_DEFINITION) + if(sql_disabled && def_type==SchemaParser::SqlDefinition) { //Creates a text stream and insert an comment start token on each line QTextStream ts(&code_def); @@ -813,10 +848,10 @@ QString BaseObject::getCodeDefinition(unsigned def_type, bool reduced_form) clearAttributes(); //Database object doesn't handles cached code. - if(use_cached_code && obj_type!=OBJ_DATABASE) + if(use_cached_code && obj_type!=ObjectType::Database) { - if(def_type==SchemaParser::SQL_DEFINITION || - (!reduced_form && def_type==SchemaParser::XML_DEFINITION)) + if(def_type==SchemaParser::SqlDefinition || + (!reduced_form && def_type==SchemaParser::XmlDefinition)) cached_code[def_type]=code_def; else if(reduced_form) cached_reduced_code=code_def; @@ -829,13 +864,13 @@ QString BaseObject::getCodeDefinition(unsigned def_type, bool reduced_form) schparser.restartParser(); clearAttributes(); - if(e.getErrorType()==ERR_UNDEF_ATTRIB_VALUE) - throw Exception(Exception::getErrorMessage(ERR_ASG_OBJ_INV_DEFINITION) + if(e.getErrorCode()==ErrorCode::UndefinedAttributeValue) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgObjectInvalidDefinition) .arg(this->getName(true)) .arg(this->getTypeName()), - ERR_ASG_OBJ_INV_DEFINITION,__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + ErrorCode::AsgObjectInvalidDefinition,__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -865,26 +900,26 @@ void BaseObject::swapObjectsIds(BaseObject *obj1, BaseObject *obj2, bool enable_ { //Raises an error if some of the objects aren't allocated if(!obj1 || !obj2) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the involved objects are the same else if(obj1==obj2) - throw Exception(ERR_INV_ID_SWAP_SAME_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InvIdSwapSameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the some of the objects are system objects else if(obj1->isSystemObject()) - throw Exception(Exception::getErrorMessage(ERR_OPR_RESERVED_OBJECT) + throw Exception(Exception::getErrorMessage(ErrorCode::OprReservedObject) .arg(obj1->getName()) .arg(obj1->getTypeName()), - ERR_OPR_RESERVED_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::OprReservedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(obj2->isSystemObject()) - throw Exception(Exception::getErrorMessage(ERR_OPR_RESERVED_OBJECT) + throw Exception(Exception::getErrorMessage(ErrorCode::OprReservedObject) .arg(obj2->getName()) .arg(obj2->getTypeName()), - ERR_OPR_RESERVED_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::OprReservedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the object is object is cluster level and the swap of these types isn't enabled else if(!enable_cl_obj_swap && - (obj1->getObjectType()==OBJ_DATABASE || obj1->getObjectType()==OBJ_TABLESPACE || obj1->getObjectType()==OBJ_ROLE || - obj2->getObjectType()==OBJ_DATABASE || obj2->getObjectType()==OBJ_TABLESPACE || obj2->getObjectType()==OBJ_ROLE)) - throw Exception(ERR_INV_ID_SWAP_INV_OBJ_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + (obj1->getObjectType()==ObjectType::Database || obj1->getObjectType()==ObjectType::Tablespace || obj1->getObjectType()==ObjectType::Role || + obj2->getObjectType()==ObjectType::Database || obj2->getObjectType()==ObjectType::Tablespace || obj2->getObjectType()==ObjectType::Role)) + throw Exception(ErrorCode::InvIdSwapInvalidObjectType,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { unsigned id_bkp=obj1->object_id; @@ -897,34 +932,34 @@ void BaseObject::updateObjectId(BaseObject *obj) { //Raises an error if some of the objects aren't allocated if(!obj) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(obj->isSystemObject()) - throw Exception(Exception::getErrorMessage(ERR_OPR_RESERVED_OBJECT) + throw Exception(Exception::getErrorMessage(ErrorCode::OprReservedObject) .arg(obj->getName()) .arg(obj->getTypeName()), - ERR_OPR_RESERVED_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::OprReservedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else obj->object_id=++global_id; } vector BaseObject::getObjectTypes(bool inc_table_objs, vector exclude_types) { - vector vet_types={ BASE_RELATIONSHIP, OBJ_AGGREGATE, OBJ_CAST, OBJ_COLLATION, - OBJ_CONVERSION, OBJ_DATABASE, OBJ_DOMAIN, OBJ_EXTENSION, OBJ_EVENT_TRIGGER, - OBJ_TAG, OBJ_FUNCTION, OBJ_LANGUAGE, OBJ_OPCLASS, OBJ_OPERATOR, - OBJ_OPFAMILY, OBJ_RELATIONSHIP, OBJ_ROLE, OBJ_SCHEMA, - OBJ_SEQUENCE, OBJ_TABLE, OBJ_TABLESPACE, OBJ_TEXTBOX, - OBJ_TYPE, OBJ_VIEW, OBJ_PERMISSION, OBJ_GENERIC_SQL }; + vector vet_types={ ObjectType::BaseRelationship, ObjectType::Aggregate, ObjectType::Cast, ObjectType::Collation, + ObjectType::Conversion, ObjectType::Database, ObjectType::Domain, ObjectType::Extension, ObjectType::EventTrigger, + ObjectType::ForeignDataWrapper, ObjectType::ForeignServer, ObjectType::Function, ObjectType::GenericSql, ObjectType::Language, ObjectType::OpClass, + ObjectType::Operator, ObjectType::OpFamily, ObjectType::Permission, ObjectType::Relationship, ObjectType::Role, ObjectType::Schema, + ObjectType::Sequence, ObjectType::Table, ObjectType::Tablespace, ObjectType::Tag, ObjectType::Textbox, + ObjectType::Type, ObjectType::UserMapping, ObjectType::View }; vector::iterator itr; if(inc_table_objs) { - vet_types.push_back(OBJ_COLUMN); - vet_types.push_back(OBJ_CONSTRAINT); - vet_types.push_back(OBJ_TRIGGER); - vet_types.push_back(OBJ_RULE); - vet_types.push_back(OBJ_INDEX); - vet_types.push_back(OBJ_POLICY); + vet_types.push_back(ObjectType::Column); + vet_types.push_back(ObjectType::Constraint); + vet_types.push_back(ObjectType::Trigger); + vet_types.push_back(ObjectType::Rule); + vet_types.push_back(ObjectType::Index); + vet_types.push_back(ObjectType::Policy); } for(ObjectType type : exclude_types) @@ -939,17 +974,26 @@ vector BaseObject::getObjectTypes(bool inc_table_objs, vector BaseObject::getChildObjectTypes(ObjectType obj_type) { - if(obj_type==OBJ_DATABASE) - return(vector()={OBJ_CAST, OBJ_ROLE, OBJ_LANGUAGE, OBJ_TABLESPACE, OBJ_SCHEMA, OBJ_EXTENSION, OBJ_EVENT_TRIGGER}); - else if(obj_type==OBJ_SCHEMA) - return(vector()={OBJ_AGGREGATE, OBJ_CONVERSION, OBJ_COLLATION, OBJ_DOMAIN, OBJ_FUNCTION, - OBJ_OPCLASS, OBJ_OPERATOR, OBJ_OPFAMILY, OBJ_SEQUENCE, OBJ_TYPE, OBJ_TABLE, OBJ_VIEW}); - else if(obj_type==OBJ_TABLE) - return(vector()={OBJ_COLUMN, OBJ_CONSTRAINT, OBJ_RULE, OBJ_TRIGGER, OBJ_INDEX, OBJ_POLICY}); - else if(obj_type==OBJ_VIEW) - return(vector()={OBJ_RULE, OBJ_TRIGGER, OBJ_INDEX}); - else - return(vector()={}); + if(obj_type==ObjectType::Database) + return(vector()={ ObjectType::Cast, ObjectType::Role, ObjectType::Language, + ObjectType::Tablespace, ObjectType::Schema, ObjectType::Extension, + ObjectType::EventTrigger, ObjectType::ForeignDataWrapper, ObjectType::ForeignServer, + ObjectType::UserMapping }); + + if(obj_type==ObjectType::Schema) + return(vector()={ ObjectType::Aggregate, ObjectType::Conversion, ObjectType::Collation, + ObjectType::Domain, ObjectType::Function, ObjectType::OpClass, + ObjectType::Operator, ObjectType::OpFamily, ObjectType::Sequence, + ObjectType::Type, ObjectType::Table, ObjectType::View }); + + if(obj_type==ObjectType::Table) + return(vector()={ ObjectType::Column, ObjectType::Constraint, ObjectType::Rule, + ObjectType::Trigger, ObjectType::Index, ObjectType::Policy }); + + if(obj_type==ObjectType::View) + return(vector()={ObjectType::Rule, ObjectType::Trigger, ObjectType::Index}); + + return(vector()={}); } void BaseObject::setPgSQLVersion(const QString &ver) @@ -962,6 +1006,11 @@ QString BaseObject::getPgSQLVersion(void) return(pgsql_ver); } +attribs_map BaseObject::getSearchAttributes(void) +{ + return(search_attribs); +} + void BaseObject::enableCachedCode(bool value) { use_cached_code=value; @@ -975,6 +1024,7 @@ void BaseObject::operator = (BaseObject &obj) this->database=obj.database; this->comment=obj.comment; this->obj_name=obj.obj_name; + this->alias=obj.alias; this->obj_type=obj.obj_type; this->is_protected=obj.is_protected; this->sql_disabled=obj.sql_disabled; @@ -997,6 +1047,16 @@ void BaseObject::setCodeInvalidated(bool value) } } +void BaseObject::configureSearchAttributes(void) +{ + search_attribs[Attributes::Name] = this->getName(false); + search_attribs[Attributes::Signature] = this->getSignature(false); + search_attribs[Attributes::Schema] = schema ? schema->getName(false) : QString(); + search_attribs[Attributes::Tablespace] = tablespace ? tablespace->getName(false) : QString(); + search_attribs[Attributes::Owner] = owner ? owner->getName(false) : QString(); + search_attribs[Attributes::Comment] = comment; +} + bool BaseObject::isCodeInvalidated(void) { return(use_cached_code && code_invalidated); @@ -1047,32 +1107,32 @@ bool BaseObject::isCodeDiffersFrom(const QString &xml_def1, const QString &xml_d bool BaseObject::isCodeDiffersFrom(BaseObject *object, const vector &ignored_attribs, const vector &ignored_tags) { if(!object) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(object->getObjectType()!=this->getObjectType()) - throw Exception(ERR_OPR_OBJ_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { - return(BaseObject::isCodeDiffersFrom(this->getCodeDefinition(SchemaParser::XML_DEFINITION), - object->getCodeDefinition(SchemaParser::XML_DEFINITION), + return(BaseObject::isCodeDiffersFrom(this->getCodeDefinition(SchemaParser::XmlDefinition), + object->getCodeDefinition(SchemaParser::XmlDefinition), ignored_attribs, ignored_tags)); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } QString BaseObject::getCachedCode(unsigned def_type, bool reduced_form) { - if(use_cached_code && def_type==SchemaParser::SQL_DEFINITION && schparser.getPgSQLVersion()!=BaseObject::pgsql_ver) + if(use_cached_code && def_type==SchemaParser::SqlDefinition && schparser.getPgSQLVersion()!=BaseObject::pgsql_ver) code_invalidated=true; if(!code_invalidated && ((!reduced_form && !cached_code[def_type].isEmpty()) || - (def_type==SchemaParser::XML_DEFINITION && reduced_form && !cached_reduced_code.isEmpty()))) + (def_type==SchemaParser::XmlDefinition && reduced_form && !cached_reduced_code.isEmpty()))) { - if(def_type==SchemaParser::XML_DEFINITION && reduced_form) + if(def_type==SchemaParser::XmlDefinition && reduced_form) return(cached_reduced_code); else return(cached_code[def_type]); @@ -1099,18 +1159,18 @@ QString BaseObject::getDropDefinition(bool cascade) /* Creating an attribute that identifies the object type in order to permit conditional code generation inside the DROP script */ if(attribs.count(this->getSchemaName())==0) - attribs[this->getSchemaName()]=ParsersAttributes::_TRUE_; + attribs[this->getSchemaName()]=Attributes::True; - attribs[ParsersAttributes::CASCADE]=(cascade ? ParsersAttributes::_TRUE_ : QString()); + attribs[Attributes::Cascade]=(cascade ? Attributes::True : QString()); - return(schparser.getCodeDefinition(ParsersAttributes::DROP, attribs, SchemaParser::SQL_DEFINITION)); + return(schparser.getCodeDefinition(Attributes::Drop, attribs, SchemaParser::SqlDefinition)); } else return(QString()); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -1119,9 +1179,9 @@ QString BaseObject::getAlterDefinition(QString sch_name, attribs_map &attribs, b try { SchemaParser schparser; - QString alter_sch_dir=GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::ALTER_SCHEMA_DIR + GlobalAttributes::DIR_SEPARATOR + - QString("%1") + GlobalAttributes::SCHEMA_EXT; + QString alter_sch_dir=GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + GlobalAttributes::AlterSchemaDir + GlobalAttributes::DirSeparator + + QString("%1") + GlobalAttributes::SchemaExt; schparser.setPgSQLVersion(BaseObject::pgsql_ver); schparser.ignoreEmptyAttributes(ignore_empty_attribs); @@ -1130,7 +1190,7 @@ QString BaseObject::getAlterDefinition(QString sch_name, attribs_map &attribs, b } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1138,12 +1198,12 @@ void BaseObject::copyAttributes(attribs_map &attribs) { if(!attribs.empty()) { - attributes[ParsersAttributes::HAS_CHANGES]=ParsersAttributes::_TRUE_; + attributes[Attributes::HasChanges]=Attributes::True; for(auto &itr : attribs) attributes[itr.first]=itr.second; } else - attributes[ParsersAttributes::HAS_CHANGES]=QString(); + attributes[Attributes::HasChanges]=QString(); } QString BaseObject::getAlterDefinition(BaseObject *object) @@ -1154,28 +1214,28 @@ QString BaseObject::getAlterDefinition(BaseObject *object) QString BaseObject::getAlterDefinition(BaseObject *object, bool ignore_name_diff) { if(!object) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); QString alter; if(object->obj_type!=this->obj_type) - throw Exception(ERR_OPR_OBJ_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); setBasicAttributes(true); try { - QStringList attribs={ ParsersAttributes::OWNER, ParsersAttributes::SCHEMA, ParsersAttributes::TABLESPACE }; + QStringList attribs={ Attributes::Owner, Attributes::Schema, Attributes::Tablespace }; bool accepts_obj[3]={ acceptsOwner(), acceptsSchema(), acceptsTablespace() }; BaseObject *dep_objs[3]={ this->getOwner(), this->getSchema(), this->getTablespace() }, *aux_dep_objs[3]={ object->getOwner(), object->getSchema(), object->getTablespace() }; if(!ignore_name_diff && this->getName()!=object->getName()) { - attributes[ParsersAttributes::NEW_NAME]=object->getName(true, false); - alter+=BaseObject::getAlterDefinition(ParsersAttributes::RENAME, attributes, true); - attributes[ParsersAttributes::NAME]=attributes[ParsersAttributes::NEW_NAME]; - attributes[ParsersAttributes::SIGNATURE]=object->getSignature(true); + attributes[Attributes::NewName]=object->getName(true, false); + alter+=BaseObject::getAlterDefinition(Attributes::Rename, attributes, true); + attributes[Attributes::Name]=attributes[Attributes::NewName]; + attributes[Attributes::Signature]=object->getSignature(true); } for(unsigned i=0; i < 3; i++) @@ -1188,22 +1248,36 @@ QString BaseObject::getAlterDefinition(BaseObject *object, bool ignore_name_diff } } + alter += getAlterCommentDefinition(object, attributes); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + } + + return(alter); +} + +QString BaseObject::getAlterCommentDefinition(BaseObject *object, attribs_map attributes) +{ + try + { if(this->getComment()!=object->getComment()) { if(object->getComment().isEmpty()) - attributes[ParsersAttributes::COMMENT]=ParsersAttributes::UNSET; + attributes[Attributes::Comment]=Attributes::Unset; else - attributes[ParsersAttributes::COMMENT]=object->getComment(); + attributes[Attributes::Comment]=object->getComment(); schparser.ignoreUnkownAttributes(true); schparser.ignoreEmptyAttributes(true); - alter+=schparser.getCodeDefinition(ParsersAttributes::COMMENT, attributes, SchemaParser::SQL_DEFINITION); + return(schparser.getCodeDefinition(Attributes::Comment, attributes, SchemaParser::SqlDefinition)); } + + return(QString()); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } - - return(alter); } diff --git a/libpgmodeler/src/baseobject.h b/libpgmodeler/src/baseobject.h index 910fcde30e..54869aa534 100644 --- a/libpgmodeler/src/baseobject.h +++ b/libpgmodeler/src/baseobject.h @@ -1,6 +1,6 @@ /* # PostgreSQL Database Modeler (pgModeler) -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -25,7 +25,7 @@ #ifndef BASE_OBJECT_H #define BASE_OBJECT_H -#include "parsersattributes.h" +#include "attributes.h" #include "exception.h" #include "pgsqltypes.h" #include "schemaparser.h" @@ -34,44 +34,48 @@ #include #include #include - -enum ObjectType { - OBJ_COLUMN, - OBJ_CONSTRAINT, - OBJ_FUNCTION, - OBJ_TRIGGER, - OBJ_INDEX, - OBJ_RULE, - OBJ_TABLE, - OBJ_VIEW, - OBJ_DOMAIN, - OBJ_SCHEMA, - OBJ_AGGREGATE, - OBJ_OPERATOR, - OBJ_SEQUENCE, - OBJ_ROLE, - OBJ_CONVERSION, - OBJ_CAST, - OBJ_LANGUAGE, - OBJ_TYPE, - OBJ_TABLESPACE, - OBJ_OPFAMILY, - OBJ_OPCLASS, - OBJ_DATABASE, - OBJ_COLLATION, - OBJ_EXTENSION, - OBJ_EVENT_TRIGGER, - OBJ_POLICY, - OBJ_RELATIONSHIP, - OBJ_TEXTBOX, - OBJ_PERMISSION, - OBJ_PARAMETER, - OBJ_TYPE_ATTRIBUTE, - OBJ_TAG, - OBJ_GENERIC_SQL, - BASE_RELATIONSHIP, - BASE_OBJECT, - BASE_TABLE +#include + +enum class ObjectType: unsigned { + Column, + Constraint, + Function, + Trigger, + Index, + Rule, + Table, + View, + Domain, + Schema, + Aggregate, + Operator, + Sequence, + Role, + Conversion, + Cast, + Language, + Type, + Tablespace, + OpFamily, + OpClass, + Database, + Collation, + Extension, + EventTrigger, + Policy, + ForeignDataWrapper, + ForeignServer, + UserMapping, + Relationship, + Textbox, + Permission, + Parameter, + TypeAttribute, + Tag, + GenericSql, + BaseRelationship, + BaseObject, + BaseTable }; class BaseObject { @@ -82,12 +86,12 @@ class BaseObject { //! \brief Indicates the the cached code enabled static bool use_cached_code; - //! \brief Stores the database wich the object belongs - BaseObject *database; - //! \brief Stores the set of special (valid) chars that forces the object's name quoting static const QByteArray special_chars; + //! \brief Stores the database wich the object belongs + BaseObject *database; + protected: SchemaParser schparser; @@ -105,7 +109,7 @@ class BaseObject { unsigned object_id; //! \brief Objects type count declared on enum ObjectType - static const int OBJECT_TYPE_COUNT=37; + static constexpr unsigned ObjectTypeCount=enum_cast(ObjectType::BaseTable) + 1; /*! \brief Indicates whether the object is protected or not. A protected object indicates that it can not suffer changes in position @@ -131,20 +135,21 @@ class BaseObject { //! \brief Stores the cached xml and sql code QString cached_code[2], + //! \brief Stores the xml code in reduced form cached_reduced_code; /*! \brief This map stores the name of each object type associated to a schema file that generates the object's code definition */ - static QString objs_schemas[OBJECT_TYPE_COUNT]; + static const QString objs_schemas[ObjectTypeCount]; /*! \brief This map associates the object type to a keyword on SQL language that represents the object */ - static QString objs_sql[OBJECT_TYPE_COUNT]; + static const QString objs_sql[ObjectTypeCount]; /*! \brief Stores the name of the type of objects to be used in error messages formatting and others operations that envolves object type name */ - static QString obj_type_names[OBJECT_TYPE_COUNT]; + static const QString obj_type_names[ObjectTypeCount]; /*! \brief Role that is owner of the object. Some objects cannot be associated to a role so if one is assigned to the object an error will be raised */ @@ -164,22 +169,29 @@ class BaseObject { //! \brief Comments related to object QString comment, + //! \brief Object's name (in PostgreSQL accepted format) obj_name, + //! \brief Object's alias (human readable / friendly) name + alias, + //! \brief The set of SQL commands appended on the objectc's definition appended_sql, //! \brief The set of SQL commands prepended on the objectc's definition prepended_sql; - /*! \brief Stores the attributes and their values ​​shaped in strings to be used by SchemaParser on the object's code definition creation. The attribute name related to model objects are defined in ParsersAttributes namespace. */ - attribs_map attributes; + attribs_map attributes, + + /*! \brief Stores the attributes and their vales which can be used by the + * searching mechanism to match patters */ + search_attribs; - /*! \brief Type of object, may have one of the values ​​of the enum ObjectType OBJ_* + /*! \brief Type of object, may have one of the values ​​of the enum ObjectType It was used a numeric type to avoid the use excessive of RTTI. */ ObjectType obj_type; @@ -224,9 +236,16 @@ class BaseObject { static QString getAlterDefinition(QString sch_name, attribs_map &attribs, bool ignore_ukn_attribs=false, bool ignore_empty_attribs=false); + QString getAlterCommentDefinition(BaseObject *object, attribs_map attributes); + public: //! \brief Maximum number of characters that an object name on PostgreSQL can have - static const int OBJECT_NAME_MAX_LENGTH=63; + static constexpr int ObjectNameMaxLength=63; + + /*! \brief The default number of objects supposed to be stored in objects list. + * This values is just a reference (hint) and is used to preallocate (reserve) space on vectors which handle objects + * to avoid excessive allocation/deallocation by resizing the vectors due to insert operation */ + static constexpr unsigned DefMaxObjectCount=20; BaseObject(void); BaseObject(bool system_obj); @@ -277,6 +296,11 @@ class BaseObject { //! \brief Defines the objects name. If the passed name isn't valid it'll raise an error virtual void setName(const QString &name); + /*! \brief Defines the object's alias (human readable / friendly name). An alias is used when the database model is being + * displayed in compact view. This method raises an error when the provided name is larger than 63 bytes + * (the same rule for PostgreSQL names length) */ + virtual void setAlias(const QString &alias); + //! \brief Toggles the object's modify protection virtual void setProtected(bool value); @@ -319,6 +343,9 @@ class BaseObject { the parameter 'prepend_schema' includes the schema name on the objects name (defult) */ virtual QString getName(bool format=false, bool prepend_schema=true); + //! \brief Returns the object's alias (user friendly) name + virtual QString getAlias(void); + //! \brief Returns the name of the object with schema name (when available) prepended by default virtual QString getSignature(bool format=true); @@ -407,6 +434,9 @@ class BaseObject { //! \brief Returns if the specified type accepts the use of DROP commands static bool acceptsDropCommand(ObjectType obj_type); + //! \brief Returns if the specified type accepts an alias (friendly name) + static bool acceptsAlias(ObjectType obj_type); + //! \brief Returns if the object accepts to have a schema assigned bool acceptsSchema(void); @@ -435,6 +465,8 @@ class BaseObject { This method has no effect when the cached code support is disables. See enableCachedCode() */ virtual void setCodeInvalidated(bool value); + virtual void configureSearchAttributes(void); + //! \brief Returns if the code (sql and xml) is invalidated bool isCodeInvalidated(void); @@ -448,7 +480,7 @@ class BaseObject { static void enableCachedCode(bool value); /*! \brief Returns the valid object types in a vector. The types - BASE_OBJECT, TYPE_ATTRIBUTE and BASE_TABLE aren't included in return vector. + ObjectType::ObjBaseObject, TYPE_ATTRIBUTE and ObjectType::ObjBaseTable aren't included in return vector. By default table objects (columns, trigger, constraints, etc) are included. To avoid the insertion of these types set the boolean param to false. */ static vector getObjectTypes(bool inc_table_objs=true, vector exclude_types={}); @@ -456,7 +488,7 @@ class BaseObject { /*! \brief Returns the valid object types that are child or grouped under the specified type. This method works a litte different from getObjectTypes() since this latter returns all valid types and this one returns only the valid types for the current specified type. For now the only accepted - types are OBJ_DATABASE, OBJ_SCHEMA and OBJ_TABLE */ + types are ObjectType::Database, ObjectType::Schema and ObjectType::Table */ static vector getChildObjectTypes(ObjectType obj_type); /*! \brief Sets the default version when generating the SQL code. This affects all instances of classes that @@ -466,6 +498,9 @@ class BaseObject { //! \brief Returns the current version for SQL code generation static QString getPgSQLVersion(void); + //! \brief Returns the set of attributes used by the search mechanism + attribs_map getSearchAttributes(void); + friend class DatabaseModel; friend class ModelValidationHelper; friend class DatabaseImportHelper; diff --git a/libpgmodeler/src/baserelationship.cpp b/libpgmodeler/src/baserelationship.cpp index 45d88161f0..72177f57eb 100644 --- a/libpgmodeler/src/baserelationship.cpp +++ b/libpgmodeler/src/baserelationship.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -22,7 +22,7 @@ BaseRelationship::BaseRelationship(BaseRelationship *rel) { if(!rel) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); for(unsigned i=0; i < 3; i++) lables[i]=nullptr; @@ -54,7 +54,7 @@ BaseRelationship::BaseRelationship(unsigned rel_type, BaseTable *src_tab, BaseTa for(unsigned i=0; i < 3; i++) { lables[i]=nullptr; - lables_dist[i]=QPointF(NAN, NAN); + lables_dist[i]=QPointF(DNaN, DNaN); } configureRelationship(); @@ -62,96 +62,99 @@ BaseRelationship::BaseRelationship(unsigned rel_type, BaseTable *src_tab, BaseTa str_aux=QApplication::translate("BaseRelationship","rel_%1_%2","") .arg(src_tab->getName()).arg(dst_tab->getName()); - if(str_aux.size() > BaseObject::OBJECT_NAME_MAX_LENGTH) - str_aux.resize(BaseObject::OBJECT_NAME_MAX_LENGTH); + if(str_aux.size() > BaseObject::ObjectNameMaxLength) + str_aux.resize(BaseObject::ObjectNameMaxLength); setName(str_aux); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void BaseRelationship::configureRelationship(void) { - obj_type=BASE_RELATIONSHIP; - - attributes[ParsersAttributes::TYPE]=QString(); - attributes[ParsersAttributes::SRC_REQUIRED]=QString(); - attributes[ParsersAttributes::DST_REQUIRED]=QString(); - attributes[ParsersAttributes::SRC_TABLE]=QString(); - attributes[ParsersAttributes::DST_TABLE]=QString(); - attributes[ParsersAttributes::POINTS]=QString(); - attributes[ParsersAttributes::COLUMNS]=QString(); - attributes[ParsersAttributes::CONSTRAINTS]=QString(); - attributes[ParsersAttributes::ELEMENTS]=QString(); - attributes[ParsersAttributes::IDENTIFIER]=QString(); - attributes[ParsersAttributes::REDUCED_FORM]=QString(); - attributes[ParsersAttributes::DEFERRABLE]=QString(); - attributes[ParsersAttributes::DEFER_TYPE]=QString(); - attributes[ParsersAttributes::TABLE_NAME]=QString(); - attributes[ParsersAttributes::SPECIAL_PK_COLS]=QString(); - attributes[ParsersAttributes::RELATIONSHIP_NN]=QString(); - attributes[ParsersAttributes::RELATIONSHIP_GEN]=QString(); - attributes[ParsersAttributes::RELATIONSHIP_DEP]=QString(); - attributes[ParsersAttributes::RELATIONSHIP_1N]=QString(); - attributes[ParsersAttributes::RELATIONSHIP_11]=QString(); - attributes[ParsersAttributes::CONSTRAINTS]=QString(); - attributes[ParsersAttributes::TABLE]=QString(); - attributes[ParsersAttributes::ANCESTOR_TABLE]=QString(); - attributes[ParsersAttributes::COPY_OPTIONS]=QString(); - attributes[ParsersAttributes::COPY_MODE]=QString(); - attributes[ParsersAttributes::SRC_COL_PATTERN]=QString(); - attributes[ParsersAttributes::DST_COL_PATTERN]=QString(); - attributes[ParsersAttributes::PK_PATTERN]=QString(); - attributes[ParsersAttributes::UQ_PATTERN]=QString(); - attributes[ParsersAttributes::SRC_FK_PATTERN]=QString(); - attributes[ParsersAttributes::DST_FK_PATTERN]=QString(); - attributes[ParsersAttributes::PK_COL_PATTERN]=QString(); - attributes[ParsersAttributes::SINGLE_PK_COLUMN]=QString(); - attributes[ParsersAttributes::UPD_ACTION]=QString(); - attributes[ParsersAttributes::DEL_ACTION]=QString(); - attributes[ParsersAttributes::CUSTOM_COLOR]=QString(); - attributes[ParsersAttributes::REFERENCE_FK]=QString(); + obj_type=ObjectType::BaseRelationship; + + attributes[Attributes::Type]=QString(); + attributes[Attributes::SrcRequired]=QString(); + attributes[Attributes::DstRequired]=QString(); + attributes[Attributes::SrcTable]=QString(); + attributes[Attributes::DstTable]=QString(); + attributes[Attributes::Points]=QString(); + attributes[Attributes::Columns]=QString(); + attributes[Attributes::Constraints]=QString(); + attributes[Attributes::Elements]=QString(); + attributes[Attributes::Identifier]=QString(); + attributes[Attributes::ReducedForm]=QString(); + attributes[Attributes::Deferrable]=QString(); + attributes[Attributes::DeferType]=QString(); + attributes[Attributes::TableName]=QString(); + attributes[Attributes::SpecialPkCols]=QString(); + attributes[Attributes::RelationshipNn]=QString(); + attributes[Attributes::RelationshipGen]=QString(); + attributes[Attributes::RelationshipDep]=QString(); + attributes[Attributes::RelationshipPart]=QString(); + attributes[Attributes::Relationship1n]=QString(); + attributes[Attributes::Relationship11]=QString(); + attributes[Attributes::Constraints]=QString(); + attributes[Attributes::Table]=QString(); + attributes[Attributes::AncestorTable]=QString(); + attributes[Attributes::CopyOptions]=QString(); + attributes[Attributes::CopyMode]=QString(); + attributes[Attributes::SrcColPattern]=QString(); + attributes[Attributes::DstColPattern]=QString(); + attributes[Attributes::PkPattern]=QString(); + attributes[Attributes::UqPattern]=QString(); + attributes[Attributes::SrcFkPattern]=QString(); + attributes[Attributes::DstFkPattern]=QString(); + attributes[Attributes::PkColPattern]=QString(); + attributes[Attributes::SinglePkColumn]=QString(); + attributes[Attributes::UpdAction]=QString(); + attributes[Attributes::DelAction]=QString(); + attributes[Attributes::CustomColor]=QString(); + attributes[Attributes::ReferenceFk]=QString(); + attributes[Attributes::PartitionBoundExpr]=QString(); + attributes[Attributes::OriginalPk]=QString(); //Check if the relationship type is valid - if(rel_type <= RELATIONSHIP_FK) + if(rel_type <= RelationshipFk) { //Raises an error if one of the tables is not allocated if(!src_table || !dst_table) - throw Exception(Exception::getErrorMessage(ERR_ASG_NOT_ALOC_TABLE) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgNotAllocatedTable) .arg(this->getName()) - .arg(BaseObject::getTypeName(BASE_RELATIONSHIP)), - ERR_ASG_NOT_ALOC_TABLE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::BaseRelationship)), + ErrorCode::AsgNotAllocatedTable,__PRETTY_FUNCTION__,__FILE__,__LINE__); /* Raises an error if the relationship type is generalization or dependency and the source and destination table are the same. */ - if((rel_type==RELATIONSHIP_GEN || - rel_type==RELATIONSHIP_DEP) && src_table==dst_table) - throw Exception(ERR_INV_INH_COPY_RELATIONSHIP,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if((rel_type==RelationshipGen || rel_type==RelationshipDep || rel_type==RelationshipPart) && src_table==dst_table) + throw Exception(ErrorCode::InvInheritCopyPartRelationship,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Allocates the textbox for the name label - lables[REL_NAME_LABEL]=new Textbox; - lables[REL_NAME_LABEL]->setTextAttribute(Textbox::ITALIC_TXT, true); + lables[RelNameLabel]=new Textbox; + lables[RelNameLabel]->setTextAttribute(Textbox::ItalicText, true); //Allocates the cardinality labels only when the relationship is not generalization or dependency (copy) - if(rel_type!=RELATIONSHIP_GEN && - rel_type!=RELATIONSHIP_DEP) + if(rel_type!=RelationshipGen && + rel_type!=RelationshipDep && + rel_type!=RelationshipPart) { - lables[SRC_CARD_LABEL]=new Textbox; - lables[DST_CARD_LABEL]=new Textbox; - lables[SRC_CARD_LABEL]->setTextAttribute(Textbox::ITALIC_TXT, true); - lables[DST_CARD_LABEL]->setTextAttribute(Textbox::ITALIC_TXT, true); + lables[SrcCardLabel]=new Textbox; + lables[DstCardLabel]=new Textbox; + lables[SrcCardLabel]->setTextAttribute(Textbox::ItalicText, true); + lables[DstCardLabel]->setTextAttribute(Textbox::ItalicText, true); //Configures the mandatory participation for both tables - setMandatoryTable(SRC_TABLE,src_mandatory); - setMandatoryTable(DST_TABLE,dst_mandatory); + setMandatoryTable(SrcTable,src_mandatory); + setMandatoryTable(DstTable,dst_mandatory); } } else //Raises an error if the specified relationship typ is invalid - throw Exception(ERR_ALOC_OBJECT_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AllocationObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); } BaseRelationship::~BaseRelationship(void) @@ -169,12 +172,12 @@ void BaseRelationship::setName(const QString &name) { BaseObject::setName(name); - if(lables[REL_NAME_LABEL]) - lables[REL_NAME_LABEL]->setComment(name); + if(lables[RelNameLabel]) + lables[RelNameLabel]->setComment(name); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -187,21 +190,21 @@ void BaseRelationship::setMandatoryTable(unsigned table_id, bool value) One to One where both tables are mandatory partitipation (1,1)-<>-(1,1). This type of relationship is not implemented because it requires the table fusion. */ - if(rel_type==RELATIONSHIP_11 && - ((table_id==SRC_TABLE && value && dst_mandatory) || - (table_id==DST_TABLE && value && src_mandatory))) - throw Exception(ERR_NOT_IMPL_REL_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(rel_type==Relationship11 && + ((table_id==SrcTable && value && dst_mandatory) || + (table_id==DstTable && value && src_mandatory))) + throw Exception(ErrorCode::NotImplementedRelationshipType,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Case the source table is mandatory - if(table_id==SRC_TABLE) + if(table_id==SrcTable) { src_mandatory=value; //Indicates that the source cardinality label will be configured - label_id=SRC_CARD_LABEL; + label_id=SrcCardLabel; } else { - if(rel_type!=RELATIONSHIP_1N) + if(rel_type!=Relationship1n) dst_mandatory=value; else /* For One to many (1-n) relationship the entity on the "many" side @@ -209,7 +212,7 @@ void BaseRelationship::setMandatoryTable(unsigned table_id, bool value) dst_mandatory=false; //Indicates that the destination cardinality label will be configured - label_id=DST_CARD_LABEL; + label_id=DstCardLabel; } if(!value) cmin=QString("0"); @@ -217,24 +220,24 @@ void BaseRelationship::setMandatoryTable(unsigned table_id, bool value) if(lables[label_id]) { - if(rel_type==RELATIONSHIP_11) + if(rel_type==Relationship11) lables[label_id]->setComment(cmin + QString(":1")); - else if(rel_type==RELATIONSHIP_1N) + else if(rel_type==Relationship1n) { - aux=(table_id==SRC_TABLE ? QString("1") : QString("n")); + aux=(table_id==SrcTable ? QString("1") : QString("n")); lables[label_id]->setComment(cmin + QString(":") + aux); } - else if(rel_type==RELATIONSHIP_FK) + else if(rel_type==RelationshipFk) { - if((table_id==SRC_TABLE && dynamic_cast
(src_table)->isReferTableOnForeignKey(dynamic_cast
(dst_table))) || - (!isSelfRelationship() && table_id==DST_TABLE && dynamic_cast
(dst_table)->isReferTableOnForeignKey(dynamic_cast
(src_table)))) + if((table_id==SrcTable && dynamic_cast
(src_table)->isReferTableOnForeignKey(dynamic_cast
(dst_table))) || + (!isSelfRelationship() && table_id==DstTable && dynamic_cast
(dst_table)->isReferTableOnForeignKey(dynamic_cast
(src_table)))) aux=QString("n"); else aux=QString("1"); lables[label_id]->setComment(aux); } - else if(rel_type==RELATIONSHIP_NN) + else if(rel_type==RelationshipNn) lables[label_id]->setComment(QString("n")); lables[label_id]->setModified(true); @@ -243,9 +246,9 @@ void BaseRelationship::setMandatoryTable(unsigned table_id, bool value) BaseTable *BaseRelationship::getTable(unsigned table_id) { - if(table_id==SRC_TABLE) + if(table_id==SrcTable) return(src_table); - else if(table_id==DST_TABLE) + else if(table_id==DstTable) return(dst_table); else return(nullptr); @@ -253,7 +256,7 @@ BaseTable *BaseRelationship::getTable(unsigned table_id) bool BaseRelationship::isTableMandatory(unsigned table_id) { - if(table_id==SRC_TABLE) + if(table_id==SrcTable) return(src_mandatory); else return(dst_mandatory); @@ -263,17 +266,20 @@ void BaseRelationship::setConnected(bool value) { connected=value; - src_table->setModified(true); + if(!this->signalsBlocked()) + { + src_table->setModified(true); - if(dst_table!=src_table) - dst_table->setModified(true); + if(dst_table!=src_table) + dst_table->setModified(true); - dynamic_cast(src_table->getSchema())->setModified(true); + dynamic_cast(src_table->getSchema())->setModified(true); - if(dst_table->getSchema()!=src_table->getSchema()) - dynamic_cast(dst_table->getSchema())->setModified(true); + if(dst_table->getSchema()!=src_table->getSchema()) + dynamic_cast(dst_table->getSchema())->setModified(true); - this->setModified(true); + this->setModified(true); + } } void BaseRelationship::disconnectRelationship(void) @@ -296,11 +302,11 @@ void BaseRelationship::connectRelationship(void) Textbox *BaseRelationship::getLabel(unsigned label_id) { - if(label_id<=REL_NAME_LABEL) + if(label_id<=RelNameLabel) return(lables[label_id]); - else - //Raises an error when the label id is invalid - throw Exception(ERR_REF_LABEL_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + //Raises an error when the label id is invalid + throw Exception(ErrorCode::RefLabelInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); } unsigned BaseRelationship::getRelationshipType(void) @@ -322,47 +328,47 @@ void BaseRelationship::setRelationshipAttributes(void) { unsigned count, i; QString str_aux, - label_attribs[3]={ ParsersAttributes::SRC_LABEL, - ParsersAttributes::DST_LABEL, - ParsersAttributes::NAME_LABEL}; + label_attribs[3]={ Attributes::SrcLabel, + Attributes::DstLabel, + Attributes::NameLabel}; - - attributes[ParsersAttributes::TYPE]=getRelTypeAttribute(); - attributes[ParsersAttributes::SRC_REQUIRED]=(src_mandatory ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::DST_REQUIRED]=(dst_mandatory ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::Layer]=QString::number(layer); + attributes[Attributes::Type]=getRelTypeAttribute(); + attributes[Attributes::SrcRequired]=(src_mandatory ? Attributes::True : QString()); + attributes[Attributes::DstRequired]=(dst_mandatory ? Attributes::True : QString()); if(src_table) - attributes[ParsersAttributes::SRC_TABLE]=src_table->getName(true); + attributes[Attributes::SrcTable]=src_table->getName(true); if(dst_table) - attributes[ParsersAttributes::DST_TABLE]=dst_table->getName(true); + attributes[Attributes::DstTable]=dst_table->getName(true); count=points.size(); for(i=0; i < count; i++) { - attributes[ParsersAttributes::X_POS]=QString("%1").arg(points[i].x()); - attributes[ParsersAttributes::Y_POS]=QString("%1").arg(points[i].y()); - str_aux+=schparser.getCodeDefinition(ParsersAttributes::POSITION, attributes, SchemaParser::XML_DEFINITION); + attributes[Attributes::XPos]=QString("%1").arg(points[i].x()); + attributes[Attributes::YPos]=QString("%1").arg(points[i].y()); + str_aux+=schparser.getCodeDefinition(Attributes::Position, attributes, SchemaParser::XmlDefinition); } - attributes[ParsersAttributes::POINTS]=str_aux; + attributes[Attributes::Points]=str_aux; str_aux=QString(); for(i=0; i < 3; i++) { if(!std::isnan(lables_dist[i].x())) { - attributes[ParsersAttributes::X_POS]=QString("%1").arg(lables_dist[i].x()); - attributes[ParsersAttributes::Y_POS]=QString("%1").arg(lables_dist[i].y()); - attributes[ParsersAttributes::POSITION]=schparser.getCodeDefinition(ParsersAttributes::POSITION, attributes, SchemaParser::XML_DEFINITION); - attributes[ParsersAttributes::REF_TYPE]=label_attribs[i]; - str_aux+=schparser.getCodeDefinition(ParsersAttributes::LABEL, attributes, SchemaParser::XML_DEFINITION); + attributes[Attributes::XPos]=QString("%1").arg(lables_dist[i].x()); + attributes[Attributes::YPos]=QString("%1").arg(lables_dist[i].y()); + attributes[Attributes::Position]=schparser.getCodeDefinition(Attributes::Position, attributes, SchemaParser::XmlDefinition); + attributes[Attributes::RefType]=label_attribs[i]; + str_aux+=schparser.getCodeDefinition(Attributes::Label, attributes, SchemaParser::XmlDefinition); } } - attributes[ParsersAttributes::LABELS_POS]=str_aux; - attributes[ParsersAttributes::CUSTOM_COLOR]=(custom_color!=Qt::transparent ? custom_color.name() : QString()); - attributes[ParsersAttributes::REFERENCE_FK]=(reference_fk ? reference_fk->getName() : QString()); + attributes[Attributes::LabelsPos]=str_aux; + attributes[Attributes::CustomColor]=(custom_color!=Qt::transparent ? custom_color.name() : QString()); + attributes[Attributes::ReferenceFk]=(reference_fk ? reference_fk->getName() : QString()); setFadedOutAttribute(); } @@ -370,9 +376,9 @@ QString BaseRelationship::getCachedCode(unsigned def_type) { if(!code_invalidated && ((!cached_code[def_type].isEmpty()) || - (def_type==SchemaParser::XML_DEFINITION && !cached_reduced_code.isEmpty()))) + (def_type==SchemaParser::XmlDefinition && !cached_reduced_code.isEmpty()))) { - if(def_type==SchemaParser::XML_DEFINITION && !cached_reduced_code.isEmpty()) + if(def_type==SchemaParser::XmlDefinition && !cached_reduced_code.isEmpty()) return(cached_reduced_code); else return(cached_code[def_type]); @@ -399,13 +405,13 @@ QString BaseRelationship::getCodeDefinition(unsigned def_type) QString code_def=getCachedCode(def_type); if(!code_def.isEmpty()) return(code_def); - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) { - if(rel_type!=RELATIONSHIP_FK) + if(rel_type!=RelationshipFk) return(QString()); else { - cached_code[def_type] = reference_fk->getCodeDefinition(SchemaParser::SQL_DEFINITION); + cached_code[def_type] = reference_fk->getCodeDefinition(SchemaParser::SqlDefinition); return(cached_code[def_type]); } } @@ -413,13 +419,13 @@ QString BaseRelationship::getCodeDefinition(unsigned def_type) { bool reduced_form; setRelationshipAttributes(); - reduced_form=(attributes[ParsersAttributes::POINTS].isEmpty() && - attributes[ParsersAttributes::LABELS_POS].isEmpty()); + reduced_form=(attributes[Attributes::Points].isEmpty() && + attributes[Attributes::LabelsPos].isEmpty()); if(!reduced_form) cached_reduced_code.clear(); - return(BaseObject::getCodeDefinition(SchemaParser::XML_DEFINITION,reduced_form)); + return(BaseObject::getCodeDefinition(SchemaParser::XmlDefinition,reduced_form)); } } @@ -431,8 +437,8 @@ void BaseRelationship::setPoints(const vector &points) void BaseRelationship::setLabelDistance(unsigned label_id, QPointF label_dist) { - if(label_id > REL_NAME_LABEL) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(label_id > RelNameLabel) + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->lables_dist[label_id]=label_dist; this->setCodeInvalidated(true); @@ -440,8 +446,8 @@ void BaseRelationship::setLabelDistance(unsigned label_id, QPointF label_dist) QPointF BaseRelationship::getLabelDistance(unsigned label_id) { - if(label_id > REL_NAME_LABEL) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(label_id > RelNameLabel) + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(this->lables_dist[label_id]); } @@ -459,7 +465,7 @@ QColor BaseRelationship::getCustomColor(void) void BaseRelationship::resetLabelsDistance(void) { for(unsigned i=0; i < 3; i++) - this->setLabelDistance(i, QPointF(NAN,NAN)); + this->setLabelDistance(i, QPointF(DNaN,DNaN)); } vector BaseRelationship::getPoints(void) @@ -488,31 +494,58 @@ void BaseRelationship::operator = (BaseRelationship &rel) this->lables_dist[i]=rel.lables_dist[i]; } - this->setMandatoryTable(SRC_TABLE, false); - this->setMandatoryTable(DST_TABLE, false); + this->setMandatoryTable(SrcTable, false); + this->setMandatoryTable(DstTable, false); - this->setMandatoryTable(SRC_TABLE, rel.src_mandatory); - this->setMandatoryTable(DST_TABLE, rel.dst_mandatory); + this->setMandatoryTable(SrcTable, rel.src_mandatory); + this->setMandatoryTable(DstTable, rel.dst_mandatory); } QString BaseRelationship::getRelTypeAttribute(void) { switch(rel_type) { - case RELATIONSHIP_11: return(ParsersAttributes::RELATIONSHIP_11); break; - case RELATIONSHIP_1N: return(ParsersAttributes::RELATIONSHIP_1N); break; - case RELATIONSHIP_NN: return(ParsersAttributes::RELATIONSHIP_NN); break; - case RELATIONSHIP_GEN: return(ParsersAttributes::RELATIONSHIP_GEN); break; - case RELATIONSHIP_FK: return(ParsersAttributes::RELATIONSHIP_FK); break; + case Relationship11: return(Attributes::Relationship11); + case Relationship1n: return(Attributes::Relationship1n); + case RelationshipNn: return(Attributes::RelationshipNn); + case RelationshipGen: return(Attributes::RelationshipGen); + case RelationshipPart: return(Attributes::RelationshipPart); + case RelationshipFk: return(Attributes::RelationshipFk); default: - if(src_table->getObjectType()==OBJ_VIEW) - return(ParsersAttributes::RELATION_TAB_VIEW); + { + if(src_table->getObjectType()==ObjectType::View) + return(Attributes::RelationshipTabView); else - return(ParsersAttributes::RELATIONSHIP_DEP); - break; + return(Attributes::RelationshipDep); + } } } +QString BaseRelationship::getRelationshipTypeName(unsigned rel_type, bool is_view) +{ + switch(rel_type) + { + case Relationship11: return(trUtf8("One-to-one")); + case Relationship1n: return(trUtf8("One-to-many")); + case RelationshipNn: return(trUtf8("Many-to-many")); + case RelationshipGen: return(trUtf8("Inheritance")); + case RelationshipPart: return(trUtf8("Partitioning")); + case RelationshipFk: return(trUtf8("FK relationship")); + default: + { + if(is_view) + return(trUtf8("Dependency")); + else + return(trUtf8("Copy")); + } + } +} + +QString BaseRelationship::getRelationshipTypeName(void) +{ + return(getRelationshipTypeName(rel_type, src_table->getObjectType()==ObjectType::View)); +} + void BaseRelationship::setCodeInvalidated(bool value) { BaseObject::setCodeInvalidated(value); diff --git a/libpgmodeler/src/baserelationship.h b/libpgmodeler/src/baserelationship.h index d26cee1e74..5aa2701420 100644 --- a/libpgmodeler/src/baserelationship.h +++ b/libpgmodeler/src/baserelationship.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -94,21 +94,22 @@ class BaseRelationship: public BaseGraphicObject { public: //! \brief Constants used to assign the type to relationship - static const unsigned RELATIONSHIP_11=10, //! \brief One to one - RELATIONSHIP_1N=11, //! \brief One to many - RELATIONSHIP_NN=12, //! \brief Many to many - RELATIONSHIP_GEN=13, //! \brief Generalization (Inheritance) - RELATIONSHIP_DEP=14, //! \brief Dependency (table-view) / Copy (table-table) - RELATIONSHIP_FK=15; //! \brief Relationship generated by creating a foreign key manually on a table + static constexpr unsigned Relationship11=10, //! \brief One to one + Relationship1n=11, //! \brief One to many + RelationshipNn=12, //! \brief Many to many + RelationshipGen=13, //! \brief Generalization (Inheritance) + RelationshipDep=14, //! \brief Dependency (table-view) / Copy (table-table) + RelationshipPart=15,//! \brief Partitioning relationship + RelationshipFk=16; //! \brief Relationship generated by creating a foreign key manually on a table //! \brief Constats used to reference the relationship labels - static const unsigned SRC_CARD_LABEL=0, - DST_CARD_LABEL=1, - REL_NAME_LABEL=2; + static constexpr unsigned SrcCardLabel=0, + DstCardLabel=1, + RelNameLabel=2; //! \brief Constants used to reference the source and destination tables - static const unsigned SRC_TABLE=0, - DST_TABLE=1; + static constexpr unsigned SrcTable=0, + DstTable=1; BaseRelationship(BaseRelationship *rel); @@ -171,6 +172,10 @@ class BaseRelationship: public BaseGraphicObject { virtual QString getAlterDefinition(BaseObject *) { return(""); } + static QString getRelationshipTypeName(unsigned rel_type, bool is_view = false); + + QString getRelationshipTypeName(void); + friend class DatabaseModel; friend class RelationshipWidget; friend class ModelWidget; diff --git a/libpgmodeler/src/basetable.cpp b/libpgmodeler/src/basetable.cpp index 4a796acf70..2610475291 100644 --- a/libpgmodeler/src/basetable.cpp +++ b/libpgmodeler/src/basetable.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -21,21 +21,22 @@ BaseTable::BaseTable(void) { tag=nullptr; - obj_type=BASE_TABLE; - attributes[ParsersAttributes::TAG]=QString(); - attributes[ParsersAttributes::HIDE_EXT_ATTRIBS]=QString(); - hide_ext_attribs=false; + obj_type=ObjectType::BaseTable; + attributes[Attributes::Tag]=QString(); + attributes[Attributes::MaxObjCount]=QString(); + attributes[Attributes::CollapseMode]=QString(); + attributes[Attributes::Pagination]=QString(); + attributes[Attributes::AttribsPage]=QString(); + attributes[Attributes::ExtAttribsPage]=QString(); + pagination_enabled = false; + collapse_mode = CollapseMode::NotCollapsed; + resetCurrentPages(); } -void BaseTable::setExtAttribsHidden(bool value) +void BaseTable::resetCurrentPages(void) { - setCodeInvalidated(hide_ext_attribs != value); - hide_ext_attribs = value; -} - -bool BaseTable::isExtAttribsHidden(void) -{ - return(hide_ext_attribs); + curr_page[AttribsSection] = 0; + curr_page[ExtAttribsSection] = 0; } void BaseTable::setTag(Tag *tag) @@ -57,7 +58,7 @@ QString BaseTable::getAlterDefinition(BaseObject *object) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -66,3 +67,45 @@ void BaseTable::operator = (BaseTable &tab) (*dynamic_cast(this))=dynamic_cast(tab); this->tag=tab.tag; } + +CollapseMode BaseTable::getCollapseMode(void) +{ + return(collapse_mode); +} + +void BaseTable::setPaginationEnabled(bool value) +{ + setCodeInvalidated(pagination_enabled != value); + pagination_enabled = value; + + if(!pagination_enabled) + resetCurrentPages(); +} + +bool BaseTable::isPaginationEnabled(void) +{ + return(pagination_enabled); +} + +void BaseTable::setCurrentPage(unsigned section_id, unsigned value) +{ + if(section_id > ExtAttribsSection) + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + setCodeInvalidated(curr_page[section_id] != value); + curr_page[section_id] = value; +} + +unsigned BaseTable::getCurrentPage(unsigned section_id) +{ + if(section_id > ExtAttribsSection) + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + return(curr_page[section_id]); +} + +void BaseTable::setCollapseMode(CollapseMode coll_mode) +{ + setCodeInvalidated(collapse_mode != coll_mode); + collapse_mode = coll_mode; +} diff --git a/libpgmodeler/src/basetable.h b/libpgmodeler/src/basetable.h index 7f4a465156..0e12d680f6 100644 --- a/libpgmodeler/src/basetable.h +++ b/libpgmodeler/src/basetable.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -29,18 +29,31 @@ #include "basegraphicobject.h" #include "tag.h" -class BaseTable: public BaseGraphicObject { - private: - bool hide_ext_attribs; +//! \brief This enum is used to control the collapsing of the tables +enum class CollapseMode: unsigned { + AllAttribsCollapsed, //Columns (attributes) and extended attributes are collapsed + ExtAttribsCollapsed, //Extended attributes are collapsed + NotCollapsed //Table is fully expanded (columns and extended attributes) +}; +class BaseTable: public BaseGraphicObject { protected: Tag *tag; + //! \brief Indicates if the pagination is enabled for the table + bool pagination_enabled; + + //! \brief Stores the current collpase mode for the table + CollapseMode collapse_mode; + + //! \brief Stores the current page visible on the table + unsigned curr_page[2]; + public: - BaseTable(void); + static constexpr unsigned AttribsSection = 0, + ExtAttribsSection = 1; - virtual void setExtAttribsHidden(bool value); - virtual bool isExtAttribsHidden(void); + BaseTable(void); virtual void setTag(Tag *tag); virtual Tag *getTag(void); @@ -73,16 +86,45 @@ class BaseTable: public BaseGraphicObject { //! \brief Returns the index for the specified table object virtual int getObjectIndex(BaseObject *obj)=0; - //! \brief Returns all child objects of the table - virtual vector getObjects(void)=0; + //! \brief Returns all children objects of the table but excluding the ones of the provided type + virtual vector getObjects(const vector &excl_types = {})=0; virtual QString getCodeDefinition(unsigned tipo_def)=0; virtual QString getAlterDefinition(BaseObject *object); + /*! \brief Set the initial capacity of the objects list for a optimized memory usage. + * This method should be called prior to adding the first object to the table because, depending o the capacity, + * there'll be memory reallocations which can degradate the performance */ + virtual void setObjectListsCapacity(unsigned capacity) = 0; + + //! \brief Returns the maximum item count from all of the objects lists + virtual unsigned getMaxObjectCount(void) = 0; + //! \brief Copy the attributes between two tables void operator = (BaseTable &tab); + /*! \brief Defines the current collapse mode for the table. Calling this method direclty + * will not update the geometry of the graphical representation of this object. For that, + * the setModified(true) should be called */ + void setCollapseMode(CollapseMode coll_mode); + + CollapseMode getCollapseMode(void); + + /*! \brief Defines the pagination enabling for the table. Calling this method direclty + * will not update the geometry of the graphical representation of this object. For that, + * the setModified(true) should be called */ + void setPaginationEnabled(bool value); + + bool isPaginationEnabled(void); + + /*! \brief Defines the current page visible on the table. Calling this method direclty + * will not update the geometry of the graphical representation of this object. For that, + * the setModified(true) should be called */ + void setCurrentPage(unsigned section_id, unsigned value); + void resetCurrentPages(void); + unsigned getCurrentPage(unsigned section_id); + friend class DatabaseModel; }; diff --git a/libpgmodeler/src/cast.cpp b/libpgmodeler/src/cast.cpp index 906c35092e..5656e4c3a8 100644 --- a/libpgmodeler/src/cast.cpp +++ b/libpgmodeler/src/cast.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,45 +20,45 @@ Cast::Cast(void) { - obj_type=OBJ_CAST; + obj_type=ObjectType::Cast; cast_function=nullptr; - cast_type=EXPLICIT; + cast_type=Explicit; is_in_out=false; - attributes[ParsersAttributes::SOURCE_TYPE]=QString(); - attributes[ParsersAttributes::DEST_TYPE]=QString(); - attributes[ParsersAttributes::CAST_TYPE]=QString(); - attributes[ParsersAttributes::IO_CAST]=QString(); - attributes[ParsersAttributes::FUNCTION]=QString(); + attributes[Attributes::SourceType]=QString(); + attributes[Attributes::DestType]=QString(); + attributes[Attributes::CastType]=QString(); + attributes[Attributes::IoCast]=QString(); + attributes[Attributes::Function]=QString(); } -void Cast::setDataType(unsigned type_idx, PgSQLType type) +void Cast::setDataType(unsigned type_idx, PgSqlType type) { //Check if the type index is valid - if(type_idx<=DST_TYPE) + if(type_idx<=DstType) { //Raises an error if the passed data type is null if((*type).isEmpty()) - throw Exception(Exception::getErrorMessage(ERR_ASG_NULL_TYPE_OBJECT) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgNullTypeObject) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_CAST)), - ERR_ASG_NULL_TYPE_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Cast)), + ErrorCode::AsgNullTypeObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->types[type_idx] != type); this->types[type_idx]=type; } else //Raises an error if the type index is invalid - throw Exception(ERR_REF_TYPE_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefTypeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Configures the cast name (in form of signature: cast(src_type, dst_type) ) - this->obj_name=QString("cast(%1,%2)").arg(~types[SRC_TYPE]).arg(~types[DST_TYPE]); + this->obj_name=QString("cast(%1,%2)").arg(~types[SrcType]).arg(~types[DstType]); } void Cast::setCastType(unsigned cast_type) { //Raises an error if the user tries to assign an invalid cast type - if(cast_type > IMPLICIT) - throw Exception(ERR_ASG_INV_TYPE_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(cast_type > Implicit) + throw Exception(ErrorCode::AsgInvalidTypeObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->cast_type != cast_type); this->cast_type=cast_type; @@ -74,29 +74,29 @@ void Cast::setCastFunction(Function *cast_func) { unsigned param_count; bool error=false; - PgSQLType ret_type; + PgSqlType ret_type; if(!cast_func) - throw Exception(Exception::getErrorMessage(ERR_ASG_NOT_ALOC_FUNCTION) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgNotAllocatedFunction) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_CAST)), - ERR_ASG_NOT_ALOC_FUNCTION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Cast)), + ErrorCode::AsgNotAllocatedFunction,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Retrieve the cast function parameter count for specific validations param_count=cast_func->getParameterCount(); //Raises an error if the function don't have at least 1 parameter or a maximum of 3 if(param_count==0 || param_count > 3) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNC_INV_PARAM_COUNT) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidParamCount) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_CAST)), - ERR_ASG_FUNC_INV_PARAM_COUNT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Cast)), + ErrorCode::AsgFunctionInvalidParamCount,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { /* Error condition 1: Check if the first function parameter data type differs from cast source data type */ - error=(cast_func->getParameter(0).getType()!=this->types[SRC_TYPE] && - !cast_func->getParameter(0).getType().canCastTo(this->types[SRC_TYPE])); + error=(cast_func->getParameter(0).getType()!=this->types[SrcType] && + !cast_func->getParameter(0).getType().canCastTo(this->types[SrcType])); /* Error condition 2: Check if the second function parameter data type is different from 'integer' */ @@ -110,30 +110,30 @@ void Cast::setCastFunction(Function *cast_func) //In case some error condition is reached raises an error if(error) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNCTION_INV_PARAMS) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidParameters) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_CAST)), - ERR_ASG_FUNCTION_INV_PARAMS,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Cast)), + ErrorCode::AsgFunctionInvalidParameters,__PRETTY_FUNCTION__,__FILE__,__LINE__); } /* Raises an error if the return type of the function differs from the destination data type. If the types can be casted between them no error is returned */ ret_type=cast_func->getReturnType(); - if(ret_type!=this->types[DST_TYPE] && !ret_type.canCastTo(this->types[DST_TYPE])) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNCTION_INV_RET_TYPE) + if(ret_type!=this->types[DstType] && !ret_type.canCastTo(this->types[DstType])) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidReturnType) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_CAST)), - ERR_ASG_FUNCTION_INV_RET_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Cast)), + ErrorCode::AsgFunctionInvalidReturnType,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(cast_function != cast_func); this->cast_function=cast_func; } -PgSQLType Cast::getDataType(unsigned type_idx) +PgSqlType Cast::getDataType(unsigned type_idx) { - if(type_idx > DST_TYPE) - throw Exception(ERR_REF_TYPE_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(type_idx > DstType) + throw Exception(ErrorCode::RefTypeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(this->types[type_idx]); } @@ -155,7 +155,7 @@ unsigned Cast::getCastType(void) QString Cast::getDropDefinition(bool cascade) { - attributes[ParsersAttributes::SIGNATURE].replace(QString(","), QString(" AS ")); + attributes[Attributes::Signature].replace(QString(","), QString(" AS ")); return(BaseObject::getDropDefinition(cascade)); } @@ -164,43 +164,53 @@ QString Cast::getCodeDefinition(unsigned def_type) QString code_def=getCachedCode(def_type, false); if(!code_def.isEmpty()) return(code_def); - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) { - attributes[ParsersAttributes::SOURCE_TYPE]=(*types[SRC_TYPE]); - attributes[ParsersAttributes::DEST_TYPE]=(*types[DST_TYPE]); + attributes[Attributes::SourceType]=(*types[SrcType]); + attributes[Attributes::DestType]=(*types[DstType]); } else { - attributes[ParsersAttributes::SOURCE_TYPE]=types[SRC_TYPE].getCodeDefinition(def_type); - attributes[ParsersAttributes::DEST_TYPE]=types[DST_TYPE].getCodeDefinition(def_type); + attributes[Attributes::SourceType]=types[SrcType].getCodeDefinition(def_type); + attributes[Attributes::DestType]=types[DstType].getCodeDefinition(def_type); } if(!is_in_out && cast_function) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::FUNCTION]=cast_function->getSignature(); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Function]=cast_function->getSignature(); else - attributes[ParsersAttributes::FUNCTION]=cast_function->getCodeDefinition(def_type, true); + attributes[Attributes::Function]=cast_function->getCodeDefinition(def_type, true); } else - attributes[ParsersAttributes::IO_CAST]=(is_in_out ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::IoCast]=(is_in_out ? Attributes::True : QString()); - if(cast_type==ASSIGNMENT) - attributes[ParsersAttributes::CAST_TYPE]=ParsersAttributes::ASSIGNMENT; - else if(cast_type==IMPLICIT) - attributes[ParsersAttributes::CAST_TYPE]=ParsersAttributes::IMPLICIT; + if(cast_type==Assignment) + attributes[Attributes::CastType]=Attributes::Assignment; + else if(cast_type==Implicit) + attributes[Attributes::CastType]=Attributes::Implicit; else - attributes[ParsersAttributes::CAST_TYPE]=QString(); + attributes[Attributes::CastType]=QString(); - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::CAST_TYPE]=attributes[ParsersAttributes::CAST_TYPE].toUpper(); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::CastType]=attributes[Attributes::CastType].toUpper(); return(BaseObject::__getCodeDefinition(def_type)); } QString Cast::getSignature(bool) { - attributes[ParsersAttributes::SIGNATURE]=this->getName().remove(QString("cast")); + attributes[Attributes::Signature]=this->getName().remove(QString("cast")); return(BaseObject::getSignature(false)); } +void Cast::configureSearchAttributes(void) +{ + QStringList arg_types; + + BaseObject::configureSearchAttributes(); + + arg_types += *types[0]; + arg_types += *types[1]; + search_attribs[Attributes::Type] = arg_types.join("; "); +} diff --git a/libpgmodeler/src/cast.h b/libpgmodeler/src/cast.h index 7658f82143..23a08f448a 100644 --- a/libpgmodeler/src/cast.h +++ b/libpgmodeler/src/cast.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -34,7 +34,7 @@ class Cast: public BaseObject { /*! \brief Data types used on the cast: 0 -> Source data type 1 -> Destination data type */ - PgSQLType types[2]; + PgSqlType types[2]; //! \brief Conversion type (ASSIGNMENT or IMPLICIT) unsigned cast_type; @@ -47,19 +47,24 @@ class Cast: public BaseObject { function of the source data type */ bool is_in_out; + protected: + virtual void configureSearchAttributes(void); + public: //! \brief Constants used to access the data types envolved in the cast - static const unsigned SRC_TYPE=0, - DST_TYPE=1, + static constexpr unsigned SrcType=0, + DstType=1, + //! \brief Constants used to define the cast type - EXPLICIT=0, - ASSIGNMENT=1, - IMPLICIT=2; + Explicit=0, + Assignment=1, + Implicit=2; + Cast(void); /*! \brief Defines one of the data types envolved on the cast (using constants SRC_TYPE | DST_TYPE) */ - void setDataType(unsigned type_idx, PgSQLType type); + void setDataType(unsigned type_idx, PgSqlType type); //! \brief Defines the cast type (using constants ASSINGMENT | IMPLICIT) void setCastType(unsigned cast_type); @@ -73,7 +78,7 @@ class Cast: public BaseObject { void setInOut(bool value); //! \brief Returns one of the cast envolved data types - PgSQLType getDataType(unsigned type_idx); + PgSqlType getDataType(unsigned type_idx); //! \brief Returns the cast type unsigned getCastType(void); diff --git a/libpgmodeler/src/collation.cpp b/libpgmodeler/src/collation.cpp index fe1870fb2d..0c06819926 100644 --- a/libpgmodeler/src/collation.cpp +++ b/libpgmodeler/src/collation.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,19 +20,19 @@ Collation::Collation(void) { - obj_type=OBJ_COLLATION; - encoding=BaseType::null; + obj_type=ObjectType::Collation; + encoding=BaseType::Null; - attributes[ParsersAttributes::_LC_CTYPE_]=QString(); - attributes[ParsersAttributes::_LC_COLLATE_]=QString(); - attributes[ParsersAttributes::LOCALE]=QString(); - attributes[ParsersAttributes::ENCODING]=QString(); + attributes[Attributes::LcCtype]=QString(); + attributes[Attributes::LcCollate]=QString(); + attributes[Attributes::Locale]=QString(); + attributes[Attributes::Encoding]=QString(); } void Collation::setLocale(const QString &locale) { - setLocalization(_LC_CTYPE, locale); - setLocalization(_LC_COLLATE, locale); + setLocalization(LcCtype, locale); + setLocalization(LcCollate, locale); this->locale=locale; } @@ -40,8 +40,8 @@ void Collation::setLocalization(unsigned lc_id, QString lc_name) { if(locale.isEmpty()) { - if(lc_id > _LC_COLLATE) - throw Exception(ERR_REF_ELEM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(lc_id > LcCollate) + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); /* Removes encoding specification from localization e.g 'aa_BB.ENC' will turn into 'aa_BB' since the encoding is appended on code generation */ @@ -60,14 +60,14 @@ void Collation::setEncoding(EncodingType encoding) void Collation::setCollation(BaseObject *collation) { if(collation==this) - throw Exception(Exception::getErrorMessage(ERR_OBJECT_REFERENCING_ITSELF) + throw Exception(Exception::getErrorMessage(ErrorCode::ObjectReferencingItself) .arg(this->getName(true)) .arg(this->getTypeName()), - ERR_OBJECT_REFERENCING_ITSELF,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::ObjectReferencingItself,__PRETTY_FUNCTION__,__FILE__,__LINE__); BaseObject::setCollation(collation); - encoding=BaseType::null; + encoding=BaseType::Null; locale.clear(); localization[0]=localization[1]=QString(); } @@ -79,8 +79,8 @@ QString Collation::getLocale(void) QString Collation::getLocalization(unsigned lc_id) { - if(lc_id > _LC_COLLATE) - throw Exception(ERR_REF_ELEM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(lc_id > LcCollate) + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(localization[lc_id]); } @@ -102,31 +102,31 @@ QString Collation::getCodeDefinition(unsigned def_type, bool reduced_form) if(!locale.isEmpty()) { - attributes[ParsersAttributes::LOCALE]=locale; + attributes[Attributes::Locale]=locale; - if(def_type==SchemaParser::SQL_DEFINITION && encoding!=BaseType::null) - attributes[ParsersAttributes::LOCALE]=locale + "." + (~encoding).toLower(); + if(def_type==SchemaParser::SqlDefinition && encoding!=BaseType::Null) + attributes[Attributes::Locale]=locale + "." + (~encoding).toLower(); } else if(collation) - attributes[ParsersAttributes::COLLATION]=collation->getName(true); + attributes[Attributes::Collation]=collation->getName(true); else { - QString lc_attribs[2]={ ParsersAttributes::_LC_CTYPE_, ParsersAttributes::_LC_COLLATE_ }; + QString lc_attribs[2]={ Attributes::LcCtype, Attributes::LcCollate }; - if(localization[_LC_CTYPE].isEmpty() && localization[_LC_COLLATE].isEmpty()) - throw Exception(ERR_EMPTY_LOCAL_ATTRIB_COLLATION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(localization[LcCtype].isEmpty() && localization[LcCollate].isEmpty()) + throw Exception(ErrorCode::EmptyLCCollationAttributes,__PRETTY_FUNCTION__,__FILE__,__LINE__); - for(unsigned int i=_LC_CTYPE; i <= _LC_COLLATE; i++) + for(unsigned int i=LcCtype; i <= LcCollate; i++) { attributes[lc_attribs[i]]=getLocalization(i); - if(def_type==SchemaParser::SQL_DEFINITION && encoding!=BaseType::null && + if(def_type==SchemaParser::SqlDefinition && encoding!=BaseType::Null && !attributes[lc_attribs[i]].isEmpty()) attributes[lc_attribs[i]]+="." + (~encoding).toLower(); } } - attributes[ParsersAttributes::ENCODING]=~encoding; + attributes[Attributes::Encoding]=~encoding; return(BaseObject::getCodeDefinition(def_type, reduced_form)); } @@ -134,11 +134,11 @@ QString Collation::getAlterDefinition(BaseObject *object) { try { - attributes[ParsersAttributes::ALTER_CMDS]=BaseObject::getAlterDefinition(object); + attributes[Attributes::AlterCmds]=BaseObject::getAlterDefinition(object); return(BaseObject::getAlterDefinition(this->getSchemaName(), attributes, false, false)); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } diff --git a/libpgmodeler/src/collation.h b/libpgmodeler/src/collation.h index 3551a12c6d..4872ccbbc6 100644 --- a/libpgmodeler/src/collation.h +++ b/libpgmodeler/src/collation.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -48,8 +48,8 @@ class Collation : public BaseObject { locale; public: - static const unsigned _LC_CTYPE=0, - _LC_COLLATE=1; + static constexpr unsigned LcCtype=0, + LcCollate=1; Collation(void); diff --git a/libpgmodeler/src/column.cpp b/libpgmodeler/src/column.cpp index dc2a7defe2..5c35b09a33 100644 --- a/libpgmodeler/src/column.cpp +++ b/libpgmodeler/src/column.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,17 +20,24 @@ Column::Column(void) { - obj_type=OBJ_COLUMN; - not_null=false; - attributes[ParsersAttributes::TYPE]=QString(); - attributes[ParsersAttributes::DEFAULT_VALUE]=QString(); - attributes[ParsersAttributes::NOT_NULL]=QString(); - attributes[ParsersAttributes::TABLE]=QString(); - attributes[ParsersAttributes::SEQUENCE]=QString(); - attributes[ParsersAttributes::DECL_IN_TABLE]=QString(); - attributes[ParsersAttributes::IDENTITY_TYPE]=QString(); + obj_type=ObjectType::Column; + not_null=seq_cycle=false; + attributes[Attributes::Type]=QString(); + attributes[Attributes::DefaultValue]=QString(); + attributes[Attributes::NotNull]=QString(); + attributes[Attributes::Table]=QString(); + attributes[Attributes::Sequence]=QString(); + attributes[Attributes::DeclInTable]=QString(); + attributes[Attributes::IdentityType]=QString(); + attributes[Attributes::Increment]=QString(); + attributes[Attributes::MinValue]=QString(); + attributes[Attributes::MaxValue]=QString(); + attributes[Attributes::Start]=QString(); + attributes[Attributes::Cache]=QString(); + attributes[Attributes::Cycle]=QString(); + parent_rel=sequence=nullptr; - identity_type=BaseType::null; + identity_type=BaseType::Null; } void Column::setName(const QString &name) @@ -51,19 +58,19 @@ void Column::setName(const QString &name) } catch(Exception &e) { - throw Exception(e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } -void Column::setType(PgSQLType type) +void Column::setType(PgSqlType type) { //An error is raised if the column receive a pseudo-type as data type. if(type.isPseudoType()) - throw Exception(ERR_ASG_PSDTYPE_COLUMN,__PRETTY_FUNCTION__,__FILE__,__LINE__); - else if(this->identity_type != BaseType::null && !type.isIntegerType()) + throw Exception(ErrorCode::AsgPseudoTypeColumn,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(this->identity_type != BaseType::Null && !type.isIntegerType()) { - throw Exception(Exception::getErrorMessage(ERR_INV_IDENTITY_COLUMN).arg(getSignature()), - ERR_INV_IDENTITY_COLUMN, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidIdentityColumn).arg(getSignature()), + ErrorCode::InvalidIdentityColumn, __PRETTY_FUNCTION__, __FILE__, __LINE__); } setCodeInvalidated(this->type != type); @@ -72,10 +79,10 @@ void Column::setType(PgSQLType type) void Column::setIdentityType(IdentityType id_type) { - if(id_type != BaseType::null && !type.isIntegerType()) + if(id_type != BaseType::Null && !type.isIntegerType()) { - throw Exception(Exception::getErrorMessage(ERR_INV_IDENTITY_COLUMN).arg(getSignature()), - ERR_INV_IDENTITY_COLUMN, __PRETTY_FUNCTION__, __FILE__, __LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::InvalidIdentityColumn).arg(getSignature()), + ErrorCode::InvalidIdentityColumn, __PRETTY_FUNCTION__, __FILE__, __LINE__); } setCodeInvalidated(identity_type != id_type); @@ -84,7 +91,7 @@ void Column::setIdentityType(IdentityType id_type) sequence = nullptr; //Identity column implies NOT NULL constraint - if(id_type != BaseType::null) + if(id_type != BaseType::Null) setNotNull(true); } @@ -93,7 +100,7 @@ void Column::setDefaultValue(const QString &value) setCodeInvalidated(default_value != value); default_value=value.trimmed(); sequence=nullptr; - identity_type=BaseType::null; + identity_type=BaseType::Null; } void Column::setNotNull(bool value) @@ -102,7 +109,7 @@ void Column::setNotNull(bool value) not_null=value; } -PgSQLType Column::getType(void) +PgSqlType Column::getType(void) { return(type); } @@ -119,7 +126,7 @@ bool Column::isNotNull(void) bool Column::isIdentity(void) { - return(identity_type != BaseType::null); + return(identity_type != BaseType::Null); } QString Column::getTypeReference(void) @@ -145,8 +152,8 @@ QString Column::getOldName(bool format) void Column::setParentRelationship(BaseObject *parent_rel) { - if(parent_rel && parent_rel->getObjectType()!=OBJ_RELATIONSHIP) - throw Exception(ERR_ASG_OBJECT_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(parent_rel && parent_rel->getObjectType()!=ObjectType::Relationship) + throw Exception(ErrorCode::AsgObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->parent_rel=parent_rel; } @@ -160,20 +167,20 @@ void Column::setSequence(BaseObject *seq) { if(seq) { - if(seq->getObjectType()!=OBJ_SEQUENCE) - throw Exception(Exception::getErrorMessage(ERR_ASG_INV_OBJECT_TYPE) + if(seq->getObjectType()!=ObjectType::Sequence) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidObjectType) .arg(this->obj_name) .arg(this->getTypeName()) - .arg(BaseObject::getTypeName(OBJ_SEQUENCE)), - ERR_ASG_INV_OBJECT_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Sequence)), + ErrorCode::AsgInvalidObjectType,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(!type.isIntegerType()) - throw Exception(Exception::getErrorMessage(ERR_INCOMP_COL_TYPE_FOR_SEQ) + throw Exception(Exception::getErrorMessage(ErrorCode::IncompColumnTypeForSequence) .arg(seq->getName(true)) .arg(this->obj_name), - ERR_INCOMP_COL_TYPE_FOR_SEQ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::IncompColumnTypeForSequence,__PRETTY_FUNCTION__,__FILE__,__LINE__); default_value=QString(); - identity_type=BaseType::null; + identity_type=BaseType::Null; } setCodeInvalidated(sequence != seq); @@ -185,36 +192,84 @@ BaseObject *Column::getSequence(void) return(sequence); } +bool Column::isIdSeqCycle(void) +{ + return(seq_cycle); +} + +QString Column::getIdSeqMaxValue(void) +{ + return(seq_max_value); +} + +QString Column::getIdSeqMinValue(void) +{ + return(seq_min_value); +} + +QString Column::getIdSeqIncrement(void) +{ + return(seq_increment); +} + +QString Column::getIdSeqStart(void) +{ + return(seq_start); +} + +QString Column::getIdSeqCache(void) +{ + return(seq_cache); +} + +void Column::setIdSeqAttributes(QString minv, QString maxv, QString inc, QString start, QString cache, bool cycle) +{ + seq_min_value = minv; + seq_max_value = maxv; + seq_increment = inc; + seq_start = start; + seq_cache = cache; + seq_cycle = cycle; +} + QString Column::getCodeDefinition(unsigned def_type) { QString code_def=getCachedCode(def_type, false); if(!code_def.isEmpty()) return(code_def); if(getParentTable()) - attributes[ParsersAttributes::TABLE]=getParentTable()->getName(true); + attributes[Attributes::Table]=getParentTable()->getName(true); - attributes[ParsersAttributes::TYPE]=type.getCodeDefinition(def_type); - attributes[ParsersAttributes::DEFAULT_VALUE]=QString(); - attributes[ParsersAttributes::IDENTITY_TYPE]=QString(); + attributes[Attributes::Type]=type.getCodeDefinition(def_type); + attributes[Attributes::DefaultValue]=QString(); + attributes[Attributes::IdentityType]=QString(); - if(identity_type != BaseType::null) - attributes[ParsersAttributes::IDENTITY_TYPE] = ~identity_type; + if(identity_type != BaseType::Null) + { + attributes[Attributes::IdentityType] = ~identity_type; + attributes[Attributes::Increment]=seq_increment; + attributes[Attributes::MinValue]=seq_min_value; + attributes[Attributes::MaxValue]=seq_max_value; + attributes[Attributes::Start]=seq_start; + attributes[Attributes::Cache]=seq_cache; + attributes[Attributes::Cycle]=(seq_cycle ? Attributes::True : QString()); + } else { if(!sequence) - attributes[ParsersAttributes::DEFAULT_VALUE]=default_value; + attributes[Attributes::DefaultValue]=default_value; else { //Configuring the default value of the column to get the next value of the sequence - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::DEFAULT_VALUE]=QString("nextval('%1'::regclass)").arg(sequence->getSignature());//.remove("\"")); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::DefaultValue]=QString("nextval('%1'::regclass)").arg(sequence->getSignature()); - attributes[ParsersAttributes::SEQUENCE]=sequence->getName(true); + attributes[Attributes::Sequence]=sequence->getName(true); } } - attributes[ParsersAttributes::NOT_NULL]=(!not_null ? QString() : ParsersAttributes::_TRUE_); - attributes[ParsersAttributes::DECL_IN_TABLE]=(isDeclaredInTable() ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::NotNull]=(!not_null ? QString() : Attributes::True); + attributes[Attributes::DeclInTable]=(isDeclaredInTable() ? Attributes::True : QString()); return(BaseObject::__getCodeDefinition(def_type)); } @@ -224,23 +279,24 @@ QString Column::getAlterDefinition(BaseObject *object) Column *col=dynamic_cast(object); if(!col) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { attribs_map attribs; - QString def_val; + QString def_val, alter_def; + bool ident_seq_changed = false; BaseObject::setBasicAttributes(true); if(getParentTable()) - attribs[ParsersAttributes::TABLE]=getParentTable()->getName(true); + attribs[Attributes::Table]=getParentTable()->getName(true); if(!this->type.isEquivalentTo(col->type) || (this->type.isEquivalentTo(col->type) && ((this->type.hasVariableLength() && (this->type.getLength()!=col->type.getLength())) || (this->type.acceptsPrecision() && (this->type.getPrecision()!=col->type.getPrecision()))))) - attribs[ParsersAttributes::TYPE]=col->type.getCodeDefinition(SchemaParser::SQL_DEFINITION); + attribs[Attributes::Type]=col->type.getCodeDefinition(SchemaParser::SqlDefinition); if(col->sequence) def_val=QString("nextval('%1'::regclass)").arg(col->sequence->getSignature()); @@ -248,36 +304,97 @@ QString Column::getAlterDefinition(BaseObject *object) def_val=col->default_value; if(this->default_value!=def_val) - attribs[ParsersAttributes::DEFAULT_VALUE]=(def_val.isEmpty() ? ParsersAttributes::UNSET : def_val); + attribs[Attributes::DefaultValue]=(def_val.isEmpty() ? Attributes::Unset : def_val); if(this->not_null!=col->not_null) - attribs[ParsersAttributes::NOT_NULL]=(!col->not_null ? ParsersAttributes::UNSET : ParsersAttributes::_TRUE_); + attribs[Attributes::NotNull]=(!col->not_null ? Attributes::Unset : Attributes::True); - attribs[ParsersAttributes::NEW_IDENTITY_TYPE] = QString(); + attribs[Attributes::NewIdentityType] = QString(); - if(this->identity_type == BaseType::null && col->identity_type != BaseType::null) - attribs[ParsersAttributes::IDENTITY_TYPE] = ~col->identity_type; - else if(this->identity_type != BaseType::null && col->identity_type == BaseType::null) - attribs[ParsersAttributes::IDENTITY_TYPE] = ParsersAttributes::UNSET; - else if(this->identity_type != BaseType::null && col->identity_type != BaseType::null && + if(this->identity_type == BaseType::Null && col->identity_type != BaseType::Null) + attribs[Attributes::IdentityType] = ~col->identity_type; + else if(this->identity_type != BaseType::Null && col->identity_type == BaseType::Null) + attribs[Attributes::IdentityType] = Attributes::Unset; + else if(this->identity_type != BaseType::Null && col->identity_type != BaseType::Null && this->identity_type != col->identity_type) - attribs[ParsersAttributes::NEW_IDENTITY_TYPE] = ~col->identity_type; + attribs[Attributes::NewIdentityType] = ~col->identity_type; + + attribs[Attributes::CurIdentityType] = QString(); + attribs[Attributes::MinValue] = QString(); + attribs[Attributes::MaxValue] = QString(); + attribs[Attributes::Start] = QString(); + attribs[Attributes::Increment] = QString(); + attribs[Attributes::Cache] = QString(); + attribs[Attributes::Cycle] = QString(); + + //Checking differences in the underlying sequence (identity col) + if(attribs[Attributes::IdentityType] != Attributes::Unset) + { + if(!col->seq_min_value.isEmpty() && this->seq_min_value != col->seq_min_value) + { + attribs[Attributes::MinValue] = col->seq_min_value; + ident_seq_changed = true; + } + + if(!col->seq_max_value.isEmpty() && this->seq_max_value != col->seq_max_value) + { + attribs[Attributes::MaxValue] = col->seq_max_value; + ident_seq_changed = true; + } + + if(!col->seq_start.isEmpty() && this->seq_start != col->seq_start) + { + attribs[Attributes::Start] = col->seq_start; + ident_seq_changed = true; + } + + if(!col->seq_increment.isEmpty() && this->seq_increment != col->seq_increment) + { + attribs[Attributes::Increment] = col->seq_increment; + ident_seq_changed = true; + } + + if(!col->seq_cache.isEmpty() && this->seq_cache != col->seq_cache) + { + attribs[Attributes::Cache] = col->seq_cache; + ident_seq_changed = true; + } + + if(this->seq_cycle != col->seq_cycle) + { + attribs[Attributes::Cycle] = (col->seq_cycle ? Attributes::True : Attributes::False); + ident_seq_changed = true; + } + + if(ident_seq_changed) + attribs[Attributes::CurIdentityType] = ~this->identity_type; + } copyAttributes(attribs); - return(BaseObject::getAlterDefinition(this->getSchemaName(), attributes, false, true)); + alter_def = BaseObject::getAlterDefinition(this->getSchemaName(), attributes, false, true); + alter_def += getAlterCommentDefinition(object, attributes); + + return(alter_def); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } +void Column::configureSearchAttributes(void) +{ + BaseObject::configureSearchAttributes(); + search_attribs[Attributes::Type] = *type; +} + void Column::operator = (Column &col) { this->comment=col.comment; this->is_protected=col.is_protected; this->obj_name=col.obj_name; + this->alias=col.alias; this->old_name=col.old_name; this->type=col.type; @@ -288,6 +405,13 @@ void Column::operator = (Column &col) this->sequence=col.sequence; this->identity_type=col.identity_type; + this->seq_cache = col.seq_cache; + this->seq_cycle = col.seq_cycle; + this->seq_increment = col.seq_increment; + this->seq_max_value = col.seq_max_value; + this->seq_min_value = col.seq_min_value; + this->seq_start = col.seq_start; + this->setParentTable(col.getParentTable()); this->setAddedByCopy(false); this->setAddedByGeneralization(false); diff --git a/libpgmodeler/src/column.h b/libpgmodeler/src/column.h index e68e9402a4..0c937e01ed 100644 --- a/libpgmodeler/src/column.h +++ b/libpgmodeler/src/column.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -39,7 +39,7 @@ class Column: public TableObject{ bool not_null; //! \brief Data type of the column - PgSQLType type; + PgSqlType type; /*! \brief Default value of the column. Note: The user must format the default value in @@ -58,6 +58,27 @@ class Column: public TableObject{ //! \brief Identity type of the column (GENERATED BY DEFAULT | ALWAYS) IdentityType identity_type; + /*! \brief Indicates that the underlying sequence is cyclic + (the counter resets when maximum value is reached) (only for identity column) */ + bool seq_cycle; + + //! \brief Underlying sequence's minimum value (only for identity column) + QString seq_min_value, + + //! \brief Underlying sequence's maximum value (only for identity column) + seq_max_value, + + //! \brief Underlying sequence's current sequence value (only for identity column) + seq_start, + + //! \brief Underlying sequence's value increment (only for identity column) + seq_increment, + + //! \brief Underlying sequence's cache value (only for identity column) + seq_cache; + + virtual void configureSearchAttributes(void); + public: Column(void); @@ -65,7 +86,7 @@ class Column: public TableObject{ void setNotNull(bool value); //! \brief Defines the column data type - void setType(PgSQLType type); + void setType(PgSqlType type); //! \brief Defines the identity mode of the column void setIdentityType(IdentityType id_type); @@ -86,7 +107,7 @@ class Column: public TableObject{ bool isIdentity(void); //! \brief Returns the data type of the column - PgSQLType getType(void); + PgSqlType getType(void); //! \brief Returns the identity mode of the column IdentityType getIdentityType(void); @@ -116,6 +137,16 @@ class Column: public TableObject{ //! \brief Returns the sequence generator of default value BaseObject *getSequence(void); + //! \brief Sets at once all the necessary fields to define the underlying sequence's attributes + void setIdSeqAttributes(QString minv, QString maxv, QString inc, QString start, QString cache, bool cycle); + + bool isIdSeqCycle(void); + QString getIdSeqMaxValue(void); + QString getIdSeqMinValue(void); + QString getIdSeqIncrement(void); + QString getIdSeqStart(void); + QString getIdSeqCache(void); + //! \brief Copies on column to other void operator = (Column &col); }; diff --git a/libpgmodeler/src/constraint.cpp b/libpgmodeler/src/constraint.cpp index 8bb2818b97..84c56b70eb 100644 --- a/libpgmodeler/src/constraint.cpp +++ b/libpgmodeler/src/constraint.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -21,33 +21,33 @@ Constraint::Constraint(void) { ref_table=nullptr; - obj_type=OBJ_CONSTRAINT; + obj_type=ObjectType::Constraint; deferrable=false; no_inherit=false; fill_factor=0; - index_type=BaseType::null; - - attributes[ParsersAttributes::PK_CONSTR]=QString(); - attributes[ParsersAttributes::FK_CONSTR]=QString(); - attributes[ParsersAttributes::CK_CONSTR]=QString(); - attributes[ParsersAttributes::UQ_CONSTR]=QString(); - attributes[ParsersAttributes::EX_CONSTR]=QString(); - attributes[ParsersAttributes::REF_TABLE]=QString(); - attributes[ParsersAttributes::SRC_COLUMNS]=QString(); - attributes[ParsersAttributes::DST_COLUMNS]=QString(); - attributes[ParsersAttributes::DEL_ACTION]=QString(); - attributes[ParsersAttributes::UPD_ACTION]=QString(); - attributes[ParsersAttributes::EXPRESSION]=QString(); - attributes[ParsersAttributes::TYPE]=QString(); - attributes[ParsersAttributes::COMPARISON_TYPE]=QString(); - attributes[ParsersAttributes::DEFER_TYPE]=QString(); - attributes[ParsersAttributes::INDEX_TYPE]=QString(); - attributes[ParsersAttributes::DEFERRABLE]=QString(); - attributes[ParsersAttributes::TABLE]=QString(); - attributes[ParsersAttributes::DECL_IN_TABLE]=QString(); - attributes[ParsersAttributes::FACTOR]=QString(); - attributes[ParsersAttributes::NO_INHERIT]=QString(); - attributes[ParsersAttributes::ELEMENTS]=QString(); + index_type=BaseType::Null; + + attributes[Attributes::PkConstr]=QString(); + attributes[Attributes::FkConstr]=QString(); + attributes[Attributes::CkConstr]=QString(); + attributes[Attributes::UqConstr]=QString(); + attributes[Attributes::ExConstr]=QString(); + attributes[Attributes::RefTable]=QString(); + attributes[Attributes::SrcColumns]=QString(); + attributes[Attributes::DstColumns]=QString(); + attributes[Attributes::DelAction]=QString(); + attributes[Attributes::UpdAction]=QString(); + attributes[Attributes::Expression]=QString(); + attributes[Attributes::Type]=QString(); + attributes[Attributes::ComparisonType]=QString(); + attributes[Attributes::DeferType]=QString(); + attributes[Attributes::IndexType]=QString(); + attributes[Attributes::Deferrable]=QString(); + attributes[Attributes::Table]=QString(); + attributes[Attributes::DeclInTable]=QString(); + attributes[Attributes::Factor]=QString(); + attributes[Attributes::NoInherit]=QString(); + attributes[Attributes::Elements]=QString(); } Constraint::~Constraint(void) @@ -63,7 +63,7 @@ void Constraint::setConstraintType(ConstraintType constr_type) void Constraint::setActionType(ActionType action_type, unsigned act_id) { - if(act_id==DELETE_ACTION) + if(act_id==DeleteAction) { setCodeInvalidated(this->del_action != action_type); this->del_action=action_type; @@ -88,10 +88,10 @@ bool Constraint::isColumnExists(Column *column, unsigned col_type) //Raises an error if the column is not allocated if(!column) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Gets the iterators from the specified internal list - if(col_type==SOURCE_COLS) + if(col_type==SourceCols) { itr=columns.begin(); itr_end=columns.end(); @@ -117,17 +117,17 @@ bool Constraint::isColumnReferenced(Column *column, bool search_only_ref_cols) bool found=false; vector::iterator itr, itr_end; - if(constr_type == ConstraintType::primary_key || - constr_type == ConstraintType::unique || - constr_type == ConstraintType::foreign_key) + if(constr_type == ConstraintType::PrimaryKey || + constr_type == ConstraintType::Unique || + constr_type == ConstraintType::ForeignKey) { if(!search_only_ref_cols) - found=isColumnExists(column, SOURCE_COLS); + found=isColumnExists(column, SourceCols); - if(!found && constr_type==ConstraintType::foreign_key) - found=isColumnExists(column, REFERENCED_COLS); + if(!found && constr_type==ConstraintType::ForeignKey) + found=isColumnExists(column, ReferencedCols); } - else if(constr_type==ConstraintType::exclude) + else if(constr_type==ConstraintType::Exclude) { //Iterates over the exclude elements itr=excl_elements.begin(); @@ -147,16 +147,16 @@ void Constraint::addColumn(Column *column, unsigned col_type) { //Raises an error if the column is not allocated if(!column) - throw Exception(Exception::getErrorMessage(ERR_ASG_NOT_ALOC_COLUMN) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgNotAllocatedColumn) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_CONSTRAINT)), - ERR_ASG_NOT_ALOC_COLUMN,__PRETTY_FUNCTION__,__FILE__,__LINE__); - else if(constr_type!=ConstraintType::check) + .arg(BaseObject::getTypeName(ObjectType::Constraint)), + ErrorCode::AsgNotAllocatedColumn,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(constr_type!=ConstraintType::Check) { //Adds the column only if the column doesn't exists on the internal list if(!isColumnExists(column,col_type)) { - if(col_type==REFERENCED_COLS) + if(col_type==ReferencedCols) ref_columns.push_back(column); else { @@ -174,15 +174,15 @@ void Constraint::setTablespace(BaseObject *tabspc) try { if(tabspc && - constr_type!=ConstraintType::primary_key && - constr_type!=ConstraintType::unique) - throw Exception(ERR_ASG_TABSPC_INV_CONSTR_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + constr_type!=ConstraintType::PrimaryKey && + constr_type!=ConstraintType::Unique) + throw Exception(ErrorCode::AsgTablespaceInvalidConstraintType,__PRETTY_FUNCTION__,__FILE__,__LINE__); BaseObject::setTablespace(tabspc); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -192,17 +192,17 @@ void Constraint::setColumnsAttribute(unsigned col_type, unsigned def_type, bool Column *col=nullptr; QString str_cols, attrib; unsigned i, count; - bool format=(def_type==SchemaParser::SQL_DEFINITION); + bool format=(def_type==SchemaParser::SqlDefinition); - if(col_type==REFERENCED_COLS) + if(col_type==ReferencedCols) { col_vector=&ref_columns; - attrib=ParsersAttributes::DST_COLUMNS; + attrib=Attributes::DstColumns; } else { col_vector=&columns; - attrib=ParsersAttributes::SRC_COLUMNS; + attrib=Attributes::SrcColumns; } count=col_vector->size(); @@ -214,8 +214,8 @@ void Constraint::setColumnsAttribute(unsigned col_type, unsigned def_type, bool through relationship can not be included because they are inserted to the restriction on the time of creation of the relationship from its XML so the parameter 'inc_addedbyrel' can be used to solve this case. */ - if((def_type==SchemaParser::SQL_DEFINITION) || - ((def_type==SchemaParser::XML_DEFINITION) && + if((def_type==SchemaParser::SqlDefinition) || + ((def_type==SchemaParser::XmlDefinition) && ((inc_addedbyrel && col->isAddedByRelationship()) || (inc_addedbyrel && !col->isAddedByRelationship()) || (!inc_addedbyrel && !col->isAddedByRelationship())))) @@ -273,10 +273,15 @@ ConstraintType Constraint::getConstraintType(void) ActionType Constraint::getActionType(unsigned act_id) { - if(act_id==DELETE_ACTION) + if(act_id==DeleteAction) return(del_action); else - return(upd_action); + return(upd_action); +} + +vector Constraint::getColumns(unsigned col_type) +{ + return(col_type==SourceCols ? columns : ref_columns); } QString Constraint::getExpression(void) @@ -288,11 +293,11 @@ Column *Constraint::getColumn(unsigned col_idx, unsigned col_type) { vector *col_list=nullptr; - col_list=(col_type==SOURCE_COLS ? &columns : &ref_columns); + col_list=(col_type==SourceCols ? &columns : &ref_columns); //Raises an error if the column index is invalid (out of bound) if(col_idx>=col_list->size()) - throw Exception(ERR_REF_COLUMN_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefColumnInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(col_list->at(col_idx)); } @@ -303,7 +308,7 @@ Column *Constraint::getColumn(const QString &name, unsigned col_type) vector *col_list=nullptr; vector::iterator itr_col, itr_end_col; - col_list=(col_type==SOURCE_COLS? &columns : &ref_columns); + col_list=(col_type==SourceCols? &columns : &ref_columns); itr_col=col_list->begin(); itr_end_col=col_list->end(); @@ -326,7 +331,7 @@ BaseTable *Constraint::getReferencedTable(void) unsigned Constraint::getColumnCount(unsigned col_type) { - if(col_type==REFERENCED_COLS) + if(col_type==ReferencedCols) return(ref_columns.size()); else return(columns.size()); @@ -347,7 +352,7 @@ void Constraint::removeColumn(const QString &name, unsigned col_type) Column *col=nullptr; //Gets the column list using the specified internal list type - if(col_type==REFERENCED_COLS) + if(col_type==ReferencedCols) cols=&ref_columns; else cols=&columns; @@ -362,7 +367,7 @@ void Constraint::removeColumn(const QString &name, unsigned col_type) //Case the column is found if(col->getName()==name) { - if(constr_type==ConstraintType::primary_key) + if(constr_type==ConstraintType::PrimaryKey) col->setNotNull(false); //Remove its iterator from the list @@ -494,16 +499,17 @@ void Constraint::addExcludeElements(vector &elems) catch(Exception &e) { excl_elements = elems_bkp; - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void Constraint::addExcludeElement(ExcludeElement elem) { if(getExcludeElementIndex(elem) >= 0) - throw Exception(ERR_INS_DUPLIC_ELEMENT,__PRETTY_FUNCTION__,__FILE__,__LINE__); - else if(elem.getExpression().isEmpty() && !elem.getColumn()) - throw Exception(ERR_ASG_INV_EXPR_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InsDuplicatedElement,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + if(elem.getExpression().isEmpty() && !elem.getColumn()) + throw Exception(ErrorCode::AsgInvalidExpressionObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); excl_elements.push_back(elem); setCodeInvalidated(true); @@ -517,25 +523,25 @@ void Constraint::addExcludeElement(const QString &expr, Operator *oper, Operator //Raises an error if the expression is empty if(expr.isEmpty()) - throw Exception(ERR_ASG_INV_EXPR_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidExpressionObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Configures the element elem.setExpression(expr); elem.setOperatorClass(op_class); elem.setOperator(oper); elem.setSortingEnabled(use_sorting); - elem.setSortingAttribute(ExcludeElement::NULLS_FIRST, nulls_first); - elem.setSortingAttribute(ExcludeElement::ASC_ORDER, asc_order); + elem.setSortingAttribute(ExcludeElement::NullsFirst, nulls_first); + elem.setSortingAttribute(ExcludeElement::AscOrder, asc_order); if(getExcludeElementIndex(elem) >= 0) - throw Exception(ERR_INS_DUPLIC_ELEMENT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InsDuplicatedElement,__PRETTY_FUNCTION__,__FILE__,__LINE__); excl_elements.push_back(elem); setCodeInvalidated(true); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -547,35 +553,35 @@ void Constraint::addExcludeElement(Column *column, Operator *oper, OperatorClass //Case the column is not allocated raises an error if(!column) - throw Exception(Exception::getErrorMessage(ERR_ASG_NOT_ALOC_COLUMN) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgNotAllocatedColumn) .arg(this->getName()) .arg(this->getTypeName()), - ERR_ASG_NOT_ALOC_COLUMN,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgNotAllocatedColumn,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Configures the element elem.setColumn(column); elem.setOperatorClass(op_class); elem.setOperator(oper); elem.setSortingEnabled(use_sorting); - elem.setSortingAttribute(ExcludeElement::NULLS_FIRST, nulls_first); - elem.setSortingAttribute(ExcludeElement::ASC_ORDER, asc_order); + elem.setSortingAttribute(ExcludeElement::NullsFirst, nulls_first); + elem.setSortingAttribute(ExcludeElement::AscOrder, asc_order); if(getExcludeElementIndex(elem) >= 0) - throw Exception(ERR_INS_DUPLIC_ELEMENT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InsDuplicatedElement,__PRETTY_FUNCTION__,__FILE__,__LINE__); excl_elements.push_back(elem); setCodeInvalidated(true); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void Constraint::removeExcludeElement(unsigned elem_idx) { if(elem_idx >= excl_elements.size()) - throw Exception(ERR_REF_ELEM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); excl_elements.erase(excl_elements.begin() + elem_idx); setCodeInvalidated(true); @@ -589,7 +595,7 @@ void Constraint::removeExcludeElements(void) void Constraint::setColumnsNotNull(bool value) { - if(constr_type==ConstraintType::primary_key) + if(constr_type==ConstraintType::PrimaryKey) { for(auto &col : columns) { @@ -602,7 +608,7 @@ void Constraint::setColumnsNotNull(bool value) ExcludeElement Constraint::getExcludeElement(unsigned elem_idx) { if(elem_idx >= excl_elements.size()) - throw Exception(ERR_REF_ELEM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(excl_elements[elem_idx]); } @@ -621,10 +627,10 @@ void Constraint::setExcludeElementsAttribute(unsigned def_type) for(i=0; i < count; i++) { str_elem+=excl_elements[i].getCodeDefinition(def_type); - if(i < (count-1) && def_type==SchemaParser::SQL_DEFINITION) str_elem+=','; + if(i < (count-1) && def_type==SchemaParser::SqlDefinition) str_elem+=','; } - attributes[ParsersAttributes::ELEMENTS]=str_elem; + attributes[Attributes::Elements]=str_elem; } void Constraint::setIndexType(IndexingType index_type) @@ -644,10 +650,10 @@ QString Constraint::getCodeDefinition(unsigned def_type) void Constraint::setDeclInTableAttribute(void) { - if(!isDeclaredInTable() || (constr_type==ConstraintType::foreign_key && !isAddedByLinking())) - attributes[ParsersAttributes::DECL_IN_TABLE]=QString(); - else if(!isReferRelationshipAddedColumn() || constr_type==ConstraintType::primary_key) - attributes[ParsersAttributes::DECL_IN_TABLE]=ParsersAttributes::_TRUE_; + if(!isDeclaredInTable() || (constr_type==ConstraintType::ForeignKey && !isAddedByLinking())) + attributes[Attributes::DeclInTable]=QString(); + else if(!isReferRelationshipAddedColumn() || constr_type==ConstraintType::PrimaryKey) + attributes[Attributes::DeclInTable]=Attributes::True; } QString Constraint::getCodeDefinition(unsigned def_type, bool inc_addedbyrel) @@ -657,41 +663,41 @@ QString Constraint::getCodeDefinition(unsigned def_type, bool inc_addedbyrel) QString attrib; - attributes[ParsersAttributes::PK_CONSTR]=QString(); - attributes[ParsersAttributes::FK_CONSTR]=QString(); - attributes[ParsersAttributes::CK_CONSTR]=QString(); - attributes[ParsersAttributes::UQ_CONSTR]=QString(); - attributes[ParsersAttributes::EX_CONSTR]=QString(); + attributes[Attributes::PkConstr]=QString(); + attributes[Attributes::FkConstr]=QString(); + attributes[Attributes::CkConstr]=QString(); + attributes[Attributes::UqConstr]=QString(); + attributes[Attributes::ExConstr]=QString(); switch(!constr_type) { - case ConstraintType::check: - attrib=ParsersAttributes::CK_CONSTR; + case ConstraintType::Check: + attrib=Attributes::CkConstr; break; - case ConstraintType::primary_key: - attrib=ParsersAttributes::PK_CONSTR; + case ConstraintType::PrimaryKey: + attrib=Attributes::PkConstr; break; - case ConstraintType::foreign_key: - attrib=ParsersAttributes::FK_CONSTR; + case ConstraintType::ForeignKey: + attrib=Attributes::FkConstr; break; - case ConstraintType::unique: - attrib=ParsersAttributes::UQ_CONSTR; + case ConstraintType::Unique: + attrib=Attributes::UqConstr; break; default: - attrib=ParsersAttributes::EX_CONSTR; + attrib=Attributes::ExConstr; break; } - attributes[attrib]=ParsersAttributes::_TRUE_; + attributes[attrib]=Attributes::True; - attributes[ParsersAttributes::TYPE]=attrib; - attributes[ParsersAttributes::UPD_ACTION]=(~upd_action); - attributes[ParsersAttributes::DEL_ACTION]=(~del_action); - attributes[ParsersAttributes::EXPRESSION]=expression; + attributes[Attributes::Type]=attrib; + attributes[Attributes::UpdAction]=(~upd_action); + attributes[Attributes::DelAction]=(~del_action); + attributes[Attributes::Expression]=expression; - if(constr_type!=ConstraintType::check) + if(constr_type!=ConstraintType::Check) { - if(constr_type!=ConstraintType::exclude) - setColumnsAttribute(SOURCE_COLS, def_type, inc_addedbyrel); + if(constr_type!=ConstraintType::Exclude) + setColumnsAttribute(SourceCols, def_type, inc_addedbyrel); else setExcludeElementsAttribute(def_type); @@ -700,26 +706,26 @@ QString Constraint::getCodeDefinition(unsigned def_type, bool inc_addedbyrel) this means the constraint is configured correctly, otherwise don't generates the attribute forcing the schema parser to return an error because the foreign key is misconfigured. */ - if(constr_type==ConstraintType::foreign_key && columns.size() == ref_columns.size()) - setColumnsAttribute(REFERENCED_COLS, def_type, inc_addedbyrel); + if(constr_type==ConstraintType::ForeignKey && columns.size() == ref_columns.size()) + setColumnsAttribute(ReferencedCols, def_type, inc_addedbyrel); } - attributes[ParsersAttributes::REF_TABLE]=(ref_table ? ref_table->getName(true) : QString()); - attributes[ParsersAttributes::DEFERRABLE]=(deferrable ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::NO_INHERIT]=(no_inherit ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::COMPARISON_TYPE]=(~match_type); - attributes[ParsersAttributes::DEFER_TYPE]=(~deferral_type); - attributes[ParsersAttributes::INDEX_TYPE]=(~ index_type); + attributes[Attributes::RefTable]=(ref_table ? ref_table->getName(true) : QString()); + attributes[Attributes::Deferrable]=(deferrable ? Attributes::True : QString()); + attributes[Attributes::NoInherit]=(no_inherit ? Attributes::True : QString()); + attributes[Attributes::ComparisonType]=(~match_type); + attributes[Attributes::DeferType]=(~deferral_type); + attributes[Attributes::IndexType]=(~ index_type); if(getParentTable()) - attributes[ParsersAttributes::TABLE]=getParentTable()->getName(true); + attributes[Attributes::Table]=getParentTable()->getName(true); setDeclInTableAttribute(); - if(fill_factor!=0 && (constr_type==ConstraintType::primary_key || constr_type==ConstraintType::unique)) - attributes[ParsersAttributes::FACTOR]=QString("%1").arg(fill_factor); + if(fill_factor!=0 && (constr_type==ConstraintType::PrimaryKey || constr_type==ConstraintType::Unique)) + attributes[Attributes::Factor]=QString("%1").arg(fill_factor); else - attributes[ParsersAttributes::FACTOR]=QString(); + attributes[Attributes::Factor]=QString(); return(BaseObject::__getCodeDefinition(def_type)); } @@ -741,18 +747,18 @@ QString Constraint::getSignature(bool format) bool Constraint::isCodeDiffersFrom(BaseObject *object, const vector &ignored_attribs, const vector &ignored_tags) { if(!object) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(object->getObjectType()!=this->getObjectType()) - throw Exception(ERR_OPR_OBJ_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { - return(BaseObject::isCodeDiffersFrom(this->getCodeDefinition(SchemaParser::XML_DEFINITION, true), - object->getCodeDefinition(SchemaParser::XML_DEFINITION, true), + return(BaseObject::isCodeDiffersFrom(this->getCodeDefinition(SchemaParser::XmlDefinition, true), + object->getCodeDefinition(SchemaParser::XmlDefinition, true), ignored_attribs, ignored_tags)); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler/src/constraint.h b/libpgmodeler/src/constraint.h index b0c335931b..da94135e3f 100644 --- a/libpgmodeler/src/constraint.h +++ b/libpgmodeler/src/constraint.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -86,14 +86,14 @@ class Constraint: public TableObject{ public: /*! \brief Access the source columns that means the columns that constrais is applied (from the constraint's parent table) */ - static const unsigned SOURCE_COLS=0, + static constexpr unsigned SourceCols=0, /*! \brief Access the referenced columns that means the columns from the referenced table primary key (only for foreign keys) */ - REFERENCED_COLS=1; + ReferencedCols=1; - static const unsigned DELETE_ACTION=0, - UPDATE_ACTION=1; + static constexpr unsigned DeleteAction=0, + UpdateAction=1; Constraint(void); ~Constraint(void); @@ -146,6 +146,9 @@ class Constraint: public TableObject{ //! \brief Retuns the action type (ON DELETE or ON UPDATE) of a foreign key ActionType getActionType(unsigned act_id); + //! \brief Returns the list of columns of the specified type SOURCE_COLS or REFERENCED_COLS + vector getColumns(unsigned col_type); + /*! \brief Returns one column (using its index) from the internal constraint column lists. Use the constants SOURCE_COLS or REFERENCED_COLS to access the lists */ Column *getColumn(unsigned col_idx, unsigned col_type); diff --git a/libpgmodeler/src/conversion.cpp b/libpgmodeler/src/conversion.cpp index 3b8d3bae95..352266a004 100644 --- a/libpgmodeler/src/conversion.cpp +++ b/libpgmodeler/src/conversion.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,50 +20,50 @@ Conversion::Conversion(void) { - obj_type=OBJ_CONVERSION; + obj_type=ObjectType::Conversion; conversion_func=nullptr; is_default=false; - attributes[ParsersAttributes::DEFAULT]=QString(); - attributes[ParsersAttributes::SRC_ENCODING]=QString(); - attributes[ParsersAttributes::DST_ENCODING]=QString(); - attributes[ParsersAttributes::FUNCTION]=QString(); + attributes[Attributes::Default]=QString(); + attributes[Attributes::SrcEncoding]=QString(); + attributes[Attributes::DstEncoding]=QString(); + attributes[Attributes::Function]=QString(); } void Conversion::setEncoding(unsigned encoding_idx, EncodingType encoding_type) { //Checks if the encoding index is valid - if(encoding_idx<=DST_ENCODING) + if(encoding_idx<=DstEncoding) { //If the passed enconding type is null an error is raised if((~encoding_type).isEmpty()) - throw Exception(Exception::getErrorMessage(ERR_ASG_NULL_TYPE_OBJECT) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgNullTypeObject) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_CONVERSION)), - ERR_ASG_NULL_TYPE_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Conversion)), + ErrorCode::AsgNullTypeObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Assigns the encoding to the conversion in the specified index this->encodings[encoding_idx]=encoding_type; } else //Raises an error if the encoding index is invalid - throw Exception(ERR_REF_TYPE_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefTypeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); } void Conversion::setConversionFunction(Function *conv_func) { //Raises an error in case the passed conversion function is null if(!conv_func) - throw Exception(Exception::getErrorMessage(ERR_ASG_NOT_ALOC_FUNCTION) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgNotAllocatedFunction) .arg(this->getName(true)) - .arg(BaseObject::getTypeName(OBJ_CONVERSION)), - ERR_ASG_NOT_ALOC_FUNCTION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Conversion)), + ErrorCode::AsgNotAllocatedFunction,__PRETTY_FUNCTION__,__FILE__,__LINE__); /* The conversion function must have 5 parameters if it's not the case raises an error. */ else if(conv_func->getParameterCount()!=5) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNC_INV_PARAM_COUNT) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidParamCount) .arg(this->getName(true)) - .arg(BaseObject::getTypeName(OBJ_CONVERSION)), - ERR_ASG_FUNC_INV_PARAM_COUNT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Conversion)), + ErrorCode::AsgFunctionInvalidParamCount,__PRETTY_FUNCTION__,__FILE__,__LINE__); /* Raises an error if the function parameters does not following the type order: interger, integer, cstring, internal, integer */ else if(conv_func->getParameter(0).getType()!=QString("integer") || @@ -71,16 +71,16 @@ void Conversion::setConversionFunction(Function *conv_func) conv_func->getParameter(2).getType()!=QString("cstring") || conv_func->getParameter(3).getType()!=QString("internal") || conv_func->getParameter(4).getType()!=QString("integer")) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNCTION_INV_PARAMS) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidParameters) .arg(this->getName(true)) - .arg(BaseObject::getTypeName(OBJ_CONVERSION)), - ERR_ASG_FUNCTION_INV_PARAMS,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Conversion)), + ErrorCode::AsgFunctionInvalidParameters,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the conversion function return type is not 'void' else if(conv_func->getReturnType()!=QString("void")) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNCTION_INV_RET_TYPE) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidReturnType) .arg(this->getName(true)) - .arg(BaseObject::getTypeName(OBJ_CONVERSION)), - ERR_ASG_FUNCTION_INV_RET_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Conversion)), + ErrorCode::AsgFunctionInvalidReturnType,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(conversion_func != conv_func); this->conversion_func=conv_func; @@ -94,8 +94,8 @@ void Conversion::setDefault(bool value) EncodingType Conversion::getEncoding(unsigned encoding_idx) { - if(encoding_idx > DST_ENCODING) - throw Exception(ERR_REF_TYPE_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(encoding_idx > DstEncoding) + throw Exception(ErrorCode::RefTypeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(this->encodings[encoding_idx]); } @@ -115,16 +115,16 @@ QString Conversion::getCodeDefinition(unsigned def_type) QString code_def=getCachedCode(def_type, false); if(!code_def.isEmpty()) return(code_def); - attributes[ParsersAttributes::DEFAULT]=(is_default ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::SRC_ENCODING]=(~encodings[SRC_ENCODING]); - attributes[ParsersAttributes::DST_ENCODING]=(~encodings[DST_ENCODING]); + attributes[Attributes::Default]=(is_default ? Attributes::True : QString()); + attributes[Attributes::SrcEncoding]=(~encodings[SrcEncoding]); + attributes[Attributes::DstEncoding]=(~encodings[DstEncoding]); if(conversion_func) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::FUNCTION]=conversion_func->getName(true); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Function]=conversion_func->getName(true); else - attributes[ParsersAttributes::FUNCTION]=conversion_func->getCodeDefinition(def_type, true); + attributes[Attributes::Function]=conversion_func->getCodeDefinition(def_type, true); } return(BaseObject::__getCodeDefinition(def_type)); diff --git a/libpgmodeler/src/conversion.h b/libpgmodeler/src/conversion.h index e67e2f7c4b..86bb1942fa 100644 --- a/libpgmodeler/src/conversion.h +++ b/libpgmodeler/src/conversion.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -45,8 +45,8 @@ class Conversion: public BaseObject { public: //! \brief Constants used to access the conversion encodings - static const unsigned SRC_ENCODING=0, - DST_ENCODING=1; + static constexpr unsigned SrcEncoding=0, + DstEncoding=1; Conversion(void); diff --git a/libpgmodeler/src/copyoptions.cpp b/libpgmodeler/src/copyoptions.cpp index cfb06271ac..349cb95a1d 100644 --- a/libpgmodeler/src/copyoptions.cpp +++ b/libpgmodeler/src/copyoptions.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -17,6 +17,7 @@ */ #include "copyoptions.h" +#include "baseobject.h" CopyOptions::CopyOptions(void) { @@ -25,8 +26,8 @@ CopyOptions::CopyOptions(void) CopyOptions::CopyOptions(unsigned copy_mode, unsigned copy_op_ids) { - if((copy_mode!=0 && copy_mode!=INCLUDING && copy_mode!=EXCLUDING) || copy_op_ids > ALL) - throw Exception(ERR_REF_INV_LIKE_OP_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if((copy_mode!=0 && copy_mode!=Including && copy_mode!=Excluding) || copy_op_ids > All) + throw Exception(ErrorCode::RefInvalidLikeOptionType,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->copy_mode = copy_mode; this->copy_op_ids = copy_op_ids; @@ -39,20 +40,20 @@ unsigned CopyOptions::getCopyMode(void) bool CopyOptions::isOptionSet(unsigned op) { - if(op > ALL) - throw Exception(ERR_REF_INV_LIKE_OP_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(op > All) + throw Exception(ErrorCode::RefInvalidLikeOptionType,__PRETTY_FUNCTION__,__FILE__,__LINE__); return((copy_op_ids & op) == op); } bool CopyOptions::isIncluding(void) { - return(copy_mode & INCLUDING); + return(copy_mode & Including); } bool CopyOptions::isExcluding(void) { - return(copy_mode & EXCLUDING); + return(copy_mode & Excluding); } unsigned CopyOptions::getCopyOptionsIds(void) @@ -64,11 +65,11 @@ QString CopyOptions::getSQLDefinition(void) { QString def, mode, op_name; unsigned op_id, - ids[]={ALL, DEFAULTS, CONSTRAINTS, - INDEXES, STORAGE, COMMENTS }, + ids[]={All, Defaults, Constraints, Indexes, + Storage, Comments, Identity, Statistics }, cnt = sizeof(ids) / sizeof(unsigned); - mode = (copy_mode == INCLUDING ? QString(" INCLUDING") : QString(" EXCLUDING")); + mode = (copy_mode == Including ? QString(" INCLUDING") : QString(" EXCLUDING")); if(copy_mode!=0 && copy_op_ids!=0) { for(unsigned i=0; i < cnt; i++) @@ -77,12 +78,14 @@ QString CopyOptions::getSQLDefinition(void) switch(op_id) { - case ALL: op_name=QString(" ALL"); break; - case DEFAULTS: op_name=QString(" DEFAULTS"); break; - case CONSTRAINTS: op_name=QString(" CONSTRAINTS"); break; - case INDEXES: op_name=QString(" INDEXES"); break; - case STORAGE: op_name=QString(" STORAGE"); break; - case COMMENTS: op_name=QString(" COMMENTS"); break; + case All: op_name=QString(" ALL"); break; + case Defaults: op_name=QString(" DEFAULTS"); break; + case Constraints: op_name=QString(" CONSTRAINTS"); break; + case Indexes: op_name=QString(" INDEXES"); break; + case Storage: op_name=QString(" STORAGE"); break; + case Comments: op_name=QString(" COMMENTS"); break; + case Identity: op_name=(BaseObject::getPgSQLVersion().toFloat() > PgSqlVersions::PgSqlVersion96.toFloat() ? QString(" IDENTITY") : QString()); break; + case Statistics: op_name=(BaseObject::getPgSQLVersion().toFloat() > PgSqlVersions::PgSqlVersion96.toFloat() ? QString(" STATISTICS") : QString()); break; } if(!op_name.isEmpty()) @@ -91,7 +94,7 @@ QString CopyOptions::getSQLDefinition(void) op_name.clear(); } - if(op_id==ALL) break; + if(op_id==All) break; } } diff --git a/libpgmodeler/src/copyoptions.h b/libpgmodeler/src/copyoptions.h index 16107d8072..26bcc5d7ab 100644 --- a/libpgmodeler/src/copyoptions.h +++ b/libpgmodeler/src/copyoptions.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -33,14 +33,16 @@ class CopyOptions { unsigned copy_mode, copy_op_ids; public: - static const unsigned DEFAULTS=1, - CONSTRAINTS=2, - INDEXES=4, - STORAGE=8, - COMMENTS=16, - ALL=31, - INCLUDING=64, - EXCLUDING=128; + static constexpr unsigned Defaults=1, + Constraints=2, + Indexes=4, + Storage=8, + Comments=16, + Identity=32, + Statistics=64, + All=127, + Including=256, + Excluding=512; CopyOptions(void); CopyOptions(unsigned copy_mode, unsigned copy_op_ids); diff --git a/libpgmodeler/src/databasemodel.cpp b/libpgmodeler/src/databasemodel.cpp index 201a197e27..9cf98c4a5a 100644 --- a/libpgmodeler/src/databasemodel.cpp +++ b/libpgmodeler/src/databasemodel.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -25,31 +25,62 @@ DatabaseModel::DatabaseModel(void) { this->model_wgt=nullptr; object_id=DatabaseModel::dbmodel_id++; - obj_type=OBJ_DATABASE; + obj_type=ObjectType::Database; is_template = false; allow_conns = true; - encoding=BaseType::null; + encoding=BaseType::Null; BaseObject::setName(QObject::trUtf8("new_database").toUtf8()); - default_objs[OBJ_SCHEMA]=nullptr; - default_objs[OBJ_ROLE]=nullptr; - default_objs[OBJ_TABLESPACE]=nullptr; - default_objs[OBJ_COLLATION]=nullptr; + default_objs[ObjectType::Schema]=nullptr; + default_objs[ObjectType::Role]=nullptr; + default_objs[ObjectType::Tablespace]=nullptr; + default_objs[ObjectType::Collation]=nullptr; conn_limit=-1; last_zoom=1; loading_model=invalidated=append_at_eod=prepend_at_bod=false; - attributes[ParsersAttributes::ENCODING]=QString(); - attributes[ParsersAttributes::TEMPLATE_DB]=QString(); - attributes[ParsersAttributes::CONN_LIMIT]=QString(); - attributes[ParsersAttributes::_LC_COLLATE_]=QString(); - attributes[ParsersAttributes::_LC_CTYPE_]=QString(); - attributes[ParsersAttributes::APPEND_AT_EOD]=QString(); - attributes[ParsersAttributes::PREPEND_AT_BOD]=QString(); - attributes[ParsersAttributes::ALLOW_CONNS]=QString(); - attributes[ParsersAttributes::IS_TEMPLATE]=QString(); + attributes[Attributes::Encoding]=QString(); + attributes[Attributes::TemplateDb]=QString(); + attributes[Attributes::ConnLimit]=QString(); + attributes[Attributes::LcCollate]=QString(); + attributes[Attributes::LcCtype]=QString(); + attributes[Attributes::AppendAtEod]=QString(); + attributes[Attributes::PrependAtBod]=QString(); + attributes[Attributes::AllowConns]=QString(); + attributes[Attributes::IsTemplate]=QString(); + + obj_lists = { + { ObjectType::Textbox, &textboxes }, + { ObjectType::Table, &tables }, + { ObjectType::Function, &functions }, + { ObjectType::Aggregate, &aggregates }, + { ObjectType::Schema, &schemas }, + { ObjectType::View, &views }, + { ObjectType::Type, &types }, + { ObjectType::Role, &roles }, + { ObjectType::Tablespace, &tablespaces }, + { ObjectType::Language, &languages }, + { ObjectType::Cast, &casts }, + { ObjectType::Conversion, &conversions }, + { ObjectType::Operator, &operators }, + { ObjectType::OpClass, &op_classes }, + { ObjectType::OpFamily, &op_families }, + { ObjectType::Domain, &domains }, + { ObjectType::Sequence, &sequences }, + { ObjectType::BaseRelationship, &base_relationships }, + { ObjectType::Relationship, &relationships }, + { ObjectType::Permission, &permissions }, + { ObjectType::Collation, &collations }, + { ObjectType::Extension, &extensions }, + { ObjectType::Tag, &tags }, + { ObjectType::EventTrigger, &eventtriggers }, + { ObjectType::GenericSql, &genericsqls }, + { ObjectType::ForeignDataWrapper, &fdata_wrappers }, + { ObjectType::ForeignServer, &foreign_servers }, + { ObjectType::UserMapping, &usermappings } + }; } DatabaseModel::DatabaseModel(ModelWidget *model_wgt):DatabaseModel() @@ -75,8 +106,8 @@ void DatabaseModel::setEncoding(EncodingType encod) void DatabaseModel::setLocalization(unsigned localiz_id, const QString &value) { - if(localiz_id > Collation::_LC_COLLATE) - throw Exception(ERR_REF_ELEM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(localiz_id > Collation::LcCollate) + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); localizations[localiz_id]=value; } @@ -90,7 +121,7 @@ void DatabaseModel::setConnectionLimit(int conn_lim) void DatabaseModel::setTemplateDB(const QString &temp_db) { if(!temp_db.isEmpty() && !BaseObject::isValidName(temp_db)) - throw Exception(ERR_ASG_INV_NAME_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidNameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->template_db=temp_db; } @@ -102,124 +133,81 @@ void DatabaseModel::setAuthor(const QString &author) vector *DatabaseModel::getObjectList(ObjectType obj_type) { - if(obj_type==OBJ_TEXTBOX) - return(&textboxes); - else if(obj_type==OBJ_TABLE) - return(&tables); - else if(obj_type==OBJ_FUNCTION) - return(&functions); - else if(obj_type==OBJ_AGGREGATE) - return(&aggregates); - else if(obj_type==OBJ_SCHEMA) - return(&schemas); - else if(obj_type==OBJ_VIEW) - return(&views); - else if(obj_type==OBJ_TYPE) - return(&types); - else if(obj_type==OBJ_ROLE) - return(&roles); - else if(obj_type==OBJ_TABLESPACE) - return(&tablespaces); - else if(obj_type==OBJ_LANGUAGE) - return(&languages); - else if(obj_type==OBJ_CAST) - return(&casts); - else if(obj_type==OBJ_CONVERSION) - return(&conversions); - else if(obj_type==OBJ_OPERATOR) - return(&operators); - else if(obj_type==OBJ_OPCLASS) - return(&op_classes); - else if(obj_type==OBJ_OPFAMILY) - return(&op_families); - else if(obj_type==OBJ_DOMAIN) - return(&domains); - else if(obj_type==OBJ_SEQUENCE) - return(&sequences); - else if(obj_type==BASE_RELATIONSHIP) - return(&base_relationships); - else if(obj_type==OBJ_RELATIONSHIP) - return(&relationships); - else if(obj_type==OBJ_PERMISSION) - return(&permissions); - else if(obj_type==OBJ_COLLATION) - return(&collations); - else if(obj_type==OBJ_EXTENSION) - return(&extensions); - else if(obj_type==OBJ_TAG) - return(&tags); - else if(obj_type==OBJ_EVENT_TRIGGER) - return(&eventtriggers); - else if(obj_type==OBJ_GENERIC_SQL) - return(&genericsqls); - else + if(obj_lists.count(obj_type) == 0) return(nullptr); + + return(obj_lists[obj_type]); } void DatabaseModel::addObject(BaseObject *object, int obj_idx) { ObjectType obj_type; - if(object) + if(!object) + return; + + try { - try - { - obj_type=object->getObjectType(); + obj_type=object->getObjectType(); - if(obj_type==OBJ_RELATIONSHIP || - obj_type==BASE_RELATIONSHIP) - addRelationship(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_TEXTBOX) - addTextbox(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_TABLE) - addTable(dynamic_cast
(object), obj_idx); - else if(obj_type==OBJ_FUNCTION) - addFunction(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_AGGREGATE) - addAggregate(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_SCHEMA) - addSchema(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_VIEW) - addView(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_TYPE) - addType(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_ROLE) - addRole(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_TABLESPACE) - addTablespace(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_LANGUAGE) - addLanguage(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_CAST) - addCast(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_CONVERSION) - addConversion(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_OPERATOR) - addOperator(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_OPCLASS) - addOperatorClass(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_OPFAMILY) - addOperatorFamily(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_DOMAIN) - addDomain(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_SEQUENCE) - addSequence(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_COLLATION) - addCollation(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_EXTENSION) - addExtension(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_TAG) - addTag(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_PERMISSION) - addPermission(dynamic_cast(object)); - else if(obj_type==OBJ_EVENT_TRIGGER) - addEventTrigger(dynamic_cast(object)); - else if(obj_type==OBJ_GENERIC_SQL) - addGenericSQL(dynamic_cast(object)); - } - catch(Exception &e) - { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); - } + if(obj_type==ObjectType::Relationship || obj_type==ObjectType::BaseRelationship) + addRelationship(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Textbox) + addTextbox(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Table) + addTable(dynamic_cast
(object), obj_idx); + else if(obj_type==ObjectType::Function) + addFunction(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Aggregate) + addAggregate(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Schema) + addSchema(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::View) + addView(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Type) + addType(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Role) + addRole(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Tablespace) + addTablespace(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Language) + addLanguage(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Cast) + addCast(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Conversion) + addConversion(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Operator) + addOperator(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::OpClass) + addOperatorClass(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::OpFamily) + addOperatorFamily(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Domain) + addDomain(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Sequence) + addSequence(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Collation) + addCollation(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Extension) + addExtension(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Tag) + addTag(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Permission) + addPermission(dynamic_cast(object)); + else if(obj_type==ObjectType::EventTrigger) + addEventTrigger(dynamic_cast(object)); + else if(obj_type==ObjectType::GenericSql) + addGenericSQL(dynamic_cast(object)); + else if(obj_type==ObjectType::ForeignDataWrapper) + addForeignDataWrapper(dynamic_cast(object)); + else if(obj_type==ObjectType::ForeignServer) + addForeignServer(dynamic_cast(object)); + else if(obj_type==ObjectType::UserMapping) + addUserMapping(dynamic_cast(object)); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -227,132 +215,137 @@ void DatabaseModel::removeObject(BaseObject *object, int obj_idx) { ObjectType obj_type; + if(!object) + return; - if(object) - { - try - { - obj_type=object->getObjectType(); - - if(obj_type==OBJ_RELATIONSHIP || - obj_type==BASE_RELATIONSHIP) - removeRelationship(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_TEXTBOX) - removeTextbox(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_TABLE) - removeTable(dynamic_cast
(object), obj_idx); - else if(obj_type==OBJ_FUNCTION) - removeFunction(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_AGGREGATE) - removeAggregate(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_SCHEMA) - removeSchema(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_VIEW) - removeView(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_TYPE) - removeType(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_ROLE) - removeRole(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_TABLESPACE) - removeTablespace(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_LANGUAGE) - removeLanguage(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_CAST) - removeCast(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_CONVERSION) - removeConversion(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_OPERATOR) - removeOperator(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_OPCLASS) - removeOperatorClass(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_OPFAMILY) - removeOperatorFamily(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_DOMAIN) - removeDomain(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_SEQUENCE) - removeSequence(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_COLLATION) - removeCollation(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_EXTENSION) - removeExtension(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_TAG) - removeTag(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_PERMISSION) - removePermission(dynamic_cast(object)); - else if(obj_type==OBJ_EVENT_TRIGGER) - removeEventTrigger(dynamic_cast(object)); - else if(obj_type==OBJ_GENERIC_SQL) - removeGenericSQL(dynamic_cast(object)); - } - catch(Exception &e) - { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); - } - } -} - -void DatabaseModel::removeObject(unsigned obj_idx, ObjectType obj_type) -{ - if(TableObject::isTableObject(obj_type) || - obj_type==BASE_OBJECT || obj_type==BASE_RELATIONSHIP || - obj_type==OBJ_DATABASE) - throw Exception(ERR_REM_OBJ_INVALID_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); - - else + try { - vector *obj_list=nullptr; - BaseObject *object=nullptr; - - obj_list=getObjectList(obj_type); - if(obj_idx >= obj_list->size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + obj_type=object->getObjectType(); - object=(*obj_list)[obj_idx]; - if(obj_type==OBJ_TEXTBOX) + if(obj_type==ObjectType::Relationship || obj_type==ObjectType::BaseRelationship) + removeRelationship(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Textbox) removeTextbox(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_TABLE) + else if(obj_type==ObjectType::Table) removeTable(dynamic_cast
(object), obj_idx); - else if(obj_type==OBJ_FUNCTION) + else if(obj_type==ObjectType::Function) removeFunction(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_AGGREGATE) + else if(obj_type==ObjectType::Aggregate) removeAggregate(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_SCHEMA) + else if(obj_type==ObjectType::Schema) removeSchema(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_VIEW) + else if(obj_type==ObjectType::View) removeView(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_TYPE) + else if(obj_type==ObjectType::Type) removeType(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_ROLE) + else if(obj_type==ObjectType::Role) removeRole(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_TABLESPACE) + else if(obj_type==ObjectType::Tablespace) removeTablespace(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_LANGUAGE) + else if(obj_type==ObjectType::Language) removeLanguage(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_CAST) + else if(obj_type==ObjectType::Cast) removeCast(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_CONVERSION) + else if(obj_type==ObjectType::Conversion) removeConversion(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_OPERATOR) + else if(obj_type==ObjectType::Operator) removeOperator(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_OPCLASS) + else if(obj_type==ObjectType::OpClass) removeOperatorClass(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_OPFAMILY) + else if(obj_type==ObjectType::OpFamily) removeOperatorFamily(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_DOMAIN) + else if(obj_type==ObjectType::Domain) removeDomain(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_SEQUENCE) + else if(obj_type==ObjectType::Sequence) removeSequence(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_COLLATION) + else if(obj_type==ObjectType::Collation) removeCollation(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_RELATIONSHIP || obj_type==BASE_RELATIONSHIP) - removeRelationship(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_PERMISSION) + else if(obj_type==ObjectType::Extension) + removeExtension(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Tag) + removeTag(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Permission) removePermission(dynamic_cast(object)); - else if(obj_type==OBJ_EVENT_TRIGGER) - removeEventTrigger(dynamic_cast(object), obj_idx); - else if(obj_type==OBJ_GENERIC_SQL) - removeGenericSQL(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::EventTrigger) + removeEventTrigger(dynamic_cast(object)); + else if(obj_type==ObjectType::GenericSql) + removeGenericSQL(dynamic_cast(object)); + else if(obj_type==ObjectType::ForeignDataWrapper) + removeForeignDataWrapper(dynamic_cast(object)); + else if(obj_type==ObjectType::ForeignServer) + removeForeignServer(dynamic_cast(object)); + else if(obj_type==ObjectType::UserMapping) + removeUserMapping(dynamic_cast(object)); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } + +} + +void DatabaseModel::removeObject(unsigned obj_idx, ObjectType obj_type) +{ + if(TableObject::isTableObject(obj_type) || + obj_type==ObjectType::BaseObject || obj_type==ObjectType::BaseRelationship || + obj_type==ObjectType::Database) + throw Exception(ErrorCode::RemObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + vector *obj_list=nullptr; + BaseObject *object=nullptr; + + obj_list=getObjectList(obj_type); + if(obj_idx >= obj_list->size()) + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + object=(*obj_list)[obj_idx]; + if(obj_type==ObjectType::Textbox) + removeTextbox(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Table) + removeTable(dynamic_cast
(object), obj_idx); + else if(obj_type==ObjectType::Function) + removeFunction(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Aggregate) + removeAggregate(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Schema) + removeSchema(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::View) + removeView(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Type) + removeType(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Role) + removeRole(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Tablespace) + removeTablespace(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Language) + removeLanguage(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Cast) + removeCast(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Conversion) + removeConversion(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Operator) + removeOperator(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::OpClass) + removeOperatorClass(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::OpFamily) + removeOperatorFamily(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Domain) + removeDomain(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Sequence) + removeSequence(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Collation) + removeCollation(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Relationship || obj_type==ObjectType::BaseRelationship) + removeRelationship(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::Permission) + removePermission(dynamic_cast(object)); + else if(obj_type==ObjectType::EventTrigger) + removeEventTrigger(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::GenericSql) + removeGenericSQL(dynamic_cast(object), obj_idx); + else if(obj_type==ObjectType::ForeignDataWrapper) + removeForeignDataWrapper(dynamic_cast(object), obj_idx); + } void DatabaseModel::__addObject(BaseObject *object, int obj_idx) @@ -363,7 +356,7 @@ void DatabaseModel::__addObject(BaseObject *object, int obj_idx) vector::iterator itr, itr_end; if(!object) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); obj_type=object->getObjectType(); @@ -371,15 +364,15 @@ void DatabaseModel::__addObject(BaseObject *object, int obj_idx) #ifdef DEMO_VERSION #warning "DEMO VERSION: database model object creation limit." obj_list=getObjectList(obj_type); - if(obj_list && obj_list->size() >= GlobalAttributes::MAX_OBJECT_COUNT) + if(obj_list && obj_list->size() >= GlobalAttributes::MaxObjectCount) throw Exception(trUtf8("The demonstration version can create only `%1' instances of each object type! You've reach this limit for the type: `%2'") - .arg(GlobalAttributes::MAX_OBJECT_COUNT) + .arg(GlobalAttributes::MaxObjectCount) .arg(BaseObject::getTypeName(obj_type)), - ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); #endif - if(obj_type==OBJ_TABLESPACE) + if(obj_type==ObjectType::Tablespace) { Tablespace *tabspc=nullptr, *aux_tabspc=nullptr; @@ -396,10 +389,10 @@ void DatabaseModel::__addObject(BaseObject *object, int obj_idx) there is some other tablespace pointing to the same directory */ if(tabspc->getDirectory()==aux_tabspc->getDirectory()) { - throw Exception(Exception::getErrorMessage(ERR_ASG_DUP_TABLESPACE_DIR) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgTablespaceDuplicatedDirectory) .arg(tabspc->getName()) .arg(aux_tabspc->getName()), - ERR_ASG_DUP_TABLESPACE_DIR,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgTablespaceDuplicatedDirectory,__PRETTY_FUNCTION__,__FILE__,__LINE__); } itr++; @@ -409,34 +402,34 @@ void DatabaseModel::__addObject(BaseObject *object, int obj_idx) /* Raises an error if there is an object with the same name. Special cases are for: functions/operator that are search by signature and views that are search on tables and views list */ - if((obj_type==OBJ_VIEW && (getObject(object->getName(true), obj_type, idx) || - getObject(object->getName(true), OBJ_TABLE, idx))) || - (obj_type==OBJ_TABLE && (getObject(object->getName(true), obj_type, idx) || - getObject(object->getName(true), OBJ_VIEW, idx))) || - (obj_type==OBJ_EXTENSION && (getObject(object->getName(false), obj_type, idx))) || + if((obj_type==ObjectType::View && (getObject(object->getName(true), obj_type, idx) || + getObject(object->getName(true), ObjectType::Table, idx))) || + (obj_type==ObjectType::Table && (getObject(object->getName(true), obj_type, idx) || + getObject(object->getName(true), ObjectType::View, idx))) || + (obj_type==ObjectType::Extension && (getObject(object->getName(false), obj_type, idx))) || (getObject(object->getSignature(), obj_type, idx))) { QString str_aux; - str_aux=QString(Exception::getErrorMessage(ERR_ASG_DUPLIC_OBJECT)) - .arg(object->getName(obj_type != OBJ_EXTENSION)) + str_aux=Exception::getErrorMessage(ErrorCode::AsgDuplicatedObject) + .arg(object->getName(obj_type != ObjectType::Extension)) .arg(object->getTypeName()) .arg(this->getName(true)) .arg(this->getTypeName()); - throw Exception(str_aux,ERR_ASG_DUPLIC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(str_aux,ErrorCode::AsgDuplicatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); } try { - if(obj_type==OBJ_TEXTBOX || obj_type==BASE_RELATIONSHIP) - object->getCodeDefinition(SchemaParser::XML_DEFINITION); + if(obj_type==ObjectType::Textbox || obj_type==ObjectType::BaseRelationship) + object->getCodeDefinition(SchemaParser::XmlDefinition); else - object->getCodeDefinition(SchemaParser::SQL_DEFINITION); + object->getCodeDefinition(SchemaParser::SqlDefinition); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } obj_list=getObjectList(object->getObjectType()); @@ -464,7 +457,7 @@ void DatabaseModel::__addObject(BaseObject *object, int obj_idx) void DatabaseModel::__removeObject(BaseObject *object, int obj_idx, bool check_refs) { if(!object) - throw Exception(ERR_REM_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RemNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { vector *obj_list=nullptr; @@ -474,7 +467,7 @@ void DatabaseModel::__removeObject(BaseObject *object, int obj_idx, bool check_r obj_list=getObjectList(obj_type); if(!obj_list) - throw Exception(ERR_OBT_OBJ_INVALID_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::ObtObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { vector refs; @@ -486,32 +479,32 @@ void DatabaseModel::__removeObject(BaseObject *object, int obj_idx, bool check_r //If there are objects referencing the table if(!refs.empty()) { - ErrorType err_type; + ErrorCode err_code; //Raises an error indicating the object that is referencing the table if(!dynamic_cast(refs[0])) { - err_type=ERR_REM_DIRECT_REFERENCE; - throw Exception(QString(Exception::getErrorMessage(err_type)) + err_code=ErrorCode::RemDirectReference; + throw Exception(Exception::getErrorMessage(err_code) .arg(object->getName(true)) .arg(object->getTypeName()) .arg(refs[0]->getName(true)) .arg(refs[0]->getTypeName()), - err_type,__PRETTY_FUNCTION__,__FILE__,__LINE__); + err_code,__PRETTY_FUNCTION__,__FILE__,__LINE__); } else { BaseObject *ref_obj_parent=dynamic_cast(refs[0])->getParentTable(); - err_type=ERR_REM_INDIRECT_REFERENCE; - throw Exception(QString(Exception::getErrorMessage(err_type)) + err_code=ErrorCode::RemInderectReference; + throw Exception(Exception::getErrorMessage(err_code) .arg(object->getName(true)) .arg(object->getTypeName()) .arg(refs[0]->getName(true)) .arg(refs[0]->getTypeName()) .arg(ref_obj_parent->getName(true)) .arg(ref_obj_parent->getTypeName()), - err_type,__PRETTY_FUNCTION__,__FILE__,__LINE__); + err_code,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } @@ -520,7 +513,7 @@ void DatabaseModel::__removeObject(BaseObject *object, int obj_idx, bool check_r if(obj_idx >= 0) { - if(Permission::objectAcceptsPermission(obj_type)) + if(Permission::acceptsPermission(obj_type)) removePermissions(object); obj_list->erase(obj_list->begin() + obj_idx); @@ -541,7 +534,7 @@ vector DatabaseModel::getObjects(ObjectType obj_type, BaseObject * obj_list=getObjectList(obj_type); if(!obj_list) - throw Exception(ERR_OBT_OBJ_INVALID_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::ObtObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); itr=obj_list->begin(); itr_end=obj_list->end(); @@ -551,8 +544,8 @@ vector DatabaseModel::getObjects(ObjectType obj_type, BaseObject * rel=dynamic_cast(*itr); if((!rel && (*itr)->getSchema()==schema) || - (rel && (rel->getTable(BaseRelationship::SRC_TABLE)->getSchema()==schema || - rel->getTable(BaseRelationship::DST_TABLE)->getSchema()==schema))) + (rel && (rel->getTable(BaseRelationship::SrcTable)->getSchema()==schema || + rel->getTable(BaseRelationship::DstTable)->getSchema()==schema))) sel_list.push_back(*itr); itr++; @@ -565,9 +558,9 @@ vector DatabaseModel::getObjects(BaseObject *schema) { vector *obj_list=nullptr, sel_list; vector::iterator itr, itr_end; - ObjectType types[]={ OBJ_FUNCTION, OBJ_TABLE, OBJ_VIEW, OBJ_DOMAIN, - OBJ_AGGREGATE, OBJ_OPERATOR, OBJ_SEQUENCE, OBJ_CONVERSION, - OBJ_TYPE, OBJ_OPCLASS, OBJ_OPFAMILY, OBJ_COLLATION }; + ObjectType types[]={ ObjectType::Function, ObjectType::Table, ObjectType::View, ObjectType::Domain, + ObjectType::Aggregate, ObjectType::Operator, ObjectType::Sequence, ObjectType::Conversion, + ObjectType::Type, ObjectType::OpClass, ObjectType::OpFamily, ObjectType::Collation }; unsigned i, count=sizeof(types)/sizeof(ObjectType); for(i=0; i < count; i++) @@ -598,7 +591,7 @@ BaseObject *DatabaseModel::getObject(const QString &name, ObjectType obj_type, i obj_list=getObjectList(obj_type); if(!obj_list) - throw Exception(ERR_OBT_OBJ_INVALID_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::ObtObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { QString signature; @@ -618,7 +611,7 @@ BaseObject *DatabaseModel::getObject(const QString &name, ObjectType obj_type, i if(found) { object=(*itr); - obj_idx=(itr-obj_list->begin()); + obj_idx=(itr - obj_list->begin()); } else obj_idx=-1; } @@ -633,9 +626,9 @@ BaseObject *DatabaseModel::getObject(unsigned obj_idx, ObjectType obj_type) obj_list=getObjectList(obj_type); if(!obj_list) - throw Exception(ERR_OBT_OBJ_INVALID_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::ObtObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(obj_idx >= obj_list->size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); else return(obj_list->at(obj_idx)); } @@ -647,20 +640,28 @@ unsigned DatabaseModel::getObjectCount(ObjectType obj_type) obj_list=getObjectList(obj_type); if(!obj_list) - throw Exception(ERR_OBT_OBJ_INVALID_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::ObtObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); else - return(obj_list->size()); + return(obj_list->size()); +} + +unsigned DatabaseModel::getMaxObjectCount(void) +{ + vector types = getObjectTypes(false, {ObjectType::Database}); + unsigned count = 0, max = 0; + + for(auto &type : types) + { + count = getObjectList(type)->size(); + if(count > max) max = count; + } + + return(max); } unsigned DatabaseModel::getObjectCount(void) { - vector types={ - BASE_RELATIONSHIP,OBJ_RELATIONSHIP, OBJ_TABLE, OBJ_VIEW, - OBJ_AGGREGATE, OBJ_OPERATOR, OBJ_SEQUENCE, OBJ_CONVERSION, - OBJ_CAST, OBJ_OPFAMILY, OBJ_OPCLASS, OBJ_TEXTBOX, OBJ_DOMAIN, - OBJ_TYPE, OBJ_FUNCTION, OBJ_SCHEMA, OBJ_LANGUAGE, OBJ_TABLESPACE, - OBJ_ROLE, OBJ_PERMISSION, OBJ_COLLATION, OBJ_EXTENSION, OBJ_TAG, - OBJ_EVENT_TRIGGER, OBJ_GENERIC_SQL}; + vector types= getObjectTypes(false, {ObjectType::Database}); unsigned count=0; for(auto &type : types) @@ -671,8 +672,8 @@ unsigned DatabaseModel::getObjectCount(void) QString DatabaseModel::getLocalization(unsigned localiz_id) { - if(localiz_id > Collation::_LC_COLLATE) - throw Exception(ERR_REF_ELEM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(localiz_id > Collation::LcCollate) + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(localizations[localiz_id]); } @@ -695,7 +696,7 @@ EncodingType DatabaseModel::getEncoding(void) BaseObject *DatabaseModel::getDefaultObject(ObjectType obj_type) { if(default_objs.count(obj_type)==0) - throw Exception(ERR_REF_OBJ_INV_TYPE, __PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidType, __PRETTY_FUNCTION__,__FILE__,__LINE__); return(default_objs[obj_type]); } @@ -708,14 +709,14 @@ QString DatabaseModel::getAuthor(void) void DatabaseModel::setProtected(bool value) { vector types = { - BASE_RELATIONSHIP,OBJ_RELATIONSHIP, OBJ_TABLE, OBJ_VIEW, - OBJ_AGGREGATE, OBJ_OPERATOR, - OBJ_SEQUENCE, OBJ_CONVERSION, - OBJ_CAST, OBJ_OPFAMILY, OBJ_OPCLASS, - BASE_RELATIONSHIP, OBJ_TEXTBOX, - OBJ_DOMAIN, OBJ_TYPE, OBJ_FUNCTION, - OBJ_LANGUAGE, OBJ_TABLESPACE, OBJ_ROLE, OBJ_COLLATION, - OBJ_EXTENSION, OBJ_SCHEMA, OBJ_PERMISSION, OBJ_TAG, OBJ_GENERIC_SQL + ObjectType::BaseRelationship,ObjectType::Relationship, ObjectType::Table, ObjectType::View, + ObjectType::Aggregate, ObjectType::Operator, + ObjectType::Sequence, ObjectType::Conversion, + ObjectType::Cast, ObjectType::OpFamily, ObjectType::OpClass, + ObjectType::BaseRelationship, ObjectType::Textbox, + ObjectType::Domain, ObjectType::Type, ObjectType::Function, + ObjectType::Language, ObjectType::Tablespace, ObjectType::Role, ObjectType::Collation, + ObjectType::Extension, ObjectType::Schema, ObjectType::Permission, ObjectType::Tag, ObjectType::GenericSql }; for(auto &type : types) @@ -731,60 +732,91 @@ void DatabaseModel::setProtected(bool value) void DatabaseModel::destroyObjects(void) { - ObjectType types[]={ - BASE_RELATIONSHIP,OBJ_RELATIONSHIP, OBJ_TABLE, OBJ_VIEW, - OBJ_AGGREGATE, OBJ_OPERATOR, - OBJ_SEQUENCE, OBJ_CONVERSION, - OBJ_CAST, OBJ_OPFAMILY, OBJ_OPCLASS, - BASE_RELATIONSHIP, OBJ_TEXTBOX, - OBJ_DOMAIN, OBJ_TYPE, OBJ_FUNCTION, - OBJ_LANGUAGE, OBJ_TABLESPACE, OBJ_ROLE, OBJ_COLLATION, - OBJ_EXTENSION, OBJ_SCHEMA, OBJ_PERMISSION, OBJ_TAG, OBJ_GENERIC_SQL }; - - ObjectType graph_types[]={ OBJ_SCHEMA, BASE_RELATIONSHIP, OBJ_RELATIONSHIP, OBJ_TABLE, OBJ_VIEW }; - vector *list=nullptr; + ObjectType graph_types[]={ ObjectType::Schema, ObjectType::BaseRelationship, ObjectType::Relationship, ObjectType::Table, ObjectType::View }; BaseObject *object=nullptr; - unsigned i, cnt=sizeof(types)/sizeof(ObjectType); + map objects; + map::reverse_iterator ritr, ritr_end; + vector rem_obj_types; + BaseGraphicObject *graph_obj = nullptr; //Blocking signals of all graphical objects to avoid uneeded updates in the destruction this->blockSignals(true); - for(i=0; i < 5; i++) + for(unsigned i=0; i < 5; i++) { for(auto &object : *this->getObjectList(graph_types[i])) - dynamic_cast(object)->blockSignals(true); + { + graph_obj = dynamic_cast(object); + + if(graph_obj) + dynamic_cast(object)->blockSignals(true); + } + } + + try + { + //Removing the special objects first + storeSpecialObjectsXML(); + disconnectRelationships(); + } + catch(Exception &e) + { + /* DEBUG: An exception at this point shouldn't never occur but if + * it is raised, we spit out the error to the stdout in order to try to + * find out the problem! */ + qDebug("** FAIL TO DESTROY ALL OBJECTS **"); + qDebug(e.getExceptionsText().toStdString().c_str()); } - //Removing the special objects first - storeSpecialObjectsXML(); - disconnectRelationships(); + objects = getCreationOrder(SchemaParser::XmlDefinition, true); + ritr = objects.rbegin(); + ritr_end = objects.rend(); - for(i=0; i < cnt; i++) + while(ritr != ritr_end) { - list=getObjectList(types[i]); + object = ritr->second; + ritr++; - while(!list->empty()) - { - object=list->back(); + // We ignore the database itself, permission objects (destroyed separetely) and table children objects + if(object->getObjectType() == ObjectType::Database || + object->getObjectType() == ObjectType::Permission || + TableObject::isTableObject(object->getObjectType())) + continue; - /* If the object is graphical destroy using the __removeObject in order - emit the signal to object scene to remove the graphical representation - of the to-be-destroyed object */ - if(dynamic_cast(object)) - { - __removeObject(object,-1,false); + // Register the type of the object being removed so the respective list can be cleaned in the end + rem_obj_types.push_back(object->getObjectType()); - if(object->getObjectType()==OBJ_RELATIONSHIP) - dynamic_cast(object)->destroyObjects(); - } - else - list->pop_back(); + /* If the object is graphical destroy using the __removeObject in order + emit the signal to object scene to remove the graphical representation + of the to-be-destroyed object */ + if(dynamic_cast(object)) + { + __removeObject(object,-1,false); - delete(object); + if(object->getObjectType()==ObjectType::Relationship) + dynamic_cast(object)->destroyObjects(); } + + delete(object); } - PgSQLType::removeUserTypes(this); + PgSqlType::removeUserTypes(this); + + for(auto &perm : permissions) + delete(perm); + + permissions.clear(); + + //Cleaning out the list of removed objects to avoid segfaults while calling this method again + if(!rem_obj_types.empty()) + { + std::sort(rem_obj_types.begin(), rem_obj_types.end()); + vector::iterator end = std::unique(rem_obj_types.begin(), rem_obj_types.end()); + rem_obj_types.erase(end, rem_obj_types.end()); + + for(auto type : rem_obj_types) + getObjectList(type)->clear(); + } } void DatabaseModel::addTable(Table *table, int obj_idx) @@ -793,7 +825,7 @@ void DatabaseModel::addTable(Table *table, int obj_idx) { __addObject(table, obj_idx); - PgSQLType::addUserType(table->getName(true), table, this, UserTypeConfig::TABLE_TYPE); + PgSqlType::addUserType(table->getName(true), table, this, UserTypeConfig::TableType); updateTableFKRelationships(table); @@ -801,18 +833,18 @@ void DatabaseModel::addTable(Table *table, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } Table *DatabaseModel::getTable(unsigned obj_idx) { - return(dynamic_cast
(getObject(obj_idx, OBJ_TABLE))); + return(dynamic_cast
(getObject(obj_idx, ObjectType::Table))); } Table *DatabaseModel::getTable(const QString &name) { - return(dynamic_cast
(getObject(name, OBJ_TABLE))); + return(dynamic_cast
(getObject(name, ObjectType::Table))); } void DatabaseModel::removeTable(Table *table, int obj_idx) @@ -820,12 +852,12 @@ void DatabaseModel::removeTable(Table *table, int obj_idx) try { __removeObject(table, obj_idx); - PgSQLType::removeUserType(table->getName(true), table); + PgSqlType::removeUserType(table->getName(true), table); updateTableFKRelationships(table); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -834,22 +866,22 @@ void DatabaseModel::addSequence(Sequence *sequence, int obj_idx) try { __addObject(sequence, obj_idx); - PgSQLType::addUserType(sequence->getName(true), sequence, this, UserTypeConfig::SEQUENCE_TYPE); + PgSqlType::addUserType(sequence->getName(true), sequence, this, UserTypeConfig::SequenceType); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } Sequence *DatabaseModel::getSequence(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_SEQUENCE))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Sequence))); } Sequence *DatabaseModel::getSequence(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_SEQUENCE))); + return(dynamic_cast(getObject(name, ObjectType::Sequence))); } void DatabaseModel::removeSequence(Sequence *sequence, int obj_idx) @@ -860,7 +892,7 @@ void DatabaseModel::removeSequence(Sequence *sequence, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -872,18 +904,18 @@ void DatabaseModel::addCollation(Collation *collation, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } Collation *DatabaseModel::getCollation(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_COLLATION))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Collation))); } Collation *DatabaseModel::getCollation(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_COLLATION))); + return(dynamic_cast(getObject(name, ObjectType::Collation))); } void DatabaseModel::removeCollation(Collation *collation, int obj_idx) @@ -894,7 +926,7 @@ void DatabaseModel::removeCollation(Collation *collation, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -905,22 +937,22 @@ void DatabaseModel::addExtension(Extension *extension, int obj_idx) __addObject(extension, obj_idx); if(extension->handlesType()) - PgSQLType::addUserType(extension->getName(true), extension, this, UserTypeConfig::EXTENSION_TYPE); + PgSqlType::addUserType(extension->getName(true), extension, this, UserTypeConfig::ExtensionType); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } Extension *DatabaseModel::getExtension(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_COLLATION))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Collation))); } Extension *DatabaseModel::getExtension(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_EXTENSION))); + return(dynamic_cast(getObject(name, ObjectType::Extension))); } void DatabaseModel::addTag(Tag *tag, int obj_idx) @@ -931,7 +963,7 @@ void DatabaseModel::addTag(Tag *tag, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -943,18 +975,18 @@ void DatabaseModel::removeTag(Tag *tag, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } Tag *DatabaseModel::getTag(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_TAG))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Tag))); } Tag *DatabaseModel::getTag(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_TAG))); + return(dynamic_cast(getObject(name, ObjectType::Tag))); } void DatabaseModel::addEventTrigger(EventTrigger *evnttrig, int obj_idx) @@ -965,7 +997,7 @@ void DatabaseModel::addEventTrigger(EventTrigger *evnttrig, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -977,18 +1009,18 @@ void DatabaseModel::removeEventTrigger(EventTrigger *evnttrig, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } EventTrigger *DatabaseModel::getEventTrigger(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_EVENT_TRIGGER))); + return(dynamic_cast(getObject(obj_idx, ObjectType::EventTrigger))); } EventTrigger *DatabaseModel::getEventTrigger(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_EVENT_TRIGGER))); + return(dynamic_cast(getObject(name, ObjectType::EventTrigger))); } void DatabaseModel::addGenericSQL(GenericSQL *genericsql, int obj_idx) @@ -999,7 +1031,7 @@ void DatabaseModel::addGenericSQL(GenericSQL *genericsql, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -1011,18 +1043,120 @@ void DatabaseModel::removeGenericSQL(GenericSQL *genericsql, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } GenericSQL *DatabaseModel::getGenericSQL(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_GENERIC_SQL))); + return(dynamic_cast(getObject(obj_idx, ObjectType::GenericSql))); } GenericSQL *DatabaseModel::getGenericSQL(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_GENERIC_SQL))); + return(dynamic_cast(getObject(name, ObjectType::GenericSql))); +} + +void DatabaseModel::addForeignDataWrapper(ForeignDataWrapper *fdata_wrapper, int obj_idx) +{ + try + { + __addObject(fdata_wrapper, obj_idx); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +void DatabaseModel::removeForeignDataWrapper(ForeignDataWrapper *fdata_wrapper, int obj_idx) +{ + try + { + __removeObject(fdata_wrapper, obj_idx); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + } +} + +ForeignDataWrapper *DatabaseModel::getForeignDataWrapper(unsigned obj_idx) +{ + return(dynamic_cast(getObject(obj_idx, ObjectType::ForeignDataWrapper))); +} + +ForeignDataWrapper *DatabaseModel::getForeignDataWrapper(const QString &name) +{ + return(dynamic_cast(getObject(name, ObjectType::ForeignDataWrapper))); +} + +void DatabaseModel::addForeignServer(ForeignServer *server, int obj_idx) +{ + try + { + __addObject(server, obj_idx); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +void DatabaseModel::removeForeignServer(ForeignServer *server, int obj_idx) +{ + try + { + __removeObject(server, obj_idx); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + } +} + +ForeignServer *DatabaseModel::getForeignServer(unsigned obj_idx) +{ + return(dynamic_cast(getObject(obj_idx, ObjectType::ForeignServer))); +} + +ForeignServer *DatabaseModel::getForeignServer(const QString &name) +{ + return(dynamic_cast(getObject(name, ObjectType::ForeignServer))); +} + +void DatabaseModel::addUserMapping(UserMapping *usrmap, int obj_idx) +{ + try + { + __addObject(usrmap, obj_idx); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +void DatabaseModel::removeUserMapping(UserMapping *usrmap, int obj_idx) +{ + try + { + __removeObject(usrmap, obj_idx); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + } +} + +UserMapping *DatabaseModel::getUserMapping(unsigned obj_idx) +{ + return(dynamic_cast(getObject(obj_idx, ObjectType::UserMapping))); +} + +UserMapping *DatabaseModel::getUserMapping(const QString &name) +{ + return(dynamic_cast(getObject(name, ObjectType::UserMapping))); } void DatabaseModel::removeExtension(Extension *extension, int obj_idx) @@ -1036,7 +1170,7 @@ void DatabaseModel::removeExtension(Extension *extension, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1045,26 +1179,25 @@ void DatabaseModel::addView(View *view, int obj_idx) try { __addObject(view, obj_idx); - - PgSQLType::addUserType(view->getName(true), view, this, UserTypeConfig::VIEW_TYPE); + PgSqlType::addUserType(view->getName(true), view, this, UserTypeConfig::ViewType); updateViewRelationships(view); dynamic_cast(view->getSchema())->setModified(true); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } View *DatabaseModel::getView(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_VIEW))); + return(dynamic_cast(getObject(obj_idx, ObjectType::View))); } View *DatabaseModel::getView(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_VIEW))); + return(dynamic_cast(getObject(name, ObjectType::View))); } void DatabaseModel::removeView(View *view, int obj_idx) @@ -1075,31 +1208,28 @@ void DatabaseModel::removeView(View *view, int obj_idx) updateViewRelationships(view, true); __removeObject(view, obj_idx); - PgSQLType::removeUserType(view->getName(true), view); + PgSqlType::removeUserType(view->getName(true), view); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void DatabaseModel::updateTableFKRelationships(Table *table) { if(!table) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); - else if(table->getDatabase()==this) + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + if(table->getDatabase()==this) { Table *ref_tab=nullptr; BaseRelationship *rel=nullptr; - Constraint *fk=nullptr; unsigned idx; vector fks; - vector::iterator itr, itr_end; vector::iterator itr1, itr1_end; table->getForeignKeys(fks); - itr=fks.begin(); - itr_end=fks.end(); /* First remove the invalid relationships (the foreign key that generates the relationship no longer exists) */ @@ -1111,18 +1241,26 @@ void DatabaseModel::updateTableFKRelationships(Table *table) { rel=dynamic_cast(*itr1); - if(rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_FK && - (rel->getTable(BaseRelationship::SRC_TABLE)==table || - rel->getTable(BaseRelationship::DST_TABLE)==table)) + if(rel->getRelationshipType()==BaseRelationship::RelationshipFk && + (rel->getTable(BaseRelationship::SrcTable)==table || + rel->getTable(BaseRelationship::DstTable)==table)) { Constraint *fk = rel->getReferenceForeignKey(); - if(rel->getTable(BaseRelationship::SRC_TABLE)==table) - ref_tab=dynamic_cast
(rel->getTable(BaseRelationship::DST_TABLE)); - else - ref_tab=dynamic_cast
(rel->getTable(BaseRelationship::SRC_TABLE)); - //Removes the relationship if the table does'nt references the 'ref_tab' - if(fk->getReferencedTable() == ref_tab && table->getObjectIndex(fk) < 0) + if(rel->getTable(BaseRelationship::SrcTable)==table) + ref_tab=dynamic_cast
(rel->getTable(BaseRelationship::DstTable)); + else + ref_tab=dynamic_cast
(rel->getTable(BaseRelationship::SrcTable)); + + /* Removes the relationship if the following cases happen: + * 1) The foreign key references a table different from ref_tab, which means, the user + * have changed the fk manually by setting a new referenced table but the relationship tied to the fk + * does not reflect the new reference. + * + * 2) The fk references the correct table but the source table does not own the fk anymore, which means, + * the fk as removed manually by the user. */ + if((table->getObjectIndex(fk) >= 0 && fk->getReferencedTable() != ref_tab) || + (table->getObjectIndex(fk) < 0 && fk->getReferencedTable() == ref_tab)) { removeRelationship(rel); itr1=base_relationships.begin() + idx; @@ -1130,7 +1268,7 @@ void DatabaseModel::updateTableFKRelationships(Table *table) } else { - rel->setModified(true); + rel->setModified(!loading_model); itr1++; idx++; } } @@ -1141,26 +1279,24 @@ void DatabaseModel::updateTableFKRelationships(Table *table) } //Creating the relationships from the foreign keys - while(itr!=itr_end) + for(auto &fk : fks) { - fk=(*itr); ref_tab=dynamic_cast
(fk->getReferencedTable()); - itr++; //Only creates the relationship if does'nt exist one between the tables rel=getRelationship(table, ref_tab, fk); if(!rel && ref_tab->getDatabase()==this) { - rel=new BaseRelationship(BaseRelationship::RELATIONSHIP_FK, table, ref_tab, false, false); + rel=new BaseRelationship(BaseRelationship::RelationshipFk, table, ref_tab, false, false); rel->setReferenceForeignKey(fk); rel->setCustomColor(Qt::transparent); /* Workaround: In some cases the combination of the two tablenames can generate a duplicated relationship name so it`s necessary to check if a relationship with the same name already exists. If exists changes the name of the new one */ - if(getObjectIndex(rel->getName(), BASE_RELATIONSHIP) >= 0) - rel->setName(PgModelerNS::generateUniqueName(rel, base_relationships)); + if(getObjectIndex(rel->getName(), ObjectType::BaseRelationship) >= 0) + rel->setName(PgModelerNs::generateUniqueName(rel, base_relationships)); addRelationship(rel); } @@ -1181,15 +1317,17 @@ void DatabaseModel::updateTablesFKRelationships(void) void DatabaseModel::updateViewRelationships(View *view, bool force_rel_removal) { - Table *tab=nullptr; + Table *table=nullptr; BaseRelationship *rel=nullptr; Reference ref; unsigned i, ref_count, idx; vector::iterator itr, itr_end; + vector
tables; if(!view) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); - else if(getObjectIndex(view) < 0 || force_rel_removal) + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + if(getObjectIndex(view) < 0 || force_rel_removal) { //Remove all the relationship related to the view when this latter no longer exists itr=base_relationships.begin(); @@ -1200,8 +1338,8 @@ void DatabaseModel::updateViewRelationships(View *view, bool force_rel_removal) { rel=dynamic_cast(*itr); - if(rel->getTable(BaseRelationship::SRC_TABLE)==view || - rel->getTable(BaseRelationship::DST_TABLE)==view) + if(rel->getTable(BaseRelationship::SrcTable)==view || + rel->getTable(BaseRelationship::DstTable)==view) { removeRelationship(rel); itr=base_relationships.begin() + idx; @@ -1225,15 +1363,15 @@ void DatabaseModel::updateViewRelationships(View *view, bool force_rel_removal) { rel=dynamic_cast(*itr); - if(rel->getTable(BaseRelationship::SRC_TABLE)==view || - rel->getTable(BaseRelationship::DST_TABLE)==view) + if(rel->getTable(BaseRelationship::SrcTable)==view || + rel->getTable(BaseRelationship::DstTable)==view) { - if(rel->getTable(BaseRelationship::SRC_TABLE)->getObjectType()==OBJ_TABLE) - tab=dynamic_cast
(rel->getTable(BaseRelationship::SRC_TABLE)); + if(rel->getTable(BaseRelationship::SrcTable)->getObjectType()==ObjectType::Table) + table=dynamic_cast
(rel->getTable(BaseRelationship::SrcTable)); else - tab=dynamic_cast
(rel->getTable(BaseRelationship::DST_TABLE)); + table=dynamic_cast
(rel->getTable(BaseRelationship::DstTable)); - if(!view->isReferencingTable(tab)) + if(!view->isReferencingTable(table)) { removeRelationship(rel); itr=base_relationships.begin() + idx; @@ -1250,18 +1388,30 @@ void DatabaseModel::updateViewRelationships(View *view, bool force_rel_removal) } } - //Creates the relationships from the view references - ref_count=view->getReferenceCount(Reference::SQL_REFER_SELECT); - + /* Creates the relationships from the view references + * First we try to create relationship from referecences in SELECT portion of view's definition */ + ref_count=view->getReferenceCount(Reference::SqlReferSelect); for(i=0; i < ref_count; i++) { - ref=view->getReference(i, Reference::SQL_REFER_SELECT); - tab=ref.getTable(); + table = view->getReference(i, Reference::SqlReferSelect).getTable(); + if(table) tables.push_back(table); + } + + /* If the view does have tables referenced from SELECT portion we check if + * the table was constructed from a single reference (Reference::SqlViewDefinition). In + * that case we use the list of referenced tables configured in that view reference object */ + if(tables.empty() && view->getReferenceCount(Reference::SqlViewDefinition) > 0) + tables = view->getReference(0, Reference::SqlViewDefinition).getReferencedTables(); + + // Effectively creating the relationships + for(auto &tab : tables) + { + rel = getRelationship(view, tab); - rel=getRelationship(view,tab); - if(tab && !rel) + if(!rel) { - rel=new BaseRelationship(BaseRelationship::RELATIONSHIP_DEP,view,tab,false,false); + rel=new BaseRelationship(BaseRelationship::RelationshipDep, view, tab, false, false); + rel->setName(PgModelerNs::generateUniqueName(rel, base_relationships)); addRelationship(rel); } } @@ -1284,19 +1434,22 @@ void DatabaseModel::disconnectRelationships(void) { base_rel=dynamic_cast(*ritr_rel); ritr_rel++; + base_rel->blockSignals(loading_model); - if(base_rel->getObjectType()==OBJ_RELATIONSHIP) + if(base_rel->getObjectType()==ObjectType::Relationship) { rel=dynamic_cast(base_rel); rel->disconnectRelationship(); } else base_rel->disconnectRelationship(); + + base_rel->blockSignals(false); } } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1330,8 +1483,8 @@ void DatabaseModel::validateRelationships(void) itr++; if(rel && - (rel->getRelationshipType()==Relationship::RELATIONSHIP_11 || - rel->getRelationshipType()==Relationship::RELATIONSHIP_1N) && + (rel->getRelationshipType()==Relationship::Relationship11 || + rel->getRelationshipType()==Relationship::Relationship1n) && rel->getReferenceTable()->getPrimaryKey() && rel->getReferenceTable()->getPrimaryKey()->isAddedByRelationship()) rels_gen_pk++; @@ -1351,7 +1504,7 @@ void DatabaseModel::validateRelationships(void) itr++; //Validates only table-table relationships - if(base_rel->getObjectType()==OBJ_RELATIONSHIP) + if(base_rel->getObjectType()==ObjectType::Relationship) { //Makes a cast to the correct object class rel=dynamic_cast(base_rel); @@ -1409,8 +1562,8 @@ void DatabaseModel::validateRelationships(void) rel->connectRelationship(); //Storing the schemas on a auxiliary vector to update them later - tab1=rel->getTable(BaseRelationship::SRC_TABLE); - tab2=rel->getTable(BaseRelationship::DST_TABLE); + tab1=rel->getTable(BaseRelationship::SrcTable); + tab2=rel->getTable(BaseRelationship::DstTable); if(std::find(schemas.begin(), schemas.end(), tab1->getSchema())==schemas.end()) schemas.push_back(dynamic_cast(tab1->getSchema())); @@ -1444,7 +1597,7 @@ void DatabaseModel::validateRelationships(void) /* If the relationship connection failed after 'rels_gen_pk' times at the different errors or exists on the fail_rels vector (already tried to be validated) it will be deleted from model */ - if((e.getErrorType()!=ERR_LINK_TABLES_NO_PK && conn_tries[rel] > rels_gen_pk) || + if((e.getErrorCode() != ErrorCode::InvLinkTablesNoPrimaryKey && conn_tries[rel] > rels_gen_pk) || (std::find(fail_rels.begin(), fail_rels.end(), rel)!=fail_rels.end())) { //Removes the relationship @@ -1460,9 +1613,9 @@ void DatabaseModel::validateRelationships(void) the connection tries exceed the size of the relationship the relationship is isolated on a "failed to validate" list. This list will be appended to the main rel list when there is only one relationship to be validated */ - else if(e.getErrorType()==ERR_LINK_TABLES_NO_PK && + else if(e.getErrorCode()==ErrorCode::InvLinkTablesNoPrimaryKey && (conn_tries[rel] > rels.size() || - rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_NN)) + rel->getRelationshipType()==BaseRelationship::RelationshipNn)) { fail_rels.push_back(rel); rels.erase(itr_ant); @@ -1542,11 +1695,14 @@ void DatabaseModel::validateRelationships(void) //The validation continues until there is some invalid relationship while(found_inval_rel); - //Updates the schemas to ajdust its sizes due to the tables resizings - while(!schemas.empty()) + if(!loading_model) { - schemas.back()->setModified(true); - schemas.pop_back(); + //Updates the schemas to ajdust its sizes due to the tables resizings + while(!schemas.empty()) + { + schemas.back()->setModified(true); + schemas.pop_back(); + } } //Stores the errors related to creation of special objects on the general error vector @@ -1573,8 +1729,8 @@ void DatabaseModel::validateRelationships(void) { base_rel=dynamic_cast(*itr); - if(base_rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_FK) - this->updateTableFKRelationships(dynamic_cast
(base_rel->getTable(BaseRelationship::SRC_TABLE))); + if(base_rel->getRelationshipType()==BaseRelationship::RelationshipFk) + this->updateTableFKRelationships(dynamic_cast
(base_rel->getTable(BaseRelationship::SrcTable))); itr++; } @@ -1583,7 +1739,7 @@ void DatabaseModel::validateRelationships(void) this->setObjectsModified(); //Redirects all the errors captured on the revalidation - throw Exception(ERR_INVALIDATED_OBJECTS,__PRETTY_FUNCTION__,__FILE__,__LINE__,errors); + throw Exception(ErrorCode::RemInvalidatedObjects,__PRETTY_FUNCTION__,__FILE__,__LINE__,errors); } if(!loading_model) @@ -1603,18 +1759,18 @@ void DatabaseModel::checkRelationshipRedundancy(Relationship *rel) //Raises an error if the user try to check the redundancy starting from a unnallocated relationship if(!rel) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); rel_type=rel->getRelationshipType(); /* Only identifier relationships or relationship that has identifier attributes (primary keys) are checked */ if((!rel->isSelfRelationship() && - (rel->isIdentifier() || - rel->hasIndentifierAttribute())) || - - (rel_type==Relationship::RELATIONSHIP_GEN || - rel_type==Relationship::RELATIONSHIP_DEP)) + (rel->isIdentifier() || + rel->hasIndentifierAttribute())) || + (rel_type==Relationship::RelationshipGen || + rel_type==Relationship::RelationshipDep || + rel_type==Relationship::RelationshipPart)) { BaseTable *ref_table=nullptr, *src_table=nullptr; Table *recv_table=nullptr; @@ -1640,7 +1796,7 @@ void DatabaseModel::checkRelationshipRedundancy(Relationship *rel) base_rel=dynamic_cast(*itr); itr++; - if(base_rel->getObjectType()==OBJ_RELATIONSHIP) + if(base_rel->getObjectType()==ObjectType::Relationship) { rel_aux=dynamic_cast(base_rel); aux_rel_type=rel_aux->getRelationshipType(); @@ -1655,8 +1811,9 @@ void DatabaseModel::checkRelationshipRedundancy(Relationship *rel) ((!rel_aux->isSelfRelationship() && (rel_aux->isIdentifier() || rel_aux->hasIndentifierAttribute())) || - (aux_rel_type==Relationship::RELATIONSHIP_GEN || - aux_rel_type==Relationship::RELATIONSHIP_DEP))) + (aux_rel_type==Relationship::RelationshipGen || + aux_rel_type==Relationship::RelationshipDep || + aux_rel_type==Relationship::RelationshipPart))) { //The receiver table will be the receiver from the current relationship @@ -1678,16 +1835,16 @@ void DatabaseModel::checkRelationshipRedundancy(Relationship *rel) if(found_cycle) { str_aux+=rel->getName(); - msg=Exception::getErrorMessage(ERR_INS_REL_GENS_REDUNDACY) + msg=Exception::getErrorMessage(ErrorCode::InsRelationshipRedundancy) .arg(rel->getName()) .arg(str_aux); - throw Exception(msg,ERR_INS_REL_GENS_REDUNDACY,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(msg,ErrorCode::InsRelationshipRedundancy,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1704,10 +1861,11 @@ void DatabaseModel::storeSpecialObjectsXML(void) Trigger *trigger=nullptr; View *view=nullptr; BaseRelationship *rel=nullptr; + GenericSQL *generic_sql=nullptr; Reference ref; - ObjectType tab_obj_type[3]={ OBJ_CONSTRAINT, OBJ_TRIGGER, OBJ_INDEX }; + ObjectType tab_obj_type[3]={ ObjectType::Constraint, ObjectType::Trigger, ObjectType::Index }; bool found=false; - vector objects, rem_objects; + vector objects, rem_objects, upd_tables_rels; try { @@ -1731,7 +1889,7 @@ void DatabaseModel::storeSpecialObjectsXML(void) tab_obj=dynamic_cast(table->getObject(i, tab_obj_type[type_id])); found=false; - if(tab_obj_type[type_id]==OBJ_CONSTRAINT) + if(tab_obj_type[type_id]==ObjectType::Constraint) { constr=dynamic_cast(tab_obj); @@ -1740,19 +1898,19 @@ void DatabaseModel::storeSpecialObjectsXML(void) relationship (created manually by the user) */ found=(!constr->isAddedByRelationship() && constr->isReferRelationshipAddedColumn() && - constr->getConstraintType()!=ConstraintType::primary_key); + constr->getConstraintType()!=ConstraintType::PrimaryKey); //When found some special object, stores is xml definition if(found) - xml_special_objs[constr->getObjectId()]=constr->getCodeDefinition(SchemaParser::XML_DEFINITION, true); + xml_special_objs[constr->getObjectId()]=constr->getCodeDefinition(SchemaParser::XmlDefinition, true); } - else if(tab_obj_type[type_id]==OBJ_TRIGGER) + else if(tab_obj_type[type_id]==ObjectType::Trigger) { trigger=dynamic_cast(tab_obj); found=trigger->isReferRelationshipAddedColumn(); if(found) - xml_special_objs[trigger->getObjectId()]=trigger->getCodeDefinition(SchemaParser::XML_DEFINITION); + xml_special_objs[trigger->getObjectId()]=trigger->getCodeDefinition(SchemaParser::XmlDefinition); } else { @@ -1760,14 +1918,20 @@ void DatabaseModel::storeSpecialObjectsXML(void) found=index->isReferRelationshipAddedColumn(); if(found) - xml_special_objs[index->getObjectId()]=index->getCodeDefinition(SchemaParser::XML_DEFINITION); + xml_special_objs[index->getObjectId()]=index->getCodeDefinition(SchemaParser::XmlDefinition); } if(found) { + constr = dynamic_cast(tab_obj); + //When found the special object must be removed from the parent table table->removeObject(tab_obj->getName(), tab_obj->getObjectType()); + //We need to store the table which fk was referencing relationship added columns in order to update the fk relationships of that table + if(constr && constr->getConstraintType() == ConstraintType::ForeignKey) + upd_tables_rels.push_back(table); + //Removes the permission from the table object removePermissions(tab_obj); @@ -1777,6 +1941,22 @@ void DatabaseModel::storeSpecialObjectsXML(void) } } + //Updating fk rels of tables which had fks referencing relationship added columns + if(!upd_tables_rels.empty()) + { + vector::iterator end; + + if(upd_tables_rels.size() > 1) + { + std::sort(upd_tables_rels.begin(), upd_tables_rels.end()); + end = std::unique(upd_tables_rels.begin(), upd_tables_rels.end()); + upd_tables_rels.erase(end, upd_tables_rels.end()); + } + + for(auto &tab : upd_tables_rels) + updateTableFKRelationships(dynamic_cast
(tab)); + } + //Making a copy of the sequences list to avoid iterator invalidation when removing an object rem_objects.assign(sequences.begin(), sequences.end()); itr=rem_objects.begin(); @@ -1789,7 +1969,7 @@ void DatabaseModel::storeSpecialObjectsXML(void) if(sequence->isReferRelationshipAddedColumn()) { - xml_special_objs[sequence->getObjectId()]=sequence->getCodeDefinition(SchemaParser::XML_DEFINITION); + xml_special_objs[sequence->getObjectId()]=sequence->getCodeDefinition(SchemaParser::XmlDefinition); removeSequence(sequence); delete(sequence); } @@ -1807,16 +1987,16 @@ void DatabaseModel::storeSpecialObjectsXML(void) if(view->isReferRelationshipAddedColumn()) { - xml_special_objs[view->getObjectId()]=view->getCodeDefinition(SchemaParser::XML_DEFINITION); + xml_special_objs[view->getObjectId()]=view->getCodeDefinition(SchemaParser::XmlDefinition); /* Relationships linking the view and the referenced tables are considered as special objects in this case only to be recreated more easely latter */ - count=view->getReferenceCount(Reference::SQL_REFER_SELECT); + count=view->getReferenceCount(Reference::SqlReferSelect); for(i=0; i < count; i++) { - ref=view->getReference(i, Reference::SQL_REFER_SELECT); + ref=view->getReference(i, Reference::SqlReferSelect); table=ref.getTable(); if(table) @@ -1826,7 +2006,7 @@ void DatabaseModel::storeSpecialObjectsXML(void) if(rel) { - xml_special_objs[rel->getObjectId()]=rel->getCodeDefinition(SchemaParser::XML_DEFINITION); + xml_special_objs[rel->getObjectId()]=rel->getCodeDefinition(SchemaParser::XmlDefinition); removeRelationship(rel); delete(rel); } @@ -1838,7 +2018,7 @@ void DatabaseModel::storeSpecialObjectsXML(void) objects=view->getObjects(); for(auto &obj : objects) { - xml_special_objs[obj->getObjectId()]=obj->getCodeDefinition(SchemaParser::XML_DEFINITION); + xml_special_objs[obj->getObjectId()]=obj->getCodeDefinition(SchemaParser::XmlDefinition); view->removeObject(obj); delete(obj); } @@ -1850,8 +2030,8 @@ void DatabaseModel::storeSpecialObjectsXML(void) //Making a copy of the permissions list to avoid iterator invalidation when removing an object rem_objects.assign(permissions.begin(), permissions.end()); - itr=permissions.begin(); - itr_end=permissions.end(); + itr=rem_objects.begin(); + itr_end=rem_objects.end(); while(itr!=itr_end) { @@ -1861,15 +2041,33 @@ void DatabaseModel::storeSpecialObjectsXML(void) if(tab_obj) { - xml_special_objs[permission->getObjectId()]=permission->getCodeDefinition(SchemaParser::XML_DEFINITION); + xml_special_objs[permission->getObjectId()]=permission->getCodeDefinition(SchemaParser::XmlDefinition); removePermission(permission); delete(permission); } } + + //Making a copy of the generic SQL objects list to avoid iterator invalidation when removing an object + rem_objects.assign(genericsqls.begin(), genericsqls.end()); + itr=rem_objects.begin(); + itr_end=rem_objects.end(); + + while(itr!=itr_end) + { + generic_sql = dynamic_cast(*itr); + itr++; + + if(generic_sql->isReferRelationshipAddedObject()) + { + xml_special_objs[generic_sql->getObjectId()] = generic_sql->getCodeDefinition(SchemaParser::XmlDefinition); + removeGenericSQL(generic_sql); + delete(generic_sql); + } + } } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1887,16 +2085,16 @@ void DatabaseModel::createSpecialObject(const QString &xml_def, unsigned obj_id) //Identifies the object type through the start element on xml buffer obj_type=BaseObject::getObjectType(xmlparser.getElementName()); - if(obj_type==OBJ_SEQUENCE) + if(obj_type==ObjectType::Sequence) object=createSequence(true); else object=createObject(obj_type); - if(obj_type==OBJ_SEQUENCE) + if(obj_type==ObjectType::Sequence) addSequence(dynamic_cast(object)); - else if(obj_type==OBJ_VIEW) + else if(obj_type==ObjectType::View) addView(dynamic_cast(object)); - else if(obj_type==OBJ_PERMISSION) + else if(obj_type==ObjectType::Permission) addPermission(createPermission()); /* When the special object is recreated it receive a new id but to maintain @@ -1907,7 +2105,7 @@ void DatabaseModel::createSpecialObject(const QString &xml_def, unsigned obj_id) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e, xml_def); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e, xml_def); } } @@ -1920,41 +2118,44 @@ void DatabaseModel::addRelationship(BaseRelationship *rel, int obj_idx) if(rel) { - tab1=rel->getTable(BaseRelationship::SRC_TABLE); - tab2=rel->getTable(BaseRelationship::DST_TABLE); + tab1=rel->getTable(BaseRelationship::SrcTable); + tab2=rel->getTable(BaseRelationship::DstTable); //Raises an error if already exists an relationship between the tables - if(rel->getRelationshipType() != Relationship::RELATIONSHIP_1N && - rel->getRelationshipType() != Relationship::RELATIONSHIP_NN && - rel->getRelationshipType() != Relationship::RELATIONSHIP_FK && + if(rel->getRelationshipType() != Relationship::Relationship1n && + rel->getRelationshipType() != Relationship::RelationshipNn && + rel->getRelationshipType() != Relationship::RelationshipFk && getRelationship(tab1,tab2)) { - msg=Exception::getErrorMessage(ERR_DUPLIC_RELATIONSHIP) + msg=Exception::getErrorMessage(ErrorCode::InsDuplicatedRelationship) .arg(tab1->getName(true)) .arg(tab1->getTypeName()) .arg(tab2->getName(true)) .arg(tab2->getTypeName()); - throw Exception(msg,ERR_DUPLIC_RELATIONSHIP,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(msg,ErrorCode::InsDuplicatedRelationship,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } //Before add the relationship, checks if a redundancy can occur case the relationship is added - if(rel->getObjectType()==OBJ_RELATIONSHIP) + if(rel->getObjectType()==ObjectType::Relationship) checkRelationshipRedundancy(dynamic_cast(rel)); + rel->blockSignals(loading_model); __addObject(rel, obj_idx); - if(rel->getObjectType()==OBJ_RELATIONSHIP) + if(rel->getObjectType()==ObjectType::Relationship) { dynamic_cast(rel)->connectRelationship(); validateRelationships(); } else rel->connectRelationship(); + + rel->blockSignals(false); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1966,24 +2167,26 @@ void DatabaseModel::removeRelationship(BaseRelationship *rel, int obj_idx) { Table *recv_tab=nullptr; - if(rel->getObjectType()==OBJ_RELATIONSHIP) + if(rel->getObjectType()==ObjectType::Relationship) { /* If the relationship is not a many-to-many we store the receiver table in order to update the fk relationships (if there are any) */ - if(rel->getRelationshipType()!=Relationship::RELATIONSHIP_NN) + if(rel->getRelationshipType()!=Relationship::RelationshipNn) recv_tab=dynamic_cast(rel)->getReceiverTable(); storeSpecialObjectsXML(); disconnectRelationships(); } - else if(rel->getObjectType()==BASE_RELATIONSHIP) + else if(rel->getObjectType()==ObjectType::BaseRelationship) { + rel->blockSignals(loading_model); rel->disconnectRelationship(); + rel->blockSignals(false); } __removeObject(rel, obj_idx); - if(rel->getObjectType()==OBJ_RELATIONSHIP) + if(rel->getObjectType()==ObjectType::Relationship) { validateRelationships(); } @@ -1995,25 +2198,25 @@ void DatabaseModel::removeRelationship(BaseRelationship *rel, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } BaseRelationship *DatabaseModel::getRelationship(unsigned obj_idx, ObjectType rel_type) { //Raises an error if the object type used to get a relationship is invalid - if(rel_type!=OBJ_RELATIONSHIP && rel_type!=BASE_RELATIONSHIP) - throw Exception(ERR_OBT_OBJ_INVALID_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(rel_type!=ObjectType::Relationship && rel_type!=ObjectType::BaseRelationship) + throw Exception(ErrorCode::ObtObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(dynamic_cast(getObject(obj_idx, rel_type))); } BaseRelationship *DatabaseModel::getRelationship(const QString &name) { - BaseRelationship *rel=dynamic_cast(getObject(name, BASE_RELATIONSHIP)); + BaseRelationship *rel=dynamic_cast(getObject(name, ObjectType::BaseRelationship)); if(!rel) - rel=dynamic_cast(getObject(name, OBJ_RELATIONSHIP)); + rel=dynamic_cast(getObject(name, ObjectType::Relationship)); return(rel); } @@ -2034,7 +2237,7 @@ BaseRelationship *DatabaseModel::getRelationship(BaseTable *src_tab, BaseTable * search_uniq_tab=true; } - if(ref_fk || src_tab->getObjectType()==OBJ_VIEW || dst_tab->getObjectType()==OBJ_VIEW) + if(ref_fk || src_tab->getObjectType()==ObjectType::View || dst_tab->getObjectType()==ObjectType::View) { itr=base_relationships.begin(); itr_end=base_relationships.end(); @@ -2050,8 +2253,8 @@ BaseRelationship *DatabaseModel::getRelationship(BaseTable *src_tab, BaseTable * while(itr!=itr_end && !found) { rel=dynamic_cast(*itr); - tab1=rel->getTable(BaseRelationship::SRC_TABLE); - tab2=rel->getTable(BaseRelationship::DST_TABLE); + tab1=rel->getTable(BaseRelationship::SrcTable); + tab2=rel->getTable(BaseRelationship::DstTable); found=((!ref_fk || (ref_fk && rel->getReferenceForeignKey() == ref_fk)) && ((tab1==src_tab && tab2==dst_tab) || @@ -2079,8 +2282,8 @@ vector DatabaseModel::getRelationships(BaseTable *tab) { base_rel=dynamic_cast(obj); - if(base_rel->getTable(BaseRelationship::SRC_TABLE)==tab || - base_rel->getTable(BaseRelationship::DST_TABLE)==tab) + if(base_rel->getTable(BaseRelationship::SrcTable)==tab || + base_rel->getTable(BaseRelationship::DstTable)==tab) aux_rels.push_back(base_rel); } @@ -2095,7 +2298,7 @@ void DatabaseModel::addTextbox(Textbox *txtbox, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -2107,18 +2310,18 @@ void DatabaseModel::removeTextbox(Textbox *txtbox, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } Textbox *DatabaseModel::getTextbox(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_TEXTBOX))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Textbox))); } Textbox *DatabaseModel::getTextbox(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_TEXTBOX))); + return(dynamic_cast(getObject(name, ObjectType::Textbox))); } void DatabaseModel::addSchema(Schema *schema, int obj_idx) @@ -2129,18 +2332,18 @@ void DatabaseModel::addSchema(Schema *schema, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } Schema *DatabaseModel::getSchema(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_SCHEMA))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Schema))); } Schema *DatabaseModel::getSchema(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_SCHEMA))); + return(dynamic_cast(getObject(name, ObjectType::Schema))); } void DatabaseModel::removeSchema(Schema *schema, int obj_idx) @@ -2151,7 +2354,7 @@ void DatabaseModel::removeSchema(Schema *schema, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -2163,18 +2366,18 @@ void DatabaseModel::addRole(Role *role, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } Role *DatabaseModel::getRole(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_ROLE))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Role))); } Role *DatabaseModel::getRole(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_ROLE))); + return(dynamic_cast(getObject(name, ObjectType::Role))); } void DatabaseModel::removeRole(Role *role, int obj_idx) @@ -2185,7 +2388,7 @@ void DatabaseModel::removeRole(Role *role, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -2197,18 +2400,18 @@ void DatabaseModel::addTablespace(Tablespace *tabspc, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } Tablespace *DatabaseModel::getTablespace(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_TABLESPACE))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Tablespace))); } Tablespace *DatabaseModel::getTablespace(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_TABLESPACE))); + return(dynamic_cast(getObject(name, ObjectType::Tablespace))); } void DatabaseModel::removeTablespace(Tablespace *tabspc, int obj_idx) @@ -2219,7 +2422,7 @@ void DatabaseModel::removeTablespace(Tablespace *tabspc, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -2231,7 +2434,7 @@ void DatabaseModel::addCast(Cast *cast, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -2243,18 +2446,18 @@ void DatabaseModel::removeCast(Cast *cast, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } Cast *DatabaseModel::getCast(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_CAST))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Cast))); } Cast *DatabaseModel::getCast(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_CAST))); + return(dynamic_cast(getObject(name, ObjectType::Cast))); } void DatabaseModel::addConversion(Conversion *conv, int obj_idx) @@ -2265,7 +2468,7 @@ void DatabaseModel::addConversion(Conversion *conv, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -2277,19 +2480,19 @@ void DatabaseModel::removeConversion(Conversion *conv, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } Conversion *DatabaseModel::getConversion(unsigned obj_idx) { return(dynamic_cast(getObject(obj_idx, - OBJ_CONVERSION))); + ObjectType::Conversion))); } Conversion *DatabaseModel::getConversion(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_CONVERSION))); + return(dynamic_cast(getObject(name, ObjectType::Conversion))); } void DatabaseModel::addLanguage(Language *lang, int obj_idx) @@ -2300,18 +2503,18 @@ void DatabaseModel::addLanguage(Language *lang, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } Language *DatabaseModel::getLanguage(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_LANGUAGE))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Language))); } Language *DatabaseModel::getLanguage(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_LANGUAGE))); + return(dynamic_cast(getObject(name, ObjectType::Language))); } void DatabaseModel::removeLanguage(Language *lang, int obj_idx) @@ -2322,7 +2525,7 @@ void DatabaseModel::removeLanguage(Language *lang, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -2334,18 +2537,18 @@ void DatabaseModel::addFunction(Function *func, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } Function *DatabaseModel::getFunction(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_FUNCTION))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Function))); } Function *DatabaseModel::getFunction(const QString &signature) { - return(dynamic_cast(getObject(signature, OBJ_FUNCTION))); + return(dynamic_cast(getObject(signature, ObjectType::Function))); } void DatabaseModel::removeFunction(Function *func, int obj_idx) @@ -2356,7 +2559,7 @@ void DatabaseModel::removeFunction(Function *func, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -2368,18 +2571,18 @@ void DatabaseModel::addAggregate(Aggregate *aggreg, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } Aggregate *DatabaseModel::getAggregate(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_AGGREGATE))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Aggregate))); } Aggregate *DatabaseModel::getAggregate(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_AGGREGATE))); + return(dynamic_cast(getObject(name, ObjectType::Aggregate))); } void DatabaseModel::removeAggregate(Aggregate *aggreg, int obj_idx) @@ -2390,7 +2593,7 @@ void DatabaseModel::removeAggregate(Aggregate *aggreg, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -2415,12 +2618,12 @@ void DatabaseModel::addDomain(Domain *domain, int obj_idx) //Raises an error if found a type with the same name as the domain if(found) { - str_aux=QString(Exception::getErrorMessage(ERR_ASG_DUPLIC_OBJECT)) + str_aux=Exception::getErrorMessage(ErrorCode::AsgDuplicatedObject) .arg(domain->getName(true)) .arg(domain->getTypeName()) .arg(this->getName(true)) .arg(this->getTypeName()); - throw Exception(str_aux, ERR_ASG_DUPLIC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(str_aux, ErrorCode::AsgDuplicatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); } try @@ -2428,11 +2631,11 @@ void DatabaseModel::addDomain(Domain *domain, int obj_idx) __addObject(domain, obj_idx); //When added to the model the domain is inserted on the pgsql base type list to be used as a column type - PgSQLType::addUserType(domain->getName(true), domain, this, UserTypeConfig::DOMAIN_TYPE); + PgSqlType::addUserType(domain->getName(true), domain, this, UserTypeConfig::DomainType); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } } @@ -2445,18 +2648,18 @@ void DatabaseModel::removeDomain(Domain *domain, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } Domain *DatabaseModel::getDomain(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_DOMAIN))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Domain))); } Domain *DatabaseModel::getDomain(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_DOMAIN))); + return(dynamic_cast(getObject(name, ObjectType::Domain))); } void DatabaseModel::addOperatorFamily(OperatorFamily *op_family, int obj_idx) @@ -2467,18 +2670,18 @@ void DatabaseModel::addOperatorFamily(OperatorFamily *op_family, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } OperatorFamily *DatabaseModel::getOperatorFamily(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_OPFAMILY))); + return(dynamic_cast(getObject(obj_idx, ObjectType::OpFamily))); } OperatorFamily *DatabaseModel::getOperatorFamily(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_OPFAMILY))); + return(dynamic_cast(getObject(name, ObjectType::OpFamily))); } void DatabaseModel::removeOperatorFamily(OperatorFamily *op_family, int obj_idx) @@ -2489,7 +2692,7 @@ void DatabaseModel::removeOperatorFamily(OperatorFamily *op_family, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -2501,7 +2704,7 @@ void DatabaseModel::addOperatorClass(OperatorClass *op_class, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -2513,18 +2716,18 @@ void DatabaseModel::removeOperatorClass(OperatorClass *op_class, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } OperatorClass *DatabaseModel::getOperatorClass(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_OPCLASS))); + return(dynamic_cast(getObject(obj_idx, ObjectType::OpClass))); } OperatorClass *DatabaseModel::getOperatorClass(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_OPCLASS))); + return(dynamic_cast(getObject(name, ObjectType::OpClass))); } void DatabaseModel::addOperator(Operator *oper, int obj_idx) @@ -2535,7 +2738,7 @@ void DatabaseModel::addOperator(Operator *oper, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -2547,18 +2750,18 @@ void DatabaseModel::removeOperator(Operator *oper, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } Operator *DatabaseModel::getOperator(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_OPERATOR))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Operator))); } Operator *DatabaseModel::getOperator(const QString &signature) { - return(dynamic_cast(getObject(signature, OBJ_OPERATOR))); + return(dynamic_cast(getObject(signature, ObjectType::Operator))); } void DatabaseModel::addType(Type *type, int obj_idx) @@ -2581,12 +2784,12 @@ void DatabaseModel::addType(Type *type, int obj_idx) if(found) { - str_aux=QString(Exception::getErrorMessage(ERR_ASG_DUPLIC_OBJECT)) + str_aux=Exception::getErrorMessage(ErrorCode::AsgDuplicatedObject) .arg(type->getName(true)) .arg(type->getTypeName()) .arg(this->getName(true)) .arg(this->getTypeName()); - throw Exception(str_aux, ERR_ASG_DUPLIC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(str_aux, ErrorCode::AsgDuplicatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); } try @@ -2594,11 +2797,11 @@ void DatabaseModel::addType(Type *type, int obj_idx) __addObject(type, obj_idx); //When added to the model the user type is inserted on the pgsql base type list to be used as a column type - PgSQLType::addUserType(type->getName(true), type, this, UserTypeConfig::BASE_TYPE); + PgSqlType::addUserType(type->getName(true), type, this, UserTypeConfig::BaseType); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } } @@ -2611,18 +2814,18 @@ void DatabaseModel::removeType(Type *type, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } Type *DatabaseModel::getType(unsigned obj_idx) { - return(dynamic_cast(getObject(obj_idx, OBJ_TYPE))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Type))); } Type *DatabaseModel::getType(const QString &name) { - return(dynamic_cast(getObject(name, OBJ_TYPE))); + return(dynamic_cast(getObject(name, ObjectType::Type))); } void DatabaseModel::removeUserType(BaseObject *object, int obj_idx) @@ -2632,11 +2835,11 @@ void DatabaseModel::removeUserType(BaseObject *object, int obj_idx) __removeObject(object, obj_idx); //Removes the user type from the list of base types of pgsql - PgSQLType::removeUserType(object->getName(true), object); + PgSqlType::removeUserType(object->getName(true), object); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -2664,7 +2867,7 @@ void DatabaseModel::addPermissions(const vector &perms) itr++; } - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -2673,42 +2876,42 @@ void DatabaseModel::addPermission(Permission *perm) try { if(!perm) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); TableObject *tab_obj=dynamic_cast(perm->getObject()); if(getPermissionIndex(perm, false) >=0) { - throw Exception(Exception::getErrorMessage(ERR_ASG_DUPLIC_PERMISSION) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgDuplicatedPermission) .arg(perm->getObject()->getName()) .arg(perm->getObject()->getTypeName()), - ERR_ASG_DUPLIC_PERMISSION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgDuplicatedPermission,__PRETTY_FUNCTION__,__FILE__,__LINE__); } //Raises an error if the permission is referencing an object that does not exists on model else if(perm->getObject()!=this && ((tab_obj && (getObjectIndex(tab_obj->getParentTable()) < 0)) || (!tab_obj && (getObjectIndex(perm->getObject()) < 0)))) - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(perm->getName()) .arg(perm->getObject()->getTypeName()) .arg(perm->getObject()->getName()) .arg(perm->getObject()->getTypeName()), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); permissions.push_back(perm); perm->setDatabase(this); } catch(Exception &e) { - if(e.getErrorType()==ERR_ASG_DUPLIC_OBJECT) + if(e.getErrorCode()==ErrorCode::AsgDuplicatedObject) throw - Exception(Exception::getErrorMessage(ERR_ASG_DUPLIC_PERMISSION) + Exception(Exception::getErrorMessage(ErrorCode::AsgDuplicatedPermission) .arg(perm->getObject()->getName()) .arg(perm->getObject()->getTypeName()), - ERR_ASG_DUPLIC_PERMISSION,__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + ErrorCode::AsgDuplicatedPermission,__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); else - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -2720,7 +2923,7 @@ void DatabaseModel::removePermission(Permission *perm) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -2731,7 +2934,7 @@ void DatabaseModel::removePermissions(BaseObject *object) unsigned idx=0; if(!object) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); itr=permissions.begin(); itr_end=permissions.end(); @@ -2759,7 +2962,7 @@ void DatabaseModel::getPermissions(BaseObject *object, vector &per Permission *perm=nullptr; if(!object) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); itr=permissions.begin(); itr_end=permissions.end(); @@ -2873,7 +3076,7 @@ int DatabaseModel::getObjectIndex(BaseObject *object) obj_list=getObjectList(obj_type); if(!obj_list) - throw Exception(ERR_OBT_OBJ_INVALID_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::ObtObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { itr=obj_list->begin(); @@ -2895,17 +3098,17 @@ int DatabaseModel::getObjectIndex(BaseObject *object) void DatabaseModel::configureDatabase(attribs_map &attribs) { - encoding=attribs[ParsersAttributes::ENCODING]; - template_db=attribs[ParsersAttributes::TEMPLATE_DB]; - localizations[0]=attribs[ParsersAttributes::_LC_CTYPE_]; - localizations[1]=attribs[ParsersAttributes::_LC_COLLATE_]; - append_at_eod=attribs[ParsersAttributes::APPEND_AT_EOD]==ParsersAttributes::_TRUE_; - prepend_at_bod=attribs[ParsersAttributes::PREPEND_AT_BOD]==ParsersAttributes::_TRUE_; - is_template=attribs[ParsersAttributes::IS_TEMPLATE]==ParsersAttributes::_TRUE_; - allow_conns=attribs[ParsersAttributes::ALLOW_CONNS] != ParsersAttributes::_FALSE_; + encoding=attribs[Attributes::Encoding]; + template_db=attribs[Attributes::TemplateDb]; + localizations[0]=attribs[Attributes::LcCtype]; + localizations[1]=attribs[Attributes::LcCollate]; + append_at_eod=attribs[Attributes::AppendAtEod]==Attributes::True; + prepend_at_bod=attribs[Attributes::PrependAtBod]==Attributes::True; + is_template=attribs[Attributes::IsTemplate]==Attributes::True; + allow_conns=attribs[Attributes::AllowConns] != Attributes::False; - if(!attribs[ParsersAttributes::CONN_LIMIT].isEmpty()) - conn_limit=attribs[ParsersAttributes::CONN_LIMIT].toInt(); + if(!attribs[Attributes::ConnLimit].isEmpty()) + conn_limit=attribs[Attributes::ConnLimit].toInt(); setBasicAttributes(this); } @@ -2923,12 +3126,12 @@ void DatabaseModel::loadModel(const QString &filename) map def_objs; //Configuring the path to the base path for objects DTD - dtd_file=GlobalAttributes::SCHEMAS_ROOT_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::XML_SCHEMA_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::OBJECT_DTD_DIR + - GlobalAttributes::DIR_SEPARATOR; + dtd_file=GlobalAttributes::SchemasRootDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::XMLSchemaDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::ObjectDTDDir + + GlobalAttributes::DirSeparator; try { @@ -2936,9 +3139,9 @@ void DatabaseModel::loadModel(const QString &filename) xmlparser.restartParser(); //Loads the root DTD - xmlparser.setDTDFile(dtd_file + GlobalAttributes::ROOT_DTD + - GlobalAttributes::OBJECT_DTD_EXT, - GlobalAttributes::ROOT_DTD); + xmlparser.setDTDFile(dtd_file + GlobalAttributes::RootDTD + + GlobalAttributes::ObjectDTDExt, + GlobalAttributes::RootDTD); //Loads the file validating it against the root DTD xmlparser.loadXMLFile(filename); @@ -2946,28 +3149,44 @@ void DatabaseModel::loadModel(const QString &filename) //Gets the basic model information xmlparser.getElementAttributes(attribs); - this->author=attribs[ParsersAttributes::MODEL_AUTHOR]; + setObjectListsCapacity(attribs[Attributes::MaxObjCount].toUInt()); - pos_str=attribs[ParsersAttributes::LAST_POSITION].split(','); + this->author=attribs[Attributes::ModelAuthor]; + + pos_str=attribs[Attributes::LastPosition].split(','); if(pos_str.size()>=2) this->last_pos=QPoint(pos_str[0].toUInt(),pos_str[1].toUInt()); - this->last_zoom=attribs[ParsersAttributes::LAST_ZOOM].toDouble(); + this->last_zoom=attribs[Attributes::LastZoom].toDouble(); if(this->last_zoom <= 0) this->last_zoom=1; - this->is_template = attribs[ParsersAttributes::IS_TEMPLATE] == ParsersAttributes::_TRUE_; - this->allow_conns = (attribs[ParsersAttributes::ALLOW_CONNS].isEmpty() || - attribs[ParsersAttributes::ALLOW_CONNS] == ParsersAttributes::_TRUE_); + this->is_template = attribs[Attributes::IsTemplate] == Attributes::True; + this->allow_conns = (attribs[Attributes::AllowConns].isEmpty() || + attribs[Attributes::AllowConns] == Attributes::True); + + layers = attribs[Attributes::Layers].split(';', QString::SkipEmptyParts); - protected_model=(attribs[ParsersAttributes::PROTECTED]==ParsersAttributes::_TRUE_); + active_layers.clear(); - def_objs[OBJ_SCHEMA]=attribs[ParsersAttributes::DEFAULT_SCHEMA]; - def_objs[OBJ_ROLE]=attribs[ParsersAttributes::DEFAULT_OWNER]; - def_objs[OBJ_COLLATION]=attribs[ParsersAttributes::DEFAULT_COLLATION]; - def_objs[OBJ_TABLESPACE]=attribs[ParsersAttributes::DEFAULT_TABLESPACE]; + /* Compatibility with models created prior the layers features: + * If the "active-layers" is absent we make the default layer always visible */ + if(!attribs.count(Attributes::ActiveLayers)) + active_layers.push_back(0); + else + { + for(auto &layer_id : attribs[Attributes::ActiveLayers].split(';', QString::SkipEmptyParts)) + active_layers.push_back(layer_id.toInt()); + } + + protected_model=(attribs[Attributes::Protected]==Attributes::True); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + def_objs[ObjectType::Schema]=attribs[Attributes::DefaultSchema]; + def_objs[ObjectType::Role]=attribs[Attributes::DefaultOwner]; + def_objs[ObjectType::Collation]=attribs[Attributes::DefaultCollation]; + def_objs[ObjectType::Tablespace]=attribs[Attributes::DefaultTablespace]; + + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -2978,7 +3197,7 @@ void DatabaseModel::loadModel(const QString &filename) //Indentifies the object type to be load according to the current element on the parser obj_type=getObjectType(elem_name); - if(obj_type==OBJ_DATABASE) + if(obj_type==ObjectType::Database) { xmlparser.getElementAttributes(attribs); configureDatabase(attribs); @@ -2993,20 +3212,20 @@ void DatabaseModel::loadModel(const QString &filename) if(object) { - if(!dynamic_cast(object) && obj_type!=OBJ_RELATIONSHIP && obj_type!=BASE_RELATIONSHIP) + if(!dynamic_cast(object) && obj_type!=ObjectType::Relationship && obj_type!=ObjectType::BaseRelationship) addObject(object); /* If there is at least one inheritance relationship we need to flag this situation in order to do an addtional rel. validation in the end of loading */ - if(!found_inh_rel && object->getObjectType()==OBJ_RELATIONSHIP && - dynamic_cast(object)->getRelationshipType()==BaseRelationship::RELATIONSHIP_GEN) + if(!found_inh_rel && object->getObjectType()==ObjectType::Relationship && + dynamic_cast(object)->getRelationshipType()==BaseRelationship::RelationshipGen) found_inh_rel=true; - emit s_objectLoaded((xmlparser.getCurrentBufferLine()/static_cast(xmlparser.getBufferLineCount()))*100, + emit s_objectLoaded((xmlparser.getCurrentBufferLine()/static_cast(xmlparser.getBufferLineCount()))*100, trUtf8("Loading: `%1' (%2)") .arg(object->getName()) .arg(object->getTypeName()), - obj_type); + enum_cast(obj_type)); } xmlparser.restorePosition(); @@ -3014,12 +3233,12 @@ void DatabaseModel::loadModel(const QString &filename) catch(Exception &e) { QString info_adicional=QString(QObject::trUtf8("%1 (line: %2)")).arg(xmlparser.getLoadedFilename()).arg(xmlparser.getCurrentElement()->line); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, info_adicional); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, info_adicional); } } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } this->BaseObject::setProtected(protected_model); @@ -3032,12 +3251,12 @@ void DatabaseModel::loadModel(const QString &filename) object=this->getObject(itr.second, itr.first); if(!object) - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(this->getName()) .arg(this->getTypeName()) .arg(itr.second) .arg(BaseObject::getTypeName(itr.first)), - ERR_ASG_DUPLIC_PERMISSION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgDuplicatedPermission,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->setDefaultObject(object); } @@ -3050,21 +3269,25 @@ void DatabaseModel::loadModel(const QString &filename) //If there are relationship make a relationship validation to recreate any special object left behind if(!relationships.empty()) { - emit s_objectLoaded(100, trUtf8("Validating relationships..."), OBJ_RELATIONSHIP); + emit s_objectLoaded(100, trUtf8("Validating relationships..."), enum_cast(ObjectType::Relationship)); storeSpecialObjectsXML(); disconnectRelationships(); validateRelationships(); } this->setInvalidated(false); - this->setObjectsModified({OBJ_RELATIONSHIP, BASE_RELATIONSHIP}); + emit s_objectLoaded(100, trUtf8("Validating relationships..."), enum_cast(ObjectType::Relationship)); //Doing another relationship validation when there are inheritances to avoid incomplete tables if(found_inh_rel) { - emit s_objectLoaded(100, trUtf8("Validating relationships..."), OBJ_RELATIONSHIP); + emit s_objectLoaded(100, trUtf8("Validating relationships..."), enum_cast(ObjectType::Relationship)); validateRelationships(); } + + updateTablesFKRelationships(); + emit s_objectLoaded(100, trUtf8("Rendering database model..."), enum_cast(ObjectType::BaseObject)); + this->setObjectsModified(); } catch(Exception &e) { @@ -3074,13 +3297,13 @@ void DatabaseModel::loadModel(const QString &filename) if(xmlparser.getCurrentElement()) extra_info=QString(QObject::trUtf8("%1 (line: %2)")).arg(xmlparser.getLoadedFilename()).arg(xmlparser.getCurrentElement()->line); - if(e.getErrorType()>=ERR_INV_SYNTAX) + if(e.getErrorCode()>=ErrorCode::InvalidSyntax) { - str_aux=QString(Exception::getErrorMessage(ERR_LOAD_INV_MODEL_FILE)).arg(filename); - throw Exception(str_aux,ERR_LOAD_INV_MODEL_FILE,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, extra_info); + str_aux=Exception::getErrorMessage(ErrorCode::InvModelFileNotLoaded).arg(filename); + throw Exception(str_aux,ErrorCode::InvModelFileNotLoaded,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, extra_info); } else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, extra_info); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, extra_info); } } } @@ -3089,69 +3312,75 @@ BaseObject *DatabaseModel::createObject(ObjectType obj_type) { BaseObject *object=nullptr; - if(obj_type!=BASE_OBJECT) + if(obj_type!=ObjectType::BaseObject) { - if(obj_type==OBJ_ROLE) + if(obj_type==ObjectType::Role) object=createRole(); - else if(obj_type==OBJ_TABLESPACE) + else if(obj_type==ObjectType::Tablespace) object=createTablespace(); - else if(obj_type==OBJ_SCHEMA) + else if(obj_type==ObjectType::Schema) object=createSchema(); - else if(obj_type==OBJ_LANGUAGE) + else if(obj_type==ObjectType::Language) object=createLanguage(); - else if(obj_type==OBJ_FUNCTION) + else if(obj_type==ObjectType::Function) object=createFunction(); - else if(obj_type==OBJ_TYPE) + else if(obj_type==ObjectType::Type) object=createType(); - else if(obj_type==OBJ_DOMAIN) + else if(obj_type==ObjectType::Domain) object=createDomain(); - else if(obj_type==OBJ_CAST) + else if(obj_type==ObjectType::Cast) object=createCast(); - else if(obj_type==OBJ_CONVERSION) + else if(obj_type==ObjectType::Conversion) object=createConversion(); - else if(obj_type==OBJ_OPERATOR) + else if(obj_type==ObjectType::Operator) object=createOperator(); - else if(obj_type==OBJ_OPFAMILY) + else if(obj_type==ObjectType::OpFamily) object=createOperatorFamily(); - else if(obj_type==OBJ_OPCLASS) + else if(obj_type==ObjectType::OpClass) object=createOperatorClass(); - else if(obj_type==OBJ_AGGREGATE) + else if(obj_type==ObjectType::Aggregate) object=createAggregate(); - else if(obj_type==OBJ_TABLE) + else if(obj_type==ObjectType::Table) object=createTable(); - else if(obj_type==OBJ_SEQUENCE) + else if(obj_type==ObjectType::Sequence) object=createSequence(); - else if(obj_type==OBJ_VIEW) + else if(obj_type==ObjectType::View) object=createView(); - else if(obj_type==OBJ_TEXTBOX) + else if(obj_type==ObjectType::Textbox) object=createTextbox(); - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) object=createConstraint(nullptr); - else if(obj_type==OBJ_TRIGGER) + else if(obj_type==ObjectType::Trigger) object=createTrigger(); - else if(obj_type==OBJ_INDEX) + else if(obj_type==ObjectType::Index) object=createIndex(); - else if(obj_type==OBJ_COLUMN) + else if(obj_type==ObjectType::Column) object=createColumn(); - else if(obj_type==OBJ_RULE) + else if(obj_type==ObjectType::Rule) object=createRule(); - else if(obj_type==OBJ_RELATIONSHIP || - obj_type==BASE_RELATIONSHIP) + else if(obj_type==ObjectType::Relationship || + obj_type==ObjectType::BaseRelationship) object=createRelationship(); - else if(obj_type==OBJ_COLLATION) + else if(obj_type==ObjectType::Collation) object=createCollation(); - else if(obj_type==OBJ_EXTENSION) + else if(obj_type==ObjectType::Extension) object=createExtension(); - else if(obj_type==OBJ_TAG) + else if(obj_type==ObjectType::Tag) object=createTag(); - else if(obj_type==OBJ_PERMISSION) + else if(obj_type==ObjectType::Permission) object=createPermission(); - else if(obj_type==OBJ_EVENT_TRIGGER) + else if(obj_type==ObjectType::EventTrigger) object=createEventTrigger(); - else if(obj_type==OBJ_GENERIC_SQL) + else if(obj_type==ObjectType::GenericSql) object=createGenericSQL(); - else if(obj_type==OBJ_POLICY) + else if(obj_type==ObjectType::Policy) object=createPolicy(); + else if(obj_type==ObjectType::ForeignDataWrapper) + object=createForeignDataWrapper(); + else if(obj_type==ObjectType::ForeignServer) + object=createForeignServer(); + else if(obj_type==ObjectType::UserMapping) + object=createUserMapping(); } return(object); @@ -3163,24 +3392,44 @@ void DatabaseModel::setBasicAttributes(BaseObject *object) QString elem_name; BaseObject *tabspc=nullptr, *owner=nullptr, *collation=nullptr; Schema *schema=nullptr; - ObjectType obj_type=BASE_OBJECT, obj_type_aux; + ObjectType obj_type=ObjectType::BaseObject, obj_type_aux; bool has_error=false, protected_obj=false, sql_disabled=false; + ForeignObject *frn_object = dynamic_cast(object); if(!object) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); xmlparser.getElementAttributes(attribs); obj_type_aux=object->getObjectType(); - if(obj_type_aux!=OBJ_CAST) - object->setName(attribs[ParsersAttributes::NAME]); - protected_obj=attribs[ParsersAttributes::PROTECTED]==ParsersAttributes::_TRUE_; - sql_disabled=attribs[ParsersAttributes::SQL_DISABLED]==ParsersAttributes::_TRUE_; + if(obj_type_aux!=ObjectType::Cast && obj_type_aux != ObjectType::UserMapping) + object->setName(attribs[Attributes::Name]); + + if(BaseObject::acceptsAlias(obj_type_aux)) + object->setAlias(attribs[Attributes::Alias]); + + protected_obj=attribs[Attributes::Protected]==Attributes::True; + sql_disabled=attribs[Attributes::SqlDisabled]==Attributes::True; + + if(frn_object) + { + QStringList opt_val; + + for(auto &option : attribs[Attributes::Options].split(ForeignObject::OptionsSeparator)) + { + opt_val = option.split(UserMapping::OptionValueSeparator); + + if(opt_val.size() < 2) + continue; + + frn_object->setOption(opt_val[0], opt_val[1]); + } + } xmlparser.savePosition(); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -3189,81 +3438,81 @@ void DatabaseModel::setBasicAttributes(BaseObject *object) elem_name=xmlparser.getElementName(); //Defines the object's comment - if(elem_name==ParsersAttributes::COMMENT) + if(elem_name==Attributes::Comment) { xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); object->setComment(xmlparser.getElementContent()); xmlparser.restorePosition(); } //Defines the object's schema - else if(elem_name==ParsersAttributes::SCHEMA) + else if(elem_name==Attributes::Schema) { - obj_type=OBJ_SCHEMA; + obj_type=ObjectType::Schema; xmlparser.getElementAttributes(attribs_aux); - schema=dynamic_cast(getObject(attribs_aux[ParsersAttributes::NAME], obj_type)); + schema=dynamic_cast(getObject(attribs_aux[Attributes::Name], obj_type)); object->setSchema(schema); - has_error=(!schema && !attribs_aux[ParsersAttributes::NAME].isEmpty()); + has_error=(!schema && !attribs_aux[Attributes::Name].isEmpty()); } //Defines the object's tablespace - else if(elem_name==ParsersAttributes::TABLESPACE) + else if(elem_name==Attributes::Tablespace) { - obj_type=OBJ_TABLESPACE; + obj_type=ObjectType::Tablespace; xmlparser.getElementAttributes(attribs_aux); - tabspc=getObject(attribs_aux[ParsersAttributes::NAME], obj_type); + tabspc=getObject(attribs_aux[Attributes::Name], obj_type); object->setTablespace(tabspc); - has_error=(!tabspc && !attribs_aux[ParsersAttributes::NAME].isEmpty()); + has_error=(!tabspc && !attribs_aux[Attributes::Name].isEmpty()); } //Defines the object's owner - else if(elem_name==ParsersAttributes::ROLE) + else if(elem_name==Attributes::Role) { - obj_type=OBJ_ROLE; + obj_type=ObjectType::Role; xmlparser.getElementAttributes(attribs_aux); - owner=getObject(attribs_aux[ParsersAttributes::NAME], obj_type); + owner=getObject(attribs_aux[Attributes::Name], obj_type); object->setOwner(owner); - has_error=(!owner && !attribs_aux[ParsersAttributes::NAME].isEmpty()); + has_error=(!owner && !attribs_aux[Attributes::Name].isEmpty()); } //Defines the object's schema - else if(elem_name==ParsersAttributes::COLLATION) + else if(elem_name==Attributes::Collation) { - obj_type=OBJ_COLLATION; + obj_type=ObjectType::Collation; xmlparser.getElementAttributes(attribs_aux); - collation=getObject(attribs_aux[ParsersAttributes::NAME], obj_type); + collation=getObject(attribs_aux[Attributes::Name], obj_type); object->setCollation(collation); - has_error=(!collation && !attribs_aux[ParsersAttributes::NAME].isEmpty()); + has_error=(!collation && !attribs_aux[Attributes::Name].isEmpty()); } - else if(elem_name==ParsersAttributes::APPENDED_SQL) + else if(elem_name==Attributes::AppendedSql) { xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); object->setAppendedSQL(xmlparser.getElementContent()); xmlparser.restorePosition(); } - else if(elem_name==ParsersAttributes::PREPENDED_SQL) + else if(elem_name==Attributes::PrependedSql) { xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); object->setPrependedSQL(xmlparser.getElementContent()); xmlparser.restorePosition(); } //Defines the object's position (only for graphical objects) - else if(elem_name==ParsersAttributes::POSITION) + else if(elem_name==Attributes::Position) { xmlparser.getElementAttributes(attribs); - if(elem_name==ParsersAttributes::POSITION && - (obj_type_aux!=OBJ_RELATIONSHIP && - obj_type_aux!=BASE_RELATIONSHIP)) + if(elem_name==Attributes::Position && + (obj_type_aux!=ObjectType::Relationship && + obj_type_aux!=ObjectType::BaseRelationship)) { - dynamic_cast(object)->setPosition(QPointF(attribs[ParsersAttributes::X_POS].toDouble(), - attribs[ParsersAttributes::Y_POS].toDouble())); + dynamic_cast(object)->setPosition(QPointF(attribs[Attributes::XPos].toDouble(), + attribs[Attributes::YPos].toDouble())); } } } } - while(!has_error && xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(!has_error && xmlparser.accessElement(XmlParser::NextElement)); } xmlparser.restorePosition(); @@ -3272,25 +3521,25 @@ void DatabaseModel::setBasicAttributes(BaseObject *object) if(has_error) { - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(object->getName()) .arg(object->getTypeName()) - .arg(attribs_aux[ParsersAttributes::NAME]) + .arg(attribs_aux[Attributes::Name]) .arg(BaseObject::getTypeName(obj_type)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } else if(!object->getSchema() && - (obj_type_aux==OBJ_FUNCTION || obj_type_aux==OBJ_TABLE || - obj_type_aux==OBJ_VIEW || obj_type_aux==OBJ_DOMAIN || - obj_type_aux==OBJ_AGGREGATE || obj_type_aux==OBJ_OPERATOR || - obj_type_aux==OBJ_SEQUENCE || obj_type_aux==OBJ_CONVERSION || - obj_type_aux==OBJ_TYPE || obj_type_aux==OBJ_OPFAMILY || - obj_type_aux==OBJ_OPCLASS)) - { - throw Exception(Exception::getErrorMessage(ERR_ALOC_OBJECT_NO_SCHEMA) + (obj_type_aux==ObjectType::Function || obj_type_aux==ObjectType::Table || + obj_type_aux==ObjectType::View || obj_type_aux==ObjectType::Domain || + obj_type_aux==ObjectType::Aggregate || obj_type_aux==ObjectType::Operator || + obj_type_aux==ObjectType::Sequence || obj_type_aux==ObjectType::Conversion || + obj_type_aux==ObjectType::Type || obj_type_aux==ObjectType::OpFamily || + obj_type_aux==ObjectType::OpClass)) + { + throw Exception(Exception::getErrorMessage(ErrorCode::InvObjectAllocationNoSchema) .arg(object->getName()) .arg(object->getTypeName()), - ERR_ALOC_OBJECT_NO_SCHEMA,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvObjectAllocationNoSchema,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } @@ -3307,6 +3556,46 @@ QString DatabaseModel::getErrorExtraInfo(void) return extra_info; } +void DatabaseModel::setLoadingModel(bool value) +{ + loading_model = value; +} + +void DatabaseModel::setObjectListsCapacity(unsigned capacity) +{ + if(capacity < BaseObject::DefMaxObjectCount || + capacity > (BaseObject::DefMaxObjectCount * 1000)) + capacity = BaseObject::DefMaxObjectCount; + + unsigned half_cap = capacity/2, one_fourth_cap = capacity/4; + + views.reserve(capacity); + tables.reserve(capacity); + relationships.reserve(capacity); + base_relationships.reserve(capacity); + sequences.reserve(capacity); + permissions.reserve(capacity); + schemas.reserve(half_cap); + roles.reserve(half_cap); + functions.reserve(half_cap); + types.reserve(half_cap); + textboxes.reserve(half_cap); + aggregates.reserve(half_cap); + operators.reserve(half_cap); + op_classes.reserve(half_cap); + op_families.reserve(half_cap); + domains.reserve(half_cap); + collations.reserve(half_cap); + extensions.reserve(half_cap); + tags.reserve(half_cap); + genericsqls.reserve(half_cap); + tablespaces.reserve(one_fourth_cap); + languages.reserve(one_fourth_cap); + casts.reserve(one_fourth_cap); + conversions.reserve(one_fourth_cap); + eventtriggers.reserve(one_fourth_cap); +} + void DatabaseModel::setLastPosition(const QPoint &pnt) { last_pos=pnt; @@ -3337,15 +3626,15 @@ Role *DatabaseModel::createRole(void) QString elem_name; unsigned role_type; - QString op_attribs[]={ ParsersAttributes::SUPERUSER, ParsersAttributes::CREATEDB, - ParsersAttributes::CREATEROLE, ParsersAttributes::INHERIT, - ParsersAttributes::LOGIN, ParsersAttributes::ENCRYPTED, - ParsersAttributes::REPLICATION, ParsersAttributes::BYPASSRLS }; + QString op_attribs[]={ Attributes::Superuser, Attributes::CreateDb, + Attributes::CreateRole, Attributes::Inherit, + Attributes::Login, Attributes::Encrypted, + Attributes::Replication, Attributes::BypassRls }; - unsigned op_vect[]={ Role::OP_SUPERUSER, Role::OP_CREATEDB, - Role::OP_CREATEROLE, Role::OP_INHERIT, - Role::OP_LOGIN, Role::OP_ENCRYPTED, - Role::OP_REPLICATION, Role::OP_BYPASSRLS }; + unsigned op_vect[]={ Role::OpSuperuser, Role::OpCreateDb, + Role::OpCreateRole, Role::OpInherit, + Role::OpLogin, Role::OpEncrypted, + Role::OpReplication, Role::OpBypassRls }; try { @@ -3355,20 +3644,20 @@ Role *DatabaseModel::createRole(void) //Gets all the attributes values from the XML xmlparser.getElementAttributes(attribs); - role->setPassword(attribs[ParsersAttributes::PASSWORD]); - role->setValidity(attribs[ParsersAttributes::VALIDITY]); + role->setPassword(attribs[Attributes::Password]); + role->setValidity(attribs[Attributes::Validity]); - if(!attribs[ParsersAttributes::CONN_LIMIT].isEmpty()) - role->setConnectionLimit(attribs[ParsersAttributes::CONN_LIMIT].toInt()); + if(!attribs[Attributes::ConnLimit].isEmpty()) + role->setConnectionLimit(attribs[Attributes::ConnLimit].toInt()); //Setting up the role options according to the configured on the XML for(i=0; i < 8; i++) { - marked=attribs[op_attribs[i]]==ParsersAttributes::_TRUE_; + marked=attribs[op_attribs[i]]==Attributes::True; role->setOption(op_vect[i], marked); } - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -3377,37 +3666,37 @@ Role *DatabaseModel::createRole(void) elem_name=xmlparser.getElementName(); //Getting the member roles - if(elem_name==ParsersAttributes::ROLES) + if(elem_name==Attributes::Roles) { //Gets the member roles attributes xmlparser.getElementAttributes(attribs_aux); //The member roles names are separated by comma, so it is needed to split them - list=attribs_aux[ParsersAttributes::NAMES].split(','); + list=attribs_aux[Attributes::Names].split(','); len=list.size(); //Identifying the member role type - if(attribs_aux[ParsersAttributes::ROLE_TYPE]==ParsersAttributes::REFER) - role_type=Role::REF_ROLE; - else if(attribs_aux[ParsersAttributes::ROLE_TYPE]==ParsersAttributes::MEMBER) - role_type=Role::MEMBER_ROLE; + if(attribs_aux[Attributes::RoleType]==Attributes::Refer) + role_type=Role::RefRole; + else if(attribs_aux[Attributes::RoleType]==Attributes::Member) + role_type=Role::MemberRole; else - role_type=Role::ADMIN_ROLE; + role_type=Role::AdminRole; for(i=0; i < len; i++) { //Gets the role using the name from the model using the name from the list - ref_role=dynamic_cast(getObject(list[i].trimmed(),OBJ_ROLE)); + ref_role=dynamic_cast(getObject(list[i].trimmed(),ObjectType::Role)); //Raises an error if the roles doesn't exists if(!ref_role) { - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(role->getName()) - .arg(BaseObject::getTypeName(OBJ_ROLE)) + .arg(BaseObject::getTypeName(ObjectType::Role)) .arg(list[i]) - .arg(BaseObject::getTypeName(OBJ_ROLE)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Role)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } role->addRole(role_type, ref_role); @@ -3415,13 +3704,13 @@ Role *DatabaseModel::createRole(void) } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) { if(role) delete(role); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(role); @@ -3437,12 +3726,12 @@ Tablespace *DatabaseModel::createTablespace(void) tabspc=new Tablespace; setBasicAttributes(tabspc); xmlparser.getElementAttributes(attribs); - tabspc->setDirectory(attribs[ParsersAttributes::DIRECTORY]); + tabspc->setDirectory(attribs[Attributes::Directory]); } catch(Exception &e) { if(tabspc) delete(tabspc); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(tabspc); @@ -3458,14 +3747,15 @@ Schema *DatabaseModel::createSchema(void) schema=new Schema; xmlparser.getElementAttributes(attribs); setBasicAttributes(schema); - schema->setFillColor(QColor(attribs[ParsersAttributes::FILL_COLOR])); - schema->setRectVisible(attribs[ParsersAttributes::RECT_VISIBLE]==ParsersAttributes::_TRUE_); - schema->setFadedOut(attribs[ParsersAttributes::FADED_OUT]==ParsersAttributes::_TRUE_); + schema->setFillColor(QColor(attribs[Attributes::FillColor])); + schema->setRectVisible(attribs[Attributes::RectVisible]==Attributes::True); + schema->setFadedOut(attribs[Attributes::FadedOut]==Attributes::True); + schema->setLayer(attribs[Attributes::Layer].toUInt()); } catch(Exception &e) { if(schema) delete(schema); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(schema); @@ -3485,9 +3775,9 @@ Language *DatabaseModel::createLanguage(void) xmlparser.getElementAttributes(attribs); setBasicAttributes(lang); - lang->setTrusted(attribs[ParsersAttributes::TRUSTED]==ParsersAttributes::_TRUE_); + lang->setTrusted(attribs[Attributes::Trusted]==Attributes::True); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -3495,53 +3785,53 @@ Language *DatabaseModel::createLanguage(void) { obj_type=BaseObject::getObjectType(xmlparser.getElementName()); - if(obj_type==OBJ_FUNCTION) + if(obj_type==ObjectType::Function) { xmlparser.getElementAttributes(attribs); //Gets the function reference type - ref_type=attribs[ParsersAttributes::REF_TYPE]; + ref_type=attribs[Attributes::RefType]; //Only VALIDATOR, HANDLER and INLINE functions are accepted for the language - if(ref_type==ParsersAttributes::VALIDATOR_FUNC || - ref_type==ParsersAttributes::HANDLER_FUNC || - ref_type==ParsersAttributes::INLINE_FUNC) + if(ref_type==Attributes::ValidatorFunc || + ref_type==Attributes::HandlerFunc || + ref_type==Attributes::InlineFunc) { //Gets the function signature and tries to retrieve it from the model - signature=attribs[ParsersAttributes::SIGNATURE]; - func=getObject(signature, OBJ_FUNCTION); + signature=attribs[Attributes::Signature]; + func=getObject(signature, ObjectType::Function); //Raises an error if the function doesn't exists if(!func) - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(lang->getName()) .arg(lang->getTypeName()) .arg(signature) - .arg(BaseObject::getTypeName(OBJ_FUNCTION)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Function)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(ref_type==ParsersAttributes::VALIDATOR_FUNC) - lang->setFunction(dynamic_cast(func), Language::VALIDATOR_FUNC); - else if(ref_type==ParsersAttributes::HANDLER_FUNC) - lang->setFunction(dynamic_cast(func), Language::HANDLER_FUNC); + if(ref_type==Attributes::ValidatorFunc) + lang->setFunction(dynamic_cast(func), Language::ValidatorFunc); + else if(ref_type==Attributes::HandlerFunc) + lang->setFunction(dynamic_cast(func), Language::HandlerFunc); else - lang->setFunction(dynamic_cast(func), Language::INLINE_FUNC); + lang->setFunction(dynamic_cast(func), Language::InlineFunc); } else //Raises an error if the function type is invalid - throw Exception(ERR_REF_FUNCTION_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefFunctionInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) { if(lang) delete(lang); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(lang); @@ -3553,7 +3843,7 @@ Function *DatabaseModel::createFunction(void) Function *func=nullptr; ObjectType obj_type; BaseObject *object=nullptr; - PgSQLType type; + PgSqlType type; Parameter param; QString str_aux, elem; @@ -3563,34 +3853,34 @@ Function *DatabaseModel::createFunction(void) setBasicAttributes(func); xmlparser.getElementAttributes(attribs); - if(!attribs[ParsersAttributes::RETURNS_SETOF].isEmpty()) - func->setReturnSetOf(attribs[ParsersAttributes::RETURNS_SETOF]== - ParsersAttributes::_TRUE_); + if(!attribs[Attributes::ReturnsSetOf].isEmpty()) + func->setReturnSetOf(attribs[Attributes::ReturnsSetOf]== + Attributes::True); - if(!attribs[ParsersAttributes::WINDOW_FUNC].isEmpty()) - func->setWindowFunction(attribs[ParsersAttributes::WINDOW_FUNC]== - ParsersAttributes::_TRUE_); + if(!attribs[Attributes::WindowFunc].isEmpty()) + func->setWindowFunction(attribs[Attributes::WindowFunc]== + Attributes::True); - if(!attribs[ParsersAttributes::LEAKPROOF].isEmpty()) - func->setLeakProof(attribs[ParsersAttributes::LEAKPROOF]== - ParsersAttributes::_TRUE_); + if(!attribs[Attributes::LeakProof].isEmpty()) + func->setLeakProof(attribs[Attributes::LeakProof]== + Attributes::True); - if(!attribs[ParsersAttributes::BEHAVIOR_TYPE].isEmpty()) - func->setBehaviorType(BehaviorType(attribs[ParsersAttributes::BEHAVIOR_TYPE])); + if(!attribs[Attributes::BehaviorType].isEmpty()) + func->setBehaviorType(BehaviorType(attribs[Attributes::BehaviorType])); - if(!attribs[ParsersAttributes::FUNCTION_TYPE].isEmpty()) - func->setFunctionType(FunctionType(attribs[ParsersAttributes::FUNCTION_TYPE])); + if(!attribs[Attributes::FunctionType].isEmpty()) + func->setFunctionType(FunctionType(attribs[Attributes::FunctionType])); - if(!attribs[ParsersAttributes::SECURITY_TYPE].isEmpty()) - func->setSecurityType(SecurityType(attribs[ParsersAttributes::SECURITY_TYPE])); + if(!attribs[Attributes::SecurityType].isEmpty()) + func->setSecurityType(SecurityType(attribs[Attributes::SecurityType])); - if(!attribs[ParsersAttributes::EXECUTION_COST].isEmpty()) - func->setExecutionCost(attribs[ParsersAttributes::EXECUTION_COST].toInt()); + if(!attribs[Attributes::ExecutionCost].isEmpty()) + func->setExecutionCost(attribs[Attributes::ExecutionCost].toInt()); - if(!attribs[ParsersAttributes::ROW_AMOUNT].isEmpty()) - func->setRowAmount(attribs[ParsersAttributes::ROW_AMOUNT].toInt()); + if(!attribs[Attributes::RowAmount].isEmpty()) + func->setRowAmount(attribs[Attributes::RowAmount].toInt()); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -3600,84 +3890,84 @@ Function *DatabaseModel::createFunction(void) obj_type=BaseObject::getObjectType(elem); //Gets the function return type from the XML - if(elem==ParsersAttributes::RETURN_TYPE) + if(elem==Attributes::ReturnType) { xmlparser.savePosition(); try { - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); do { if(xmlparser.getElementType()==XML_ELEMENT_NODE) { //when the element found is a TYPE indicates that the function return type is a single one - if(xmlparser.getElementName()==ParsersAttributes::TYPE) + if(xmlparser.getElementName()==Attributes::Type) { type=createPgSQLType(); func->setReturnType(type); } //when the element found is a PARAMETER indicates that the function return type is a table - else if(xmlparser.getElementName()==ParsersAttributes::PARAMETER) + else if(xmlparser.getElementName()==Attributes::Parameter) { param=createParameter(); func->addReturnedTableColumn(param.getName(), param.getType()); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); xmlparser.restorePosition(); } catch(Exception &e) { xmlparser.restorePosition(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } //Gets the function language - else if(obj_type==OBJ_LANGUAGE) + else if(obj_type==ObjectType::Language) { xmlparser.getElementAttributes(attribs); - object=getObject(attribs[ParsersAttributes::NAME], obj_type); + object=getObject(attribs[Attributes::Name], obj_type); //Raises an error if the function doesn't exisits if(!object) - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(func->getName()) .arg(func->getTypeName()) - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(OBJ_LANGUAGE)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Language)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); func->setLanguage(dynamic_cast(object)); } //Gets a function parameter - else if(xmlparser.getElementName()==ParsersAttributes::PARAMETER) + else if(xmlparser.getElementName()==Attributes::Parameter) { param=createParameter(); func->addParameter(param); } //Gets the function code definition - else if(xmlparser.getElementName()==ParsersAttributes::DEFINITION) + else if(xmlparser.getElementName()==Attributes::Definition) { xmlparser.savePosition(); xmlparser.getElementAttributes(attribs_aux); - if(!attribs_aux[ParsersAttributes::LIBRARY].isEmpty()) + if(!attribs_aux[Attributes::Library].isEmpty()) { - func->setLibrary(attribs_aux[ParsersAttributes::LIBRARY]); - func->setSymbol(attribs_aux[ParsersAttributes::SYMBOL]); + func->setLibrary(attribs_aux[Attributes::Library]); + func->setSymbol(attribs_aux[Attributes::Symbol]); } - else if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + else if(xmlparser.accessElement(XmlParser::ChildElement)) func->setSourceCode(xmlparser.getElementContent()); xmlparser.restorePosition(); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) @@ -3688,13 +3978,13 @@ Function *DatabaseModel::createFunction(void) delete(func); } - if(e.getErrorType()==ERR_REF_INEXIST_USER_TYPE) - throw Exception(Exception::getErrorMessage(ERR_ASG_OBJ_INV_DEFINITION) + if(e.getErrorCode()==ErrorCode::RefUserTypeInexistsModel) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgObjectInvalidDefinition) .arg(str_aux) - .arg(BaseObject::getTypeName(OBJ_FUNCTION)), - ERR_ASG_OBJ_INV_DEFINITION,__PRETTY_FUNCTION__,__FILE__,__LINE__,&e, getErrorExtraInfo()); + .arg(BaseObject::getTypeName(ObjectType::Function)), + ErrorCode::AsgObjectInvalidDefinition,__PRETTY_FUNCTION__,__FILE__,__LINE__,&e, getErrorExtraInfo()); else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(func); @@ -3711,10 +4001,10 @@ Parameter DatabaseModel::createParameter(void) xmlparser.savePosition(); xmlparser.getElementAttributes(attribs); - param.setName(attribs[ParsersAttributes::NAME]); - param.setDefaultValue(attribs[ParsersAttributes::DEFAULT_VALUE]); + param.setName(attribs[Attributes::Name]); + param.setDefaultValue(attribs[Attributes::DefaultValue]); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -3722,18 +4012,18 @@ Parameter DatabaseModel::createParameter(void) { elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::TYPE) + if(elem==Attributes::Type) { param.setType(createPgSQLType()); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } - param.setIn(attribs[ParsersAttributes::PARAM_IN]==ParsersAttributes::_TRUE_); - param.setOut(attribs[ParsersAttributes::PARAM_OUT]==ParsersAttributes::_TRUE_); - param.setVariadic(attribs[ParsersAttributes::PARAM_VARIADIC]==ParsersAttributes::_TRUE_); + param.setIn(attribs[Attributes::ParamIn]==Attributes::True); + param.setOut(attribs[Attributes::ParamOut]==Attributes::True); + param.setVariadic(attribs[Attributes::ParamVariadic]==Attributes::True); xmlparser.restorePosition(); } @@ -3741,7 +4031,7 @@ Parameter DatabaseModel::createParameter(void) { QString extra_info=getErrorExtraInfo(); xmlparser.restorePosition(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, extra_info); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, extra_info); } return(param); @@ -3759,9 +4049,9 @@ TypeAttribute DatabaseModel::createTypeAttribute(void) xmlparser.savePosition(); xmlparser.getElementAttributes(attribs); - tpattrib.setName(attribs[ParsersAttributes::NAME]); + tpattrib.setName(attribs[Attributes::Name]); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -3769,32 +4059,32 @@ TypeAttribute DatabaseModel::createTypeAttribute(void) { elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::TYPE) + if(elem==Attributes::Type) { tpattrib.setType(createPgSQLType()); } - else if(elem==ParsersAttributes::COLLATION) + else if(elem==Attributes::Collation) { xmlparser.getElementAttributes(attribs); - collation=getObject(attribs[ParsersAttributes::NAME], OBJ_COLLATION); + collation=getObject(attribs[Attributes::Name], ObjectType::Collation); //Raises an error if the operator class doesn't exists if(!collation) { - throw Exception(QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(tpattrib.getName()) .arg(tpattrib.getTypeName()) - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(OBJ_COLLATION)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Collation)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } tpattrib.setCollation(collation); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } xmlparser.restorePosition(); @@ -3803,13 +4093,13 @@ TypeAttribute DatabaseModel::createTypeAttribute(void) { QString extra_info=getErrorExtraInfo(); xmlparser.restorePosition(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, extra_info); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, extra_info); } return(tpattrib); } -PgSQLType DatabaseModel::createPgSQLType(void) +PgSqlType DatabaseModel::createPgSQLType(void) { attribs_map attribs; unsigned length=1, dimension=0, type_idx=0; @@ -3822,47 +4112,47 @@ PgSQLType DatabaseModel::createPgSQLType(void) xmlparser.getElementAttributes(attribs); - if(!attribs[ParsersAttributes::LENGTH].isEmpty()) - length=attribs[ParsersAttributes::LENGTH].toUInt(); + if(!attribs[Attributes::Length].isEmpty()) + length=attribs[Attributes::Length].toUInt(); - if(!attribs[ParsersAttributes::DIMENSION].isEmpty()) - dimension=attribs[ParsersAttributes::DIMENSION].toUInt(); + if(!attribs[Attributes::Dimension].isEmpty()) + dimension=attribs[Attributes::Dimension].toUInt(); - if(!attribs[ParsersAttributes::PRECISION].isEmpty()) - precision=attribs[ParsersAttributes::PRECISION].toInt(); + if(!attribs[Attributes::Precision].isEmpty()) + precision=attribs[Attributes::Precision].toInt(); - with_timezone=(attribs[ParsersAttributes::WITH_TIMEZONE]==ParsersAttributes::_TRUE_); - interv_type=attribs[ParsersAttributes::INTERVAL_TYPE]; + with_timezone=(attribs[Attributes::WithTimezone]==Attributes::True); + interv_type=attribs[Attributes::IntervalType]; - if(!attribs[ParsersAttributes::SPATIAL_TYPE].isEmpty()) - spatial_type=SpatialType(attribs[ParsersAttributes::SPATIAL_TYPE], - attribs[ParsersAttributes::SRID].toUInt(), - attribs[ParsersAttributes::VARIATION].toUInt()); + if(!attribs[Attributes::SpatialType].isEmpty()) + spatial_type=SpatialType(attribs[Attributes::SpatialType], + attribs[Attributes::Srid].toUInt(), + attribs[Attributes::Variation].toUInt()); - name=attribs[ParsersAttributes::NAME]; + name=attribs[Attributes::Name]; /* A small tweak to detect a timestamp/date type which name contains the time zone modifier. This situation can occur mainly on reverse engineering operation where the data type of objects in most of times came as string form and need to be parsed */ - if(!with_timezone && attribs[ParsersAttributes::NAME].contains(QString("with time zone"), Qt::CaseInsensitive)) + if(!with_timezone && attribs[Attributes::Name].contains(QString("with time zone"), Qt::CaseInsensitive)) { with_timezone=true; name.remove(QString(" with time zone"), Qt::CaseInsensitive); } - type_idx=PgSQLType::getBaseTypeIndex(name); - if(type_idx!=PgSQLType::null) + type_idx=PgSqlType::getBaseTypeIndex(name); + if(type_idx!=PgSqlType::Null) { - return(PgSQLType(name,length,dimension,precision,with_timezone,interv_type, spatial_type)); + return(PgSqlType(name, dimension, length, precision, with_timezone, interv_type, spatial_type)); } else { //Raises an error if the referenced type name doesn't exists - if(PgSQLType::getUserTypeIndex(name,nullptr,this) == BaseType::null) - throw Exception(ERR_REF_INEXIST_USER_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(PgSqlType::getUserTypeIndex(name,nullptr,this) == BaseType::Null) + throw Exception(ErrorCode::RefUserTypeInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); - type_idx=PgSQLType::getUserTypeIndex(name, ptype); - return(PgSQLType(type_idx,length,dimension,precision,with_timezone,interv_type,spatial_type)); + type_idx=PgSqlType::getUserTypeIndex(name, ptype); + return(PgSqlType(type_idx, dimension, length, precision, with_timezone, interv_type, spatial_type)); } } @@ -3876,7 +4166,7 @@ Type *DatabaseModel::createType(void) QString elem, str_aux; BaseObject *func=nullptr, *collation=nullptr; OperatorClass *op_class=nullptr; - PgSQLType aux_type; + PgSqlType aux_type; try { @@ -3884,56 +4174,56 @@ Type *DatabaseModel::createType(void) setBasicAttributes(type); xmlparser.getElementAttributes(attribs); - if(attribs[ParsersAttributes::CONFIGURATION]==ParsersAttributes::BASE_TYPE) + if(attribs[Attributes::Configuration]==Attributes::BaseType) { - type->setConfiguration(Type::BASE_TYPE); - type->setByValue(attribs[ParsersAttributes::BY_VALUE]==ParsersAttributes::_TRUE_); + type->setConfiguration(Type::BaseType); + type->setByValue(attribs[Attributes::ByValue]==Attributes::True); - if(!attribs[ParsersAttributes::INTERNAL_LENGTH].isEmpty()) - type->setInternalLength(attribs[ParsersAttributes::INTERNAL_LENGTH].toUInt()); + if(!attribs[Attributes::InternalLength].isEmpty()) + type->setInternalLength(attribs[Attributes::InternalLength].toUInt()); - if(!attribs[ParsersAttributes::ALIGNMENT].isEmpty()) - type->setAlignment(attribs[ParsersAttributes::ALIGNMENT]); + if(!attribs[Attributes::Alignment].isEmpty()) + type->setAlignment(attribs[Attributes::Alignment]); - if(!attribs[ParsersAttributes::STORAGE].isEmpty()) - type->setStorage(attribs[ParsersAttributes::STORAGE]); + if(!attribs[Attributes::Storage].isEmpty()) + type->setStorage(attribs[Attributes::Storage]); - if(!attribs[ParsersAttributes::ELEMENT].isEmpty()) - type->setElement(attribs[ParsersAttributes::ELEMENT]); + if(!attribs[Attributes::Element].isEmpty()) + type->setElement(attribs[Attributes::Element]); - if(!attribs[ParsersAttributes::DELIMITER].isEmpty()) - type->setDelimiter(attribs[ParsersAttributes::DELIMITER][0].toLatin1()); + if(!attribs[Attributes::Delimiter].isEmpty()) + type->setDelimiter(attribs[Attributes::Delimiter][0].toLatin1()); - if(!attribs[ParsersAttributes::DEFAULT_VALUE].isEmpty()) - type->setDefaultValue(attribs[ParsersAttributes::DEFAULT_VALUE]); + if(!attribs[Attributes::DefaultValue].isEmpty()) + type->setDefaultValue(attribs[Attributes::DefaultValue]); - if(!attribs[ParsersAttributes::CATEGORY].isEmpty()) - type->setCategory(attribs[ParsersAttributes::CATEGORY]); + if(!attribs[Attributes::Category].isEmpty()) + type->setCategory(attribs[Attributes::Category]); - if(!attribs[ParsersAttributes::PREFERRED].isEmpty()) - type->setPreferred(attribs[ParsersAttributes::PREFERRED]==ParsersAttributes::_TRUE_); + if(!attribs[Attributes::Preferred].isEmpty()) + type->setPreferred(attribs[Attributes::Preferred]==Attributes::True); //Configuring an auxiliary map used to reference the functions used by base type - func_types[ParsersAttributes::INPUT_FUNC]=Type::INPUT_FUNC; - func_types[ParsersAttributes::OUTPUT_FUNC]=Type::OUTPUT_FUNC; - func_types[ParsersAttributes::SEND_FUNC]=Type::SEND_FUNC; - func_types[ParsersAttributes::RECV_FUNC]=Type::RECV_FUNC; - func_types[ParsersAttributes::TPMOD_IN_FUNC]=Type::TPMOD_IN_FUNC; - func_types[ParsersAttributes::TPMOD_OUT_FUNC]=Type::TPMOD_OUT_FUNC; - func_types[ParsersAttributes::ANALYZE_FUNC]=Type::ANALYZE_FUNC; - } - else if(attribs[ParsersAttributes::CONFIGURATION]==ParsersAttributes::COMPOSITE_TYPE) - type->setConfiguration(Type::COMPOSITE_TYPE); - else if(attribs[ParsersAttributes::CONFIGURATION]==ParsersAttributes::ENUM_TYPE) - type->setConfiguration(Type::ENUMERATION_TYPE); + func_types[Attributes::InputFunc]=Type::InputFunc; + func_types[Attributes::OutputFunc]=Type::OutputFunc; + func_types[Attributes::SendFunc]=Type::SendFunc; + func_types[Attributes::RecvFunc]=Type::RecvFunc; + func_types[Attributes::TpmodInFunc]=Type::TpmodInFunc; + func_types[Attributes::TpmodOutFunc]=Type::TpmodOutFunc; + func_types[Attributes::AnalyzeFunc]=Type::AnalyzeFunc; + } + else if(attribs[Attributes::Configuration]==Attributes::CompositeType) + type->setConfiguration(Type::CompositeType); + else if(attribs[Attributes::Configuration]==Attributes::EnumType) + type->setConfiguration(Type::EnumerationType); else { - type->setConfiguration(Type::RANGE_TYPE); - func_types[ParsersAttributes::CANONICAL_FUNC]=Type::CANONICAL_FUNC; - func_types[ParsersAttributes::SUBTYPE_DIFF_FUNC]=Type::SUBTYPE_DIFF_FUNC; + type->setConfiguration(Type::RangeType); + func_types[Attributes::CanonicalFunc]=Type::CanonicalFunc; + func_types[Attributes::SubtypeDiffFunc]=Type::SubtypeDiffFunc; } - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -3942,91 +4232,91 @@ Type *DatabaseModel::createType(void) elem=xmlparser.getElementName(); //Specific operations for ENUM type - if(elem==ParsersAttributes::ENUM_TYPE) + if(elem==Attributes::EnumType) { xmlparser.getElementAttributes(attribs); - enums=attribs[ParsersAttributes::VALUES].split(','); + enums=attribs[Attributes::Values].split(','); count=enums.size(); for(i=0; i < count; i++) type->addEnumeration(enums[i]); } //Specific operations for COMPOSITE types - else if(elem==ParsersAttributes::TYPE_ATTRIBUTE) + else if(elem==Attributes::TypeAttribute) { type->addAttribute(createTypeAttribute()); } //Specific operations for BASE / RANGE type - else if(elem==ParsersAttributes::TYPE) + else if(elem==Attributes::Type) { aux_type=createPgSQLType(); - if(type->getConfiguration()==Type::RANGE_TYPE) + if(type->getConfiguration()==Type::RangeType) type->setSubtype(aux_type); else type->setLikeType(aux_type); } - else if(elem==ParsersAttributes::COLLATION) + else if(elem==Attributes::Collation) { xmlparser.getElementAttributes(attribs); - collation=getObject(attribs[ParsersAttributes::NAME], OBJ_COLLATION); + collation=getObject(attribs[Attributes::Name], ObjectType::Collation); //Raises an error if the operator class doesn't exists if(!collation) { - throw Exception(QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(type->getName()) .arg(type->getTypeName()) - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(OBJ_COLLATION)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Collation)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } type->setCollation(collation); } - if(elem==ParsersAttributes::OP_CLASS) + if(elem==Attributes::OpClass) { xmlparser.getElementAttributes(attribs); - op_class=dynamic_cast(getObject(attribs[ParsersAttributes::NAME], OBJ_OPCLASS)); + op_class=dynamic_cast(getObject(attribs[Attributes::Name], ObjectType::OpClass)); //Raises an error if the operator class doesn't exists if(!op_class) { - throw Exception(QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(type->getName()) .arg(type->getTypeName()) - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(OBJ_OPCLASS)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::OpClass)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } type->setSubtypeOpClass(op_class); } //Configuring the functions used by the type (only for BASE type) - else if(elem==ParsersAttributes::FUNCTION) + else if(elem==Attributes::Function) { xmlparser.getElementAttributes(attribs); //Tries to get the function from the model - func=getObject(attribs[ParsersAttributes::SIGNATURE], OBJ_FUNCTION); + func=getObject(attribs[Attributes::Signature], ObjectType::Function); //Raises an error if the function doesn't exists - if(!func && !attribs[ParsersAttributes::SIGNATURE].isEmpty()) - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + if(!func && !attribs[Attributes::Signature].isEmpty()) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(type->getName()) .arg(type->getTypeName()) - .arg(attribs[ParsersAttributes::SIGNATURE]) - .arg(BaseObject::getTypeName(OBJ_FUNCTION)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs[Attributes::Signature]) + .arg(BaseObject::getTypeName(ObjectType::Function)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the function type is invalid - else if(func_types.count(attribs[ParsersAttributes::REF_TYPE])==0) - throw Exception(ERR_REF_FUNCTION_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(func_types.count(attribs[Attributes::RefType])==0) + throw Exception(ErrorCode::RefFunctionInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); - type->setFunction(func_types[attribs[ParsersAttributes::REF_TYPE]], dynamic_cast(func)); + type->setFunction(func_types[attribs[Attributes::RefType]], dynamic_cast(func)); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) @@ -4037,13 +4327,13 @@ Type *DatabaseModel::createType(void) delete(type); } - if(e.getErrorType()==ERR_REF_INEXIST_USER_TYPE) - throw Exception(Exception::getErrorMessage(ERR_ASG_OBJ_INV_DEFINITION) + if(e.getErrorCode()==ErrorCode::RefUserTypeInexistsModel) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgObjectInvalidDefinition) .arg(str_aux) .arg(type->getTypeName()), - ERR_ASG_OBJ_INV_DEFINITION,__PRETTY_FUNCTION__,__FILE__,__LINE__,&e, getErrorExtraInfo()); + ErrorCode::AsgObjectInvalidDefinition,__PRETTY_FUNCTION__,__FILE__,__LINE__,&e, getErrorExtraInfo()); else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(type); @@ -4061,12 +4351,12 @@ Domain *DatabaseModel::createDomain(void) setBasicAttributes(domain); xmlparser.getElementAttributes(attribs); - if(!attribs[ParsersAttributes::DEFAULT_VALUE].isEmpty()) - domain->setDefaultValue(attribs[ParsersAttributes::DEFAULT_VALUE]); + if(!attribs[Attributes::DefaultValue].isEmpty()) + domain->setDefaultValue(attribs[Attributes::DefaultValue]); - domain->setNotNull(attribs[ParsersAttributes::NOT_NULL]==ParsersAttributes::_TRUE_); + domain->setNotNull(attribs[Attributes::NotNull]==Attributes::True); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -4075,28 +4365,28 @@ Domain *DatabaseModel::createDomain(void) elem=xmlparser.getElementName(); //If a type element is found it'll be extracted an type which the domain is applied - if(elem==ParsersAttributes::TYPE) + if(elem==Attributes::Type) { domain->setType(createPgSQLType()); } - else if(elem==ParsersAttributes::CONSTRAINT) + else if(elem==Attributes::Constraint) { xmlparser.savePosition(); xmlparser.getElementAttributes(attribs); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); - domain->addCheckConstraint(attribs[ParsersAttributes::NAME], xmlparser.getElementContent()); + xmlparser.accessElement(XmlParser::ChildElement); + xmlparser.accessElement(XmlParser::ChildElement); + domain->addCheckConstraint(attribs[Attributes::Name], xmlparser.getElementContent()); xmlparser.restorePosition(); } } } - while(xmlparser.accessElement(xmlparser.NEXT_ELEMENT)); + while(xmlparser.accessElement(xmlparser.NextElement)); } } catch(Exception &e) { if(domain) delete(domain); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(domain); @@ -4108,7 +4398,7 @@ Cast *DatabaseModel::createCast(void) Cast *cast=nullptr; QString elem; unsigned type_idx=0; - PgSQLType type; + PgSqlType type; BaseObject *func=nullptr; try @@ -4117,16 +4407,16 @@ Cast *DatabaseModel::createCast(void) setBasicAttributes(cast); xmlparser.getElementAttributes(attribs); - if(attribs[ParsersAttributes::CAST_TYPE]==ParsersAttributes::IMPLICIT) - cast->setCastType(Cast::IMPLICIT); - else if(attribs[ParsersAttributes::CAST_TYPE]==ParsersAttributes::ASSIGNMENT) - cast->setCastType(Cast::ASSIGNMENT); + if(attribs[Attributes::CastType]==Attributes::Implicit) + cast->setCastType(Cast::Implicit); + else if(attribs[Attributes::CastType]==Attributes::Assignment) + cast->setCastType(Cast::Assignment); else - cast->setCastType(Cast::EXPLICIT); + cast->setCastType(Cast::Explicit); - cast->setInOut(attribs[ParsersAttributes::IO_CAST]==ParsersAttributes::_TRUE_); + cast->setInOut(attribs[Attributes::IoCast]==Attributes::True); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -4135,41 +4425,41 @@ Cast *DatabaseModel::createCast(void) elem=xmlparser.getElementName(); //Extract one argument type from the XML - if(elem==ParsersAttributes::TYPE) + if(elem==Attributes::Type) { type=createPgSQLType(); if(type_idx==0) - cast->setDataType(Cast::SRC_TYPE, type); + cast->setDataType(Cast::SrcType, type); else - cast->setDataType(Cast::DST_TYPE, type); + cast->setDataType(Cast::DstType, type); type_idx++; } //Extracts the conversion function - else if(elem==ParsersAttributes::FUNCTION) + else if(elem==Attributes::Function) { xmlparser.getElementAttributes(attribs); - func=getObject(attribs[ParsersAttributes::SIGNATURE], OBJ_FUNCTION); + func=getObject(attribs[Attributes::Signature], ObjectType::Function); //Raises an error if the function doesn't exists - if(!func && !attribs[ParsersAttributes::SIGNATURE].isEmpty()) - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + if(!func && !attribs[Attributes::Signature].isEmpty()) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(cast->getName()) .arg(cast->getTypeName()) - .arg(attribs[ParsersAttributes::SIGNATURE]) - .arg(BaseObject::getTypeName(OBJ_FUNCTION)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs[Attributes::Signature]) + .arg(BaseObject::getTypeName(ObjectType::Function)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); cast->setCastFunction(dynamic_cast(func)); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) { if(cast) delete(cast); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(cast); @@ -4188,15 +4478,15 @@ Conversion *DatabaseModel::createConversion(void) setBasicAttributes(conv); xmlparser.getElementAttributes(attribs); - conv->setEncoding(Conversion::SRC_ENCODING, - EncodingType(attribs[ParsersAttributes::SRC_ENCODING])); + conv->setEncoding(Conversion::SrcEncoding, + EncodingType(attribs[Attributes::SrcEncoding])); - conv->setEncoding(Conversion::DST_ENCODING, - EncodingType(attribs[ParsersAttributes::DST_ENCODING])); + conv->setEncoding(Conversion::DstEncoding, + EncodingType(attribs[Attributes::DstEncoding])); - conv->setDefault(attribs[ParsersAttributes::DEFAULT]==ParsersAttributes::_TRUE_); + conv->setDefault(attribs[Attributes::Default]==Attributes::True); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -4204,31 +4494,31 @@ Conversion *DatabaseModel::createConversion(void) { elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::FUNCTION) + if(elem==Attributes::Function) { xmlparser.getElementAttributes(attribs); - func=getObject(attribs[ParsersAttributes::SIGNATURE], OBJ_FUNCTION); + func=getObject(attribs[Attributes::Signature], ObjectType::Function); //Raises an error if the function doesn't exists - if(!func && !attribs[ParsersAttributes::SIGNATURE].isEmpty()) - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + if(!func && !attribs[Attributes::Signature].isEmpty()) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(conv->getName()) .arg(conv->getTypeName()) - .arg(attribs[ParsersAttributes::SIGNATURE]) - .arg(BaseObject::getTypeName(OBJ_FUNCTION)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs[Attributes::Signature]) + .arg(BaseObject::getTypeName(ObjectType::Function)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); conv->setConversionFunction(dynamic_cast(func)); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) { if(conv) delete(conv); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(conv); @@ -4243,7 +4533,7 @@ Operator *DatabaseModel::createOperator(void) QString elem; BaseObject *func=nullptr,*oper_aux=nullptr; unsigned arg_type; - PgSQLType type; + PgSqlType type; try { @@ -4251,17 +4541,17 @@ Operator *DatabaseModel::createOperator(void) setBasicAttributes(oper); xmlparser.getElementAttributes(attribs); - oper->setMerges(attribs[ParsersAttributes::MERGES]==ParsersAttributes::_TRUE_); - oper->setHashes(attribs[ParsersAttributes::HASHES]==ParsersAttributes::_TRUE_); + oper->setMerges(attribs[Attributes::Merges]==Attributes::True); + oper->setHashes(attribs[Attributes::Hashes]==Attributes::True); - func_types[ParsersAttributes::OPERATOR_FUNC]=Operator::FUNC_OPERATOR; - func_types[ParsersAttributes::JOIN_FUNC]=Operator::FUNC_JOIN; - func_types[ParsersAttributes::RESTRICTION_FUNC]=Operator::FUNC_RESTRICT; + func_types[Attributes::OperatorFunc]=Operator::FuncOperator; + func_types[Attributes::JoinFunc]=Operator::FuncJoin; + func_types[Attributes::RestrictionFunc]=Operator::FuncRestrict; - oper_types[ParsersAttributes::COMMUTATOR_OP]=Operator::OPER_COMMUTATOR; - oper_types[ParsersAttributes::NEGATOR_OP]=Operator::OPER_NEGATOR; + oper_types[Attributes::CommutatorOp]=Operator::OperCommutator; + oper_types[Attributes::NegatorOp]=Operator::OperNegator; - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -4269,61 +4559,61 @@ Operator *DatabaseModel::createOperator(void) { elem=xmlparser.getElementName(); - if(elem==objs_schemas[OBJ_OPERATOR]) + if(elem==objs_schemas[enum_cast(ObjectType::Operator)]) { xmlparser.getElementAttributes(attribs); - oper_aux=getObject(attribs[ParsersAttributes::SIGNATURE], OBJ_OPERATOR); + oper_aux=getObject(attribs[Attributes::Signature], ObjectType::Operator); //Raises an error if the auxiliary operator doesn't exists - if(!oper_aux && !attribs[ParsersAttributes::SIGNATURE].isEmpty()) - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + if(!oper_aux && !attribs[Attributes::Signature].isEmpty()) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(oper->getSignature(true)) .arg(oper->getTypeName()) - .arg(attribs[ParsersAttributes::SIGNATURE]) - .arg(BaseObject::getTypeName(OBJ_OPERATOR)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs[Attributes::Signature]) + .arg(BaseObject::getTypeName(ObjectType::Operator)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); oper->setOperator(dynamic_cast(oper_aux), - oper_types[attribs[ParsersAttributes::REF_TYPE]]); + oper_types[attribs[Attributes::RefType]]); } - else if(elem==ParsersAttributes::TYPE) + else if(elem==Attributes::Type) { xmlparser.getElementAttributes(attribs); - if(attribs[ParsersAttributes::REF_TYPE]!=ParsersAttributes::RIGHT_TYPE) - arg_type=Operator::LEFT_ARG; + if(attribs[Attributes::RefType]!=Attributes::RightType) + arg_type=Operator::LeftArg; else - arg_type=Operator::RIGHT_ARG; + arg_type=Operator::RightArg; type=createPgSQLType(); oper->setArgumentType(type, arg_type); } - else if(elem==ParsersAttributes::FUNCTION) + else if(elem==Attributes::Function) { xmlparser.getElementAttributes(attribs); - func=getObject(attribs[ParsersAttributes::SIGNATURE], OBJ_FUNCTION); + func=getObject(attribs[Attributes::Signature], ObjectType::Function); //Raises an error if the function doesn't exists on the model - if(!func && !attribs[ParsersAttributes::SIGNATURE].isEmpty()) - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + if(!func && !attribs[Attributes::Signature].isEmpty()) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(oper->getName()) .arg(oper->getTypeName()) - .arg(attribs[ParsersAttributes::SIGNATURE]) - .arg(BaseObject::getTypeName(OBJ_FUNCTION)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs[Attributes::Signature]) + .arg(BaseObject::getTypeName(ObjectType::Function)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); oper->setFunction(dynamic_cast(func), - func_types[attribs[ParsersAttributes::REF_TYPE]]); + func_types[attribs[Attributes::RefType]]); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) { if(oper) delete(oper); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(oper); @@ -4335,7 +4625,7 @@ OperatorClass *DatabaseModel::createOperatorClass(void) map elem_types; BaseObject *object=nullptr; QString elem; - PgSQLType type; + PgSqlType type; OperatorClass *op_class=nullptr; OperatorClassElement class_elem; unsigned stg_number, elem_type; @@ -4346,14 +4636,14 @@ OperatorClass *DatabaseModel::createOperatorClass(void) setBasicAttributes(op_class); xmlparser.getElementAttributes(attribs); - op_class->setIndexingType(IndexingType(attribs[ParsersAttributes::INDEX_TYPE])); - op_class->setDefault(attribs[ParsersAttributes::DEFAULT]==ParsersAttributes::_TRUE_); + op_class->setIndexingType(IndexingType(attribs[Attributes::IndexType])); + op_class->setDefault(attribs[Attributes::Default]==Attributes::True); - elem_types[ParsersAttributes::FUNCTION]=OperatorClassElement::FUNCTION_ELEM; - elem_types[ParsersAttributes::OPERATOR]=OperatorClassElement::OPERATOR_ELEM; - elem_types[ParsersAttributes::STORAGE]=OperatorClassElement::STORAGE_ELEM; + elem_types[Attributes::Function]=OperatorClassElement::FunctionElem; + elem_types[Attributes::Operator]=OperatorClassElement::OperatorElem; + elem_types[Attributes::Storage]=OperatorClassElement::StorageElem; - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -4361,69 +4651,69 @@ OperatorClass *DatabaseModel::createOperatorClass(void) { elem=xmlparser.getElementName(); - if(elem==objs_schemas[OBJ_OPFAMILY]) + if(elem==objs_schemas[enum_cast(ObjectType::OpFamily)]) { xmlparser.getElementAttributes(attribs); - object=getObject(attribs[ParsersAttributes::SIGNATURE], OBJ_OPFAMILY); + object=getObject(attribs[Attributes::Signature], ObjectType::OpFamily); //Raises an error if the operator family doesn't exists if(!object) - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(op_class->getName()) .arg(op_class->getTypeName()) - .arg(attribs[ParsersAttributes::SIGNATURE]) - .arg(BaseObject::getTypeName(OBJ_OPFAMILY)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs[Attributes::Signature]) + .arg(BaseObject::getTypeName(ObjectType::OpFamily)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); op_class->setFamily(dynamic_cast(object)); } - else if(elem==ParsersAttributes::TYPE) + else if(elem==Attributes::Type) { xmlparser.getElementAttributes(attribs); type=createPgSQLType(); op_class->setDataType(type); } - else if(elem==ParsersAttributes::ELEMENT) + else if(elem==Attributes::Element) { xmlparser.getElementAttributes(attribs); - stg_number=attribs[ParsersAttributes::STRATEGY_NUM].toUInt(); - elem_type=elem_types[attribs[ParsersAttributes::TYPE]]; + stg_number=attribs[Attributes::StrategyNum].toUInt(); + elem_type=elem_types[attribs[Attributes::Type]]; xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); xmlparser.getElementAttributes(attribs); - if(elem_type==OperatorClassElement::STORAGE_ELEM) + if(elem_type==OperatorClassElement::StorageElem) { type=createPgSQLType(); class_elem.setStorage(type); } - else if(elem_type==OperatorClassElement::FUNCTION_ELEM) + else if(elem_type==OperatorClassElement::FunctionElem) { - object=getObject(attribs[ParsersAttributes::SIGNATURE],OBJ_FUNCTION); + object=getObject(attribs[Attributes::Signature],ObjectType::Function); class_elem.setFunction(dynamic_cast(object),stg_number); } - else if(elem_type==OperatorClassElement::OPERATOR_ELEM) + else if(elem_type==OperatorClassElement::OperatorElem) { - object=getObject(attribs[ParsersAttributes::SIGNATURE],OBJ_OPERATOR); + object=getObject(attribs[Attributes::Signature],ObjectType::Operator); class_elem.setOperator(dynamic_cast(object),stg_number); - if(xmlparser.hasElement(XMLParser::NEXT_ELEMENT)) + if(xmlparser.hasElement(XmlParser::NextElement)) { xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::NEXT_ELEMENT); + xmlparser.accessElement(XmlParser::NextElement); xmlparser.getElementAttributes(attribs_aux); - object=getObject(attribs_aux[ParsersAttributes::SIGNATURE],OBJ_OPFAMILY); + object=getObject(attribs_aux[Attributes::Signature],ObjectType::OpFamily); - if(!object && !attribs_aux[ParsersAttributes::SIGNATURE].isEmpty()) - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + if(!object && !attribs_aux[Attributes::Signature].isEmpty()) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(op_class->getName()) .arg(op_class->getTypeName()) - .arg(attribs_aux[ParsersAttributes::SIGNATURE]) - .arg(BaseObject::getTypeName(OBJ_OPFAMILY)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs_aux[Attributes::Signature]) + .arg(BaseObject::getTypeName(ObjectType::OpFamily)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); class_elem.setOperatorFamily(dynamic_cast(object)); xmlparser.restorePosition(); @@ -4435,13 +4725,13 @@ OperatorClass *DatabaseModel::createOperatorClass(void) } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) { if(op_class) delete(op_class); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(op_class); @@ -4457,12 +4747,12 @@ OperatorFamily *DatabaseModel::createOperatorFamily(void) op_family=new OperatorFamily; setBasicAttributes(op_family); xmlparser.getElementAttributes(attribs); - op_family->setIndexingType(IndexingType(attribs[ParsersAttributes::INDEX_TYPE])); + op_family->setIndexingType(IndexingType(attribs[Attributes::IndexType])); } catch(Exception &e) { if(op_family) delete(op_family); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(op_family); @@ -4473,7 +4763,7 @@ Aggregate *DatabaseModel::createAggregate(void) attribs_map attribs; BaseObject *func=nullptr; QString elem; - PgSQLType type; + PgSqlType type; Aggregate *aggreg=nullptr; try @@ -4482,9 +4772,9 @@ Aggregate *DatabaseModel::createAggregate(void) setBasicAttributes(aggreg); xmlparser.getElementAttributes(attribs); - aggreg->setInitialCondition(attribs[ParsersAttributes::INITIAL_COND]); + aggreg->setInitialCondition(attribs[Attributes::InitialCond]); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -4492,46 +4782,46 @@ Aggregate *DatabaseModel::createAggregate(void) { elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::TYPE) + if(elem==Attributes::Type) { xmlparser.getElementAttributes(attribs); type=createPgSQLType(); - if(attribs[ParsersAttributes::REF_TYPE]==ParsersAttributes::STATE_TYPE) + if(attribs[Attributes::RefType]==Attributes::StateType) aggreg->setStateType(type); else aggreg->addDataType(type); } - else if(elem==ParsersAttributes::FUNCTION) + else if(elem==Attributes::Function) { xmlparser.getElementAttributes(attribs); - func=getObject(attribs[ParsersAttributes::SIGNATURE], OBJ_FUNCTION); + func=getObject(attribs[Attributes::Signature], ObjectType::Function); //Raises an error if the function doesn't exists on the model - if(!func && !attribs[ParsersAttributes::SIGNATURE].isEmpty()) - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + if(!func && !attribs[Attributes::Signature].isEmpty()) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(aggreg->getName()) .arg(aggreg->getTypeName()) - .arg(attribs[ParsersAttributes::SIGNATURE]) - .arg(BaseObject::getTypeName(OBJ_FUNCTION)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs[Attributes::Signature]) + .arg(BaseObject::getTypeName(ObjectType::Function)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(attribs[ParsersAttributes::REF_TYPE]==ParsersAttributes::TRANSITION_FUNC) - aggreg->setFunction(Aggregate::TRANSITION_FUNC, + if(attribs[Attributes::RefType]==Attributes::TransitionFunc) + aggreg->setFunction(Aggregate::TransitionFunc, dynamic_cast(func)); else - aggreg->setFunction(Aggregate::FINAL_FUNC, + aggreg->setFunction(Aggregate::FinalFunc, dynamic_cast(func)); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) { if(aggreg) delete(aggreg); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(aggreg); @@ -4547,6 +4837,8 @@ Table *DatabaseModel::createTable(void) ObjectType obj_type; vector idxs; vector names; + PartitionKey part_key; + vector partition_keys; try { @@ -4554,15 +4846,20 @@ Table *DatabaseModel::createTable(void) setBasicAttributes(table); xmlparser.getElementAttributes(attribs); - table->setWithOIDs(attribs[ParsersAttributes::OIDS]==ParsersAttributes::_TRUE_); - table->setUnlogged(attribs[ParsersAttributes::UNLOGGED]==ParsersAttributes::_TRUE_); - table->setRLSEnabled(attribs[ParsersAttributes::RLS_ENABLED]==ParsersAttributes::_TRUE_); - table->setRLSForced(attribs[ParsersAttributes::RLS_FORCED]==ParsersAttributes::_TRUE_); - table->setGenerateAlterCmds(attribs[ParsersAttributes::GEN_ALTER_CMDS]==ParsersAttributes::_TRUE_); - table->setExtAttribsHidden(attribs[ParsersAttributes::HIDE_EXT_ATTRIBS]==ParsersAttributes::_TRUE_); - table->setFadedOut(attribs[ParsersAttributes::FADED_OUT]==ParsersAttributes::_TRUE_); - - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + table->setObjectListsCapacity(attribs[Attributes::MaxObjCount].toUInt()); + table->setWithOIDs(attribs[Attributes::Oids]==Attributes::True); + table->setUnlogged(attribs[Attributes::Unlogged]==Attributes::True); + table->setRLSEnabled(attribs[Attributes::RlsEnabled]==Attributes::True); + table->setRLSForced(attribs[Attributes::RlsForced]==Attributes::True); + table->setGenerateAlterCmds(attribs[Attributes::GenAlterCmds]==Attributes::True); + table->setCollapseMode(attribs[Attributes::CollapseMode].isEmpty() ? CollapseMode::NotCollapsed : static_cast(attribs[Attributes::CollapseMode].toUInt())); + table->setPaginationEnabled(attribs[Attributes::Pagination]==Attributes::True); + table->setCurrentPage(BaseTable::AttribsSection, attribs[Attributes::AttribsPage].toUInt()); + table->setCurrentPage(BaseTable::ExtAttribsSection, attribs[Attributes::ExtAttribsPage].toUInt()); + table->setFadedOut(attribs[Attributes::FadedOut]==Attributes::True); + table->setLayer(attribs[Attributes::Layer].toUInt()); + + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -4572,36 +4869,36 @@ Table *DatabaseModel::createTable(void) xmlparser.savePosition(); object=nullptr; - if(elem==BaseObject::objs_schemas[OBJ_COLUMN]) + if(elem==BaseObject::objs_schemas[enum_cast(ObjectType::Column)]) object=createColumn(); - else if(elem==BaseObject::objs_schemas[OBJ_CONSTRAINT]) + else if(elem==BaseObject::objs_schemas[enum_cast(ObjectType::Constraint)]) object=createConstraint(table); - else if(elem==BaseObject::objs_schemas[OBJ_TAG]) + else if(elem==BaseObject::objs_schemas[enum_cast(ObjectType::Tag)]) { xmlparser.getElementAttributes(aux_attribs); - tag=getObject(aux_attribs[ParsersAttributes::NAME] ,OBJ_TAG); + tag=getObject(aux_attribs[Attributes::Name], ObjectType::Tag); if(!tag) { - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(OBJ_TABLE)) - .arg(aux_attribs[ParsersAttributes::TABLE]) - .arg(BaseObject::getTypeName(OBJ_TAG)) - , ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Table)) + .arg(aux_attribs[Attributes::Table]) + .arg(BaseObject::getTypeName(ObjectType::Tag)) + , ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } table->setTag(dynamic_cast(tag)); } //Retrieving custom columns / constraint indexes - else if(elem==ParsersAttributes::CUSTOMIDXS) + else if(elem==Attributes::CustomIdxs) { xmlparser.getElementAttributes(aux_attribs); - obj_type=BaseObject::getObjectType(aux_attribs[ParsersAttributes::OBJECT_TYPE]); + obj_type=BaseObject::getObjectType(aux_attribs[Attributes::ObjectType]); xmlparser.savePosition(); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -4610,15 +4907,15 @@ Table *DatabaseModel::createTable(void) elem=xmlparser.getElementName(); //The element stores the index for each object in the current group - if(elem==ParsersAttributes::OBJECT) + if(elem==Attributes::Object) { xmlparser.getElementAttributes(aux_attribs); - names.push_back(aux_attribs[ParsersAttributes::NAME]); - idxs.push_back(aux_attribs[ParsersAttributes::INDEX].toUInt()); + names.push_back(aux_attribs[Attributes::Name]); + idxs.push_back(aux_attribs[Attributes::Index].toUInt()); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); table->setRelObjectsIndexes(names, idxs, obj_type); names.clear(); @@ -4627,11 +4924,35 @@ Table *DatabaseModel::createTable(void) xmlparser.restorePosition(); } + else if(elem==Attributes::Partitioning) + { + xmlparser.getElementAttributes(aux_attribs); + table->setPartitioningType(aux_attribs[Attributes::Type]); + xmlparser.savePosition(); + + if(xmlparser.accessElement(XmlParser::ChildElement)) + { + do + { + if(xmlparser.getElementType()==XML_ELEMENT_NODE && + xmlparser.getElementName()==Attributes::PartitionKey) + { + createElement(part_key, nullptr, table); + partition_keys.push_back(part_key); + } + } + while(xmlparser.accessElement(XmlParser::NextElement)); + + table->addPartitionKeys(partition_keys); + } + + xmlparser.restorePosition(); + } //Retrieving initial data - else if(elem==ParsersAttributes::INITIAL_DATA) + else if(elem==Attributes::InitialData) { xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); table->setInitialData(xmlparser.getElementContent()); xmlparser.restorePosition(); } @@ -4642,7 +4963,7 @@ Table *DatabaseModel::createTable(void) xmlparser.restorePosition(); } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } table->setProtected(table->isProtected()); @@ -4653,7 +4974,7 @@ Table *DatabaseModel::createTable(void) xmlparser.restorePosition(); if(table) delete(table); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, extra_info); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, extra_info); } return(table); @@ -4672,29 +4993,31 @@ Column *DatabaseModel::createColumn(void) setBasicAttributes(column); xmlparser.getElementAttributes(attribs); - column->setNotNull(attribs[ParsersAttributes::NOT_NULL]==ParsersAttributes::_TRUE_); - column->setDefaultValue(attribs[ParsersAttributes::DEFAULT_VALUE]); + column->setNotNull(attribs[Attributes::NotNull]==Attributes::True); + column->setDefaultValue(attribs[Attributes::DefaultValue]); + column->setIdSeqAttributes(attribs[Attributes::MinValue], attribs[Attributes::MaxValue], attribs[Attributes::Increment], + attribs[Attributes::Start], attribs[Attributes::Cache], attribs[Attributes::Cycle] == Attributes::True); - if(!attribs[ParsersAttributes::IDENTITY_TYPE].isEmpty()) - column->setIdentityType(IdentityType(attribs[ParsersAttributes::IDENTITY_TYPE])); + if(!attribs[Attributes::IdentityType].isEmpty()) + column->setIdentityType(IdentityType(attribs[Attributes::IdentityType])); - if(!attribs[ParsersAttributes::SEQUENCE].isEmpty()) + if(!attribs[Attributes::Sequence].isEmpty()) { - seq=getObject(attribs[ParsersAttributes::SEQUENCE], OBJ_SEQUENCE); + seq=getObject(attribs[Attributes::Sequence], ObjectType::Sequence); if(!seq) - throw Exception(QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(OBJ_COLUMN)) - .arg(attribs[ParsersAttributes::SEQUENCE]) - .arg(BaseObject::getTypeName(OBJ_SEQUENCE)), - ERR_PERM_REF_INEXIST_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Column)) + .arg(attribs[Attributes::Sequence]) + .arg(BaseObject::getTypeName(ObjectType::Sequence)), + ErrorCode::PermissionRefInexistObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); column->setSequence(seq); } - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -4702,19 +5025,19 @@ Column *DatabaseModel::createColumn(void) { elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::TYPE) + if(elem==Attributes::Type) { column->setType(createPgSQLType()); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) { if(column) delete(column); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(column); @@ -4747,31 +5070,31 @@ Constraint *DatabaseModel::createConstraint(BaseObject *parent_obj) obj_type=parent_obj->getObjectType(); //Identifies the correct parent type - if(obj_type==OBJ_TABLE) + if(obj_type==ObjectType::Table) table=dynamic_cast
(parent_obj); - else if(obj_type==OBJ_RELATIONSHIP) + else if(obj_type==ObjectType::Relationship) rel=dynamic_cast(parent_obj); else //Raises an error if the user tries to create a constraint in a invalid parent - throw Exception(ERR_OPR_OBJ_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); } else { - obj_type=OBJ_TABLE; - table=dynamic_cast
(getObject(attribs[ParsersAttributes::TABLE], OBJ_TABLE)); + obj_type=ObjectType::Table; + table=dynamic_cast
(getObject(attribs[Attributes::Table], ObjectType::Table)); parent_obj=table; ins_constr_table=true; //Raises an error if the parent table doesn't exists if(!table) { - str_aux=QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(OBJ_CONSTRAINT)) - .arg(attribs[ParsersAttributes::TABLE]) - .arg(BaseObject::getTypeName(OBJ_TABLE)); + str_aux=Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Constraint)) + .arg(attribs[Attributes::Table]) + .arg(BaseObject::getTypeName(ObjectType::Table)); - throw Exception(str_aux,ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(str_aux,ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } @@ -4779,77 +5102,76 @@ Constraint *DatabaseModel::createConstraint(BaseObject *parent_obj) constr->setParentTable(table); //Configuring the constraint type - if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::CK_CONSTR) - constr_type=ConstraintType::check; - else if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::PK_CONSTR) - constr_type=ConstraintType::primary_key; - else if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::FK_CONSTR) - constr_type=ConstraintType::foreign_key; - else if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::UQ_CONSTR) - constr_type=ConstraintType::unique; + if(attribs[Attributes::Type]==Attributes::CkConstr) + constr_type=ConstraintType::Check; + else if(attribs[Attributes::Type]==Attributes::PkConstr) + constr_type=ConstraintType::PrimaryKey; + else if(attribs[Attributes::Type]==Attributes::FkConstr) + constr_type=ConstraintType::ForeignKey; + else if(attribs[Attributes::Type]==Attributes::UqConstr) + constr_type=ConstraintType::Unique; else - constr_type=ConstraintType::exclude; + constr_type=ConstraintType::Exclude; constr->setConstraintType(constr_type); - if(!attribs[ParsersAttributes::FACTOR].isEmpty()) - constr->setFillFactor(attribs[ParsersAttributes::FACTOR].toUInt()); + if(!attribs[Attributes::Factor].isEmpty()) + constr->setFillFactor(attribs[Attributes::Factor].toUInt()); setBasicAttributes(constr); //Raises an error if the constraint is a primary key and no parent object is specified - if(!parent_obj && constr_type==ConstraintType::primary_key) - throw Exception(Exception::getErrorMessage(ERR_INV_PRIM_KEY_ALOCATION) + if(!parent_obj && constr_type==ConstraintType::PrimaryKey) + throw Exception(Exception::getErrorMessage(ErrorCode::InvPrimaryKeyAllocation) .arg(constr->getName()), - ERR_INV_PRIM_KEY_ALOCATION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvPrimaryKeyAllocation,__PRETTY_FUNCTION__,__FILE__,__LINE__); - deferrable=(attribs[ParsersAttributes::DEFERRABLE]==ParsersAttributes::_TRUE_); + deferrable=(attribs[Attributes::Deferrable]==Attributes::True); constr->setDeferrable(deferrable); - if(deferrable && !attribs[ParsersAttributes::DEFER_TYPE].isEmpty()) - constr->setDeferralType(attribs[ParsersAttributes::DEFER_TYPE]); + if(deferrable && !attribs[Attributes::DeferType].isEmpty()) + constr->setDeferralType(attribs[Attributes::DeferType]); - if(constr_type==ConstraintType::foreign_key) + if(constr_type==ConstraintType::ForeignKey) { - if(!attribs[ParsersAttributes::COMPARISON_TYPE].isEmpty()) - constr->setMatchType(attribs[ParsersAttributes::COMPARISON_TYPE]); + if(!attribs[Attributes::ComparisonType].isEmpty()) + constr->setMatchType(attribs[Attributes::ComparisonType]); - if(!attribs[ParsersAttributes::DEL_ACTION].isEmpty()) - constr->setActionType(attribs[ParsersAttributes::DEL_ACTION], Constraint::DELETE_ACTION); + if(!attribs[Attributes::DelAction].isEmpty()) + constr->setActionType(attribs[Attributes::DelAction], Constraint::DeleteAction); - if(!attribs[ParsersAttributes::UPD_ACTION].isEmpty()) - constr->setActionType(attribs[ParsersAttributes::UPD_ACTION], Constraint::UPDATE_ACTION); + if(!attribs[Attributes::UpdAction].isEmpty()) + constr->setActionType(attribs[Attributes::UpdAction], Constraint::UpdateAction); - ref_table=getObject(attribs[ParsersAttributes::REF_TABLE], OBJ_TABLE); + ref_table=getObject(attribs[Attributes::RefTable], ObjectType::Table); - if(!ref_table && table->getName(true)==attribs[ParsersAttributes::REF_TABLE]) + if(!ref_table && table->getName(true)==attribs[Attributes::RefTable]) ref_table=table; //Raises an error if the referenced table doesn't exists if(!ref_table) { - str_aux=QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) + str_aux=Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(constr->getName()) .arg(constr->getTypeName()) - .arg(attribs[ParsersAttributes::REF_TABLE]) - .arg(BaseObject::getTypeName(OBJ_TABLE)); + .arg(attribs[Attributes::RefTable]) + .arg(BaseObject::getTypeName(ObjectType::Table)); - throw Exception(str_aux,ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(str_aux,ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } constr->setReferencedTable(dynamic_cast(ref_table)); } - else if(constr_type==ConstraintType::check) + else if(constr_type==ConstraintType::Check) { - constr->setNoInherit(attribs[ParsersAttributes::NO_INHERIT]==ParsersAttributes::_TRUE_); + constr->setNoInherit(attribs[Attributes::NoInherit]==Attributes::True); } - else if(constr_type==ConstraintType::exclude && !attribs[ParsersAttributes::INDEX_TYPE].isEmpty()) + else if(constr_type==ConstraintType::Exclude && !attribs[Attributes::IndexType].isEmpty()) { - constr->setIndexType(attribs[ParsersAttributes::INDEX_TYPE]); + constr->setIndexType(attribs[Attributes::IndexType]); } - - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -4857,37 +5179,37 @@ Constraint *DatabaseModel::createConstraint(BaseObject *parent_obj) { elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::EXCLUDE_ELEMENT) + if(elem==Attributes::ExcludeElement) { createElement(exc_elem, constr, parent_obj); constr->addExcludeElement(exc_elem); } - else if(elem==ParsersAttributes::EXPRESSION) + else if(elem==Attributes::Expression) { xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); constr->setExpression(xmlparser.getElementContent()); xmlparser.restorePosition(); } - else if(elem==ParsersAttributes::COLUMNS) + else if(elem==Attributes::Columns) { xmlparser.getElementAttributes(attribs); - col_list=attribs[ParsersAttributes::NAMES].split(','); + col_list=attribs[Attributes::Names].split(','); count=col_list.count(); - if(attribs[ParsersAttributes::REF_TYPE]==ParsersAttributes::SRC_COLUMNS) - col_type=Constraint::SOURCE_COLS; + if(attribs[Attributes::RefType]==Attributes::SrcColumns) + col_type=Constraint::SourceCols; else - col_type=Constraint::REFERENCED_COLS; + col_type=Constraint::ReferencedCols; for(i=0; i < count; i++) { - if(col_type==Constraint::SOURCE_COLS) + if(col_type==Constraint::SourceCols) { - if(obj_type==OBJ_TABLE) + if(obj_type==ObjectType::Table) { column=table->getColumn(col_list[i]); @@ -4896,7 +5218,7 @@ Constraint *DatabaseModel::createConstraint(BaseObject *parent_obj) column=table->getColumn(col_list[i], true); } else - column=dynamic_cast(rel->getObject(col_list[i], OBJ_COLUMN)); + column=dynamic_cast(rel->getObject(col_list[i], ObjectType::Column)); } else { @@ -4913,23 +5235,24 @@ Constraint *DatabaseModel::createConstraint(BaseObject *parent_obj) } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } if(ins_constr_table) { - if(constr->getConstraintType()!=ConstraintType::primary_key) + if(constr->getConstraintType()!=ConstraintType::PrimaryKey) { table->addConstraint(constr); + if(this->getObjectIndex(table) >= 0) - table->setModified(true); + table->setModified(!loading_model); } } } catch(Exception &e) { if(constr) delete(constr); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(constr); @@ -4943,19 +5266,26 @@ void DatabaseModel::createElement(Element &elem, TableObject *tab_obj, BaseObjec Operator *oper=nullptr; Collation *collation=nullptr; QString xml_elem; + bool is_part_key = false; xml_elem=xmlparser.getElementName(); + is_part_key = xml_elem == Attributes::PartitionKey; - if(xml_elem==ParsersAttributes::INDEX_ELEMENT || xml_elem==ParsersAttributes::EXCLUDE_ELEMENT) + if(xml_elem==Attributes::IndexElement || xml_elem==Attributes::ExcludeElement || is_part_key) { xmlparser.getElementAttributes(attribs); - elem.setSortingAttribute(Element::ASC_ORDER, attribs[ParsersAttributes::ASC_ORDER]==ParsersAttributes::_TRUE_); - elem.setSortingAttribute(Element::NULLS_FIRST, attribs[ParsersAttributes::NULLS_FIRST]==ParsersAttributes::_TRUE_); - elem.setSortingEnabled(attribs[ParsersAttributes::USE_SORTING]!=ParsersAttributes::_FALSE_); + elem.setColumn(nullptr); + elem.setCollation(nullptr); + elem.setOperator(nullptr); + elem.setOperatorClass(nullptr); + + elem.setSortingAttribute(Element::AscOrder, attribs[Attributes::AscOrder]==Attributes::True); + elem.setSortingAttribute(Element::NullsFirst, attribs[Attributes::NullsFirst]==Attributes::True); + elem.setSortingEnabled(attribs[Attributes::UseSorting]!=Attributes::False); xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); do { @@ -4963,106 +5293,139 @@ void DatabaseModel::createElement(Element &elem, TableObject *tab_obj, BaseObjec if(xmlparser.getElementType()==XML_ELEMENT_NODE) { - if(xml_elem==ParsersAttributes::OP_CLASS) + if(xml_elem==Attributes::OpClass) { xmlparser.getElementAttributes(attribs); - op_class=dynamic_cast(getObject(attribs[ParsersAttributes::SIGNATURE], OBJ_OPCLASS)); + op_class=dynamic_cast(getObject(attribs[Attributes::Signature], ObjectType::OpClass)); //Raises an error if the operator class doesn't exists if(!op_class) { - throw Exception(QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) - .arg(tab_obj->getName()) - .arg(tab_obj->getTypeName()) - .arg(attribs[ParsersAttributes::SIGNATURE]) - .arg(BaseObject::getTypeName(OBJ_OPCLASS)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); - } - + if(!is_part_key) + { + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(tab_obj->getName()) + .arg(tab_obj->getTypeName()) + .arg(attribs[Attributes::Signature]) + .arg(BaseObject::getTypeName(ObjectType::OpClass)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + else + { + throw Exception(Exception::getErrorMessage(ErrorCode::PartKeyObjectInexistsModel) + .arg(parent_obj->getName()) + .arg(attribs[Attributes::Signature]) + .arg(BaseObject::getTypeName(ObjectType::OpClass)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + } + elem.setOperatorClass(op_class); } //Checking if elem is a ExcludeElement to be able to assign an operator to it - else if(xml_elem==ParsersAttributes::OPERATOR && dynamic_cast(&elem)) + else if(xml_elem==Attributes::Operator) { xmlparser.getElementAttributes(attribs); - oper=dynamic_cast(getObject(attribs[ParsersAttributes::SIGNATURE], OBJ_OPERATOR)); + oper=dynamic_cast(getObject(attribs[Attributes::Signature], ObjectType::Operator)); //Raises an error if the operator doesn't exists if(!oper) { - throw Exception(QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(tab_obj->getName()) .arg(tab_obj->getTypeName()) - .arg(attribs[ParsersAttributes::SIGNATURE]) - .arg(BaseObject::getTypeName(OBJ_OPERATOR)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs[Attributes::Signature]) + .arg(BaseObject::getTypeName(ObjectType::Operator)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } - dynamic_cast(elem).setOperator(oper); + elem.setOperator(oper); } - else if(xml_elem==ParsersAttributes::COLLATION && dynamic_cast(&elem)) + else if(xml_elem==Attributes::Collation) { xmlparser.getElementAttributes(attribs); - collation=dynamic_cast(getObject(attribs[ParsersAttributes::NAME], OBJ_COLLATION)); + collation=dynamic_cast(getObject(attribs[Attributes::Name], ObjectType::Collation)); //Raises an error if the operator class doesn't exists if(!collation) { - throw Exception(QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) - .arg(tab_obj->getName()) - .arg(tab_obj->getTypeName()) - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(OBJ_COLLATION)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(!is_part_key) + { + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(tab_obj->getName()) + .arg(tab_obj->getTypeName()) + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Collation)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + else + { + throw Exception(Exception::getErrorMessage(ErrorCode::PartKeyObjectInexistsModel) + .arg(parent_obj->getName()) + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Collation)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } } - dynamic_cast(elem).setCollation(collation); + elem.setCollation(collation); } - else if(xml_elem==ParsersAttributes::COLUMN) + else if(xml_elem==Attributes::Column) { xmlparser.getElementAttributes(attribs); - if(parent_obj->getObjectType()==OBJ_TABLE) + if(parent_obj->getObjectType()==ObjectType::Table) { - column=dynamic_cast
(parent_obj)->getColumn(attribs[ParsersAttributes::NAME]); + column=dynamic_cast
(parent_obj)->getColumn(attribs[Attributes::Name]); if(!column) - column=dynamic_cast
(parent_obj)->getColumn(attribs[ParsersAttributes::NAME], true); + column=dynamic_cast
(parent_obj)->getColumn(attribs[Attributes::Name], true); } else { - column=dynamic_cast(dynamic_cast(parent_obj)->getObject(attribs[ParsersAttributes::NAME], OBJ_COLUMN)); + column=dynamic_cast(dynamic_cast(parent_obj)->getObject(attribs[Attributes::Name], ObjectType::Column)); } //Raises an error if the column doesn't exists if(!column) { - throw Exception(QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) - .arg(tab_obj->getName()) - .arg(tab_obj->getTypeName()) - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(OBJ_COLUMN)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(!is_part_key) + { + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(tab_obj->getName()) + .arg(tab_obj->getTypeName()) + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Column)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + else + { + throw Exception(Exception::getErrorMessage(ErrorCode::PartKeyObjectInexistsModel) + .arg(parent_obj->getName()) + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Column)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } } elem.setColumn(column); } - else if(xml_elem==ParsersAttributes::EXPRESSION) + else if(xml_elem==Attributes::Expression) { xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); elem.setExpression(xmlparser.getElementContent()); xmlparser.restorePosition(); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); xmlparser.restorePosition(); } } -XMLParser *DatabaseModel::getXMLParser(void) +XmlParser *DatabaseModel::getXMLParser(void) { return(&xmlparser); } @@ -5072,24 +5435,24 @@ QString DatabaseModel::getAlterDefinition(BaseObject *object) DatabaseModel *db_aux=dynamic_cast(object); if(!db_aux) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { QString alter_def; attribs_map aux_attribs; - aux_attribs[ParsersAttributes::SIGNATURE] = this->getSignature(); - aux_attribs[ParsersAttributes::SQL_OBJECT] = this->getSQLName(); + aux_attribs[Attributes::Signature] = this->getSignature(); + aux_attribs[Attributes::SqlObject] = this->getSQLName(); if(this->conn_limit!=db_aux->conn_limit) - aux_attribs[ParsersAttributes::CONN_LIMIT]=QString::number(db_aux->conn_limit); + aux_attribs[Attributes::ConnLimit]=QString::number(db_aux->conn_limit); if(this->is_template != db_aux->is_template) - aux_attribs[ParsersAttributes::IS_TEMPLATE] = (db_aux->is_template ? ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_); + aux_attribs[Attributes::IsTemplate] = (db_aux->is_template ? Attributes::True : Attributes::False); if(this->allow_conns != db_aux->allow_conns) - aux_attribs[ParsersAttributes::ALLOW_CONNS] = (db_aux->allow_conns ? ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_); + aux_attribs[Attributes::AllowConns] = (db_aux->allow_conns ? Attributes::True : Attributes::False); alter_def+=BaseObject::getAlterDefinition(this->getSchemaName(), aux_attribs, true, false); alter_def+=BaseObject::getAlterDefinition(object); @@ -5098,7 +5461,7 @@ QString DatabaseModel::getAlterDefinition(BaseObject *object) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -5114,34 +5477,34 @@ Index *DatabaseModel::createIndex(void) { xmlparser.getElementAttributes(attribs); - table=dynamic_cast(getObject(attribs[ParsersAttributes::TABLE], OBJ_TABLE)); + table=dynamic_cast(getObject(attribs[Attributes::Table], ObjectType::Table)); if(!table) - table=dynamic_cast(getObject(attribs[ParsersAttributes::TABLE], OBJ_VIEW)); + table=dynamic_cast(getObject(attribs[Attributes::Table], ObjectType::View)); //Raises an error if the parent table doesn't exists if(!table) { - str_aux=QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(OBJ_INDEX)) - .arg(attribs[ParsersAttributes::TABLE]) - .arg(BaseObject::getTypeName(OBJ_TABLE)); + str_aux=Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Index)) + .arg(attribs[Attributes::Table]) + .arg(BaseObject::getTypeName(ObjectType::Table)); - throw Exception(str_aux,ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(str_aux,ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } index=new Index; setBasicAttributes(index); index->setParentTable(table); - index->setIndexAttribute(Index::CONCURRENT, attribs[ParsersAttributes::CONCURRENT]==ParsersAttributes::_TRUE_); - index->setIndexAttribute(Index::UNIQUE, attribs[ParsersAttributes::UNIQUE]==ParsersAttributes::_TRUE_); - index->setIndexAttribute(Index::FAST_UPDATE, attribs[ParsersAttributes::FAST_UPDATE]==ParsersAttributes::_TRUE_); - index->setIndexAttribute(Index::BUFFERING, attribs[ParsersAttributes::BUFFERING]==ParsersAttributes::_TRUE_); - index->setIndexingType(attribs[ParsersAttributes::INDEX_TYPE]); - index->setFillFactor(attribs[ParsersAttributes::FACTOR].toUInt()); + index->setIndexAttribute(Index::Concurrent, attribs[Attributes::Concurrent]==Attributes::True); + index->setIndexAttribute(Index::Unique, attribs[Attributes::Unique]==Attributes::True); + index->setIndexAttribute(Index::FastUpdate, attribs[Attributes::FastUpdate]==Attributes::True); + index->setIndexAttribute(Index::Buffering, attribs[Attributes::Buffering]==Attributes::True); + index->setIndexingType(attribs[Attributes::IndexType]); + index->setFillFactor(attribs[Attributes::Factor].toUInt()); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -5149,31 +5512,31 @@ Index *DatabaseModel::createIndex(void) { elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::INDEX_ELEMENT) + if(elem==Attributes::IndexElement) { createElement(idx_elem, index, table); index->addIndexElement(idx_elem); } - else if(elem==ParsersAttributes::PREDICATE) + else if(elem==Attributes::Predicate) { xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); str_aux=xmlparser.getElementContent(); xmlparser.restorePosition(); index->setPredicate(str_aux); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } table->addObject(index); - table->setModified(true); + table->setModified(!loading_model); } catch(Exception &e) { if(index) delete(index); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(index); @@ -5195,24 +5558,24 @@ Rule *DatabaseModel::createRule(void) xmlparser.getElementAttributes(attribs); - table=dynamic_cast(getObject(attribs[ParsersAttributes::TABLE], OBJ_TABLE)); + table=dynamic_cast(getObject(attribs[Attributes::Table], ObjectType::Table)); if(!table) - table=dynamic_cast(getObject(attribs[ParsersAttributes::TABLE], OBJ_VIEW)); + table=dynamic_cast(getObject(attribs[Attributes::Table], ObjectType::View)); if(!table) - throw Exception(QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(OBJ_RULE)) - .arg(attribs[ParsersAttributes::TABLE]) - .arg(BaseObject::getTypeName(OBJ_TABLE)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Rule)) + .arg(attribs[Attributes::Table]) + .arg(BaseObject::getTypeName(ObjectType::Table)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); - rule->setExecutionType(attribs[ParsersAttributes::EXEC_TYPE]); - rule->setEventType(attribs[ParsersAttributes::EVENT_TYPE]); + rule->setExecutionType(attribs[Attributes::ExecType]); + rule->setEventType(attribs[Attributes::EventType]); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -5220,16 +5583,16 @@ Rule *DatabaseModel::createRule(void) { elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::COMMANDS || - elem==ParsersAttributes::CONDITION) + if(elem==Attributes::Commands || + elem==Attributes::Condition) { xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); str_aux=xmlparser.getElementContent(); xmlparser.restorePosition(); - if(elem==ParsersAttributes::COMMANDS) + if(elem==Attributes::Commands) { cmd_list=str_aux.split(';'); count=cmd_list.count(); @@ -5244,16 +5607,16 @@ Rule *DatabaseModel::createRule(void) } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } table->addObject(rule); - table->setModified(true); + table->setModified(!loading_model); } catch(Exception &e) { if(rule) delete(rule); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(rule); @@ -5274,18 +5637,18 @@ Trigger *DatabaseModel::createTrigger(void) { xmlparser.getElementAttributes(attribs); - table=dynamic_cast(getObject(attribs[ParsersAttributes::TABLE], OBJ_TABLE)); + table=dynamic_cast(getObject(attribs[Attributes::Table], ObjectType::Table)); if(!table) - table=dynamic_cast(getObject(attribs[ParsersAttributes::TABLE], OBJ_VIEW)); + table=dynamic_cast(getObject(attribs[Attributes::Table], ObjectType::View)); if(!table) - throw Exception(QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(OBJ_TRIGGER)) - .arg(attribs[ParsersAttributes::TABLE]) - .arg(BaseObject::getTypeName(OBJ_TABLE)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Trigger)) + .arg(attribs[Attributes::Table]) + .arg(BaseObject::getTypeName(ObjectType::Table)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); trigger=new Trigger; @@ -5293,26 +5656,28 @@ Trigger *DatabaseModel::createTrigger(void) setBasicAttributes(trigger); - trigger->setConstraint(attribs[ParsersAttributes::CONSTRAINT]==ParsersAttributes::_TRUE_); + trigger->setConstraint(attribs[Attributes::Constraint]==Attributes::True); - trigger->setEvent(EventType::on_insert, - (attribs[ParsersAttributes::INS_EVENT]==ParsersAttributes::_TRUE_)); + trigger->setEvent(EventType::OnInsert, + (attribs[Attributes::InsEvent]==Attributes::True)); - trigger->setEvent(EventType::on_delete, - (attribs[ParsersAttributes::DEL_EVENT]==ParsersAttributes::_TRUE_)); + trigger->setEvent(EventType::OnDelete, + (attribs[Attributes::DelEvent]==Attributes::True)); - trigger->setEvent(EventType::on_update, - (attribs[ParsersAttributes::UPD_EVENT]==ParsersAttributes::_TRUE_)); + trigger->setEvent(EventType::OnUpdate, + (attribs[Attributes::UpdEvent]==Attributes::True)); - trigger->setEvent(EventType::on_truncate, - (attribs[ParsersAttributes::TRUNC_EVENT]==ParsersAttributes::_TRUE_)); + trigger->setEvent(EventType::OnTruncate, + (attribs[Attributes::TruncEvent]==Attributes::True)); - trigger->setExecutePerRow(attribs[ParsersAttributes::PER_ROW]==ParsersAttributes::_TRUE_); + trigger->setExecutePerRow(attribs[Attributes::PerRow]==Attributes::True); - trigger->setFiringType(FiringType(attribs[ParsersAttributes::FIRING_TYPE])); + trigger->setFiringType(FiringType(attribs[Attributes::FiringType])); + trigger->setTransitionTableName(Trigger::OldTableName, attribs[Attributes::OldTableName]); + trigger->setTransitionTableName(Trigger::NewTableName, attribs[Attributes::NewTableName]); - list_aux=attribs[ParsersAttributes::ARGUMENTS].split(','); + list_aux=attribs[Attributes::Arguments].split(','); count=list_aux.count(); for(i=0; i < count; i++) { @@ -5320,33 +5685,33 @@ Trigger *DatabaseModel::createTrigger(void) trigger->addArgument(list_aux[i]); } - trigger->setDeferrable(attribs[ParsersAttributes::DEFERRABLE]==ParsersAttributes::_TRUE_); + trigger->setDeferrable(attribs[Attributes::Deferrable]==Attributes::True); if(trigger->isDeferrable()) - trigger->setDeferralType(attribs[ParsersAttributes::DEFER_TYPE]); + trigger->setDeferralType(attribs[Attributes::DeferType]); - if(!attribs[ParsersAttributes::REF_TABLE].isEmpty()) + if(!attribs[Attributes::RefTable].isEmpty()) { - ref_table=getObject(attribs[ParsersAttributes::REF_TABLE], OBJ_TABLE); + ref_table=getObject(attribs[Attributes::RefTable], ObjectType::Table); if(!ref_table) - ref_table=getObject(attribs[ParsersAttributes::REF_TABLE], OBJ_VIEW); + ref_table=getObject(attribs[Attributes::RefTable], ObjectType::View); //Raises an error if the trigger is referencing a inexistent table if(!ref_table) { - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(trigger->getName()) .arg(trigger->getTypeName()) - .arg(attribs[ParsersAttributes::REF_TABLE]) - .arg(BaseObject::getTypeName(OBJ_TABLE)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs[Attributes::RefTable]) + .arg(BaseObject::getTypeName(ObjectType::Table)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } trigger->setReferecendTable(dynamic_cast(ref_table)); } - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -5354,43 +5719,43 @@ Trigger *DatabaseModel::createTrigger(void) { elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::FUNCTION) + if(elem==Attributes::Function) { xmlparser.getElementAttributes(attribs); - func=getObject(attribs[ParsersAttributes::SIGNATURE], OBJ_FUNCTION); + func=getObject(attribs[Attributes::Signature], ObjectType::Function); //Raises an error if the function doesn't exists - if(!func && !attribs[ParsersAttributes::SIGNATURE].isEmpty()) + if(!func && !attribs[Attributes::Signature].isEmpty()) { - str_aux=QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) + str_aux=Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(trigger->getName()) .arg(trigger->getTypeName()) - .arg(attribs[ParsersAttributes::SIGNATURE]) - .arg(BaseObject::getTypeName(OBJ_FUNCTION)); + .arg(attribs[Attributes::Signature]) + .arg(BaseObject::getTypeName(ObjectType::Function)); - throw Exception(str_aux,ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(str_aux,ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } trigger->setFunction(dynamic_cast(func)); } - else if(elem==ParsersAttributes::CONDITION) + else if(elem==Attributes::Condition) { xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); str_aux=xmlparser.getElementContent(); xmlparser.restorePosition(); trigger->setCondition(str_aux); } - else if(elem==ParsersAttributes::COLUMNS) + else if(elem==Attributes::Columns) { xmlparser.getElementAttributes(attribs); - list_aux=attribs[ParsersAttributes::NAMES].split(','); + list_aux=attribs[Attributes::Names].split(','); count=list_aux.count(); for(i=0; i < count; i++) { - column=dynamic_cast(table->getObject(list_aux[i].trimmed(), OBJ_COLUMN)); + column=dynamic_cast(table->getObject(list_aux[i].trimmed(), ObjectType::Column)); if(!column && dynamic_cast
(table)) column=dynamic_cast
(table)->getColumn(list_aux[i].trimmed(), true); @@ -5400,16 +5765,16 @@ Trigger *DatabaseModel::createTrigger(void) } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } table->addObject(trigger); - table->setModified(true); + table->setModified(!loading_model); } catch(Exception &e) { if(trigger) delete(trigger); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(trigger); @@ -5429,20 +5794,20 @@ Policy *DatabaseModel::createPolicy(void) xmlparser.getElementAttributes(attribs); - table=dynamic_cast(getObject(attribs[ParsersAttributes::TABLE], OBJ_TABLE)); + table=dynamic_cast(getObject(attribs[Attributes::Table], ObjectType::Table)); if(!table) - throw Exception(QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(OBJ_POLICY)) - .arg(attribs[ParsersAttributes::TABLE]) - .arg(BaseObject::getTypeName(OBJ_TABLE)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Policy)) + .arg(attribs[Attributes::Table]) + .arg(BaseObject::getTypeName(ObjectType::Table)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); - policy->setPermissive(attribs[ParsersAttributes::PERMISSIVE] == ParsersAttributes::_TRUE_); - policy->setPolicyCommand(PolicyCmdType(attribs[ParsersAttributes::COMMAND])); + policy->setPermissive(attribs[Attributes::Permissive] == Attributes::True); + policy->setPolicyCommand(PolicyCmdType(attribs[Attributes::Command])); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -5450,41 +5815,41 @@ Policy *DatabaseModel::createPolicy(void) { elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::EXPRESSION) + if(elem==Attributes::Expression) { xmlparser.getElementAttributes(attribs); xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); - if(attribs[ParsersAttributes::TYPE] == ParsersAttributes::USING_EXP) + if(attribs[Attributes::Type] == Attributes::UsingExp) policy->setUsingExpression(xmlparser.getElementContent()); - else if(attribs[ParsersAttributes::TYPE] == ParsersAttributes::CHECK_EXP) + else if(attribs[Attributes::Type] == Attributes::CheckExp) policy->setCheckExpression(xmlparser.getElementContent()); xmlparser.restorePosition(); } - else if(xmlparser.getElementName()==ParsersAttributes::ROLES) + else if(xmlparser.getElementName()==Attributes::Roles) { QStringList rol_names; Role *role = nullptr; xmlparser.getElementAttributes(attribs); - rol_names = attribs[ParsersAttributes::NAMES].split(','); + rol_names = attribs[Attributes::Names].split(','); for(auto &name : rol_names) { - role=dynamic_cast(getObject(name.trimmed(), OBJ_ROLE)); + role=dynamic_cast(getObject(name.trimmed(), ObjectType::Role)); //Raises an error if the referenced role doesn't exists if(!role) { - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(policy->getName()) .arg(policy->getTypeName()) .arg(name) - .arg(BaseObject::getTypeName(OBJ_ROLE)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Role)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } policy->addRole(role); @@ -5492,16 +5857,16 @@ Policy *DatabaseModel::createPolicy(void) } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } table->addObject(policy); - table->setModified(true); + table->setModified(!loading_model); } catch(Exception &e) { if(policy) delete(policy); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(policy); @@ -5519,9 +5884,9 @@ EventTrigger *DatabaseModel::createEventTrigger(void) event_trig=new EventTrigger; setBasicAttributes(event_trig); xmlparser.getElementAttributes(attribs); - event_trig->setEvent(EventTriggerType(attribs[ParsersAttributes::EVENT])); + event_trig->setEvent(EventTriggerType(attribs[Attributes::Event])); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -5529,39 +5894,39 @@ EventTrigger *DatabaseModel::createEventTrigger(void) { elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::FUNCTION) + if(elem==Attributes::Function) { xmlparser.getElementAttributes(attribs); - func=getObject(attribs[ParsersAttributes::SIGNATURE], OBJ_FUNCTION); + func=getObject(attribs[Attributes::Signature], ObjectType::Function); //Raises an error if the function doesn't exists - if(!func && !attribs[ParsersAttributes::SIGNATURE].isEmpty()) + if(!func && !attribs[Attributes::Signature].isEmpty()) { - throw Exception(QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(event_trig->getName()) .arg(event_trig->getTypeName()) - .arg(attribs[ParsersAttributes::SIGNATURE]) - .arg(BaseObject::getTypeName(OBJ_FUNCTION)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs[Attributes::Signature]) + .arg(BaseObject::getTypeName(ObjectType::Function)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } event_trig->setFunction(dynamic_cast(func)); } - else if(elem==ParsersAttributes::FILTER) + else if(elem==Attributes::Filter) { xmlparser.getElementAttributes(attribs); - event_trig->setFilter(attribs[ParsersAttributes::VARIABLE], attribs[ParsersAttributes::VALUES].split(',')); + event_trig->setFilter(attribs[Attributes::Variable], attribs[Attributes::Values].split(',')); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) { if(event_trig) delete(event_trig); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(event_trig); @@ -5571,30 +5936,288 @@ GenericSQL *DatabaseModel::createGenericSQL(void) { GenericSQL *genericsql=nullptr; attribs_map attribs; + QString elem, parent_name, obj_name; + ObjectType obj_type; + Table *parent_table = nullptr; + BaseObject *object = nullptr; try { - genericsql=new GenericSQL; + genericsql = new GenericSQL; setBasicAttributes(genericsql); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { - if(xmlparser.getElementType()==XML_ELEMENT_NODE && xmlparser.getElementName() == ParsersAttributes::DEFINITION) + do { - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); - genericsql->setDefinition(xmlparser.getElementContent()); + if(xmlparser.getElementType()==XML_ELEMENT_NODE) + { + elem = xmlparser.getElementName(); + + if(elem == Attributes::Definition) + { + xmlparser.savePosition(); + xmlparser.accessElement(XmlParser::ChildElement); + genericsql->setDefinition(xmlparser.getElementContent()); + xmlparser.restorePosition(); + } + else if(elem == Attributes::Object) + { + xmlparser.getElementAttributes(attribs); + + obj_type = BaseObject::getObjectType(attribs[Attributes::Type]); + obj_name = attribs[Attributes::Name]; + parent_name = attribs[Attributes::Parent]; + + //If the object is a column its needed to get the parent table + if(obj_type == ObjectType::Column) + { + parent_table = dynamic_cast
(getObject(parent_name, ObjectType::Table)); + + if(parent_table) + object = parent_table->getColumn(obj_name); + } + else + object = getObject(obj_name, obj_type); + + //Raises an error if the generic object references an object that does not exist + if(!object) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(genericsql->getName()) + .arg(genericsql->getTypeName()) + .arg(obj_name) + .arg(BaseObject::getTypeName(obj_type)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + genericsql->addObjectReference(object, attribs[Attributes::RefName], + attribs[Attributes::UseSignature] == Attributes::True, + attribs[Attributes::FormatName] == Attributes::True); + } + } } + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) { if(genericsql) delete(genericsql); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(genericsql); } +ForeignDataWrapper *DatabaseModel::createForeignDataWrapper(void) +{ + attribs_map attribs; + ForeignDataWrapper *fdw=nullptr; + BaseObject *func=nullptr; + QString signature, ref_type; + ObjectType obj_type; + + try + { + fdw = new ForeignDataWrapper; + + xmlparser.getElementAttributes(attribs); + setBasicAttributes(fdw); + + if(xmlparser.accessElement(XmlParser::ChildElement)) + { + do + { + if(xmlparser.getElementType() == XML_ELEMENT_NODE) + { + obj_type = BaseObject::getObjectType(xmlparser.getElementName()); + + if(obj_type == ObjectType::Function) + { + xmlparser.getElementAttributes(attribs); + + //Gets the function reference type + ref_type = attribs[Attributes::RefType]; + + //Try to retrieve one the functions of the fdw + if(ref_type == Attributes::ValidatorFunc || ref_type == Attributes::HandlerFunc) + { + //Gets the function signature and tries to retrieve it from the model + signature = attribs[Attributes::Signature]; + func = getObject(signature, ObjectType::Function); + + //Raises an error if the function doesn't exists + if(!func) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(fdw->getName()) + .arg(fdw->getTypeName()) + .arg(signature) + .arg(BaseObject::getTypeName(ObjectType::Function)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + if(ref_type == Attributes::ValidatorFunc) + fdw->setValidatorFunction(dynamic_cast(func)); + else if(ref_type == Attributes::HandlerFunc) + fdw->setHandlerFunction(dynamic_cast(func)); + } + else + //Raises an error if the function type is invalid + throw Exception(ErrorCode::RefFunctionInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + } + } + while(xmlparser.accessElement(XmlParser::NextElement)); + } + } + catch(Exception &e) + { + if(fdw) + delete(fdw); + + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + } + + return(fdw); +} + +ForeignServer *DatabaseModel::createForeignServer(void) +{ + attribs_map attribs; + ForeignServer *server = nullptr; + BaseObject *fdw = nullptr; + ObjectType obj_type; + + try + { + server = new ForeignServer; + + xmlparser.getElementAttributes(attribs); + setBasicAttributes(server); + server->setType(attribs[Attributes::Type]); + server->setVersion(attribs[Attributes::Version]); + + if(xmlparser.accessElement(XmlParser::ChildElement)) + { + do + { + if(xmlparser.getElementType() == XML_ELEMENT_NODE) + { + obj_type = BaseObject::getObjectType(xmlparser.getElementName()); + + if(obj_type == ObjectType::ForeignDataWrapper) + { + xmlparser.getElementAttributes(attribs); + fdw = getObject(attribs[Attributes::Name], ObjectType::ForeignDataWrapper); + + //Raises an error if the fdw doesn't exists + if(!fdw) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(server->getName()) + .arg(server->getTypeName()) + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::ForeignDataWrapper)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + server->setForeignDataWrapper(dynamic_cast(fdw)); + } + } + } + while(xmlparser.accessElement(XmlParser::NextElement)); + } + } + catch(Exception &e) + { + if(server) + delete(server); + + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + } + + return(server); +} + +UserMapping *DatabaseModel::createUserMapping(void) +{ + attribs_map attribs; + UserMapping *user_map = nullptr; + ForeignServer *server = nullptr; + ObjectType obj_type; + + try + { + user_map = new UserMapping; + + xmlparser.getElementAttributes(attribs); + setBasicAttributes(user_map); + + if(xmlparser.accessElement(XmlParser::ChildElement)) + { + do + { + if(xmlparser.getElementType() == XML_ELEMENT_NODE) + { + obj_type = BaseObject::getObjectType(xmlparser.getElementName()); + + if(obj_type == ObjectType::ForeignServer) + { + xmlparser.savePosition(); + xmlparser.getElementAttributes(attribs); + server = dynamic_cast(getObject(attribs[Attributes::Name], ObjectType::ForeignServer)); + + //Raises an error if the server doesn't exists + if(!server) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(user_map->getName()) + .arg(user_map->getTypeName()) + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::ForeignServer)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + user_map->setForeignServer(server); + xmlparser.restorePosition(); + } + } + } + while(xmlparser.accessElement(XmlParser::NextElement)); + } + } + catch(Exception &e) + { + if(user_map) + delete(user_map); + + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + } + + return(user_map); +} + +void DatabaseModel::updateViewsReferencingTable(Table *table) +{ + BaseRelationship *rel = nullptr; + View *view = nullptr; + Table *tab = nullptr; + + if(!table) return; + + for(auto obj : base_relationships) + { + rel = dynamic_cast(obj); + + if(rel->getRelationshipType() != BaseRelationship::RelationshipDep) + continue; + + view = dynamic_cast(rel->getTable(BaseRelationship::SrcTable)); + tab = dynamic_cast
(rel->getTable(BaseRelationship::DstTable)); + + if(view && tab == table) + { + view->generateColumns(); + view->setCodeInvalidated(true); + view->setModified(true); + dynamic_cast(view->getSchema())->setModified(true); + } + } +} + Sequence *DatabaseModel::createSequence(bool ignore_onwer) { attribs_map attribs; @@ -5611,18 +6234,18 @@ Sequence *DatabaseModel::createSequence(bool ignore_onwer) setBasicAttributes(sequence); xmlparser.getElementAttributes(attribs); - sequence->setValues(attribs[ParsersAttributes::MIN_VALUE], - attribs[ParsersAttributes::MAX_VALUE], - attribs[ParsersAttributes::INCREMENT], - attribs[ParsersAttributes::START], - attribs[ParsersAttributes::CACHE]); + sequence->setValues(attribs[Attributes::MinValue], + attribs[Attributes::MaxValue], + attribs[Attributes::Increment], + attribs[Attributes::Start], + attribs[Attributes::Cache]); - sequence->setCycle(attribs[ParsersAttributes::CYCLE]==ParsersAttributes::_TRUE_); + sequence->setCycle(attribs[Attributes::Cycle]==Attributes::True); //Getting the sequence's owner column - if(!attribs[ParsersAttributes::OWNER_COLUMN].isEmpty()) + if(!attribs[Attributes::OwnerColumn].isEmpty()) { - elem_list=attribs[ParsersAttributes::OWNER_COLUMN].split('.'); + elem_list=attribs[Attributes::OwnerColumn].split('.'); count=elem_list.count(); if(count==3) @@ -5636,18 +6259,18 @@ Sequence *DatabaseModel::createSequence(bool ignore_onwer) col_name=elem_list[1]; } - table=getObject(tab_name, OBJ_TABLE); + table=getObject(tab_name, ObjectType::Table); //Raises an error if the column parent table doesn't exists if(!table) { - str_aux=QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) + str_aux=Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(sequence->getName()) - .arg(BaseObject::getTypeName(OBJ_SEQUENCE)) + .arg(BaseObject::getTypeName(ObjectType::Sequence)) .arg(tab_name) - .arg(BaseObject::getTypeName(OBJ_TABLE)); + .arg(BaseObject::getTypeName(ObjectType::Table)); - throw Exception(str_aux,ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(str_aux,ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } column=dynamic_cast
(table)->getColumn(col_name); @@ -5657,9 +6280,9 @@ Sequence *DatabaseModel::createSequence(bool ignore_onwer) //Raises an error if the column doesn't exists if(!column && !ignore_onwer) - throw Exception(Exception::getErrorMessage(ERR_ASG_INEXIST_OWNER_COL_SEQ) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInexistentSeqOwnerColumn) .arg(sequence->getName(true)), - ERR_ASG_INEXIST_OWNER_COL_SEQ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgInexistentSeqOwnerColumn,__PRETTY_FUNCTION__,__FILE__,__LINE__); sequence->setOwnerColumn(column); } @@ -5667,7 +6290,7 @@ Sequence *DatabaseModel::createSequence(bool ignore_onwer) catch(Exception &e) { if(sequence) delete(sequence); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(sequence); @@ -5686,6 +6309,7 @@ View *DatabaseModel::createView(void) unsigned type; int ref_idx, i, count; bool refs_in_expr=false; + Reference reference; try { @@ -5693,13 +6317,18 @@ View *DatabaseModel::createView(void) setBasicAttributes(view); xmlparser.getElementAttributes(attribs); - view->setMaterialized(attribs[ParsersAttributes::MATERIALIZED]==ParsersAttributes::_TRUE_); - view->setRecursive(attribs[ParsersAttributes::RECURSIVE]==ParsersAttributes::_TRUE_); - view->setWithNoData(attribs[ParsersAttributes::WITH_NO_DATA]==ParsersAttributes::_TRUE_); - view->setExtAttribsHidden(attribs[ParsersAttributes::HIDE_EXT_ATTRIBS]==ParsersAttributes::_TRUE_); - view->setFadedOut(attribs[ParsersAttributes::FADED_OUT]==ParsersAttributes::_TRUE_); - - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + view->setObjectListsCapacity(attribs[Attributes::MaxObjCount].toUInt()); + view->setMaterialized(attribs[Attributes::Materialized]==Attributes::True); + view->setRecursive(attribs[Attributes::Recursive]==Attributes::True); + view->setWithNoData(attribs[Attributes::WithNoData]==Attributes::True); + view->setCollapseMode(attribs[Attributes::CollapseMode].isEmpty() ? CollapseMode::NotCollapsed : static_cast(attribs[Attributes::CollapseMode].toUInt())); + view->setPaginationEnabled(attribs[Attributes::Pagination]==Attributes::True); + view->setCurrentPage(BaseTable::AttribsSection, attribs[Attributes::AttribsPage].toUInt()); + view->setCurrentPage(BaseTable::ExtAttribsSection, attribs[Attributes::ExtAttribsPage].toUInt()); + view->setFadedOut(attribs[Attributes::FadedOut]==Attributes::True); + view->setLayer(attribs[Attributes::Layer].toUInt()); + + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -5707,84 +6336,117 @@ View *DatabaseModel::createView(void) { elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::REFERENCE) + if(elem==Attributes::Reference) { xmlparser.getElementAttributes(attribs); //If the table name is specified tries to create a reference to a table/column - if(!attribs[ParsersAttributes::TABLE].isEmpty()) + if(!attribs[Attributes::Table].isEmpty()) { column=nullptr; - table=dynamic_cast
(getObject(attribs[ParsersAttributes::TABLE], OBJ_TABLE)); + table=dynamic_cast
(getObject(attribs[Attributes::Table], ObjectType::Table)); //Raises an error if the table doesn't exists if(!table) { - str_aux=QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) + str_aux=Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(view->getName()) - .arg(BaseObject::getTypeName(OBJ_VIEW)) - .arg(attribs[ParsersAttributes::TABLE]) - .arg(BaseObject::getTypeName(OBJ_TABLE)); + .arg(BaseObject::getTypeName(ObjectType::View)) + .arg(attribs[Attributes::Table]) + .arg(BaseObject::getTypeName(ObjectType::Table)); - throw Exception(str_aux,ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(str_aux,ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } - if(!attribs[ParsersAttributes::COLUMN].isEmpty()) + if(!attribs[Attributes::Column].isEmpty()) { - column=table->getColumn(attribs[ParsersAttributes::COLUMN]); + column=table->getColumn(attribs[Attributes::Column]); if(!column) - column=table->getColumn(attribs[ParsersAttributes::COLUMN], true); + column=table->getColumn(attribs[Attributes::Column], true); //Raises an error if the view references an inexistant column if(!column) { - str_aux=QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) + str_aux=Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(view->getName()) - .arg(BaseObject::getTypeName(OBJ_VIEW)) - .arg(attribs[ParsersAttributes::TABLE] + QString(".") + - attribs[ParsersAttributes::COLUMN]) - .arg(BaseObject::getTypeName(OBJ_COLUMN)); + .arg(BaseObject::getTypeName(ObjectType::View)) + .arg(attribs[Attributes::Table] + QString(".") + + attribs[Attributes::Column]) + .arg(BaseObject::getTypeName(ObjectType::Column)); - throw Exception(str_aux,ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(str_aux,ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } //Adds the configured reference to a temporarily list - refs.push_back(Reference(table, column, - attribs[ParsersAttributes::ALIAS], - attribs[ParsersAttributes::COLUMN_ALIAS])); + reference = Reference(table, column, + attribs[Attributes::Alias], + attribs[Attributes::ColumnAlias]); + reference.setReferenceAlias(attribs[Attributes::RefAlias]); + refs.push_back(reference); } else { xmlparser.savePosition(); - str_aux=attribs[ParsersAttributes::ALIAS]; + str_aux=attribs[Attributes::Alias]; - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); - refs.push_back(Reference(xmlparser.getElementContent(),str_aux)); + // Retrieving the reference expression + xmlparser.accessElement(XmlParser::ChildElement); + xmlparser.savePosition(); + xmlparser.accessElement(XmlParser::ChildElement); + reference = Reference(xmlparser.getElementContent(), str_aux); + reference.setReferenceAlias(attribs[Attributes::RefAlias]); + xmlparser.restorePosition(); + + // Creating the columns related to the expression + if(xmlparser.accessElement(XmlParser::NextElement)) + { + do + { + elem = xmlparser.getElementName(); + xmlparser.savePosition(); + if(elem == Attributes::Column) + { + column = createColumn(); + reference.addColumn(column); + delete(column); + } + else if(elem == Attributes::RefTableTag) + { + xmlparser.getElementAttributes(aux_attribs); + table = getTable(aux_attribs[Attributes::Name]); + reference.addReferencedTable(table); + } + + xmlparser.restorePosition(); + } + while(xmlparser.accessElement(XmlParser::NextElement)); + } + + refs.push_back(reference); xmlparser.restorePosition(); } } - else if(elem==ParsersAttributes::EXPRESSION) + else if(elem==Attributes::Expression) { xmlparser.savePosition(); xmlparser.getElementAttributes(attribs); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); - if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::CTE_EXPRESSION) + if(attribs[Attributes::Type]==Attributes::CteExpression) view->setCommomTableExpression(xmlparser.getElementContent()); else { - if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::SELECT_EXP) - type=Reference::SQL_REFER_SELECT; - else if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::FROM_EXP) - type=Reference::SQL_REFER_FROM; - else if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::SIMPLE_EXP) - type=Reference::SQL_REFER_WHERE; + if(attribs[Attributes::Type]==Attributes::SelectExp) + type=Reference::SqlReferSelect; + else if(attribs[Attributes::Type]==Attributes::FromExp) + type=Reference::SqlReferFrom; + else if(attribs[Attributes::Type]==Attributes::SimpleExp) + type=Reference::SqlReferWhere; else - type=Reference::SQL_REFER_END_EXPR; + type=Reference::SqlReferEndExpr; list_aux=xmlparser.getElementContent().split(','); count=list_aux.size(); @@ -5802,26 +6464,26 @@ View *DatabaseModel::createView(void) xmlparser.restorePosition(); } - else if(elem==BaseObject::getSchemaName(OBJ_TAG)) + else if(elem==BaseObject::getSchemaName(ObjectType::Tag)) { xmlparser.getElementAttributes(aux_attribs); - tag=getObject(aux_attribs[ParsersAttributes::NAME] ,OBJ_TAG); + tag=getObject(aux_attribs[Attributes::Name] ,ObjectType::Tag); if(!tag) { - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(OBJ_TABLE)) - .arg(aux_attribs[ParsersAttributes::TABLE]) - .arg(BaseObject::getTypeName(OBJ_TAG)) - , ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Table)) + .arg(aux_attribs[Attributes::Table]) + .arg(BaseObject::getTypeName(ObjectType::Tag)) + , ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } view->setTag(dynamic_cast(tag)); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } /** Special case for refereces used as view definition ** @@ -5841,7 +6503,7 @@ View *DatabaseModel::createView(void) itr=refs.begin(); while(itr!=refs.end()) { - view->addReference(*itr, Reference::SQL_VIEW_DEFINITION); + view->addReference(*itr, Reference::SqlViewDefinition); itr++; } } @@ -5849,7 +6511,7 @@ View *DatabaseModel::createView(void) catch(Exception &e) { if(view) delete(view); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(view); @@ -5869,26 +6531,26 @@ Collation *DatabaseModel::createCollation(void) xmlparser.getElementAttributes(attribs); - encoding=EncodingType(attribs[ParsersAttributes::ENCODING]); + encoding=EncodingType(attribs[Attributes::Encoding]); collation->setEncoding(encoding); //Creating a collation from a base locale - if(!attribs[ParsersAttributes::LOCALE].isEmpty()) - collation->setLocale(attribs[ParsersAttributes::LOCALE]); + if(!attribs[Attributes::Locale].isEmpty()) + collation->setLocale(attribs[Attributes::Locale]); //Creating a collation from another collation - else if(!attribs[ParsersAttributes::COLLATION].isEmpty()) + else if(!attribs[Attributes::Collation].isEmpty()) { - copy_coll=this->getObject(attribs[ParsersAttributes::COLLATION], OBJ_COLLATION); + copy_coll=this->getObject(attribs[Attributes::Collation], ObjectType::Collation); //Raises an error if the copy collation doesn't exists if(!copy_coll) { - throw Exception(QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(collation->getName()) - .arg(BaseObject::getTypeName(OBJ_COLLATION)) - .arg(attribs[ParsersAttributes::COLLATION]) - .arg(BaseObject::getTypeName(OBJ_COLLATION)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Collation)) + .arg(attribs[Attributes::Collation]) + .arg(BaseObject::getTypeName(ObjectType::Collation)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } collation->setCollation(dynamic_cast(copy_coll)); @@ -5896,14 +6558,14 @@ Collation *DatabaseModel::createCollation(void) //Creating a collation using LC_COLLATE and LC_CTYPE params else { - collation->setLocalization(Collation::_LC_COLLATE, attribs[ParsersAttributes::_LC_COLLATE_]); - collation->setLocalization(Collation::_LC_CTYPE, attribs[ParsersAttributes::_LC_CTYPE_]); + collation->setLocalization(Collation::LcCollate, attribs[Attributes::LcCollate]); + collation->setLocalization(Collation::LcCtype, attribs[Attributes::LcCtype]); } } catch(Exception &e) { if(collation) delete(collation); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(collation); @@ -5920,14 +6582,14 @@ Extension *DatabaseModel::createExtension(void) xmlparser.getElementAttributes(attribs); setBasicAttributes(extension); - extension->setHandlesType(attribs[ParsersAttributes::HANDLES_TYPE]==ParsersAttributes::_TRUE_); - extension->setVersion(Extension::CUR_VERSION, attribs[ParsersAttributes::CUR_VERSION]); - extension->setVersion(Extension::OLD_VERSION, attribs[ParsersAttributes::OLD_VERSION]); + extension->setHandlesType(attribs[Attributes::HandlesType]==Attributes::True); + extension->setVersion(Extension::CurVersion, attribs[Attributes::CurVersion]); + extension->setVersion(Extension::OldVersion, attribs[Attributes::OldVersion]); } catch(Exception &e) { if(extension) delete(extension); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(extension); @@ -5944,7 +6606,7 @@ Tag *DatabaseModel::createTag(void) tag=new Tag; setBasicAttributes(tag); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -5952,14 +6614,14 @@ Tag *DatabaseModel::createTag(void) { elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::STYLE) + if(elem==Attributes::Style) { xmlparser.getElementAttributes(attribs); - tag->setElementColors(attribs[ParsersAttributes::ID],attribs[ParsersAttributes::COLORS]); + tag->setElementColors(attribs[Attributes::Id],attribs[Attributes::Colors]); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } return(tag); @@ -5967,7 +6629,7 @@ Tag *DatabaseModel::createTag(void) catch(Exception &e) { if(tag) delete(tag); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } } @@ -5983,21 +6645,22 @@ Textbox *DatabaseModel::createTextbox(void) xmlparser.getElementAttributes(attribs); - txtbox->setFadedOut(attribs[ParsersAttributes::FADED_OUT]==ParsersAttributes::_TRUE_); - txtbox->setTextAttribute(Textbox::ITALIC_TXT, attribs[ParsersAttributes::ITALIC]==ParsersAttributes::_TRUE_); - txtbox->setTextAttribute(Textbox::BOLD_TXT, attribs[ParsersAttributes::BOLD]==ParsersAttributes::_TRUE_); - txtbox->setTextAttribute(Textbox::UNDERLINE_TXT, attribs[ParsersAttributes::UNDERLINE]==ParsersAttributes::_TRUE_); + txtbox->setFadedOut(attribs[Attributes::FadedOut]==Attributes::True); + txtbox->setLayer(attribs[Attributes::Layer].toUInt()); + txtbox->setTextAttribute(Textbox::ItalicText, attribs[Attributes::Italic]==Attributes::True); + txtbox->setTextAttribute(Textbox::BoldText, attribs[Attributes::Bold]==Attributes::True); + txtbox->setTextAttribute(Textbox::UnderlineText, attribs[Attributes::Underline]==Attributes::True); - if(!attribs[ParsersAttributes::COLOR].isEmpty()) - txtbox->setTextColor(QColor(attribs[ParsersAttributes::COLOR])); + if(!attribs[Attributes::Color].isEmpty()) + txtbox->setTextColor(QColor(attribs[Attributes::Color])); - if(!attribs[ParsersAttributes::FONT_SIZE].isEmpty()) - txtbox->setFontSize(attribs[ParsersAttributes::FONT_SIZE].toDouble()); + if(!attribs[Attributes::FontSize].isEmpty()) + txtbox->setFontSize(attribs[Attributes::FontSize].toDouble()); } catch(Exception &e) { if(txtbox) delete(txtbox); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(txtbox); @@ -6006,7 +6669,7 @@ Textbox *DatabaseModel::createTextbox(void) BaseRelationship *DatabaseModel::createRelationship(void) { vector cols_special_pk; - attribs_map attribs; + attribs_map attribs, constr_attribs; map labels_id; BaseRelationship *base_rel=nullptr; Relationship *rel=nullptr; @@ -6014,38 +6677,41 @@ BaseRelationship *DatabaseModel::createRelationship(void) bool src_mand, dst_mand, identifier, protect, deferrable, sql_disabled, single_pk_col, faded_out; DeferralType defer_type; ActionType del_action, upd_action; - unsigned rel_type=0, i; - ObjectType table_types[2]={OBJ_VIEW, OBJ_TABLE}, obj_rel_type; + unsigned rel_type=0, i = 0, layer = 0; + ObjectType table_types[2]={ObjectType::View, ObjectType::Table}, obj_rel_type; QString str_aux, elem, - tab_attribs[2]={ ParsersAttributes::SRC_TABLE, - ParsersAttributes::DST_TABLE }; + tab_attribs[2]={ Attributes::SrcTable, + Attributes::DstTable }; QColor custom_color=Qt::transparent; + Table *table = nullptr; try { - labels_id[ParsersAttributes::NAME_LABEL]=BaseRelationship::REL_NAME_LABEL; - labels_id[ParsersAttributes::SRC_LABEL]=BaseRelationship::SRC_CARD_LABEL; - labels_id[ParsersAttributes::DST_LABEL]=BaseRelationship::DST_CARD_LABEL; + labels_id[Attributes::NameLabel]=BaseRelationship::RelNameLabel; + labels_id[Attributes::SrcLabel]=BaseRelationship::SrcCardLabel; + labels_id[Attributes::DstLabel]=BaseRelationship::DstCardLabel; xmlparser.getElementAttributes(attribs); - protect=(attribs[ParsersAttributes::PROTECTED]==ParsersAttributes::_TRUE_); - faded_out=(attribs[ParsersAttributes::FADED_OUT]==ParsersAttributes::_TRUE_); - if(!attribs[ParsersAttributes::CUSTOM_COLOR].isEmpty()) - custom_color=QColor(attribs[ParsersAttributes::CUSTOM_COLOR]); + protect=(attribs[Attributes::Protected]==Attributes::True); + faded_out=(attribs[Attributes::FadedOut]==Attributes::True); + layer = attribs[Attributes::Layer].toUInt(); - if(attribs[ParsersAttributes::TYPE]!=ParsersAttributes::RELATION_TAB_VIEW && - attribs[ParsersAttributes::TYPE]!=ParsersAttributes::RELATIONSHIP_FK) + if(!attribs[Attributes::CustomColor].isEmpty()) + custom_color=QColor(attribs[Attributes::CustomColor]); + + if(attribs[Attributes::Type]!=Attributes::RelationshipTabView && + attribs[Attributes::Type]!=Attributes::RelationshipFk) { - table_types[0]=OBJ_TABLE; - obj_rel_type=OBJ_RELATIONSHIP; + table_types[0]=ObjectType::Table; + obj_rel_type=ObjectType::Relationship; } else { - if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::RELATIONSHIP_FK) - table_types[0]=OBJ_TABLE; + if(attribs[Attributes::Type]==Attributes::RelationshipFk) + table_types[0]=ObjectType::Table; - obj_rel_type=BASE_RELATIONSHIP; + obj_rel_type=ObjectType::BaseRelationship; } //Gets the participant tables @@ -6056,103 +6722,126 @@ BaseRelationship *DatabaseModel::createRelationship(void) //Raises an error if some table doesn't exists if(!tables[i]) { - str_aux=QString(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL)) - .arg(attribs[ParsersAttributes::NAME]) + str_aux=Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(attribs[Attributes::Name]) .arg(BaseObject::getTypeName(obj_rel_type)) .arg(attribs[tab_attribs[i]]) .arg(BaseObject::getTypeName(table_types[i])); - throw Exception(str_aux,ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(str_aux,ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } - if(obj_rel_type==BASE_RELATIONSHIP) + if(obj_rel_type==ObjectType::BaseRelationship) { base_rel=getRelationship(tables[0], tables[1]); /* Creates the fk relationship if it not exists. This generally happens when a foreign key is added to the table after its creation. */ - if(/*!base_rel &&*/ attribs[ParsersAttributes::TYPE]==ParsersAttributes::RELATIONSHIP_FK) + if(attribs[Attributes::Type]==Attributes::RelationshipFk) { - vector fks; - dynamic_cast
(tables[0])->getForeignKeys(fks, false, dynamic_cast
(tables[1])); + base_rel=new BaseRelationship(BaseRelationship::RelationshipFk, tables[0], tables[1], false, false); + base_rel->setName(attribs[Attributes::Name]); + base_rel->setAlias(attribs[Attributes::Alias]); + addRelationship(base_rel); - /* If the tables[0] doesn't has any fk that references the tables[1] indicates that the relationship - is being created before the fk that represents it (inconsistence!). In this case an error is raised. */ - if(fks.empty()) + /* If the source table doesn't have any fk that references the destination table indicates that the relationship + is being created before the fk that represents it or the fk is invalid (inconsistence!). In this case an error is raised. */ + if(base_rel->getRelationshipType() == BaseRelationship::RelationshipFk && + !base_rel->getReferenceForeignKey()) { - throw Exception(Exception::getErrorMessage(ERR_ALOC_INV_FK_RELATIONSHIP) - .arg(attribs[ParsersAttributes::NAME]) - .arg(tables[0]->getName(true)), - ERR_ALOC_INV_FK_RELATIONSHIP,__PRETTY_FUNCTION__,__FILE__,__LINE__); - } + Table *src_tab = dynamic_cast
(base_rel->getTable(BaseRelationship::SrcTable)), + *dst_tab = dynamic_cast
(base_rel->getTable(BaseRelationship::DstTable)); + vector fks; - base_rel=new BaseRelationship(BaseRelationship::RELATIONSHIP_FK, tables[0], tables[1], false, false); - base_rel->setName(attribs[ParsersAttributes::NAME]); - addRelationship(base_rel); + src_tab->getForeignKeys(fks, false, dst_tab); + + for(auto fk : fks) + { + if(!getRelationship(src_tab, dst_tab, fk)) + { + base_rel->setReferenceForeignKey(fk); + break; + } + } + + //Throws an error if the relationship was created without a valid foreign key attached to it + if(!base_rel->getReferenceForeignKey()) + { + throw Exception(Exception::getErrorMessage(ErrorCode::InvAllocationFKRelationship) + .arg(attribs[Attributes::Name]) + .arg(src_tab->getName(true)), + ErrorCode::InvAllocationFKRelationship,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + } } else if(base_rel) - base_rel->setName(attribs[ParsersAttributes::NAME]); + base_rel->setName(attribs[Attributes::Name]); if(!base_rel) - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) .arg(this->getName()) .arg(this->getTypeName()) - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(BASE_RELATIONSHIP)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::BaseRelationship)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); + base_rel->blockSignals(loading_model); base_rel->disconnectRelationship(); + base_rel->blockSignals(false); } else { - QString pat_attrib[]= { ParsersAttributes::SRC_COL_PATTERN, ParsersAttributes::DST_COL_PATTERN, - ParsersAttributes::SRC_FK_PATTERN, ParsersAttributes::DST_FK_PATTERN, - ParsersAttributes::PK_PATTERN, ParsersAttributes::UQ_PATTERN, - ParsersAttributes::PK_COL_PATTERN }; + QString pat_attrib[]= { Attributes::SrcColPattern, Attributes::DstColPattern, + Attributes::SrcFkPattern, Attributes::DstFkPattern, + Attributes::PkPattern, Attributes::UqPattern, + Attributes::PkColPattern }; - unsigned pattern_id[]= { Relationship::SRC_COL_PATTERN, Relationship::DST_COL_PATTERN, - Relationship::SRC_FK_PATTERN, Relationship::DST_FK_PATTERN, - Relationship::PK_PATTERN, Relationship::UQ_PATTERN, - Relationship::PK_COL_PATTERN }, + unsigned pattern_id[]= { Relationship::SrcColPattern, Relationship::DstColPattern, + Relationship::SrcFkPattern, Relationship::DstFkPattern, + Relationship::PkPattern, Relationship::UqPattern, + Relationship::PkColPattern }, pat_count=sizeof(pattern_id)/sizeof(unsigned); - sql_disabled=attribs[ParsersAttributes::SQL_DISABLED]==ParsersAttributes::_TRUE_; - src_mand=attribs[ParsersAttributes::SRC_REQUIRED]==ParsersAttributes::_TRUE_; - dst_mand=attribs[ParsersAttributes::DST_REQUIRED]==ParsersAttributes::_TRUE_; - identifier=attribs[ParsersAttributes::IDENTIFIER]==ParsersAttributes::_TRUE_; - deferrable=attribs[ParsersAttributes::DEFERRABLE]==ParsersAttributes::_TRUE_; - defer_type=DeferralType(attribs[ParsersAttributes::DEFER_TYPE]); - del_action=ActionType(attribs[ParsersAttributes::DEL_ACTION]); - upd_action=ActionType(attribs[ParsersAttributes::UPD_ACTION]); - single_pk_col=(attribs[ParsersAttributes::SINGLE_PK_COLUMN]==ParsersAttributes::_TRUE_); - - if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::RELATIONSHIP_11) - rel_type=BaseRelationship::RELATIONSHIP_11; - else if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::RELATIONSHIP_1N) - rel_type=BaseRelationship::RELATIONSHIP_1N; - else if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::RELATIONSHIP_NN) - rel_type=BaseRelationship::RELATIONSHIP_NN; - else if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::RELATIONSHIP_GEN) - rel_type=BaseRelationship::RELATIONSHIP_GEN; - else if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::RELATIONSHIP_DEP) - rel_type=BaseRelationship::RELATIONSHIP_DEP; + sql_disabled=attribs[Attributes::SqlDisabled]==Attributes::True; + src_mand=attribs[Attributes::SrcRequired]==Attributes::True; + dst_mand=attribs[Attributes::DstRequired]==Attributes::True; + identifier=attribs[Attributes::Identifier]==Attributes::True; + deferrable=attribs[Attributes::Deferrable]==Attributes::True; + defer_type=DeferralType(attribs[Attributes::DeferType]); + del_action=ActionType(attribs[Attributes::DelAction]); + upd_action=ActionType(attribs[Attributes::UpdAction]); + single_pk_col=(attribs[Attributes::SinglePkColumn]==Attributes::True); + + if(attribs[Attributes::Type]==Attributes::Relationship11) + rel_type=BaseRelationship::Relationship11; + else if(attribs[Attributes::Type]==Attributes::Relationship1n) + rel_type=BaseRelationship::Relationship1n; + else if(attribs[Attributes::Type]==Attributes::RelationshipNn) + rel_type=BaseRelationship::RelationshipNn; + else if(attribs[Attributes::Type]==Attributes::RelationshipGen) + rel_type=BaseRelationship::RelationshipGen; + else if(attribs[Attributes::Type]==Attributes::RelationshipDep) + rel_type=BaseRelationship::RelationshipDep; + else if(attribs[Attributes::Type]==Attributes::RelationshipPart) + rel_type=BaseRelationship::RelationshipPart; rel=new Relationship(rel_type, dynamic_cast
(tables[0]), dynamic_cast
(tables[1]), src_mand, dst_mand, identifier, deferrable, defer_type, del_action, upd_action, - CopyOptions(attribs[ParsersAttributes::COPY_MODE].toUInt(), - attribs[ParsersAttributes::COPY_OPTIONS].toUInt())); + CopyOptions(attribs[Attributes::CopyMode].toUInt(), + attribs[Attributes::CopyOptions].toUInt())); rel->setSQLDisabled(sql_disabled); rel->setSiglePKColumn(single_pk_col); - if(!attribs[ParsersAttributes::TABLE_NAME].isEmpty()) - rel->setTableNameRelNN(attribs[ParsersAttributes::TABLE_NAME]); + if(!attribs[Attributes::TableName].isEmpty()) + rel->setTableNameRelNN(attribs[Attributes::TableName]); - rel->setName(attribs[ParsersAttributes::NAME]); + rel->setName(attribs[Attributes::Name]); + rel->setAlias(attribs[Attributes::Alias]); base_rel=rel; //Configuring the name patterns @@ -6160,7 +6849,7 @@ BaseRelationship *DatabaseModel::createRelationship(void) rel->setNamePattern(pattern_id[i], attribs[pat_attrib[i]]); } - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -6168,55 +6857,76 @@ BaseRelationship *DatabaseModel::createRelationship(void) { elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::COLUMN && rel) + if(elem == Attributes::Expression && rel) + { + xmlparser.savePosition(); + xmlparser.accessElement(XmlParser::ChildElement); + rel->setPartitionBoundingExpr(xmlparser.getElementContent()); + xmlparser.restorePosition(); + } + else if(elem==Attributes::Column && rel) { xmlparser.savePosition(); rel->addObject(createColumn()); xmlparser.restorePosition(); } - else if(elem==ParsersAttributes::CONSTRAINT && rel) + else if(elem==Attributes::Constraint && rel) { xmlparser.savePosition(); - rel->addObject(createConstraint(rel)); + xmlparser.getElementAttributes(constr_attribs); + + /* If we find a primary key constraint at this point means that we're handling the original primary key stored by the relationship. + * Since relationships can't have primary keys created manually by the users we assume that + * the relationship contains a special primary key (created during relationship connection) + * and the current constraint is the original one owned by one of the tables prior the connection + * of the relationship. */ + if(constr_attribs[Attributes::Type] == Attributes::PkConstr) + { + table = getTable(constr_attribs[Attributes::Table]); + rel->setOriginalPrimaryKey(createConstraint(table)); + } + else + rel->addObject(createConstraint(rel)); + xmlparser.restorePosition(); } - else if(elem==ParsersAttributes::LINE) + else if(elem==Attributes::Line) { vector points; xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); do { xmlparser.getElementAttributes(attribs); - points.push_back(QPointF(attribs[ParsersAttributes::X_POS].toDouble(), - attribs[ParsersAttributes::Y_POS].toDouble())); + points.push_back(QPointF(attribs[Attributes::XPos].toDouble(), + attribs[Attributes::YPos].toDouble())); } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); base_rel->setPoints(points); xmlparser.restorePosition(); } - else if(elem==ParsersAttributes::LABEL) + else if(elem==Attributes::Label) { xmlparser.getElementAttributes(attribs); - str_aux=attribs[ParsersAttributes::REF_TYPE]; + str_aux=attribs[Attributes::RefType]; xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); xmlparser.getElementAttributes(attribs); xmlparser.restorePosition(); base_rel->setLabelDistance(labels_id[str_aux], - QPointF(attribs[ParsersAttributes::X_POS].toFloat(), - attribs[ParsersAttributes::Y_POS].toFloat())); + QPointF(attribs[Attributes::XPos].toDouble(), + attribs[Attributes::YPos].toDouble())); } - else if(elem==ParsersAttributes::SPECIAL_PK_COLS && rel) + else if(elem==Attributes::SpecialPkCols && rel) { QList col_list; xmlparser.getElementAttributes(attribs); - col_list=attribs[ParsersAttributes::INDEXES].split(','); + col_list=attribs[Attributes::Indexes].split(','); while(!col_list.isEmpty()) { @@ -6228,15 +6938,15 @@ BaseRelationship *DatabaseModel::createRelationship(void) } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) { - if(base_rel && base_rel->getObjectType()==OBJ_RELATIONSHIP) + if(base_rel && base_rel->getObjectType()==ObjectType::Relationship) delete(base_rel); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } if(rel) @@ -6248,30 +6958,15 @@ BaseRelationship *DatabaseModel::createRelationship(void) base_rel->setFadedOut(faded_out); base_rel->setProtected(protect); base_rel->setCustomColor(custom_color); + base_rel->setLayer(layer); /* If the FK relationship does not reference a foreign key (models generated in older versions) * we need to assign them to the respective relationships */ - if(base_rel && base_rel->getObjectType()==BASE_RELATIONSHIP) - base_rel->connectRelationship(); - - if(base_rel && - base_rel->getRelationshipType() == BaseRelationship::RELATIONSHIP_FK && - !base_rel->getReferenceForeignKey()) + if(base_rel && base_rel->getObjectType()==ObjectType::BaseRelationship) { - Table *src_tab = dynamic_cast
(base_rel->getTable(BaseRelationship::SRC_TABLE)), - *dst_tab = dynamic_cast
(base_rel->getTable(BaseRelationship::DST_TABLE)); - vector fks; - - src_tab->getForeignKeys(fks, false, dst_tab); - - for(auto fk : fks) - { - if(!getRelationship(src_tab, dst_tab, fk)) - { - base_rel->setReferenceForeignKey(fk); - break; - } - } + base_rel->blockSignals(loading_model); + base_rel->connectRelationship(); + base_rel->blockSignals(false); } return(base_rel); @@ -6288,32 +6983,32 @@ Permission *DatabaseModel::createPermission(void) ObjectType obj_type; QString parent_name, obj_name; QStringList list; - unsigned i, len, priv_type=Permission::PRIV_SELECT; + unsigned priv_type=Permission::PrivSelect; bool priv_value, grant_op, revoke, cascade; try { xmlparser.getElementAttributes(priv_attribs); - revoke=priv_attribs[ParsersAttributes::REVOKE]==ParsersAttributes::_TRUE_; - cascade=priv_attribs[ParsersAttributes::CASCADE]==ParsersAttributes::_TRUE_; + revoke=priv_attribs[Attributes::Revoke]==Attributes::True; + cascade=priv_attribs[Attributes::Cascade]==Attributes::True; xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); xmlparser.getElementAttributes(attribs); - obj_type=BaseObject::getObjectType(attribs[ParsersAttributes::TYPE]); - obj_name=attribs[ParsersAttributes::NAME]; - parent_name=attribs[ParsersAttributes::PARENT]; + obj_type=BaseObject::getObjectType(attribs[Attributes::Type]); + obj_name=attribs[Attributes::Name]; + parent_name=attribs[Attributes::Parent]; //If the object is a column its needed to get the parent table - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) { - parent_table=dynamic_cast
(getObject(parent_name, OBJ_TABLE)); + parent_table=dynamic_cast
(getObject(parent_name, ObjectType::Table)); if(parent_table) object=parent_table->getColumn(obj_name); } - else if(obj_type==OBJ_DATABASE) + else if(obj_type==ObjectType::Database) { object=this; } @@ -6322,10 +7017,10 @@ Permission *DatabaseModel::createPermission(void) //Raises an error if the permission references an object that does not exists if(!object) - throw Exception(Exception::getErrorMessage(ERR_PERM_REF_INEXIST_OBJECT) + throw Exception(Exception::getErrorMessage(ErrorCode::PermissionRefInexistObject) .arg(obj_name) .arg(BaseObject::getTypeName(obj_type)), - ERR_PERM_REF_INEXIST_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::PermissionRefInexistObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); perm=new Permission(object); perm->setRevoke(revoke); @@ -6333,31 +7028,29 @@ Permission *DatabaseModel::createPermission(void) do { - if(xmlparser.getElementName()==ParsersAttributes::ROLES) + if(xmlparser.getElementName()==Attributes::Roles) { xmlparser.getElementAttributes(attribs); + list = attribs[Attributes::Names].split(','); - list=attribs[ParsersAttributes::NAMES].split(','); - len=list.size(); - - for(i=0; i < len; i++) + for(auto &name : list) { - role=dynamic_cast(getObject(list[i].trimmed(),OBJ_ROLE)); + role=dynamic_cast(getObject(name.trimmed(), ObjectType::Role)); //Raises an error if the referenced role doesn't exists if(!role) { - throw Exception(Exception::getErrorMessage(ERR_PERM_REF_INEXIST_OBJECT) - .arg(list[i]) - .arg(BaseObject::getTypeName(OBJ_ROLE)), - ERR_REF_OBJ_INEXISTS_MODEL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::PermissionRefInexistObject) + .arg(name) + .arg(BaseObject::getTypeName(ObjectType::Role)), + ErrorCode::RefObjectInexistsModel,__PRETTY_FUNCTION__,__FILE__,__LINE__); } perm->addRole(role); } } - else if(xmlparser.getElementName()==ParsersAttributes::PRIVILEGES) + else if(xmlparser.getElementName()==Attributes::Privileges) { xmlparser.getElementAttributes(priv_attribs); @@ -6366,35 +7059,35 @@ Permission *DatabaseModel::createPermission(void) while(itr!=itr_end) { - if(itr->first!=ParsersAttributes::GRANT_OP) - { - priv_value=(itr->second==ParsersAttributes::_TRUE_); - grant_op=(itr->second==ParsersAttributes::GRANT_OP); - - if(itr->first==ParsersAttributes::CONNECT_PRIV) - priv_type=Permission::PRIV_CONNECT; - else if(itr->first==ParsersAttributes::CREATE_PRIV) - priv_type=Permission::PRIV_CREATE; - else if(itr->first==ParsersAttributes::DELETE_PRIV) - priv_type=Permission::PRIV_DELETE; - else if(itr->first==ParsersAttributes::EXECUTE_PRIV) - priv_type=Permission::PRIV_EXECUTE; - else if(itr->first==ParsersAttributes::INSERT_PRIV) - priv_type=Permission::PRIV_INSERT; - else if(itr->first==ParsersAttributes::REFERENCES_PRIV) - priv_type=Permission::PRIV_REFERENCES; - else if(itr->first==ParsersAttributes::SELECT_PRIV) - priv_type=Permission::PRIV_SELECT; - else if(itr->first==ParsersAttributes::TEMPORARY_PRIV) - priv_type=Permission::PRIV_TEMPORARY; - else if(itr->first==ParsersAttributes::TRIGGER_PRIV) - priv_type=Permission::PRIV_TRIGGER; - else if(itr->first==ParsersAttributes::TRUNCATE_PRIV) - priv_type=Permission::PRIV_TRUNCATE; - else if(itr->first==ParsersAttributes::UPDATE_PRIV) - priv_type=Permission::PRIV_UPDATE; - else if(itr->first==ParsersAttributes::USAGE_PRIV) - priv_type=Permission::PRIV_USAGE; + if(itr->first!=Attributes::GrantOp) + { + priv_value=(itr->second==Attributes::True); + grant_op=(itr->second==Attributes::GrantOp); + + if(itr->first==Attributes::ConnectPriv) + priv_type=Permission::PrivConnect; + else if(itr->first==Attributes::CreatePriv) + priv_type=Permission::PrivCreate; + else if(itr->first==Attributes::DeletePriv) + priv_type=Permission::PrivDelete; + else if(itr->first==Attributes::ExecutPriv) + priv_type=Permission::PrivExecute; + else if(itr->first==Attributes::InsertPriv) + priv_type=Permission::PrivInsert; + else if(itr->first==Attributes::ReferencesPriv) + priv_type=Permission::PrivReferences; + else if(itr->first==Attributes::SelectPriv) + priv_type=Permission::PrivSelect; + else if(itr->first==Attributes::TemporaryPriv) + priv_type=Permission::PrivTemporary; + else if(itr->first==Attributes::TriggerPriv) + priv_type=Permission::PrivTrigger; + else if(itr->first==Attributes::TruncatePriv) + priv_type=Permission::PrivTruncate; + else if(itr->first==Attributes::UpdatePriv) + priv_type=Permission::PrivUpdate; + else if(itr->first==Attributes::UsagePriv) + priv_type=Permission::PrivUsage; perm->setPrivilege(priv_type, (priv_value || grant_op), grant_op); } @@ -6402,14 +7095,14 @@ Permission *DatabaseModel::createPermission(void) } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); xmlparser.restorePosition(); } catch(Exception &e) { if(perm) delete(perm); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, getErrorExtraInfo()); } return(perm); @@ -6424,12 +7117,12 @@ void DatabaseModel::validateColumnRemoval(Column *column) //Raises an error if there are objects referencing the column if(!refs.empty()) - throw Exception(Exception::getErrorMessage(ERR_REM_DIRECT_REFERENCE) + throw Exception(Exception::getErrorMessage(ErrorCode::RemDirectReference) .arg(column->getParentTable()->getName(true) + QString(".") + column->getName(true)) .arg(column->getTypeName()) .arg(refs[0]->getName(true)) .arg(refs[0]->getTypeName()), - ERR_REM_DIRECT_REFERENCE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::RemDirectReference,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } @@ -6448,15 +7141,17 @@ void DatabaseModel::validateRelationships(TableObject *object, Table *parent_tab /* Relationship validation condition: > Case the object is a column and its reference by the parent table primary key + > Case the parent table is a partition and a column is being removed > Case the object is a constraint and its a table primary key */ - revalidate_rels=((obj_type==OBJ_COLUMN && - parent_tab->isConstraintRefColumn(dynamic_cast(object), ConstraintType::primary_key)) || - (obj_type==OBJ_CONSTRAINT && - dynamic_cast(object)->getConstraintType()==ConstraintType::primary_key)); + revalidate_rels=((obj_type==ObjectType::Column && + (parent_tab->isConstraintRefColumn(dynamic_cast(object), ConstraintType::PrimaryKey) || + parent_tab->isPartition() || parent_tab->isPartitioned())) || + (obj_type==ObjectType::Constraint && + dynamic_cast(object)->getConstraintType()==ConstraintType::PrimaryKey)); /* Additional validation for columns: checks if the parent table participates on a generalization/copy as destination table */ - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) { itr=relationships.begin(); itr_end=relationships.end(); @@ -6465,8 +7160,8 @@ void DatabaseModel::validateRelationships(TableObject *object, Table *parent_tab { rel=dynamic_cast(*itr); itr++; - ref_tab_inheritance=(rel->getRelationshipType()==Relationship::RELATIONSHIP_GEN && - rel->getReferenceTable()==parent_tab); + ref_tab_inheritance=(rel->getRelationshipType()==Relationship::RelationshipGen && + rel->getReferenceTable()==parent_tab); } } @@ -6480,7 +7175,7 @@ void DatabaseModel::validateRelationships(TableObject *object, Table *parent_tab } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -6489,18 +7184,18 @@ QString DatabaseModel::__getCodeDefinition(unsigned def_type) QString def, bkp_appended_sql, bkp_prepended_sql; //Forcing the name/signature cleanup due to the validation temp. names feature - attributes[ParsersAttributes::NAME]=QString(); - attributes[ParsersAttributes::SIGNATURE]=QString(); + attributes[Attributes::Name]=QString(); + attributes[Attributes::Signature]=QString(); if(conn_limit >= 0) - attributes[ParsersAttributes::CONN_LIMIT]=QString("%1").arg(conn_limit); + attributes[Attributes::ConnLimit]=QString("%1").arg(conn_limit); - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) { - QString loc_attribs[]={ ParsersAttributes::_LC_CTYPE_, ParsersAttributes::_LC_COLLATE_ }; + QString loc_attribs[]={ Attributes::LcCtype, Attributes::LcCollate }; - if(encoding!=BaseType::null) - attributes[ParsersAttributes::ENCODING]=QString("'%1'").arg(~encoding); + if(encoding!=BaseType::Null) + attributes[Attributes::Encoding]=QString("'%1'").arg(~encoding); for(unsigned i=0; i < 2; i++) { @@ -6512,24 +7207,24 @@ QString DatabaseModel::__getCodeDefinition(unsigned def_type) } else { - attributes[ParsersAttributes::ENCODING]=(~encoding); - attributes[ParsersAttributes::_LC_COLLATE_]=localizations[1]; - attributes[ParsersAttributes::_LC_CTYPE_]=localizations[0]; - attributes[ParsersAttributes::APPEND_AT_EOD]=(append_at_eod ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::PREPEND_AT_BOD]=(prepend_at_bod ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::Encoding]=(~encoding); + attributes[Attributes::LcCollate]=localizations[1]; + attributes[Attributes::LcCtype]=localizations[0]; + attributes[Attributes::AppendAtEod]=(append_at_eod ? Attributes::True : QString()); + attributes[Attributes::PrependAtBod]=(prepend_at_bod ? Attributes::True : QString()); } - attributes[ParsersAttributes::IS_TEMPLATE]=(is_template ? ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_); - attributes[ParsersAttributes::ALLOW_CONNS]=(allow_conns ? ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_); - attributes[ParsersAttributes::TEMPLATE_DB]=template_db; + attributes[Attributes::IsTemplate]=(is_template ? Attributes::True : Attributes::False); + attributes[Attributes::AllowConns]=(allow_conns ? Attributes::True : Attributes::False); + attributes[Attributes::TemplateDb]=template_db; - if(def_type==SchemaParser::SQL_DEFINITION && append_at_eod) + if(def_type==SchemaParser::SqlDefinition && append_at_eod) { bkp_appended_sql=this->appended_sql; this->appended_sql.clear(); } - if(def_type==SchemaParser::SQL_DEFINITION && prepend_at_bod) + if(def_type==SchemaParser::SqlDefinition && prepend_at_bod) { bkp_prepended_sql=this->prepended_sql; this->prepended_sql.clear(); @@ -6539,10 +7234,10 @@ QString DatabaseModel::__getCodeDefinition(unsigned def_type) { def=this->BaseObject::__getCodeDefinition(def_type); - if(def_type==SchemaParser::SQL_DEFINITION && append_at_eod) + if(def_type==SchemaParser::SqlDefinition && append_at_eod) this->appended_sql=bkp_appended_sql; - if(def_type==SchemaParser::SQL_DEFINITION && prepend_at_bod) + if(def_type==SchemaParser::SqlDefinition && prepend_at_bod) this->prepended_sql=bkp_prepended_sql; return(def); @@ -6551,7 +7246,7 @@ QString DatabaseModel::__getCodeDefinition(unsigned def_type) { this->appended_sql=bkp_appended_sql; this->prepended_sql=bkp_prepended_sql; - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -6568,8 +7263,8 @@ QString DatabaseModel::getCodeDefinition(unsigned def_type, bool export_file) BaseObject *object=nullptr; QString def, search_path=QString("pg_catalog,public"), msg=trUtf8("Generating %1 code: `%2' (%3)"), - attrib=ParsersAttributes::OBJECTS, attrib_aux, - def_type_str=(def_type==SchemaParser::SQL_DEFINITION ? QString("SQL") : QString("XML")); + attrib=Attributes::Objects, attrib_aux, + def_type_str=(def_type==SchemaParser::SqlDefinition ? QString("SQL") : QString("XML")); Type *usr_type=nullptr; map objects_map; ObjectType obj_type; @@ -6580,21 +7275,21 @@ QString DatabaseModel::getCodeDefinition(unsigned def_type, bool export_file) general_obj_cnt=objects_map.size(); gen_defs_count=0; - attribs_aux[ParsersAttributes::SHELL_TYPES]=QString(); - attribs_aux[ParsersAttributes::PERMISSION]=QString(); - attribs_aux[ParsersAttributes::SCHEMA]=QString(); - attribs_aux[ParsersAttributes::TABLESPACE]=QString(); - attribs_aux[ParsersAttributes::ROLE]=QString(); + attribs_aux[Attributes::ShellTypes]=QString(); + attribs_aux[Attributes::Permission]=QString(); + attribs_aux[Attributes::Schema]=QString(); + attribs_aux[Attributes::Tablespace]=QString(); + attribs_aux[Attributes::Role]=QString(); - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) { - attribs_aux[ParsersAttributes::FUNCTION]=(!functions.empty() ? ParsersAttributes::_TRUE_ : QString()); + attribs_aux[Attributes::Function]=(!functions.empty() ? Attributes::True : QString()); for(auto &type : types) { usr_type=dynamic_cast(type); - if(usr_type->getConfiguration()==Type::BASE_TYPE) + if(usr_type->getConfiguration()==Type::BaseType) usr_type->convertFunctionParameters(); } } @@ -6604,19 +7299,19 @@ QString DatabaseModel::getCodeDefinition(unsigned def_type, bool export_file) object=obj_itr.second; obj_type=object->getObjectType(); - if(obj_type==OBJ_TYPE && def_type==SchemaParser::SQL_DEFINITION) + if(obj_type==ObjectType::Type && def_type==SchemaParser::SqlDefinition) { usr_type=dynamic_cast(object); //Generating the shell type declaration (only for base types) - if(usr_type->getConfiguration()==Type::BASE_TYPE) - attribs_aux[ParsersAttributes::SHELL_TYPES]+=usr_type->getCodeDefinition(def_type, true); + if(usr_type->getConfiguration()==Type::BaseType) + attribs_aux[Attributes::ShellTypes]+=usr_type->getCodeDefinition(def_type, true); else attribs_aux[attrib]+=usr_type->getCodeDefinition(def_type); } - else if(obj_type==OBJ_DATABASE) + else if(obj_type==ObjectType::Database) { - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) { /* The Database has the SQL code definition disabled when generating the code of the entire model because this object cannot be created from a multiline sql command */ @@ -6634,25 +7329,25 @@ QString DatabaseModel::getCodeDefinition(unsigned def_type, bool export_file) else attribs_aux[attrib]+=this->__getCodeDefinition(def_type); } - else if(obj_type==OBJ_PERMISSION) + else if(obj_type==ObjectType::Permission) { - attribs_aux[ParsersAttributes::PERMISSION]+=dynamic_cast(object)->getCodeDefinition(def_type); + attribs_aux[Attributes::Permission]+=dynamic_cast(object)->getCodeDefinition(def_type); } - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) { attribs_aux[attrib]+=dynamic_cast(object)->getCodeDefinition(def_type, true); } - else if(obj_type==OBJ_ROLE || obj_type==OBJ_TABLESPACE || obj_type==OBJ_SCHEMA) + else if(obj_type==ObjectType::Role || obj_type==ObjectType::Tablespace || obj_type==ObjectType::Schema) { //The "public" schema does not have the SQL code definition generated - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) attrib_aux=BaseObject::getSchemaName(obj_type); else attrib_aux=attrib; /* The Tablespace has the SQL code definition disabled when generating the code of the entire model because this object cannot be created from a multiline sql command */ - if(obj_type==OBJ_TABLESPACE && !object->isSystemObject() && def_type==SchemaParser::SQL_DEFINITION) + if(obj_type==ObjectType::Tablespace && !object->isSystemObject() && def_type==SchemaParser::SqlDefinition) { //Saving the sql disabled state sql_disabled=object->isSQLDisabled(); @@ -6665,12 +7360,12 @@ QString DatabaseModel::getCodeDefinition(unsigned def_type, bool export_file) object->setSQLDisabled(sql_disabled); } //System object doesn't has the XML generated (the only exception is for public schema) - else if((obj_type!=OBJ_SCHEMA && !object->isSystemObject()) || - (obj_type==OBJ_SCHEMA && - ((object->getName()==QString("public") && def_type==SchemaParser::XML_DEFINITION) || + else if((obj_type!=ObjectType::Schema && !object->isSystemObject()) || + (obj_type==ObjectType::Schema && + ((object->getName()==QString("public") && def_type==SchemaParser::XmlDefinition) || (object->getName()!=QString("public") && object->getName()!=QString("pg_catalog"))))) { - if(object->getObjectType()==OBJ_SCHEMA) + if(object->getObjectType()==ObjectType::Schema) search_path+=QString(",") + object->getName(true); //Generates the code definition and concatenates to the others @@ -6687,37 +7382,45 @@ QString DatabaseModel::getCodeDefinition(unsigned def_type, bool export_file) gen_defs_count++; - if((def_type==SchemaParser::SQL_DEFINITION && !object->isSQLDisabled()) || - (def_type==SchemaParser::XML_DEFINITION && !object->isSystemObject())) + if((def_type==SchemaParser::SqlDefinition && !object->isSQLDisabled()) || + (def_type==SchemaParser::XmlDefinition && !object->isSystemObject())) { emit s_objectLoaded((gen_defs_count/static_cast(general_obj_cnt)) * 100, msg.arg(def_type_str) .arg(object->getName()) .arg(object->getTypeName()), - object->getObjectType()); + enum_cast(object->getObjectType())); } } - attribs_aux[ParsersAttributes::SEARCH_PATH]=search_path; - attribs_aux[ParsersAttributes::MODEL_AUTHOR]=author; - attribs_aux[ParsersAttributes::PGMODELER_VERSION]=GlobalAttributes::PGMODELER_VERSION; + attribs_aux[Attributes::SearchPath]=search_path; + attribs_aux[Attributes::ModelAuthor]=author; + attribs_aux[Attributes::PgModelerVersion]=GlobalAttributes::PgModelerVersion; - if(def_type==SchemaParser::XML_DEFINITION) + if(def_type==SchemaParser::XmlDefinition) { - attribs_aux[ParsersAttributes::PROTECTED]=(this->is_protected ? ParsersAttributes::_TRUE_ : QString()); - attribs_aux[ParsersAttributes::LAST_POSITION]=QString("%1,%2").arg(last_pos.x()).arg(last_pos.y()); - attribs_aux[ParsersAttributes::LAST_ZOOM]=QString::number(last_zoom); - attribs_aux[ParsersAttributes::DEFAULT_SCHEMA]=(default_objs[OBJ_SCHEMA] ? default_objs[OBJ_SCHEMA]->getName(true) : QString()); - attribs_aux[ParsersAttributes::DEFAULT_OWNER]=(default_objs[OBJ_ROLE] ? default_objs[OBJ_ROLE]->getName(true) : QString()); - attribs_aux[ParsersAttributes::DEFAULT_TABLESPACE]=(default_objs[OBJ_TABLESPACE] ? default_objs[OBJ_TABLESPACE]->getName(true) : QString()); - attribs_aux[ParsersAttributes::DEFAULT_COLLATION]=(default_objs[OBJ_COLLATION] ? default_objs[OBJ_COLLATION]->getName(true) : QString()); + QStringList act_layers; + + for(auto &layer_id : active_layers) + act_layers.push_back(QString::number(layer_id)); + + attribs_aux[Attributes::Layers]=layers.join(';'); + attribs_aux[Attributes::ActiveLayers]=act_layers.join(';'); + attribs_aux[Attributes::MaxObjCount]=QString::number(static_cast(getMaxObjectCount() * 1.20)); + attribs_aux[Attributes::Protected]=(this->is_protected ? Attributes::True : QString()); + attribs_aux[Attributes::LastPosition]=QString("%1,%2").arg(last_pos.x()).arg(last_pos.y()); + attribs_aux[Attributes::LastZoom]=QString::number(last_zoom); + attribs_aux[Attributes::DefaultSchema]=(default_objs[ObjectType::Schema] ? default_objs[ObjectType::Schema]->getName(true) : QString()); + attribs_aux[Attributes::DefaultOwner]=(default_objs[ObjectType::Role] ? default_objs[ObjectType::Role]->getName(true) : QString()); + attribs_aux[Attributes::DefaultTablespace]=(default_objs[ObjectType::Tablespace] ? default_objs[ObjectType::Tablespace]->getName(true) : QString()); + attribs_aux[Attributes::DefaultCollation]=(default_objs[ObjectType::Collation] ? default_objs[ObjectType::Collation]->getName(true) : QString()); } else { for(auto &type : types) { usr_type=dynamic_cast(type); - if(usr_type->getConfiguration()==Type::BASE_TYPE) + if(usr_type->getConfiguration()==Type::BaseType) { attribs_aux[attrib]+=usr_type->getCodeDefinition(def_type); usr_type->convertFunctionParameters(true); @@ -6727,28 +7430,28 @@ QString DatabaseModel::getCodeDefinition(unsigned def_type, bool export_file) } catch(Exception &e) { - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) { for(auto &type : types) { usr_type=dynamic_cast(type); - if(usr_type->getConfiguration()==Type::BASE_TYPE) + if(usr_type->getConfiguration()==Type::BaseType) { attribs_aux[attrib]+=usr_type->getCodeDefinition(def_type); usr_type->convertFunctionParameters(true); } } } - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } - attribs_aux[ParsersAttributes::EXPORT_TO_FILE]=(export_file ? ParsersAttributes::_TRUE_ : QString()); - def=schparser.getCodeDefinition(ParsersAttributes::DB_MODEL, attribs_aux, def_type); + attribs_aux[Attributes::ExportToFile]=(export_file ? Attributes::True : QString()); + def=schparser.getCodeDefinition(Attributes::DbModel, attribs_aux, def_type); - if(prepend_at_bod && def_type==SchemaParser::SQL_DEFINITION) + if(prepend_at_bod && def_type==SchemaParser::SqlDefinition) def=QString("-- Prepended SQL commands --\n") + this->prepended_sql + QString("\n---\n\n") + def; - if(append_at_eod && def_type==SchemaParser::SQL_DEFINITION) + if(append_at_eod && def_type==SchemaParser::SqlDefinition) def+=QString("-- Appended SQL commands --\n") + this->appended_sql + QString("\n---\n"); return(def); @@ -6766,18 +7469,17 @@ map DatabaseModel::getCreationOrder(unsigned def_type, b Constraint *constr=nullptr; View *view=nullptr; Relationship *rel=nullptr; - ObjectType aux_obj_types[]={ OBJ_ROLE, OBJ_TABLESPACE, OBJ_SCHEMA, OBJ_TAG }, - obj_types[]={ OBJ_EVENT_TRIGGER, OBJ_COLLATION, OBJ_LANGUAGE, OBJ_FUNCTION, OBJ_TYPE, - OBJ_CAST, OBJ_CONVERSION, OBJ_EXTENSION, - OBJ_OPERATOR, OBJ_OPFAMILY, OBJ_OPCLASS, - OBJ_AGGREGATE, OBJ_DOMAIN, OBJ_TEXTBOX, BASE_RELATIONSHIP, - OBJ_RELATIONSHIP, OBJ_TABLE, OBJ_VIEW, OBJ_SEQUENCE, OBJ_GENERIC_SQL }; - unsigned i=0, aux_obj_cnt=sizeof(aux_obj_types)/sizeof(ObjectType), count=sizeof(obj_types)/sizeof(ObjectType); + ObjectType aux_obj_types[]={ ObjectType::Role, ObjectType::Tablespace, ObjectType::Schema, ObjectType::Tag }; + + vector obj_types_vect = getObjectTypes(false, { ObjectType::Role, ObjectType::Tablespace, ObjectType::Schema, + ObjectType::Tag, ObjectType::Database, ObjectType::Permission }); + + unsigned i=0, aux_obj_cnt=sizeof(aux_obj_types)/sizeof(ObjectType); //The first objects on the map will be roles, tablespaces, schemas and tags for(i=0; i < aux_obj_cnt; i++) { - if(aux_obj_types[i]!=OBJ_TAG || def_type==SchemaParser::XML_DEFINITION) + if(aux_obj_types[i]!=ObjectType::Tag || def_type==SchemaParser::XmlDefinition) { obj_list=getObjectList(aux_obj_types[i]); @@ -6789,14 +7491,14 @@ map DatabaseModel::getCreationOrder(unsigned def_type, b //Includes the database model on the objects map permitting to create the code in a correct order objects_map[this->getObjectId()]=this; - for(i=0; i < count; i++) + for(auto &obj_type : obj_types_vect) { //For SQL definition, only the textbox and base relationship does not enters to the code generation list - if(def_type==SchemaParser::SQL_DEFINITION && - (obj_types[i]==OBJ_TEXTBOX || obj_types[i]==BASE_RELATIONSHIP)) + if(def_type==SchemaParser::SqlDefinition && + (obj_type==ObjectType::Textbox || obj_type==ObjectType::BaseRelationship)) obj_list=nullptr; else - obj_list=getObjectList(obj_types[i]); + obj_list=getObjectList(obj_type); if(obj_list) { @@ -6804,14 +7506,14 @@ map DatabaseModel::getCreationOrder(unsigned def_type, b { /* If the object is a FK relationship it's stored in a separeted list in order to have the code generated at end of whole definition (after foreign keys definition) */ - if(object->getObjectType()==BASE_RELATIONSHIP && - dynamic_cast(object)->getRelationshipType()==BaseRelationship::RELATIONSHIP_FK) + if(object->getObjectType()==ObjectType::BaseRelationship && + dynamic_cast(object)->getRelationshipType()==BaseRelationship::RelationshipFk) { fk_rels.push_back(object); } else { - if(def_type==SchemaParser::XML_DEFINITION || !incl_relnn_objs) + if(def_type==SchemaParser::XmlDefinition || !incl_relnn_objs) objects_map[object->getObjectId()]=object; else { @@ -6820,7 +7522,7 @@ map DatabaseModel::getCreationOrder(unsigned def_type, b /* Avoiding many-to-many relationships to be included in the map. They are treated in a separated way below, because on the diff process (ModelsDiffHelper) the generated table need to be compared to other tables not the relationship itself */ - if(!incl_relnn_objs || !rel || (rel && rel->getRelationshipType()!=BaseRelationship::RELATIONSHIP_NN)) + if(!incl_relnn_objs || !rel || (rel && rel->getRelationshipType()!=BaseRelationship::RelationshipNn)) objects_map[object->getObjectId()]=object; } } @@ -6832,23 +7534,26 @@ map DatabaseModel::getCreationOrder(unsigned def_type, b on the map of objects. */ for(auto &obj : tables) { - table=dynamic_cast
(obj); - count=table->getConstraintCount(); - for(i=0; i < count; i++) + table = dynamic_cast
(obj); + //count = table->getConstraintCount(); + + //for(i=0; i < count; i++) + for(auto &obj : *table->getObjectList(ObjectType::Constraint)) { - constr=table->getConstraint(i); + //table->getConstraint(i); + constr = dynamic_cast(obj); /* Case the constraint is a special object stores it on the objects map. Independently to the configuration, foreign keys are discarded in this iteration because on the end of the method they have the definition generated */ - if(constr->getConstraintType()!=ConstraintType::foreign_key && !constr->isAddedByLinking() && - ((constr->getConstraintType()!=ConstraintType::primary_key && constr->isReferRelationshipAddedColumn()))) + if(constr->getConstraintType()!=ConstraintType::ForeignKey && !constr->isAddedByLinking() && + ((constr->getConstraintType()!=ConstraintType::PrimaryKey && constr->isReferRelationshipAddedColumn()))) objects_map[constr->getObjectId()]=constr; - else if(constr->getConstraintType()==ConstraintType::foreign_key && !constr->isAddedByLinking()) + else if(constr->getConstraintType()==ConstraintType::ForeignKey && !constr->isAddedByLinking()) fkeys.push_back(constr); } - for(auto obj : table->getObjects(true)) + for(auto obj : table->getObjects({ ObjectType::Column, ObjectType::Constraint })) objects_map[obj->getObjectId()]=obj; } @@ -6869,7 +7574,7 @@ map DatabaseModel::getCreationOrder(unsigned def_type, b 2) Other tables came after the objects on the step 1. 3) The sequences must have their code generated after the tables 4) View are the last objects in the list avoiding table/column reference breaking */ - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) { BaseObject *objs[3]={nullptr, nullptr, nullptr}; vector vet_aux, rel_constrs; @@ -6886,27 +7591,27 @@ map DatabaseModel::getCreationOrder(unsigned def_type, b object=(*itr); itr++; - if(object->getObjectType()==OBJ_RELATIONSHIP) + if(object->getObjectType()==ObjectType::Relationship) { rel=dynamic_cast(object); - objs[0]=rel->getTable(Relationship::SRC_TABLE); - objs[1]=rel->getTable(Relationship::DST_TABLE); + objs[0]=rel->getTable(Relationship::SrcTable); + objs[1]=rel->getTable(Relationship::DstTable); /* For many-to-many relationship, the generated table and the foreign keys that represents the link are included on the creation order map instead of the relationship itself. This is done to permit the table to be accessed and compared on the diff process */ if(incl_relnn_objs && - rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_NN && + rel->getRelationshipType()==BaseRelationship::RelationshipNn && rel->getGeneratedTable()) { table=rel->getGeneratedTable(); objs[2]=table; - for(BaseObject *tab_obj : *table->getObjectList(OBJ_CONSTRAINT)) + for(BaseObject *tab_obj : *table->getObjectList(ObjectType::Constraint)) { constr=dynamic_cast(tab_obj); - if(constr->getConstraintType()==ConstraintType::foreign_key) + if(constr->getConstraintType()==ConstraintType::ForeignKey) fkeys.push_back(constr); } } @@ -6916,7 +7621,7 @@ map DatabaseModel::getCreationOrder(unsigned def_type, b for(auto &constr : constrs) { - if(constr->getConstraintType()!=ConstraintType::primary_key) + if(constr->getConstraintType()!=ConstraintType::PrimaryKey) rel_constrs.push_back(constr); } } @@ -6966,7 +7671,7 @@ void DatabaseModel::__getObjectDependencies(BaseObject *object, vector dep_objs, chld_objs; Table *table=dynamic_cast
(object); - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; if(!object) return; @@ -6993,11 +7698,11 @@ void DatabaseModel::__getObjectDependencies(BaseObject *object, vector::iterator end; - if(obj_type==OBJ_SCHEMA) + if(obj_type==ObjectType::Schema) { //Retrieve all objects that belongs to the schema chld_objs=getObjects(object); @@ -7022,11 +7727,11 @@ void DatabaseModel::__getObjectDependencies(BaseObject *object, vectorgetObjectType()!=OBJ_COLUMN) || + if((!constr && child->getObjectType()!=ObjectType::Column) || (constr && - ((constr->getConstraintType()==ConstraintType::foreign_key) || - (constr->getConstraintType()!=ConstraintType::foreign_key && - constr->getConstraintType()!=ConstraintType::primary_key && + ((constr->getConstraintType()==ConstraintType::ForeignKey) || + (constr->getConstraintType()!=ConstraintType::ForeignKey && + constr->getConstraintType()!=ConstraintType::PrimaryKey && constr->isReferRelationshipAddedColumn())))) { __getObjectDependencies(child, objs); @@ -7064,7 +7769,7 @@ vector DatabaseModel::getCreationOrder(BaseObject *object, bool on /* Include tables generated by many-to-many relationships if their schemas are the same as the 'object' when this one is a schema too */ - if(obj_type==OBJ_SCHEMA) + if(obj_type==ObjectType::Schema) { if(only_children) { @@ -7076,7 +7781,7 @@ vector DatabaseModel::getCreationOrder(BaseObject *object, bool on { rel=dynamic_cast(obj); - if(rel->getRelationshipType()==Relationship::RELATIONSHIP_NN && + if(rel->getRelationshipType()==Relationship::RelationshipNn && rel->getGeneratedTable() && rel->getGeneratedTable()->getSchema()==object) { @@ -7106,11 +7811,11 @@ vector DatabaseModel::getCreationOrder(BaseObject *object, bool on { constr=dynamic_cast(child); - if((!constr && child->getObjectType()!=OBJ_COLUMN) || + if((!constr && child->getObjectType()!=ObjectType::Column) || (constr && - ((constr->getConstraintType()==ConstraintType::foreign_key) || - (constr->getConstraintType()!=ConstraintType::foreign_key && - constr->getConstraintType()!=ConstraintType::primary_key && + ((constr->getConstraintType()==ConstraintType::ForeignKey) || + (constr->getConstraintType()!=ConstraintType::ForeignKey && + constr->getConstraintType()!=ConstraintType::PrimaryKey && constr->isReferRelationshipAddedColumn())))) { objs_aux.push_back(child); @@ -7134,7 +7839,7 @@ vector DatabaseModel::getCreationOrder(BaseObject *object, bool on if(table) { - for(BaseObject *col : *table->getObjectList(OBJ_COLUMN)) + for(BaseObject *col : *table->getObjectList(ObjectType::Column)) { getPermissions(col, perms_aux); perms.insert(perms.end(), perms_aux.begin(), perms_aux.end()); @@ -7182,8 +7887,8 @@ void DatabaseModel::saveModel(const QString &filename, unsigned def_type) output.open(QFile::WriteOnly); if(!output.isOpen()) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(filename), - ERR_FILE_DIR_NOT_WRITTEN,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotWritten).arg(filename), + ErrorCode::FileDirectoryNotWritten,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { @@ -7194,8 +7899,8 @@ void DatabaseModel::saveModel(const QString &filename, unsigned def_type) catch(Exception &e) { if(output.isOpen()) output.close(); - throw Exception(Exception::getErrorMessage(ERR_FILE_NOT_WRITTER_INV_DEF).arg(filename), - ERR_FILE_NOT_WRITTER_INV_DEF,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(Exception::getErrorMessage(ErrorCode::FileNotWrittenInvalidDefinition).arg(filename), + ErrorCode::FileNotWrittenInvalidDefinition,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -7225,7 +7930,7 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vectorgetCollation(), deps, inc_indirect_deps); //** Getting the dependecies for operator class ** - if(obj_type==OBJ_OPCLASS) + if(obj_type==ObjectType::OpClass) { OperatorClass *opclass=dynamic_cast(object); BaseObject *usr_type=getObjectPgSQLType(opclass->getDataType()); @@ -7261,7 +7966,7 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vector(object)->getType()); @@ -7269,18 +7974,18 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vector(object)->getConversionFunction(); getObjectDependecies(func, deps, inc_indirect_deps); } //** Getting the dependecies for cast ** - else if(obj_type==OBJ_CAST) + else if(obj_type==ObjectType::Cast) { Cast *cast=dynamic_cast(object); BaseObject *usr_type=nullptr; - for(unsigned i=Cast::SRC_TYPE; i <= Cast::DST_TYPE; i++) + for(unsigned i=Cast::SrcType; i <= Cast::DstType; i++) { usr_type=getObjectPgSQLType(cast->getDataType(i)); @@ -7291,12 +7996,12 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vectorgetCastFunction(), deps, inc_indirect_deps); } //** Getting the dependecies for event trigger ** - else if(obj_type==OBJ_EVENT_TRIGGER) + else if(obj_type==ObjectType::EventTrigger) { getObjectDependecies(dynamic_cast(object)->getFunction(), deps, inc_indirect_deps); } //** Getting the dependecies for function ** - else if(obj_type==OBJ_FUNCTION) + else if(obj_type==ObjectType::Function) { Function *func=dynamic_cast(object); BaseObject *usr_type=getObjectPgSQLType(func->getReturnType()); @@ -7327,13 +8032,13 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vector(object); BaseObject *usr_type=nullptr; unsigned count, i; - for(i=Aggregate::FINAL_FUNC; i <= Aggregate::TRANSITION_FUNC; i++) + for(i=Aggregate::FinalFunc; i <= Aggregate::TransitionFunc; i++) getObjectDependecies(aggreg->getFunction(i), deps, inc_indirect_deps); usr_type=getObjectPgSQLType(aggreg->getStateType()); @@ -7354,30 +8059,30 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vector(object); - for(unsigned i=Language::VALIDATOR_FUNC; i <= Language::INLINE_FUNC; i++) + for(unsigned i=Language::ValidatorFunc; i <= Language::InlineFunc; i++) { if(lang->getFunction(i)) getObjectDependecies(lang->getFunction(i), deps, inc_indirect_deps); } } //** Getting the dependecies for operator ** - else if(obj_type==OBJ_OPERATOR) + else if(obj_type==ObjectType::Operator) { Operator *oper=dynamic_cast(object); BaseObject *usr_type=nullptr; unsigned i; - for(i=Operator::FUNC_OPERATOR; i <= Operator::FUNC_RESTRICT; i++) + for(i=Operator::FuncOperator; i <= Operator::FuncRestrict; i++) { if(oper->getFunction(i)) getObjectDependecies(oper->getFunction(i), deps, inc_indirect_deps); } - for(i=Operator::LEFT_ARG; i <= Operator::RIGHT_ARG; i++) + for(i=Operator::LeftArg; i <= Operator::RightArg; i++) { usr_type=getObjectPgSQLType(oper->getArgumentType(i)); @@ -7385,18 +8090,18 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vectorgetOperator(i)) getObjectDependecies(oper->getOperator(i), deps, inc_indirect_deps); } } //** Getting the dependecies for role ** - else if(obj_type==OBJ_ROLE) + else if(obj_type==ObjectType::Role) { Role *role=dynamic_cast(object); unsigned i, i1, count, - role_types[3]={ Role::REF_ROLE, Role::MEMBER_ROLE, Role::ADMIN_ROLE }; + role_types[3]={ Role::RefRole, Role::MemberRole, Role::AdminRole }; for(i=0; i < 3; i++) { @@ -7406,15 +8111,15 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vector(object); BaseObject *usr_type=nullptr; Constraint *constr=nullptr; unsigned i, count; - getObjectDependecies(rel->getTable(Relationship::SRC_TABLE), deps, inc_indirect_deps); - getObjectDependecies(rel->getTable(Relationship::DST_TABLE), deps, inc_indirect_deps); + getObjectDependecies(rel->getTable(Relationship::SrcTable), deps, inc_indirect_deps); + getObjectDependecies(rel->getTable(Relationship::DstTable), deps, inc_indirect_deps); count=rel->getAttributeCount(); for(i=0; i < count; i++) @@ -7435,14 +8140,14 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vector(object); if(seq->getOwnerColumn()) getObjectDependecies(seq->getOwnerColumn()->getParentTable(), deps, inc_indirect_deps); } //** Getting the dependecies for column ** - else if(obj_type==OBJ_COLUMN) + else if(obj_type==ObjectType::Column) { Column *col=dynamic_cast(object); BaseObject *usr_type=getObjectPgSQLType(col->getType()), @@ -7455,7 +8160,7 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vector(object); @@ -7466,7 +8171,7 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vectorgetFunction(), deps, inc_indirect_deps); } //** Getting the dependecies for index ** - else if(obj_type==OBJ_INDEX) + else if(obj_type==ObjectType::Index) { Index *index=dynamic_cast(object); BaseObject *usr_type=nullptr; @@ -7489,7 +8194,7 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vectorgetIndexElement(i).getCollation(), deps, inc_indirect_deps); } } - else if(obj_type==OBJ_POLICY) + else if(obj_type==ObjectType::Policy) { Policy *pol=dynamic_cast(object); @@ -7497,7 +8202,7 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vector(object); BaseObject *usr_type=nullptr, *seq=nullptr; @@ -7542,7 +8247,7 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vectorisAddedByLinking() && - constr->getConstraintType()==ConstraintType::foreign_key) + constr->getConstraintType()==ConstraintType::ForeignKey) getObjectDependecies(constr->getReferencedTable(), deps, inc_indirect_deps); if(!constr->isAddedByLinking() && constr->getTablespace()) @@ -7594,23 +8299,23 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vector(object); BaseObject *aux_type=nullptr; unsigned count, i; - if(usr_type->getConfiguration()==Type::BASE_TYPE) + if(usr_type->getConfiguration()==Type::BaseType) { aux_type=getObjectPgSQLType(usr_type->getLikeType()); if(aux_type) getObjectDependecies(aux_type, deps, inc_indirect_deps); - for(i=Type::INPUT_FUNC; i <= Type::ANALYZE_FUNC; i++) + for(i=Type::InputFunc; i <= Type::AnalyzeFunc; i++) getObjectDependecies(usr_type->getFunction(i), deps, inc_indirect_deps); } - else if(usr_type->getConfiguration()==Type::COMPOSITE_TYPE) + else if(usr_type->getConfiguration()==Type::CompositeType) { count=usr_type->getAttributeCount(); for(i=0; i < count; i++) @@ -7623,7 +8328,7 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vector(object); unsigned i, count; @@ -7644,8 +8349,35 @@ void DatabaseModel::getObjectDependecies(BaseObject *object, vectorgetTrigger(i)->getReferencedTable(), deps, inc_indirect_deps); } } + //** Getting the dependecies for foreign data wrapper ** + else if(obj_type == ObjectType::ForeignDataWrapper) + { + ForeignDataWrapper *fdw = dynamic_cast(object); + getObjectDependecies(fdw->getHandlerFunction(), deps, inc_indirect_deps); + getObjectDependecies(fdw->getValidatorFunction(), deps, inc_indirect_deps); + } + //** Getting the dependecies for server ** + else if(obj_type == ObjectType::ForeignServer) + { + ForeignServer *server = dynamic_cast(object); + getObjectDependecies(server->getForeignDataWrapper(), deps, inc_indirect_deps); + } + //** Getting the dependecies for generic sql ** + else if(obj_type==ObjectType::GenericSql) + { + GenericSQL *generic_sql = dynamic_cast(object); + vector ref_objs = generic_sql->getReferencedObjects(); + for(auto &obj : ref_objs) + getObjectDependecies(obj, deps, inc_indirect_deps); + } + //** Getting the dependecies for user mapping ** + else if(obj_type==ObjectType::UserMapping) + { + UserMapping *usr_map = dynamic_cast(object); + getObjectDependecies(usr_map->getForeignServer(), deps, inc_indirect_deps); + } - if(obj_type == OBJ_TABLE || obj_type == OBJ_VIEW) + if(obj_type == ObjectType::Table || obj_type == ObjectType::View) { BaseTable *tab = dynamic_cast(object); @@ -7691,14 +8423,14 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector refs.push_back(this); } - if(obj_type==OBJ_VIEW && (!exclusion_mode || (exclusion_mode && !refer))) + if(obj_type==ObjectType::View && (!exclusion_mode || (exclusion_mode && !refer))) { View *view=dynamic_cast(object); vector tab_objs=view->getObjects(); refs.insert(refs.end(), tab_objs.begin(), tab_objs.end()); } - if(obj_type==OBJ_TABLE && (!exclusion_mode || (exclusion_mode && !refer))) + if(obj_type==ObjectType::Table && (!exclusion_mode || (exclusion_mode && !refer))) { Table *table=dynamic_cast
(object); Sequence *seq=nullptr; @@ -7710,7 +8442,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector vector::iterator itr, itr_end; vector *tab_objs; unsigned i, count; - ObjectType tab_obj_types[4]={ OBJ_TRIGGER, OBJ_RULE, OBJ_INDEX, OBJ_POLICY }; + ObjectType tab_obj_types[4]={ ObjectType::Trigger, ObjectType::Rule, ObjectType::Index, ObjectType::Policy }; for(i=0; i < 4; i++) { @@ -7724,8 +8456,8 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { base_rel=dynamic_cast(*itr); - if(base_rel->getTable(BaseRelationship::SRC_TABLE)==table || - base_rel->getTable(BaseRelationship::DST_TABLE)==table) + if(base_rel->getTable(BaseRelationship::SrcTable)==table || + base_rel->getTable(BaseRelationship::DstTable)==table) { refer=true; refs.push_back(base_rel); @@ -7739,9 +8471,9 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { base_rel=dynamic_cast(*itr); - if(base_rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_FK && - (base_rel->getTable(BaseRelationship::SRC_TABLE)==table || - base_rel->getTable(BaseRelationship::DST_TABLE)==table)) + if(base_rel->getRelationshipType()==BaseRelationship::RelationshipFk && + (base_rel->getTable(BaseRelationship::SrcTable)==table || + base_rel->getTable(BaseRelationship::DstTable)==table)) { refer=true; refs.push_back(base_rel); @@ -7777,7 +8509,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector { constr=tab->getConstraint(i); //If a constraint references its own parent table it'll not be included on the references list - if(constr->getConstraintType()==ConstraintType::foreign_key && + if(constr->getConstraintType()==ConstraintType::ForeignKey && constr->getParentTable()!=constr->getReferencedTable() && constr->getReferencedTable()==table) { @@ -7825,8 +8557,8 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector { base_rel=dynamic_cast(*itr); - if(base_rel->getTable(BaseRelationship::SRC_TABLE)==table || - base_rel->getTable(BaseRelationship::DST_TABLE)==table) + if(base_rel->getTable(BaseRelationship::SrcTable)==table || + base_rel->getTable(BaseRelationship::DstTable)==table) { refer=true; refs.push_back(base_rel); @@ -7835,14 +8567,14 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } - if(obj_type==OBJ_FUNCTION && (!exclusion_mode || (exclusion_mode && !refer))) + if(obj_type==ObjectType::Function && (!exclusion_mode || (exclusion_mode && !refer))) { Function *func=dynamic_cast(object); vector *obj_list=nullptr; vector::iterator itr, itr_end; - ObjectType obj_types[]={OBJ_CAST, OBJ_EVENT_TRIGGER, OBJ_CONVERSION, - OBJ_AGGREGATE, OBJ_OPERATOR, OBJ_OPCLASS, - OBJ_TABLE, OBJ_TYPE, OBJ_LANGUAGE }; + ObjectType obj_types[]={ObjectType::Cast, ObjectType::EventTrigger, ObjectType::Conversion, + ObjectType::Aggregate, ObjectType::Operator, ObjectType::OpClass, + ObjectType::Table, ObjectType::Type, ObjectType::Language, ObjectType::ForeignDataWrapper }; unsigned i, i1, count, cnt=sizeof(obj_types)/sizeof(ObjectType); Table *tab=nullptr; Aggregate *aggreg=nullptr; @@ -7851,6 +8583,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector Type *type=nullptr; Language *lang=nullptr; OperatorClass *opclass=nullptr; + ForeignDataWrapper *fdw=nullptr; for(i=0; i < cnt && (!exclusion_mode || (exclusion_mode && !refer)); i++) { @@ -7858,7 +8591,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector itr=obj_list->begin(); itr_end=obj_list->end(); - if(obj_types[i]==OBJ_CAST) + if(obj_types[i]==ObjectType::Cast) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { @@ -7870,7 +8603,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector itr++; } } - else if(obj_types[i]==OBJ_EVENT_TRIGGER) + else if(obj_types[i]==ObjectType::EventTrigger) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { @@ -7882,7 +8615,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector itr++; } } - else if(obj_types[i]==OBJ_CONVERSION) + else if(obj_types[i]==ObjectType::Conversion) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { @@ -7894,14 +8627,14 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector itr++; } } - else if(obj_types[i]==OBJ_AGGREGATE) + else if(obj_types[i]==ObjectType::Aggregate) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { aggreg=dynamic_cast(*itr); - if(aggreg->getFunction(Aggregate::FINAL_FUNC)==func || - aggreg->getFunction(Aggregate::TRANSITION_FUNC)==func) + if(aggreg->getFunction(Aggregate::FinalFunc)==func || + aggreg->getFunction(Aggregate::TransitionFunc)==func) { refer=true; refs.push_back(aggreg); @@ -7909,15 +8642,15 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector itr++; } } - else if(obj_types[i]==OBJ_OPERATOR) + else if(obj_types[i]==ObjectType::Operator) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { oper=dynamic_cast(*itr); - if(oper->getFunction(Operator::FUNC_OPERATOR)==func || - oper->getFunction(Operator::FUNC_JOIN)==func || - oper->getFunction(Operator::FUNC_RESTRICT)==func) + if(oper->getFunction(Operator::FuncOperator)==func || + oper->getFunction(Operator::FuncJoin)==func || + oper->getFunction(Operator::FuncRestrict)==func) { refer=true; refs.push_back(oper); @@ -7925,7 +8658,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector itr++; } } - else if(obj_types[i]==OBJ_OPCLASS) + else if(obj_types[i]==ObjectType::OpClass) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { @@ -7943,7 +8676,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector itr++; } } - else if(obj_types[i]==OBJ_TABLE) + else if(obj_types[i]==ObjectType::Table) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { @@ -7963,14 +8696,14 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } } - else if(obj_types[i]==OBJ_TYPE) + else if(obj_types[i]==ObjectType::Type) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { type=dynamic_cast(*itr); itr++; - for(i1=Type::INPUT_FUNC; i1 <= Type::ANALYZE_FUNC && (!exclusion_mode || (exclusion_mode && !refer)); i1++) + for(i1=Type::InputFunc; i1 <= Type::AnalyzeFunc && (!exclusion_mode || (exclusion_mode && !refer)); i1++) { if(type->getFunction(i1)==func) { @@ -7980,33 +8713,47 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } } - else if(obj_types[i]==OBJ_LANGUAGE) + else if(obj_types[i]==ObjectType::Language) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { lang=dynamic_cast(*itr); itr++; - if(lang->getFunction(Language::HANDLER_FUNC)==func || - lang->getFunction(Language::VALIDATOR_FUNC)==func || - lang->getFunction(Language::INLINE_FUNC)==func) + if(lang->getFunction(Language::HandlerFunc)==func || + lang->getFunction(Language::ValidatorFunc)==func || + lang->getFunction(Language::InlineFunc)==func) { refer=true; refs.push_back(lang); } } } + else if(obj_types[i]==ObjectType::ForeignDataWrapper) + { + while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) + { + fdw=dynamic_cast(*itr); + itr++; + + if(fdw->getHandlerFunction() == func || fdw->getValidatorFunction() == func) + { + refer=true; + refs.push_back(fdw); + } + } + } } } - if(obj_type==OBJ_SCHEMA && (!exclusion_mode || (exclusion_mode && !refer))) + if(obj_type==ObjectType::Schema && (!exclusion_mode || (exclusion_mode && !refer))) { vector *obj_list=nullptr; vector::iterator itr, itr_end; - ObjectType obj_types[11]={OBJ_FUNCTION, OBJ_TABLE, OBJ_VIEW, - OBJ_DOMAIN, OBJ_AGGREGATE, OBJ_OPERATOR, - OBJ_SEQUENCE, OBJ_CONVERSION, - OBJ_TYPE, OBJ_OPFAMILY, OBJ_OPCLASS}; + ObjectType obj_types[11]={ObjectType::Function, ObjectType::Table, ObjectType::View, + ObjectType::Domain, ObjectType::Aggregate, ObjectType::Operator, + ObjectType::Sequence, ObjectType::Conversion, + ObjectType::Type, ObjectType::OpFamily, ObjectType::OpClass}; unsigned i; for(i=0; i < 11 && (!exclusion_mode || (exclusion_mode && !refer)); i++) @@ -8027,15 +8774,15 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } - if((obj_type==OBJ_TYPE || obj_type==OBJ_DOMAIN || obj_type==OBJ_SEQUENCE || - obj_type==OBJ_TABLE || obj_type==OBJ_EXTENSION || obj_type==OBJ_VIEW) + if((obj_type==ObjectType::Type || obj_type==ObjectType::Domain || obj_type==ObjectType::Sequence || + obj_type==ObjectType::Table || obj_type==ObjectType::Extension || obj_type==ObjectType::View) && (!exclusion_mode || (exclusion_mode && !refer))) { vector *obj_list=nullptr; vector::iterator itr, itr_end; - ObjectType obj_types[]={OBJ_TABLE, OBJ_OPCLASS, OBJ_CAST, - OBJ_DOMAIN, OBJ_FUNCTION, OBJ_AGGREGATE, - OBJ_OPERATOR, OBJ_TYPE, OBJ_RELATIONSHIP }; + ObjectType obj_types[]={ObjectType::Table, ObjectType::OpClass, ObjectType::Cast, + ObjectType::Domain, ObjectType::Function, ObjectType::Aggregate, + ObjectType::Operator, ObjectType::Type, ObjectType::Relationship }; unsigned i, i1, count, tp_count = sizeof(obj_types)/sizeof(ObjectType); OperatorClass *op_class=nullptr; OperatorClassElement elem; @@ -8052,11 +8799,13 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector switch(obj_type) { - case OBJ_TYPE: ptr_pgsqltype=dynamic_cast(object); break; - case OBJ_DOMAIN: ptr_pgsqltype=dynamic_cast(object); break; - case OBJ_SEQUENCE: ptr_pgsqltype=dynamic_cast(object); break; - case OBJ_EXTENSION: ptr_pgsqltype=dynamic_cast(object); break; - case OBJ_VIEW: ptr_pgsqltype=dynamic_cast(object); break; + case ObjectType::Type: ptr_pgsqltype=dynamic_cast(object); break; + case ObjectType::Domain: + ptr_pgsqltype=dynamic_cast(object); + break; + case ObjectType::Sequence: ptr_pgsqltype=dynamic_cast(object); break; + case ObjectType::Extension: ptr_pgsqltype=dynamic_cast(object); break; + case ObjectType::View: ptr_pgsqltype=dynamic_cast(object); break; default: ptr_pgsqltype=dynamic_cast(object); break; } @@ -8066,7 +8815,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector itr=obj_list->begin(); itr_end=obj_list->end(); - if(obj_types[i]==OBJ_RELATIONSHIP) + if(obj_types[i]==ObjectType::Relationship) { bool added; @@ -8089,7 +8838,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } } - else if(obj_types[i]==OBJ_TABLE) + else if(obj_types[i]==ObjectType::Table) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { @@ -8101,7 +8850,10 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector { col=tab->getColumn(i1); - if(!col->isAddedByRelationship() && col->getType()==ptr_pgsqltype) + if(!col->isAddedByRelationship() && + (col->getType()==ptr_pgsqltype || + //Special case for postgis extension + (obj_type == ObjectType::Extension && object->getName() == QString("postgis") && col->getType().isGiSType()))) { refer=true; refs.push_back(col); @@ -8109,7 +8861,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } } - else if(obj_types[i]==OBJ_OPCLASS) + else if(obj_types[i]==ObjectType::OpClass) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { @@ -8133,7 +8885,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } } - else if(obj_types[i]==OBJ_DOMAIN) + else if(obj_types[i]==ObjectType::Domain) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { @@ -8147,7 +8899,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } } - else if(obj_types[i]==OBJ_TYPE) + else if(obj_types[i]==ObjectType::Type) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { @@ -8164,7 +8916,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } } - else if(obj_types[i]==OBJ_AGGREGATE) + else if(obj_types[i]==ObjectType::Aggregate) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { @@ -8182,7 +8934,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } } - else if(obj_types[i]==OBJ_FUNCTION) + else if(obj_types[i]==ObjectType::Function) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { @@ -8208,30 +8960,30 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } } - else if(obj_types[i]==OBJ_OPERATOR) + else if(obj_types[i]==ObjectType::Operator) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { oper=dynamic_cast(*itr); itr++; - if(oper->getArgumentType(Operator::LEFT_ARG)==ptr_pgsqltype || - oper->getArgumentType(Operator::RIGHT_ARG)==ptr_pgsqltype) + if(oper->getArgumentType(Operator::LeftArg)==ptr_pgsqltype || + oper->getArgumentType(Operator::RightArg)==ptr_pgsqltype) { refer=true; refs.push_back(oper); } } } - else if(obj_types[i]==OBJ_CAST) + else if(obj_types[i]==ObjectType::Cast) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { cast=dynamic_cast(*itr); itr++; - if(cast->getDataType(Cast::SRC_TYPE)==ptr_pgsqltype || - cast->getDataType(Cast::DST_TYPE)==ptr_pgsqltype) + if(cast->getDataType(Cast::SrcType)==ptr_pgsqltype || + cast->getDataType(Cast::DstType)==ptr_pgsqltype) { refer=true; refs.push_back(cast); @@ -8241,19 +8993,22 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } - if(obj_type==OBJ_ROLE && (!exclusion_mode || (exclusion_mode && !refer))) + if(obj_type==ObjectType::Role && (!exclusion_mode || (exclusion_mode && !refer))) { vector *obj_list=nullptr; vector::iterator itr, itr_end; - ObjectType obj_types[13]={OBJ_FUNCTION, OBJ_TABLE, OBJ_DOMAIN, - OBJ_AGGREGATE, OBJ_SCHEMA, OBJ_OPERATOR, - OBJ_SEQUENCE, OBJ_CONVERSION, - OBJ_LANGUAGE, OBJ_TABLESPACE, - OBJ_TYPE, OBJ_OPFAMILY, OBJ_OPCLASS}; + vector obj_types = { + ObjectType::Function, ObjectType::Table, ObjectType::Domain, + ObjectType::Aggregate, ObjectType::Schema, ObjectType::Operator, + ObjectType::Sequence, ObjectType::Conversion, + ObjectType::Language, ObjectType::Tablespace, + ObjectType::Type, ObjectType::OpFamily, ObjectType::OpClass, + ObjectType::UserMapping }; + vector::iterator itr_tp, itr_tp_end; unsigned i,i1, count; Role *role_aux=nullptr; Role *role=dynamic_cast(object); - unsigned role_types[3]={Role::REF_ROLE, Role::MEMBER_ROLE, Role::ADMIN_ROLE}; + unsigned role_types[3]={Role::RefRole, Role::MemberRole, Role::AdminRole}; Permission *perm=nullptr; //Check if the role is being referencend by permissions @@ -8293,9 +9048,14 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } - for(i=0; i < 13 && (!exclusion_mode || (exclusion_mode && !refer)); i++) + itr_tp = obj_types.begin(); + itr_tp_end = obj_types.end(); + + while(itr_tp != itr_tp_end && (!exclusion_mode || (exclusion_mode && !refer))) { - obj_list=getObjectList(obj_types[i]); + obj_list=getObjectList(*itr_tp); + itr_tp++; + itr=obj_list->begin(); itr_end=obj_list->end(); @@ -8307,9 +9067,9 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector refs.push_back(*itr); } - if((*itr)->getObjectType() == OBJ_TABLE) + if((*itr)->getObjectType() == ObjectType::Table) { - for(auto obj : *(dynamic_cast
(*itr))->getObjectList(OBJ_POLICY)) + for(auto obj : *(dynamic_cast
(*itr))->getObjectList(ObjectType::Policy)) { if(dynamic_cast(obj)->isRoleExists(role)) { @@ -8331,7 +9091,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } - if(obj_type==OBJ_TABLESPACE && (!exclusion_mode || (exclusion_mode && !refer))) + if(obj_type==ObjectType::Tablespace && (!exclusion_mode || (exclusion_mode && !refer))) { vector::iterator itr, itr_end; unsigned i, count; @@ -8384,7 +9144,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } - if(obj_type==OBJ_LANGUAGE && (!exclusion_mode || (exclusion_mode && !refer))) + if(obj_type==ObjectType::Language && (!exclusion_mode || (exclusion_mode && !refer))) { vector::iterator itr, itr_end; Function *func=nullptr; @@ -8404,7 +9164,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } - if(obj_type==OBJ_OPCLASS && (!exclusion_mode || (exclusion_mode && !refer))) + if(obj_type==ObjectType::OpClass && (!exclusion_mode || (exclusion_mode && !refer))) { vector::iterator itr, itr_end; Type *usertype=nullptr; @@ -8467,18 +9227,29 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } + //Checking if the partition keys are referencing the operator class + for(auto &part_key : table->getPartitionKeys()) + { + if(part_key.getOperatorClass() == object) + { + refer = true; + refs.push_back(table); + break; + } + } + itr++; } } - if(obj_type==OBJ_OPERATOR && (!exclusion_mode || (exclusion_mode && !refer))) + if(obj_type==ObjectType::Operator && (!exclusion_mode || (exclusion_mode && !refer))) { vector *obj_list=nullptr; vector::iterator itr, itr_end; - ObjectType obj_types[]={OBJ_OPCLASS, - OBJ_AGGREGATE, - OBJ_OPERATOR, - OBJ_TABLE }; + ObjectType obj_types[]={ObjectType::OpClass, + ObjectType::Aggregate, + ObjectType::Operator, + ObjectType::Table }; unsigned i, i1, count; OperatorClass *op_class=nullptr; Operator *oper_aux=nullptr, *oper=dynamic_cast(object); @@ -8491,7 +9262,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector itr=obj_list->begin(); itr_end=obj_list->end(); - if(obj_types[i]==OBJ_OPCLASS) + if(obj_types[i]==ObjectType::OpClass) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { @@ -8509,7 +9280,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } } - else if(obj_types[i]==OBJ_AGGREGATE) + else if(obj_types[i]==ObjectType::Aggregate) { while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { @@ -8521,14 +9292,14 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector itr++; } } - else if(obj_types[i]==OBJ_OPERATOR) + else if(obj_types[i]==ObjectType::Operator) { while(itr!=itr_end && !refer) { oper_aux=dynamic_cast(*itr); itr++; - for(i1=Operator::OPER_COMMUTATOR; i1 <= Operator::OPER_NEGATOR && + for(i1=Operator::OperCommutator; i1 <= Operator::OperNegator && (!exclusion_mode || (exclusion_mode && !refer)); i1++) { if(oper_aux->getOperator(i1)==oper) @@ -8551,7 +9322,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector { constr=table->getConstraint(i1); - if(constr->getConstraintType()==ConstraintType::exclude) + if(constr->getConstraintType()==ConstraintType::Exclude) { for(auto &elem : constr->getExcludeElements()) { @@ -8569,7 +9340,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } - if(obj_type==OBJ_OPFAMILY && (!exclusion_mode || (exclusion_mode && !refer))) + if(obj_type==ObjectType::OpFamily && (!exclusion_mode || (exclusion_mode && !refer))) { vector::iterator itr, itr_end; OperatorFamily *op_family=dynamic_cast(object); @@ -8588,16 +9359,17 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } - if(obj_type==OBJ_COLLATION && (!exclusion_mode || (exclusion_mode && !refer))) + if(obj_type==ObjectType::Collation && (!exclusion_mode || (exclusion_mode && !refer))) { - ObjectType obj_types[]={ OBJ_DOMAIN, OBJ_COLLATION, OBJ_TYPE }, - tab_obj_types[]={ OBJ_COLUMN, OBJ_INDEX }; + ObjectType obj_types[]={ ObjectType::Domain, ObjectType::Collation, ObjectType::Type }, + tab_obj_types[]={ ObjectType::Column, ObjectType::Index }; unsigned i, count; vector *obj_list=nullptr; vector::iterator itr, itr_end; vector *tab_obj_list=nullptr; vector::iterator tab_itr, tab_itr_end; TableObject *tab_obj=nullptr; + Table *table = nullptr; count=sizeof(obj_types)/sizeof(ObjectType); for(i=0; i < count && (!exclusion_mode || (exclusion_mode && !refer)); i++) @@ -8619,23 +9391,25 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } count=sizeof(tab_obj_types)/sizeof(ObjectType); - obj_list=getObjectList(OBJ_TABLE); + obj_list=getObjectList(ObjectType::Table); itr=obj_list->begin(); itr_end=obj_list->end(); while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { + table = dynamic_cast
(*itr); + for(i=0; i < count && (!exclusion_mode || (exclusion_mode && !refer)); i++) { - tab_obj_list=dynamic_cast
(*itr)->getObjectList(tab_obj_types[i]); + tab_obj_list=table->getObjectList(tab_obj_types[i]); tab_itr=tab_obj_list->begin(); tab_itr_end=tab_obj_list->end(); while(tab_itr!=tab_itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { tab_obj=(*tab_itr); - if((tab_obj->getObjectType()==OBJ_COLUMN && tab_obj->getCollation()==object) || - (tab_obj->getObjectType()==OBJ_INDEX && + if((tab_obj->getObjectType()==ObjectType::Column && tab_obj->getCollation()==object) || + (tab_obj->getObjectType()==ObjectType::Index && dynamic_cast(tab_obj)->isReferCollation(dynamic_cast(object)))) { refer=true; @@ -8644,16 +9418,28 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector tab_itr++; } } + + //Checking if the partition keys are referencing the operator class + for(auto &part_key : table->getPartitionKeys()) + { + if(part_key.getCollation() == object) + { + refer = true; + refs.push_back(table); + break; + } + } + itr++; } } - if(obj_type==OBJ_COLUMN && (!exclusion_mode || (exclusion_mode && !refer))) + if(obj_type==ObjectType::Column && (!exclusion_mode || (exclusion_mode && !refer))) { Column *column=dynamic_cast(object); vector *obj_list=nullptr; vector::iterator itr, itr_end; - ObjectType obj_types[]={ OBJ_SEQUENCE, OBJ_VIEW, OBJ_TABLE, OBJ_RELATIONSHIP }; + ObjectType obj_types[]={ ObjectType::Sequence, ObjectType::View, ObjectType::Table, ObjectType::Relationship }; unsigned i, count=sizeof(obj_types)/sizeof(ObjectType); for(i=0; i < count && (!exclusion_mode || (exclusion_mode && !refer)); i++) @@ -8664,19 +9450,20 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) { - if((obj_types[i]==OBJ_SEQUENCE && dynamic_cast(*itr)->getOwnerColumn()==column) || - (obj_types[i]==OBJ_VIEW && dynamic_cast(*itr)->isReferencingColumn(column))) + if((obj_types[i]==ObjectType::Sequence && dynamic_cast(*itr)->getOwnerColumn()==column) || + (obj_types[i]==ObjectType::View && dynamic_cast(*itr)->isReferencingColumn(column))) { refer=true; refs.push_back(*itr); } - else if(obj_types[i]==OBJ_TABLE) + else if(obj_types[i]==ObjectType::Table) { Table *tab=dynamic_cast
(*itr); unsigned count, idx, count1, i1; Trigger *trig=nullptr; Index *index=nullptr; Constraint *constr=nullptr; + vector part_keys; count=tab->getConstraintCount(); for(idx=0; idx < count && (!exclusion_mode || (exclusion_mode && !refer)); idx++) @@ -8715,8 +9502,20 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } } + + part_keys = tab->getPartitionKeys(); + for(auto &part_key : part_keys) + { + if(part_key.getColumn() == column) + { + refer = true; + refs.push_back(tab); + break; + } + } + } - else if(obj_types[i]==OBJ_RELATIONSHIP) + else if(obj_types[i]==ObjectType::Relationship) { Relationship *rel=dynamic_cast(*itr); unsigned constr_cnt, idx; @@ -8737,8 +9536,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } - - if(obj_type==OBJ_TAG && (!exclusion_mode || (exclusion_mode && !refer))) + if(obj_type==ObjectType::Tag && (!exclusion_mode || (exclusion_mode && !refer))) { vector::iterator itr, itr_end; vector list; @@ -8761,7 +9559,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } - if(obj_type==OBJ_SEQUENCE && (!exclusion_mode || (exclusion_mode && !refer))) + if(obj_type==ObjectType::Sequence && (!exclusion_mode || (exclusion_mode && !refer))) { Table *table=nullptr; vector *cols=nullptr; @@ -8771,7 +9569,7 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector for(i=0; i < cnt && (!exclusion_mode || (exclusion_mode && !refer)); i++) { table=dynamic_cast
(tables[i]); - cols=table->getObjectList(OBJ_COLUMN); + cols=table->getObjectList(ObjectType::Column); itr=cols->begin(); itr_end=cols->end(); @@ -8786,6 +9584,61 @@ void DatabaseModel::getObjectReferences(BaseObject *object, vector } } } + + if(obj_type==ObjectType::ForeignDataWrapper && (!exclusion_mode || (exclusion_mode && !refer))) + { + vector::iterator itr, itr_end; + vector list; + ForeignDataWrapper *fdw=dynamic_cast(object); + + itr=foreign_servers.begin(); + itr_end=foreign_servers.end(); + + while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) + { + if(dynamic_cast(*itr)->getForeignDataWrapper() == fdw) + { + refer=true; + refs.push_back(*itr); + } + itr++; + } + } + + if(obj_type==ObjectType::ForeignServer && (!exclusion_mode || (exclusion_mode && !refer))) + { + vector::iterator itr, itr_end; + vector list; + ForeignServer *srv=dynamic_cast(object); + + itr=usermappings.begin(); + itr_end=usermappings.end(); + + while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !refer))) + { + if(dynamic_cast(*itr)->getForeignServer() == srv) + { + refer=true; + refs.push_back(*itr); + } + itr++; + } + } + + // Checking if any generic SQL object is referencing the object passed + vector::iterator itr = genericsqls.begin(), + itr_end = genericsqls.end(); + + while(itr != itr_end && (!exclusion_mode || (exclusion_mode && !refer))) + { + if(dynamic_cast(*itr)->isObjectReferenced(object)) + { + refer = true; + refs.push_back(*itr); + } + + itr++; + } } } @@ -8808,11 +9661,20 @@ void DatabaseModel::__getObjectReferences(BaseObject *object, vector &objects) +{ + for(auto &obj : objects) + { + if(BaseGraphicObject::isGraphicObject(obj->getObjectType())) + dynamic_cast(obj)->setModified(true); + } +} + void DatabaseModel::setObjectsModified(vector types) { - ObjectType obj_types[]={OBJ_TABLE, OBJ_VIEW, - OBJ_RELATIONSHIP, BASE_RELATIONSHIP, - OBJ_TEXTBOX, OBJ_SCHEMA }; + ObjectType obj_types[]={ObjectType::Table, ObjectType::View, + ObjectType::Relationship, ObjectType::BaseRelationship, + ObjectType::Textbox, ObjectType::Schema }; vector::iterator itr, itr_end; vector *obj_list=nullptr; Textbox *label=nullptr; @@ -8832,7 +9694,7 @@ void DatabaseModel::setObjectsModified(vector types) dynamic_cast(*itr)->setModified(true); //For relationships is needed to set the labels as modified too - if(obj_types[i]==OBJ_RELATIONSHIP || obj_types[i]==BASE_RELATIONSHIP) + if(obj_types[i]==ObjectType::Relationship || obj_types[i]==ObjectType::BaseRelationship) { rel=dynamic_cast(*itr); for(i1=0; i1 < 3; i1++) @@ -8857,8 +9719,8 @@ void DatabaseModel::setCodesInvalidated(vector types) sel_types=BaseObject::getObjectTypes(false); else { - ObjectType tab_obj_types[]={OBJ_COLUMN, OBJ_CONSTRAINT, - OBJ_TRIGGER, OBJ_RULE, OBJ_INDEX, OBJ_POLICY}; + ObjectType tab_obj_types[]={ObjectType::Column, ObjectType::Constraint, + ObjectType::Trigger, ObjectType::Rule, ObjectType::Index, ObjectType::Policy}; for(unsigned i=0; i < 6; i++) sel_types.erase(std::find(sel_types.begin(), sel_types.end(), tab_obj_types[i])); @@ -8878,50 +9740,43 @@ void DatabaseModel::setCodesInvalidated(vector types) } } -BaseObject *DatabaseModel::getObjectPgSQLType(PgSQLType type) +BaseObject *DatabaseModel::getObjectPgSQLType(PgSqlType type) { switch(type.getUserTypeConfig()) { - case UserTypeConfig::BASE_TYPE: - return(this->getObject(*type, OBJ_TYPE)); - break; + case UserTypeConfig::BaseType: + return(this->getObject(*type, ObjectType::Type)); - case UserTypeConfig::DOMAIN_TYPE: - return(this->getObject(*type, OBJ_DOMAIN)); - break; + case UserTypeConfig::DomainType: + return(this->getObject(*type, ObjectType::Domain)); - case UserTypeConfig::TABLE_TYPE: - return(this->getObject(*type, OBJ_TABLE)); - break; + case UserTypeConfig::TableType: + return(this->getObject(*type, ObjectType::Table)); - case UserTypeConfig::VIEW_TYPE: - return(this->getObject(*type, OBJ_VIEW)); - break; + case UserTypeConfig::ViewType: + return(this->getObject(*type, ObjectType::View)); - case UserTypeConfig::SEQUENCE_TYPE: - return(this->getObject(*type, OBJ_SEQUENCE)); - break; + case UserTypeConfig::SequenceType: + return(this->getObject(*type, ObjectType::Sequence)); - case UserTypeConfig::EXTENSION_TYPE: - return(this->getObject(*type, OBJ_EXTENSION)); - break; + case UserTypeConfig::ExtensionType: + return(this->getObject(*type, ObjectType::Extension)); default: return(nullptr); - break; } } void DatabaseModel::validateSchemaRenaming(Schema *schema, const QString &prev_sch_name) { - ObjectType types[]={ OBJ_TABLE, OBJ_VIEW, OBJ_DOMAIN, OBJ_TYPE, OBJ_SEQUENCE }; + ObjectType types[]={ ObjectType::Table, ObjectType::View, ObjectType::Domain, ObjectType::Type, ObjectType::Sequence }; vector list, vet; BaseObject *obj=nullptr; QString prev_name; //Raise an error if the schema is not allocated if(!schema) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Get all the objects on the informed schema for(unsigned i=0; i < 5; i++) @@ -8935,7 +9790,7 @@ void DatabaseModel::validateSchemaRenaming(Schema *schema, const QString &prev_s obj=list.back(); //For objects that is not a Views is needed to rename the pgsql type represented by the object - if(obj->getObjectType()!=OBJ_VIEW) + if(obj->getObjectType()!=ObjectType::View) { //Configures the previous type name prev_name=BaseObject::formatName(prev_sch_name) + QString(".") + @@ -8943,14 +9798,14 @@ void DatabaseModel::validateSchemaRenaming(Schema *schema, const QString &prev_s /* Special case for tables. Need to make a dynamic_cast before the reinterpret_cast to get the correct reference to table */ - if(obj->getObjectType()==OBJ_TABLE) - PgSQLType::renameUserType(prev_name, reinterpret_cast(dynamic_cast
(obj)), obj->getName(true)); + if(obj->getObjectType()==ObjectType::Table) + PgSqlType::renameUserType(prev_name, reinterpret_cast(dynamic_cast
(obj)), obj->getName(true)); else - PgSQLType::renameUserType(prev_name, reinterpret_cast(obj), obj->getName(true)); + PgSqlType::renameUserType(prev_name, reinterpret_cast(obj), obj->getName(true)); } //For graphical objects set them as modified to redraw them - if(obj->getObjectType()==OBJ_TABLE || obj->getObjectType()==OBJ_VIEW) + if(obj->getObjectType()==ObjectType::Table || obj->getObjectType()==ObjectType::View) dynamic_cast(obj)->setModified(true); list.pop_back(); @@ -8962,7 +9817,7 @@ void DatabaseModel::createSystemObjects(bool create_public) Schema *public_sch=nullptr, *pg_catalog=nullptr; Language *lang=nullptr; Tablespace *tbspace=nullptr; - LanguageType lang_types[]={ LanguageType::c, LanguageType::sql, LanguageType::plpgsql, LanguageType::internal }; + LanguageType lang_types[]={ LanguageType::C, LanguageType::Sql, LanguageType::PlPgsql, LanguageType::Internal }; Role *postgres=nullptr; Collation *collation=nullptr; QString collnames[]={ "default", "C", "POSIX" }; @@ -8970,7 +9825,7 @@ void DatabaseModel::createSystemObjects(bool create_public) /* The particular case is for public schema that is created only when the flag is set. This because the public schema is written on model file even being a system object. This strategy permits the user controls the schema rectangle behavior */ - if(create_public && getObjectIndex(QString("public"), OBJ_SCHEMA) < 0) + if(create_public && getObjectIndex(QString("public"), ObjectType::Schema) < 0) { public_sch=new Schema; public_sch->setName(QString("public")); @@ -8998,7 +9853,7 @@ void DatabaseModel::createSystemObjects(bool create_public) for(unsigned i=0; i < sizeof(lang_types)/sizeof(LanguageType); i++) { - if(getObjectIndex(~LanguageType(lang_types[i]), OBJ_LANGUAGE) < 0) + if(getObjectIndex(~LanguageType(lang_types[i]), ObjectType::Language) < 0) { lang=new Language; lang->BaseObject::setName(~LanguageType(lang_types[i])); @@ -9021,15 +9876,15 @@ void DatabaseModel::createSystemObjects(bool create_public) postgres=new Role; postgres->setName(QString("postgres")); - postgres->setOption(Role::OP_SUPERUSER, true); + postgres->setOption(Role::OpSuperuser, true); postgres->setSystemObject(true); addRole(postgres); setDefaultObject(postgres); - setDefaultObject(getObject(QString("public"), OBJ_SCHEMA), OBJ_SCHEMA); + setDefaultObject(getObject(QString("public"), ObjectType::Schema), ObjectType::Schema); } -vector DatabaseModel::findObjects(const QString &pattern, vector types, bool format_obj_names, bool case_sensitive, bool is_regexp, bool exact_match) +vector DatabaseModel::findObjects(const QString &pattern, vector types, bool case_sensitive, bool is_regexp, bool exact_match, const QString &search_attr) { vector list, objs; vector::iterator end; @@ -9038,7 +9893,8 @@ vector DatabaseModel::findObjects(const QString &pattern, vector DatabaseModel::findObjects(const QString &pattern, vectorbegin(), getObjectList(OBJ_TABLE)->end()); + tables.insert(tables.end(), getObjectList(ObjectType::Table)->begin(), getObjectList(ObjectType::Table)->end()); inc_tabs=true; } - if(!inc_views && ((*itr_tp)==OBJ_RULE || (*itr_tp)==OBJ_TRIGGER)) + if(!inc_views && ((*itr_tp)==ObjectType::Rule || (*itr_tp)==ObjectType::Trigger)) { - tables.insert(tables.end(), getObjectList(OBJ_VIEW)->begin(), getObjectList(OBJ_VIEW)->end()); + tables.insert(tables.end(), getObjectList(ObjectType::View)->begin(), getObjectList(ObjectType::View)->end()); inc_views=true; } @@ -9076,7 +9932,7 @@ vector DatabaseModel::findObjects(const QString &pattern, vectorbegin(), getObjectList(obj_type)->end()); @@ -9092,10 +9948,10 @@ vector DatabaseModel::findObjects(const QString &pattern, vectorgetObjectType()==OBJ_TABLE) + if(tab->getObjectType()==ObjectType::Table) tab_objs=dynamic_cast
(tab)->getObjectList(obj_type); - else if(tab->getObjectType()==OBJ_VIEW && - (obj_type==OBJ_TRIGGER || obj_type==OBJ_RULE)) + else if(tab->getObjectType()==ObjectType::View && + (obj_type==ObjectType::Trigger || obj_type==ObjectType::Rule)) tab_objs=dynamic_cast(tab)->getObjectList(obj_type); if(tab_objs) @@ -9107,31 +9963,16 @@ vector DatabaseModel::findObjects(const QString &pattern, vectorgetObjectType())) - { - TableObject *tab_obj=dynamic_cast(objs.back()); - - if(tab_obj->getParentTable()) - obj_name=tab_obj->getParentTable()->getName(true); - } - - obj_name+=objs.back()->getName(true, true); - obj_name.remove('"'); - } - else - obj_name=objs.back()->getName(); + object = objs.back(); + object->configureSearchAttributes(); + srch_attribs = object->getSearchAttributes(); - //Try to match the name on the configured regexp - if((exact_match && pattern==obj_name) || - (exact_match && regexp.exactMatch(obj_name)) || - (!exact_match && regexp.indexIn(obj_name) >= 0)) - list.push_back(objs.back()); + if((exact_match && pattern == srch_attribs[search_attr]) || + (exact_match && regexp.exactMatch(srch_attribs[search_attr])) || + (!exact_match && regexp.indexIn(srch_attribs[search_attr]) >= 0)) + list.push_back(object); objs.pop_back(); - obj_name.clear(); } //Removing the duplicate items on the list @@ -9166,7 +10007,7 @@ void DatabaseModel::setDefaultObject(BaseObject *object, ObjectType obj_type) { if((!object && default_objs.count(obj_type)==0) || (object && default_objs.count(object->getObjectType())==0)) - throw Exception(ERR_REF_OBJ_INV_TYPE, __PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidType, __PRETTY_FUNCTION__,__FILE__,__LINE__); if(!object) default_objs[obj_type]=nullptr; @@ -9209,7 +10050,7 @@ void DatabaseModel::saveObjectsMetadata(const QString &filename, unsigned option QFile output(filename); QByteArray buf; QString objs_def; - vector objects; + vector objects, tab_objs; attribs_map attribs; BaseGraphicObject *graph_obj=nullptr; Relationship *rel=nullptr; @@ -9222,28 +10063,29 @@ void DatabaseModel::saveObjectsMetadata(const QString &filename, unsigned option bool save_db_attribs=false, save_objs_pos=false, save_objs_prot=false, save_objs_sqldis=false, save_textboxes=false, save_tags=false, save_custom_sql=false, save_custom_colors=false, save_fadeout=false, - save_extattribs=false, save_genericsqls=false; - QStringList labels_attrs={ ParsersAttributes::SRC_LABEL, - ParsersAttributes::DST_LABEL, - ParsersAttributes::NAME_LABEL }; - - save_db_attribs=(META_DB_ATTRIBUTES & options) == META_DB_ATTRIBUTES; - save_objs_pos=(META_OBJS_POSITIONING & options) == META_OBJS_POSITIONING; - save_objs_prot=(META_OBJS_PROTECTION & options) == META_OBJS_PROTECTION; - save_objs_sqldis=(META_OBJS_SQLDISABLED & options) == META_OBJS_SQLDISABLED; - save_textboxes=(META_TEXTBOX_OBJS & options) == META_TEXTBOX_OBJS; - save_tags=(META_TAG_OBJS & options) == META_TAG_OBJS; - save_custom_sql=(META_OBJS_CUSTOMSQL & options) == META_OBJS_CUSTOMSQL; - save_custom_colors=(META_OBJS_CUSTOMCOLORS & options) == META_OBJS_CUSTOMCOLORS; - save_fadeout=(META_OBJS_FADEDOUT & options) == META_OBJS_FADEDOUT; - save_extattribs=(META_OBJS_EXTATTRIBS & options) == META_OBJS_EXTATTRIBS; - save_genericsqls=(META_GENERIC_SQL_OBJS & options) == META_GENERIC_SQL_OBJS; + save_collapsemode=false, save_genericsqls=false, save_objs_aliases=false; + QStringList labels_attrs={ Attributes::SrcLabel, + Attributes::DstLabel, + Attributes::NameLabel }; + + save_db_attribs=(MetaDbAttributes & options) == MetaDbAttributes; + save_objs_pos=(MetaObjsPositioning & options) == MetaObjsPositioning; + save_objs_prot=(MetaObjsProtection & options) == MetaObjsProtection; + save_objs_sqldis=(MetaObjsSqlDisabled & options) == MetaObjsSqlDisabled; + save_textboxes=(MetaTextboxObjs & options) == MetaTextboxObjs; + save_tags=(MetaTagObjs & options) == MetaTagObjs; + save_custom_sql=(MetaObjsCustomSql & options) == MetaObjsCustomSql; + save_custom_colors=(MetaObjsCustomColors & options) == MetaObjsCustomColors; + save_fadeout=(MetaObjsFadeOut & options) == MetaObjsFadeOut; + save_collapsemode=(MetaObjsCollapseMode & options) == MetaObjsCollapseMode; + save_genericsqls=(MetaGenericSqlObjs & options) == MetaGenericSqlObjs; + save_objs_aliases=(MetaObjsAliases & options) == MetaObjsAliases; output.open(QFile::WriteOnly); if(!output.isOpen()) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(filename), - ERR_FILE_DIR_NOT_WRITTEN,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotWritten).arg(filename), + ErrorCode::FileDirectoryNotWritten,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { @@ -9262,7 +10104,7 @@ void DatabaseModel::saveObjectsMetadata(const QString &filename, unsigned option if(save_db_attribs) objects.push_back(this); - if(save_objs_pos) + if(save_objs_pos || save_objs_aliases) { objects.insert(objects.end(), schemas.begin(), schemas.end()); objects.insert(objects.end(), tables.begin(), tables.end()); @@ -9274,33 +10116,50 @@ void DatabaseModel::saveObjectsMetadata(const QString &filename, unsigned option for(BaseObject *object : relationships) { rel=dynamic_cast(object); - if(rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_NN && rel->getReceiverTable()) + + if(save_objs_pos && rel->getRelationshipType()==BaseRelationship::RelationshipNn && rel->getReceiverTable()) { tab_nn=rel->getReceiverTable(); - src_tab=rel->getTable(BaseRelationship::SRC_TABLE); - dst_tab=rel->getTable(BaseRelationship::DST_TABLE); + src_tab=rel->getTable(BaseRelationship::SrcTable); + dst_tab=rel->getTable(BaseRelationship::DstTable); //Since the generated table does not have a position we create one based upon the source tables positions - pnt.setX((src_tab->getPosition().x() + dst_tab->getPosition().x())/2.0f); - pnt.setY((src_tab->getPosition().y() + dst_tab->getPosition().y())/2.0f); + pnt.setX((src_tab->getPosition().x() + dst_tab->getPosition().x())/2.0); + pnt.setY((src_tab->getPosition().y() + dst_tab->getPosition().y())/2.0); tab_nn->setPosition(pnt); objects.push_back(tab_nn); } } + + //Saving aliases the children of tables and views + if(save_objs_aliases) + { + for(auto &tab : tables) + { + tab_objs = dynamic_cast
(tab)->getObjects(); + objects.insert(objects.end(), tab_objs.begin(), tab_objs.end()); + } + + for(auto &vw : views) + { + tab_objs = dynamic_cast(vw)->getObjects(); + objects.insert(objects.end(), tab_objs.begin(), tab_objs.end()); + } + } } if(save_objs_prot || save_objs_sqldis) { - vector types=getChildObjectTypes(OBJ_DATABASE), sch_types=getChildObjectTypes(OBJ_SCHEMA); + vector types=getChildObjectTypes(ObjectType::Database), sch_types=getChildObjectTypes(ObjectType::Schema); types.insert(types.end(), sch_types.begin(), sch_types.end()); //Removing the types for schema, table and view to avoid retrieving the objects twice if(save_objs_pos) { - types.erase(std::find(types.begin(), types.end(), OBJ_SCHEMA)); - types.erase(std::find(types.begin(), types.end(), OBJ_TABLE)); - types.erase(std::find(types.begin(), types.end(), OBJ_VIEW)); + types.erase(std::find(types.begin(), types.end(), ObjectType::Schema)); + types.erase(std::find(types.begin(), types.end(), ObjectType::Table)); + types.erase(std::find(types.begin(), types.end(), ObjectType::View)); } //Append the other objects to the list of selected entities @@ -9313,81 +10172,91 @@ void DatabaseModel::saveObjectsMetadata(const QString &filename, unsigned option obj_type=object->getObjectType(); //When handling a tag , textbox or generic sql we just extract their XML code - if(obj_type==OBJ_TEXTBOX || obj_type==OBJ_TAG || obj_type == OBJ_GENERIC_SQL) + if(obj_type==ObjectType::Textbox || obj_type==ObjectType::Tag || obj_type == ObjectType::GenericSql) { - emit s_objectLoaded(((idx++)/static_cast(objects.size()))*100, + emit s_objectLoaded(((idx++)/static_cast(objects.size()))*100, trUtf8("Saving object `%1' (%2)") - .arg(object->getName()).arg(object->getTypeName()), obj_type); + .arg(object->getName()).arg(object->getTypeName()), enum_cast(obj_type)); - objs_def+=object->getCodeDefinition(SchemaParser::XML_DEFINITION); + objs_def+=object->getCodeDefinition(SchemaParser::XmlDefinition); continue; } + //Discarding the relationship added table objects (when extracting aliases) + else if(TableObject::isTableObject(obj_type) && dynamic_cast(object)->isAddedByRelationship()) + continue; graph_obj=dynamic_cast(object); base_tab=dynamic_cast(object); - attribs[ParsersAttributes::NAME]=object->getSignature(); - attribs[ParsersAttributes::TYPE]=object->getSchemaName(); - attribs[ParsersAttributes::PROTECTED]=(save_objs_prot && object->isProtected() && !object->isSystemObject() ? ParsersAttributes::_TRUE_ : QString()); - attribs[ParsersAttributes::SQL_DISABLED]=(save_objs_sqldis && object->isSQLDisabled() && !object->isSystemObject() ? ParsersAttributes::_TRUE_ : QString()); - attribs[ParsersAttributes::TAG]=(save_tags && base_tab && base_tab->getTag() ? base_tab->getTag()->getName() : QString()); - attribs[ParsersAttributes::APPENDED_SQL]=object->getAppendedSQL(); - attribs[ParsersAttributes::PREPENDED_SQL]=object->getPrependedSQL(); + attribs[Attributes::Table]=QString(); + attribs[Attributes::Name]=(TableObject::isTableObject(obj_type) ? object->getName() : object->getSignature()); + attribs[Attributes::Alias]=(save_objs_aliases ? object->getAlias() : QString()); + attribs[Attributes::Type]=object->getSchemaName(); + attribs[Attributes::Protected]=(save_objs_prot && object->isProtected() && !object->isSystemObject() ? Attributes::True : QString()); + attribs[Attributes::SqlDisabled]=(save_objs_sqldis && object->isSQLDisabled() && !object->isSystemObject() ? Attributes::True : QString()); + attribs[Attributes::Tag]=(save_tags && base_tab && base_tab->getTag() ? base_tab->getTag()->getName() : QString()); + attribs[Attributes::AppendedSql]=object->getAppendedSQL(); + attribs[Attributes::PrependedSql]=object->getPrependedSQL(); + attribs[Attributes::FadedOut]=(save_fadeout && graph_obj && graph_obj->isFadedOut() ? Attributes::True : QString()); + attribs[Attributes::CollapseMode]=(save_collapsemode && base_tab ? QString::number(enum_cast(base_tab->getCollapseMode())) : QString()); - attribs[ParsersAttributes::HIDE_EXT_ATTRIBS]=(save_extattribs && base_tab && base_tab->isExtAttribsHidden() ? ParsersAttributes::_TRUE_ : QString()); - attribs[ParsersAttributes::FADED_OUT]=(save_fadeout && graph_obj && graph_obj->isFadedOut() ? ParsersAttributes::_TRUE_ : QString()); + if(TableObject::isTableObject(obj_type)) + { + base_tab = dynamic_cast(object)->getParentTable(); + attribs[Attributes::Table]=base_tab->getSignature(); + } - if(save_custom_sql && obj_type==OBJ_DATABASE) + if(save_custom_sql && obj_type==ObjectType::Database) { - attribs[ParsersAttributes::APPEND_AT_EOD]=(this->isAppendAtEOD() ? ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_); - attribs[ParsersAttributes::PREPEND_AT_BOD]=(this->isPrependedAtBOD() ? ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_); + attribs[Attributes::AppendAtEod]=(this->isAppendAtEOD() ? Attributes::True : Attributes::False); + attribs[Attributes::PrependAtBod]=(this->isPrependedAtBOD() ? Attributes::True : Attributes::False); } //Configuring database model attributes if(save_db_attribs && object==this) { - attribs[ParsersAttributes::MODEL_AUTHOR]=this->getAuthor(); - attribs[ParsersAttributes::LAST_POSITION]=QString("%1,%2").arg(last_pos.x()).arg(last_pos.y()); - attribs[ParsersAttributes::LAST_ZOOM]=QString::number(last_zoom); - attribs[ParsersAttributes::DEFAULT_COLLATION]=(default_objs[OBJ_COLLATION] ? default_objs[OBJ_COLLATION]->getSignature() : QString()); - attribs[ParsersAttributes::DEFAULT_SCHEMA]=(default_objs[OBJ_SCHEMA] ? default_objs[OBJ_SCHEMA]->getSignature() : QString()); - attribs[ParsersAttributes::DEFAULT_TABLESPACE]=(default_objs[OBJ_TABLESPACE] ? default_objs[OBJ_TABLESPACE]->getSignature() : QString()); - attribs[ParsersAttributes::DEFAULT_OWNER]=(default_objs[OBJ_ROLE] ? default_objs[OBJ_ROLE]->getSignature() : QString()); + attribs[Attributes::ModelAuthor]=this->getAuthor(); + attribs[Attributes::LastPosition]=QString("%1,%2").arg(last_pos.x()).arg(last_pos.y()); + attribs[Attributes::LastZoom]=QString::number(last_zoom); + attribs[Attributes::DefaultCollation]=(default_objs[ObjectType::Collation] ? default_objs[ObjectType::Collation]->getSignature() : QString()); + attribs[Attributes::DefaultSchema]=(default_objs[ObjectType::Schema] ? default_objs[ObjectType::Schema]->getSignature() : QString()); + attribs[Attributes::DefaultTablespace]=(default_objs[ObjectType::Tablespace] ? default_objs[ObjectType::Tablespace]->getSignature() : QString()); + attribs[Attributes::DefaultOwner]=(default_objs[ObjectType::Role] ? default_objs[ObjectType::Role]->getSignature() : QString()); } //If the object is a graphic one and we need to save positions and colors if((save_objs_pos || save_custom_colors) && graph_obj) { - if(obj_type!=BASE_RELATIONSHIP && obj_type!=OBJ_RELATIONSHIP) + if(obj_type!=ObjectType::BaseRelationship && obj_type!=ObjectType::Relationship) { pnt=graph_obj->getPosition(); - if(obj_type==OBJ_SCHEMA) + if(obj_type==ObjectType::Schema) { schema=dynamic_cast(object); - attribs[ParsersAttributes::CUSTOM_COLOR]=(save_custom_colors ? schema->getFillColor().name() : QString()); - attribs[ParsersAttributes::RECT_VISIBLE]=(schema->isRectVisible() ? ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_); + attribs[Attributes::CustomColor]=(save_custom_colors ? schema->getFillColor().name() : QString()); + attribs[Attributes::RectVisible]=(schema->isRectVisible() ? Attributes::True : Attributes::False); if(schema->isRectVisible()) { - attribs[ParsersAttributes::X_POS]=QString::number(pnt.x()); - attribs[ParsersAttributes::Y_POS]=QString::number(pnt.y()); + attribs[Attributes::XPos]=QString::number(pnt.x()); + attribs[Attributes::YPos]=QString::number(pnt.y()); } } else { - attribs[ParsersAttributes::X_POS]=QString::number(pnt.x()); - attribs[ParsersAttributes::Y_POS]=QString::number(pnt.y()); + attribs[Attributes::XPos]=QString::number(pnt.x()); + attribs[Attributes::YPos]=QString::number(pnt.y()); } - if(obj_type!=OBJ_SCHEMA || !attribs[ParsersAttributes::X_POS].isEmpty()) + if(obj_type!=ObjectType::Schema || !attribs[Attributes::XPos].isEmpty()) { schparser.ignoreUnkownAttributes(true); - attribs[ParsersAttributes::POSITION]= - schparser.getCodeDefinition(GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::XML_SCHEMA_DIR + GlobalAttributes::DIR_SEPARATOR + - ParsersAttributes::POSITION + GlobalAttributes::SCHEMA_EXT, attribs); + attribs[Attributes::Position]= + schparser.getCodeDefinition(GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + GlobalAttributes::XMLSchemaDir + GlobalAttributes::DirSeparator + + Attributes::Position + GlobalAttributes::SchemaExt, attribs); } } else @@ -9397,43 +10266,43 @@ void DatabaseModel::saveObjectsMetadata(const QString &filename, unsigned option attribs_map aux_attribs; - attribs[ParsersAttributes::CUSTOM_COLOR]=(save_custom_colors && rel->getCustomColor()!=Qt::transparent ? rel->getCustomColor().name() : ParsersAttributes::NONE); + attribs[Attributes::CustomColor]=(save_custom_colors && rel->getCustomColor()!=Qt::transparent ? rel->getCustomColor().name() : Attributes::None); - attribs[ParsersAttributes::SRC_TABLE]=rel->getTable(BaseRelationship::SRC_TABLE)->getSignature(); - attribs[ParsersAttributes::SRC_TYPE]=rel->getTable(BaseRelationship::SRC_TABLE)->getSchemaName(); + attribs[Attributes::SrcTable]=rel->getTable(BaseRelationship::SrcTable)->getSignature(); + attribs[Attributes::SrcType]=rel->getTable(BaseRelationship::SrcTable)->getSchemaName(); - attribs[ParsersAttributes::DST_TABLE]=rel->getTable(BaseRelationship::DST_TABLE)->getSignature(); - attribs[ParsersAttributes::DST_TYPE]=rel->getTable(BaseRelationship::DST_TABLE)->getSchemaName(); + attribs[Attributes::DstTable]=rel->getTable(BaseRelationship::DstTable)->getSignature(); + attribs[Attributes::DstType]=rel->getTable(BaseRelationship::DstTable)->getSchemaName(); for(QPointF pnt : points) { - attribs[ParsersAttributes::X_POS]=QString::number(pnt.x()); - attribs[ParsersAttributes::Y_POS]=QString::number(pnt.y()); + attribs[Attributes::XPos]=QString::number(pnt.x()); + attribs[Attributes::YPos]=QString::number(pnt.y()); schparser.ignoreUnkownAttributes(true); - attribs[ParsersAttributes::POSITION]+= - schparser.getCodeDefinition(GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::XML_SCHEMA_DIR + GlobalAttributes::DIR_SEPARATOR + - ParsersAttributes::POSITION + GlobalAttributes::SCHEMA_EXT, attribs); + attribs[Attributes::Position]+= + schparser.getCodeDefinition(GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + GlobalAttributes::XMLSchemaDir + GlobalAttributes::DirSeparator + + Attributes::Position + GlobalAttributes::SchemaExt, attribs); } //Saving the labels' custom positions - for(unsigned id=BaseRelationship::SRC_CARD_LABEL; id <= BaseRelationship::REL_NAME_LABEL; id++) + for(unsigned id=BaseRelationship::SrcCardLabel; id <= BaseRelationship::RelNameLabel; id++) { pnt=rel->getLabelDistance(id); if(!std::isnan(pnt.x()) && !std::isnan(pnt.y())) { - aux_attribs[ParsersAttributes::X_POS]=QString::number(pnt.x()); - aux_attribs[ParsersAttributes::Y_POS]=QString::number(pnt.y()); - aux_attribs[ParsersAttributes::REF_TYPE]=labels_attrs[id]; + aux_attribs[Attributes::XPos]=QString::number(pnt.x()); + aux_attribs[Attributes::YPos]=QString::number(pnt.y()); + aux_attribs[Attributes::RefType]=labels_attrs[id]; - aux_attribs[ParsersAttributes::POSITION]=schparser.getCodeDefinition(GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::XML_SCHEMA_DIR + GlobalAttributes::DIR_SEPARATOR + - ParsersAttributes::POSITION + GlobalAttributes::SCHEMA_EXT, aux_attribs); + aux_attribs[Attributes::Position]=schparser.getCodeDefinition(GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + GlobalAttributes::XMLSchemaDir + GlobalAttributes::DirSeparator + + Attributes::Position + GlobalAttributes::SchemaExt, aux_attribs); - attribs[ParsersAttributes::POSITION]+=schparser.getCodeDefinition(GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::XML_SCHEMA_DIR + GlobalAttributes::DIR_SEPARATOR + - ParsersAttributes::LABEL + GlobalAttributes::SCHEMA_EXT, aux_attribs); + attribs[Attributes::Position]+=schparser.getCodeDefinition(GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + GlobalAttributes::XMLSchemaDir + GlobalAttributes::DirSeparator + + Attributes::Label + GlobalAttributes::SchemaExt, aux_attribs); } } } @@ -9443,42 +10312,43 @@ void DatabaseModel::saveObjectsMetadata(const QString &filename, unsigned option if(save_custom_sql) { if(!object->getAppendedSQL().isEmpty()) - attribs[ParsersAttributes::APPENDED_SQL]=schparser.getCodeDefinition(GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::XML_SCHEMA_DIR + GlobalAttributes::DIR_SEPARATOR + - QString(ParsersAttributes::APPENDED_SQL).remove(QChar('-')) + GlobalAttributes::SCHEMA_EXT, attribs); + attribs[Attributes::AppendedSql]=schparser.getCodeDefinition(GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + GlobalAttributes::XMLSchemaDir + GlobalAttributes::DirSeparator + + QString(Attributes::AppendedSql).remove(QChar('-')) + GlobalAttributes::SchemaExt, attribs); if(!object->getPrependedSQL().isEmpty()) - attribs[ParsersAttributes::PREPENDED_SQL]=schparser.getCodeDefinition(GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::XML_SCHEMA_DIR + GlobalAttributes::DIR_SEPARATOR + - QString(ParsersAttributes::PREPENDED_SQL).remove(QChar('-')) + GlobalAttributes::SCHEMA_EXT, attribs); + attribs[Attributes::PrependedSql]=schparser.getCodeDefinition(GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + GlobalAttributes::XMLSchemaDir + GlobalAttributes::DirSeparator + + QString(Attributes::PrependedSql).remove(QChar('-')) + GlobalAttributes::SchemaExt, attribs); } /* The object's metadata code will be generated only if one of the key attributes for each option were filled previously. */ - if((save_db_attribs && obj_type==OBJ_DATABASE) || + if((save_db_attribs && obj_type==ObjectType::Database) || (save_custom_colors && - ((obj_type==OBJ_RELATIONSHIP || obj_type==BASE_RELATIONSHIP) || - (!attribs[ParsersAttributes::CUSTOM_COLOR].isEmpty()))) || + ((obj_type==ObjectType::Relationship || obj_type==ObjectType::BaseRelationship) || + (!attribs[Attributes::CustomColor].isEmpty()))) || (save_objs_pos && - (!attribs[ParsersAttributes::POSITION].isEmpty() || - !attribs[ParsersAttributes::RECT_VISIBLE].isEmpty())) || - (save_tags && !attribs[ParsersAttributes::TAG].isEmpty()) || - (save_objs_prot && !attribs[ParsersAttributes::PROTECTED].isEmpty()) || - (save_objs_sqldis && !attribs[ParsersAttributes::SQL_DISABLED].isEmpty()) || - (save_custom_sql && (!attribs[ParsersAttributes::APPENDED_SQL].isEmpty() || - !attribs[ParsersAttributes::PREPENDED_SQL].isEmpty())) || - (save_fadeout && !attribs[ParsersAttributes::FADED_OUT].isEmpty()) || - (save_extattribs && !attribs[ParsersAttributes::HIDE_EXT_ATTRIBS].isEmpty())) - { - emit s_objectLoaded(((idx++)/static_cast(objects.size()))*100, + (!attribs[Attributes::Position].isEmpty() || + !attribs[Attributes::RectVisible].isEmpty())) || + (save_tags && !attribs[Attributes::Tag].isEmpty()) || + (save_objs_prot && !attribs[Attributes::Protected].isEmpty()) || + (save_objs_sqldis && !attribs[Attributes::SqlDisabled].isEmpty()) || + (save_custom_sql && (!attribs[Attributes::AppendedSql].isEmpty() || + !attribs[Attributes::PrependedSql].isEmpty())) || + (save_fadeout && !attribs[Attributes::FadedOut].isEmpty()) || + (save_collapsemode && !attribs[Attributes::CollapseMode].isEmpty()) || + (save_objs_aliases && !attribs[Attributes::Alias].isEmpty())) + { + emit s_objectLoaded(((idx++)/static_cast(objects.size()))*100, trUtf8("Saving metadata of the object `%1' (%2)") - .arg(object->getSignature()).arg(object->getTypeName()), obj_type); + .arg(object->getSignature()).arg(object->getTypeName()), enum_cast(obj_type)); schparser.ignoreUnkownAttributes(true); objs_def+=schparser.convertCharsToXMLEntities( - schparser.getCodeDefinition(GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::XML_SCHEMA_DIR + GlobalAttributes::DIR_SEPARATOR + - ParsersAttributes::INFO + GlobalAttributes::SCHEMA_EXT, attribs)); + schparser.getCodeDefinition(GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + GlobalAttributes::XMLSchemaDir + GlobalAttributes::DirSeparator + + Attributes::Info + GlobalAttributes::SchemaExt, attribs)); } else idx++; @@ -9489,80 +10359,80 @@ void DatabaseModel::saveObjectsMetadata(const QString &filename, unsigned option if(!objs_def.isEmpty()) { //Generates the metadata XML buffer - attribs[ParsersAttributes::INFO]=objs_def; - buf.append(schparser.getCodeDefinition(GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::XML_SCHEMA_DIR + GlobalAttributes::DIR_SEPARATOR + - ParsersAttributes::METADATA + GlobalAttributes::SCHEMA_EXT, attribs)); + attribs[Attributes::Info]=objs_def; + buf.append(schparser.getCodeDefinition(GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + GlobalAttributes::XMLSchemaDir + GlobalAttributes::DirSeparator + + Attributes::Metadata + GlobalAttributes::SchemaExt, attribs)); output.write(buf.data(),buf.size()); - emit s_objectLoaded(100, trUtf8("Metadata file successfully saved!"), BASE_OBJECT); + emit s_objectLoaded(100, trUtf8("Metadata file successfully saved!"), enum_cast(ObjectType::BaseObject)); } else - emit s_objectLoaded(100, trUtf8("Process successfully ended but no metadata was saved!"), BASE_OBJECT); + emit s_objectLoaded(100, trUtf8("Process successfully ended but no metadata was saved!"), enum_cast(ObjectType::BaseObject)); output.close(); } catch(Exception &e) { if(output.isOpen()) output.close(); - throw Exception(Exception::getErrorMessage(ERR_FILE_NOT_WRITTER_INV_DEF).arg(filename), - ERR_FILE_NOT_WRITTER_INV_DEF,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(Exception::getErrorMessage(ErrorCode::FileNotWrittenInvalidDefinition).arg(filename), + ErrorCode::FileNotWrittenInvalidDefinition,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void DatabaseModel::loadObjectsMetadata(const QString &filename, unsigned options) { QString elem_name, aux_elem, obj_name, ref_type, - dtd_file=GlobalAttributes::SCHEMAS_ROOT_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::XML_SCHEMA_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::OBJECT_DTD_DIR + - GlobalAttributes::DIR_SEPARATOR; + dtd_file=GlobalAttributes::SchemasRootDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::XMLSchemaDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::ObjectDTDDir + + GlobalAttributes::DirSeparator; attribs_map attribs, aux_attrib; ObjectType obj_type; BaseObject *object=nullptr, *new_object=nullptr; BaseTable *src_tab=nullptr, *dst_tab=nullptr, *base_tab=nullptr; vector points; map labels_attrs; - vector labels_pos={ QPointF(NAN,NAN), QPointF(NAN,NAN), QPointF(NAN,NAN) }; + vector labels_pos={ QPointF(DNaN,DNaN), QPointF(DNaN,DNaN), QPointF(DNaN,DNaN) }; BaseRelationship *rel=nullptr; Schema *schema=nullptr; Tag *tag=nullptr; - QPointF pnt; int progress=0; bool load_db_attribs=false, load_objs_pos=false, load_objs_prot=false, load_objs_sqldis=false, load_textboxes=false, load_tags=false, load_custom_sql=false, load_custom_colors=false, load_fadeout=false, - load_extattribs=false, load_genericsqls=false; - - load_db_attribs=(META_DB_ATTRIBUTES & options) == META_DB_ATTRIBUTES; - load_objs_pos=(META_OBJS_POSITIONING & options) == META_OBJS_POSITIONING; - load_objs_prot=(META_OBJS_PROTECTION & options) == META_OBJS_PROTECTION; - load_objs_sqldis=(META_OBJS_SQLDISABLED & options) == META_OBJS_SQLDISABLED; - load_textboxes=(META_TEXTBOX_OBJS & options) == META_TEXTBOX_OBJS; - load_tags=(META_TAG_OBJS & options) == META_TAG_OBJS; - load_custom_sql=(META_OBJS_CUSTOMSQL & options) == META_OBJS_CUSTOMSQL; - load_custom_colors=(META_OBJS_CUSTOMCOLORS & options) == META_OBJS_CUSTOMCOLORS; - load_fadeout=(META_OBJS_FADEDOUT & options) == META_OBJS_FADEDOUT; - load_extattribs=(META_OBJS_EXTATTRIBS & options) == META_OBJS_EXTATTRIBS; - load_genericsqls=(META_GENERIC_SQL_OBJS & options) == META_GENERIC_SQL_OBJS; + load_collapse_mode=false, load_genericsqls=false, load_objs_aliases=false; + + load_db_attribs=(MetaDbAttributes & options) == MetaDbAttributes; + load_objs_pos=(MetaObjsPositioning & options) == MetaObjsPositioning; + load_objs_prot=(MetaObjsProtection & options) == MetaObjsProtection; + load_objs_sqldis=(MetaObjsSqlDisabled & options) == MetaObjsSqlDisabled; + load_textboxes=(MetaTextboxObjs & options) == MetaTextboxObjs; + load_tags=(MetaTagObjs & options) == MetaTagObjs; + load_custom_sql=(MetaObjsCustomSql & options) == MetaObjsCustomSql; + load_custom_colors=(MetaObjsCustomColors & options) == MetaObjsCustomColors; + load_fadeout=(MetaObjsFadeOut & options) == MetaObjsFadeOut; + load_collapse_mode=(MetaObjsCollapseMode & options) == MetaObjsCollapseMode; + load_genericsqls=(MetaGenericSqlObjs & options) == MetaGenericSqlObjs; + load_objs_aliases=(MetaObjsAliases & options) == MetaObjsAliases; try { - labels_attrs[ParsersAttributes::SRC_LABEL]=BaseRelationship::SRC_CARD_LABEL; - labels_attrs[ParsersAttributes::DST_LABEL]=BaseRelationship::DST_CARD_LABEL; - labels_attrs[ParsersAttributes::NAME_LABEL]=BaseRelationship::REL_NAME_LABEL; + labels_attrs[Attributes::SrcLabel]=BaseRelationship::SrcCardLabel; + labels_attrs[Attributes::DstLabel]=BaseRelationship::DstCardLabel; + labels_attrs[Attributes::NameLabel]=BaseRelationship::RelNameLabel; xmlparser.restartParser(); - xmlparser.setDTDFile(dtd_file + GlobalAttributes::METADATA_DTD + - GlobalAttributes::OBJECT_DTD_EXT, - GlobalAttributes::METADATA_DTD); + xmlparser.setDTDFile(dtd_file + GlobalAttributes::MetadataDTD + + GlobalAttributes::ObjectDTDExt, + GlobalAttributes::MetadataDTD); xmlparser.loadXMLFile(filename); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -9570,9 +10440,9 @@ void DatabaseModel::loadObjectsMetadata(const QString &filename, unsigned option { elem_name=xmlparser.getElementName(); - if((elem_name==BaseObject::getSchemaName(OBJ_TAG) && load_tags) || - (elem_name==BaseObject::getSchemaName(OBJ_TEXTBOX) && load_textboxes) || - (elem_name==BaseObject::getSchemaName(OBJ_GENERIC_SQL) && load_genericsqls)) + if((elem_name==BaseObject::getSchemaName(ObjectType::Tag) && load_tags) || + (elem_name==BaseObject::getSchemaName(ObjectType::Textbox) && load_textboxes) || + (elem_name==BaseObject::getSchemaName(ObjectType::GenericSql) && load_genericsqls)) { xmlparser.savePosition(); obj_type=BaseObject::getObjectType(elem_name); @@ -9581,93 +10451,110 @@ void DatabaseModel::loadObjectsMetadata(const QString &filename, unsigned option if(getObjectIndex(new_object->getName(), obj_type) < 0) { emit s_objectLoaded(progress, trUtf8("Creating object `%1' (%2)") - .arg(new_object->getName()).arg(new_object->getTypeName()), obj_type); + .arg(new_object->getName()).arg(new_object->getTypeName()), enum_cast(obj_type)); addObject(new_object); } else { emit s_objectLoaded(progress, trUtf8("Object `%1' (%2) already exists. Ignoring.") - .arg(new_object->getName()).arg(new_object->getTypeName()), BASE_OBJECT); + .arg(new_object->getName()).arg(new_object->getTypeName()), enum_cast(ObjectType::BaseObject)); delete(new_object); } new_object=nullptr; xmlparser.restorePosition(); } - else if(elem_name==ParsersAttributes::INFO) + else if(elem_name==Attributes::Info) { xmlparser.getElementAttributes(attribs); - obj_name=attribs[ParsersAttributes::OBJECT]; + obj_name=attribs[Attributes::Object]; xmlparser.savePosition(); - obj_type=BaseObject::getObjectType(attribs[ParsersAttributes::TYPE]); - progress=xmlparser.getCurrentBufferLine()/static_cast(xmlparser.getBufferLineCount()) * 100; + obj_type=BaseObject::getObjectType(attribs[Attributes::Type]); + progress=xmlparser.getCurrentBufferLine()/static_cast(xmlparser.getBufferLineCount()) * 100; - if(obj_type==OBJ_DATABASE) + if(obj_type==ObjectType::Database) { if(load_db_attribs) { - QStringList pos=attribs[ParsersAttributes::LAST_POSITION].split(','); + QStringList pos=attribs[Attributes::LastPosition].split(','); - default_objs[OBJ_SCHEMA]=getSchema(attribs[ParsersAttributes::DEFAULT_SCHEMA]); - default_objs[OBJ_ROLE]=getRole(attribs[ParsersAttributes::DEFAULT_OWNER]); - default_objs[OBJ_COLLATION]=getCollation(attribs[ParsersAttributes::DEFAULT_COLLATION]); - default_objs[OBJ_TABLESPACE]=getTablespace(attribs[ParsersAttributes::DEFAULT_TABLESPACE]); - author=attribs[ParsersAttributes::MODEL_AUTHOR]; - last_zoom=attribs[ParsersAttributes::LAST_ZOOM].toFloat(); + default_objs[ObjectType::Schema]=getSchema(attribs[Attributes::DefaultSchema]); + default_objs[ObjectType::Role]=getRole(attribs[Attributes::DefaultOwner]); + default_objs[ObjectType::Collation]=getCollation(attribs[Attributes::DefaultCollation]); + default_objs[ObjectType::Tablespace]=getTablespace(attribs[Attributes::DefaultTablespace]); + author=attribs[Attributes::ModelAuthor]; + last_zoom=attribs[Attributes::LastZoom].toDouble(); if(pos.size()>=2) - last_pos=QPoint(pos[0].toFloat(), pos[1].toFloat()); + last_pos=QPoint(pos[0].toInt(), pos[1].toInt()); } object=this; } + else if(TableObject::isTableObject(obj_type)) + { + base_tab = getTable(attribs[Attributes::Table]); + + if(!base_tab && (obj_type == ObjectType::Rule || obj_type == ObjectType::Index || obj_type == ObjectType::Trigger)) + base_tab = getView(attribs[Attributes::Table]); + + if(base_tab) + object = base_tab->getObject(attribs[Attributes::Object], obj_type); + + //Discarding the object if it was added by relationship + if(object && dynamic_cast(object)->isAddedByRelationship()) + object = nullptr; + } else object=getObject(obj_name, obj_type); /* If the object does not exists but it is a relationship, we try to get the relationship involving the tables in paramenters src-table and dst-table */ - if(!object && obj_type==OBJ_RELATIONSHIP) + if(!object && obj_type==ObjectType::Relationship) { - src_tab=dynamic_cast(getObject(attribs[ParsersAttributes::SRC_TABLE], - BaseObject::getObjectType(attribs[ParsersAttributes::SRC_TYPE]))); - dst_tab=dynamic_cast(getObject(attribs[ParsersAttributes::DST_TABLE], - BaseObject::getObjectType(attribs[ParsersAttributes::DST_TYPE]))); + src_tab=dynamic_cast(getObject(attribs[Attributes::SrcTable], + BaseObject::getObjectType(attribs[Attributes::SrcType]))); + dst_tab=dynamic_cast(getObject(attribs[Attributes::DstTable], + BaseObject::getObjectType(attribs[Attributes::DstType]))); object=getRelationship(src_tab, dst_tab); } if(object) { emit s_objectLoaded(progress, trUtf8("Loading metadata for object `%1' (%2)") - .arg(object->getName()).arg(object->getTypeName()), obj_type); + .arg(object->getName()).arg(object->getTypeName()), enum_cast(obj_type)); if(!object->isSystemObject() && - ((!attribs[ParsersAttributes::PROTECTED].isEmpty() && load_objs_prot) || - (!attribs[ParsersAttributes::SQL_DISABLED].isEmpty() && load_objs_sqldis))) + ((!attribs[Attributes::Protected].isEmpty() && load_objs_prot) || + (!attribs[Attributes::SqlDisabled].isEmpty() && load_objs_sqldis))) { - if(!attribs[ParsersAttributes::PROTECTED].isEmpty()) - object->setProtected(attribs[ParsersAttributes::PROTECTED]==ParsersAttributes::_TRUE_); + if(!attribs[Attributes::Protected].isEmpty()) + object->setProtected(attribs[Attributes::Protected]==Attributes::True); - if(!attribs[ParsersAttributes::SQL_DISABLED].isEmpty()) - object->setSQLDisabled(attribs[ParsersAttributes::SQL_DISABLED]==ParsersAttributes::_TRUE_); + if(!attribs[Attributes::SqlDisabled].isEmpty()) + object->setSQLDisabled(attribs[Attributes::SqlDisabled]==Attributes::True); } - else if((obj_type==OBJ_TABLE || obj_type==OBJ_VIEW) && load_tags && !attribs[ParsersAttributes::TAG].isEmpty()) + else if((obj_type==ObjectType::Table || obj_type==ObjectType::View) && load_tags && !attribs[Attributes::Tag].isEmpty()) { - tag=getTag(attribs[ParsersAttributes::TAG]); + tag=getTag(attribs[Attributes::Tag]); if(tag) dynamic_cast(object)->setTag(tag); } - else if(obj_type==OBJ_DATABASE && load_custom_sql) + else if(obj_type==ObjectType::Database && load_custom_sql) { - if(!attribs[ParsersAttributes::APPEND_AT_EOD].isEmpty()) - this->setAppendAtEOD(attribs[ParsersAttributes::APPEND_AT_EOD]==ParsersAttributes::_TRUE_); + if(!attribs[Attributes::AppendAtEod].isEmpty()) + this->setAppendAtEOD(attribs[Attributes::AppendAtEod]==Attributes::True); - if(!attribs[ParsersAttributes::PREPEND_AT_BOD].isEmpty()) - this->setPrependAtBOD(attribs[ParsersAttributes::PREPEND_AT_BOD]==ParsersAttributes::_TRUE_); + if(!attribs[Attributes::PrependAtBod].isEmpty()) + this->setPrependAtBOD(attribs[Attributes::PrependAtBod]==Attributes::True); } - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(load_objs_aliases && !attribs[Attributes::Alias].isEmpty()) + object->setAlias(attribs[Attributes::Alias]); + + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -9675,44 +10562,44 @@ void DatabaseModel::loadObjectsMetadata(const QString &filename, unsigned option xmlparser.getElementAttributes(aux_attrib); //Retrieving and storing the points - if(aux_elem==ParsersAttributes::POSITION) + if(aux_elem==Attributes::Position) { - points.push_back(QPointF(aux_attrib[ParsersAttributes::X_POS].toFloat(), - aux_attrib[ParsersAttributes::Y_POS].toFloat())); + points.push_back(QPointF(aux_attrib[Attributes::XPos].toDouble(), + aux_attrib[Attributes::YPos].toDouble())); } //Retrieving and storing the labels' custom positions - else if(aux_elem==ParsersAttributes::LABEL) + else if(aux_elem==Attributes::Label) { - ref_type=aux_attrib[ParsersAttributes::REF_TYPE]; + ref_type=aux_attrib[Attributes::RefType]; xmlparser.savePosition(); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { xmlparser.getElementAttributes(aux_attrib); - labels_pos[labels_attrs[ref_type]]=QPointF(aux_attrib[ParsersAttributes::X_POS].toFloat(), - aux_attrib[ParsersAttributes::Y_POS].toFloat()); + labels_pos[labels_attrs[ref_type]]=QPointF(aux_attrib[Attributes::XPos].toDouble(), + aux_attrib[Attributes::YPos].toDouble()); } xmlparser.restorePosition(); } - else if(load_custom_sql && aux_elem==ParsersAttributes::APPENDED_SQL && - attribs[ParsersAttributes::APPENDED_SQL].isEmpty()) + else if(load_custom_sql && aux_elem==Attributes::AppendedSql && + attribs[Attributes::AppendedSql].isEmpty()) { xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); object->setAppendedSQL(xmlparser.getElementContent()); xmlparser.restorePosition(); } - else if(load_custom_sql && aux_elem==ParsersAttributes::PREPENDED_SQL && - attribs[ParsersAttributes::PREPENDED_SQL].isEmpty()) + else if(load_custom_sql && aux_elem==Attributes::PrependedSql && + attribs[Attributes::PrependedSql].isEmpty()) { xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); object->setPrependedSQL(xmlparser.getElementContent()); xmlparser.restorePosition(); } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } if(BaseGraphicObject::isGraphicObject(obj_type)) @@ -9727,36 +10614,36 @@ void DatabaseModel::loadObjectsMetadata(const QString &filename, unsigned option { if(load_custom_colors) { - if(attribs[ParsersAttributes::CUSTOM_COLOR]==ParsersAttributes::NONE) + if(attribs[Attributes::CustomColor]==Attributes::None) rel->setCustomColor(Qt::transparent); else - rel->setCustomColor(QColor(attribs[ParsersAttributes::CUSTOM_COLOR])); + rel->setCustomColor(QColor(attribs[Attributes::CustomColor])); } if(load_objs_pos) { rel->setPoints(points); - for(unsigned id=BaseRelationship::SRC_CARD_LABEL; id <= BaseRelationship::REL_NAME_LABEL; id++) + for(unsigned id=BaseRelationship::SrcCardLabel; id <= BaseRelationship::RelNameLabel; id++) { rel->setLabelDistance(id, labels_pos[id]); - labels_pos[id]=QPointF(NAN,NAN); + labels_pos[id]=QPointF(DNaN, DNaN); } } } else if(schema) { if(load_custom_colors) - schema->setFillColor(QColor(attribs[ParsersAttributes::CUSTOM_COLOR])); + schema->setFillColor(QColor(attribs[Attributes::CustomColor])); - schema->setRectVisible(attribs[ParsersAttributes::RECT_VISIBLE]==ParsersAttributes::_TRUE_); + schema->setRectVisible(attribs[Attributes::RectVisible]==Attributes::True); } if(load_fadeout) - dynamic_cast(object)->setFadedOut(attribs[ParsersAttributes::FADED_OUT]==ParsersAttributes::_TRUE_); + dynamic_cast(object)->setFadedOut(attribs[Attributes::FadedOut]==Attributes::True); - if(load_extattribs && base_tab) - base_tab->setExtAttribsHidden(attribs[ParsersAttributes::HIDE_EXT_ATTRIBS]==ParsersAttributes::_TRUE_); + if(load_collapse_mode && base_tab) + base_tab->setCollapseMode(static_cast(attribs[Attributes::CollapseMode].toUInt())); } points.clear(); @@ -9765,7 +10652,7 @@ void DatabaseModel::loadObjectsMetadata(const QString &filename, unsigned option else if(!object) { emit s_objectLoaded(progress, trUtf8("Object `%1' (%2) not found. Ignoring metadata.") - .arg(obj_name).arg(BaseObject::getTypeName(obj_type)), BASE_OBJECT); + .arg(obj_name).arg(BaseObject::getTypeName(obj_type)), enum_cast(ObjectType::BaseObject)); } xmlparser.restorePosition(); @@ -9773,10 +10660,10 @@ void DatabaseModel::loadObjectsMetadata(const QString &filename, unsigned option } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } - emit s_objectLoaded(100, trUtf8("Metadata file successfully loaded!"), BASE_OBJECT); + emit s_objectLoaded(100, trUtf8("Metadata file successfully loaded!"), enum_cast(ObjectType::BaseObject)); setObjectsModified(); } catch(Exception &e) @@ -9786,6 +10673,26 @@ void DatabaseModel::loadObjectsMetadata(const QString &filename, unsigned option if(xmlparser.getCurrentElement()) extra_info=QString(QObject::trUtf8("%1 (line: %2)")).arg(xmlparser.getLoadedFilename()).arg(xmlparser.getCurrentElement()->line); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, extra_info); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, extra_info); } } + +void DatabaseModel::setLayers(const QStringList &layers) +{ + this->layers = layers; +} + +QStringList DatabaseModel::getLayers(void) +{ + return(layers); +} + +void DatabaseModel::setActiveLayers(const QList &layers) +{ + active_layers = layers; +} + +QList DatabaseModel::getActiveLayers(void) +{ + return(active_layers); +} diff --git a/libpgmodeler/src/databasemodel.h b/libpgmodeler/src/databasemodel.h index 11406b0ad2..184bd7f24a 100644 --- a/libpgmodeler/src/databasemodel.h +++ b/libpgmodeler/src/databasemodel.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -54,6 +54,9 @@ Additionally, this class, saves, loads and generates the XML/SQL definition of a #include "tag.h" #include "eventtrigger.h" #include "genericsql.h" +#include "foreigndatawrapper.h" +#include "foreignserver.h" +#include "usermapping.h" #include #include @@ -63,9 +66,18 @@ class DatabaseModel: public QObject, public BaseObject { private: Q_OBJECT + /*! \brief Stores the references of all object lists of each type. This map is used by getObjectList() in order + * to return the list according to the provided type */ + map *> obj_lists; + static unsigned dbmodel_id; - XMLParser xmlparser; + XmlParser xmlparser; + + //! \brief Stores the layers names and active layer to write them on XML code + QStringList layers; + + QList active_layers; //! \brief Stores the model widget that is managing this database model instance ModelWidget *model_wgt; @@ -82,6 +94,7 @@ class DatabaseModel: public QObject, public BaseObject { //! \brief Database localizations (LC_CTYPE, LC_COLLATE) localizations[2]; + //! \brief Stores the objects of each type that are considered the default ones associated to new objects map default_objs; //! \brief Maximum number of connections @@ -94,31 +107,34 @@ class DatabaseModel: public QObject, public BaseObject { allow_conns; //! \brief Vectors that stores all the objects types - vector textboxes; - vector relationships; - vector base_relationships; - vector functions; - vector schemas; - vector views; - vector tables; - vector types; - vector roles; - vector tablespaces; - vector languages; - vector aggregates; - vector casts; - vector conversions; - vector operators; - vector op_classes; - vector op_families; - vector domains; - vector sequences; - vector permissions; - vector collations; - vector extensions; - vector tags; - vector eventtriggers; - vector genericsqls; + vector textboxes, + relationships, + base_relationships, + functions, + schemas, + views, + tables, + types, + roles, + tablespaces, + languages, + aggregates, + casts, + conversions, + operators, + op_classes, + op_families, + domains, + sequences, + permissions, + collations, + extensions, + tags, + eventtriggers, + genericsqls, + fdata_wrappers, + foreign_servers, + usermappings; /*! \brief Stores the xml definition for special objects. This map is used when revalidating the relationships */ @@ -161,7 +177,7 @@ class DatabaseModel: public QObject, public BaseObject { /*! \brief Returns the object on the model that represents the base pgsql type. The possible returned object can be: table, sequence, domain or type */ - BaseObject *getObjectPgSQLType(PgSQLType type); + BaseObject *getObjectPgSQLType(PgSqlType type); //! \brief Creates a IndexElement or ExcludeElement from XML depending on type of the 'elem' param. void createElement(Element &elem, TableObject *tab_obj, BaseObject *parent_obj); @@ -169,19 +185,36 @@ class DatabaseModel: public QObject, public BaseObject { //! \brief Returns extra error info when loading database models QString getErrorExtraInfo(void); + /*! \brief This method forces the indication that the model is being loaded or not by setting the attribute loading_model. + * The attribute loading_model causes the model perform certain operations only when model starts/ends the loading process, + * for instance, if loading_model = true graphical objects will be rendered only when the loading process finishes (loading_model =false) + * otherwise the objects are rendered as they are added to the model. The drawback of this approach is, depending on the operation being used after + * calling this method, the user is obligated to call the methdo setObjectsModified() to force the graphical objects rendering. */ + void setLoadingModel(bool value); + + //! \brief Set the initial capacity of the objects list for a optimized memory usage + void setObjectListsCapacity(unsigned capacity); + + protected: + void setLayers(const QStringList &layers); + void setActiveLayers(const QList &layers); + QStringList getLayers(void); + QList getActiveLayers(void); + public: - static const unsigned META_DB_ATTRIBUTES=1, //! \brief Handle database model attribute when save/load metadata file - META_OBJS_POSITIONING=2, //! \brief Handle objects' positioning when save/load metadata file - META_OBJS_PROTECTION=4, //! \brief Handle objects' protection status when save/load metadata file - META_OBJS_SQLDISABLED=8, //! \brief Handle objects' sql disabled status when save/load metadata file - META_OBJS_CUSTOMSQL=16, //! \brief Handle object's custom sql when save/load metadata file - META_OBJS_CUSTOMCOLORS=32, //! \brief Handle object's custom colors when save/load metadata file - META_OBJS_FADEDOUT=64, //! \brief Handle graphical object's fade out status when save/load metadata file - META_OBJS_EXTATTRIBS=128, //! \brief Handle tables and views extended attributes display when save/load metadata file - META_TEXTBOX_OBJS=256, //! \brief Handle textboxes object when save/load metadata file - META_TAG_OBJS=512, //! \brief Handle tags object when save/load metadata file - META_GENERIC_SQL_OBJS=1024, //! \brief Handle generic sql object when save/load metadata file - META_ALL_INFO=2047; //! \brief Handle all metadata information about objects when save/load metadata file + static constexpr unsigned MetaDbAttributes=1, //! \brief Handle database model attribute when save/load metadata file + MetaObjsPositioning=2, //! \brief Handle objects' positioning when save/load metadata file + MetaObjsProtection=4, //! \brief Handle objects' protection status when save/load metadata file + MetaObjsSqlDisabled=8, //! \brief Handle objects' sql disabled status when save/load metadata file + MetaObjsCustomSql=16, //! \brief Handle object's custom sql when save/load metadata file + MetaObjsCustomColors=32, //! \brief Handle object's custom colors when save/load metadata file + MetaObjsFadeOut=64, //! \brief Handle graphical object's fade out status when save/load metadata file + MetaObjsCollapseMode=128, //! \brief Handle tables and views collapse mode when save/load metadata file + MetaTextboxObjs=256, //! \brief Handle textboxes object when save/load metadata file + MetaTagObjs=512, //! \brief Handle tags object when save/load metadata file + MetaGenericSqlObjs=1024, //! \brief Handle generic sql object when save/load metadata file + MetaObjsAliases=2048, //! \brief Handle the object's aliases (graphical objects and table children objects) when save/load metadata file + MetaAllInfo=4095; //! \brief Handle all metadata information about objects when save/load metadata file DatabaseModel(void); @@ -231,8 +264,8 @@ class DatabaseModel: public QObject, public BaseObject { BaseObject *getObject(unsigned obj_idx, ObjectType obj_type); /*! \brief Loads a database model from a file. In case of loading errors - the objects in the model will not be destroyed automatically. The user need to call - destroyObjects() or delete the entire model */ + the objects in the model will not be destroyed automatically. The user need to call + destroyObjects() or delete the entire model */ void loadModel(const QString &filename); //! \brief Sets the database encoding @@ -259,7 +292,7 @@ class DatabaseModel: public QObject, public BaseObject { //! \brief Sets the sql prepeding at beginning of entire model definition void setPrependAtBOD(bool value); - void setDefaultObject(BaseObject *object, ObjectType obj_type=BASE_OBJECT); + void setDefaultObject(BaseObject *object, ObjectType obj_type=ObjectType::BaseObject); void setIsTemplate(bool value); @@ -281,9 +314,11 @@ class DatabaseModel: public QObject, public BaseObject { //! \brief Returns the object count for the specified type unsigned getObjectCount(ObjectType obj_type); - //! \brief Returns the object count for all object types + //! \brief Returns the object count for all object types. unsigned getObjectCount(void); + unsigned getMaxObjectCount(void); + //! \brief Retuns the specified localization value QString getLocalization(unsigned localiz_id); @@ -462,6 +497,21 @@ class DatabaseModel: public QObject, public BaseObject { GenericSQL *getGenericSQL(unsigned obj_idx); GenericSQL *getGenericSQL(const QString &name); + void addForeignDataWrapper(ForeignDataWrapper *fdata_wrapper, int obj_idx=-1); + void removeForeignDataWrapper(ForeignDataWrapper *fdata_wrapper, int obj_idx=-1); + ForeignDataWrapper *getForeignDataWrapper(unsigned obj_idx); + ForeignDataWrapper *getForeignDataWrapper(const QString &name); + + void addForeignServer(ForeignServer *server, int obj_idx=-1); + void removeForeignServer(ForeignServer *server, int obj_idx=-1); + ForeignServer *getForeignServer(unsigned obj_idx); + ForeignServer *getForeignServer(const QString &name); + + void addUserMapping(UserMapping *usrmap, int obj_idx=-1); + void removeUserMapping(UserMapping *usrmap, int obj_idx=-1); + UserMapping *getUserMapping(unsigned obj_idx); + UserMapping *getUserMapping(const QString &name); + void addPermission(Permission *perm); void removePermission(Permission *perm); @@ -486,7 +536,7 @@ class DatabaseModel: public QObject, public BaseObject { void setBasicAttributes(BaseObject *object); void configureDatabase(attribs_map &attribs); - PgSQLType createPgSQLType(void); + PgSqlType createPgSQLType(void); BaseObject *createObject(ObjectType obj_type); Role *createRole(void); Tablespace *createTablespace(void); @@ -520,6 +570,12 @@ class DatabaseModel: public QObject, public BaseObject { Policy *createPolicy(void); EventTrigger *createEventTrigger(void); GenericSQL *createGenericSQL(void); + ForeignDataWrapper *createForeignDataWrapper(void); + ForeignServer *createForeignServer(void); + UserMapping *createUserMapping(void); + + //! \brief Update views that reference the provided table forcing the column name deduction and redraw of the former objects + void updateViewsReferencingTable(Table *table); //! \brief Creates/removes the relationship between the passed view and the referecend tables void updateViewRelationships(View *view, bool force_rel_removal=false); @@ -561,10 +617,13 @@ class DatabaseModel: public QObject, public BaseObject { meaning that ALL objects directly or inderectly linked to the 'object' are retrieved. */ void __getObjectReferences(BaseObject *object, vector &refs, bool exclude_perms=false); - /*! \brief Marks the graphical objects as modified forcing their redraw. User can specify only a set of + /*! \brief Marks the graphical objects of the provided types as modified forcing their redraw. User can specify only a set of graphical objects to be marked */ void setObjectsModified(vector types={}); + //! \brief Marks the graphical objects in the list as modified forcing their redraw. + void setObjectsModified(vector &objects); + /*! \brief Marks the objects with code invalidated forcing their code regeneration. User can specify only a set of graphical objects to be marked */ void setCodesInvalidated(vector types={}); @@ -580,8 +639,9 @@ class DatabaseModel: public QObject, public BaseObject { /*! \brief Returns a list of object searching them using the specified pattern. The search can be delimited by filtering the object's types. The additional bool params are: case sensitive name search, name pattern is a regexp, exact match for names. */ - vector findObjects(const QString &pattern, vector types, bool format_obj_names, - bool case_sensitive, bool is_regexp, bool exact_match); + vector findObjects(const QString &pattern, vector types, + bool case_sensitive, bool is_regexp, bool exact_match, + const QString &search_attr = Attributes::Name); void setLastPosition(const QPoint &pnt); QPoint getLastPosition(void); @@ -594,17 +654,17 @@ class DatabaseModel: public QObject, public BaseObject { the create* method. \note: This is not the better approach and certainly will be changed in future releases */ - XMLParser *getXMLParser(void); + XmlParser *getXMLParser(void); //! \brief Returns the ALTER definition between the current model and the provided one virtual QString getAlterDefinition(BaseObject *object) final; /*! \brief Save the graphical objects positions, custom colors and custom points (for relationship lines) to an special file that can be loaded by another model in order to change their objects position */ - void saveObjectsMetadata(const QString &filename, unsigned options=META_ALL_INFO); + void saveObjectsMetadata(const QString &filename, unsigned options=MetaAllInfo); //! \brief Load the file containing the objects positioning to be applied to the model - void loadObjectsMetadata(const QString &filename, unsigned options=META_ALL_INFO); + void loadObjectsMetadata(const QString &filename, unsigned options=MetaAllInfo); signals: //! \brief Signal emitted when a new object is added to the model @@ -615,6 +675,10 @@ class DatabaseModel: public QObject, public BaseObject { //! \brief Signal emitted when an object is created from a xml code void s_objectLoaded(int progress, QString object_id, unsigned obj_type); + + friend class DatabaseImportHelper; + friend class ModelWidget; + friend class PgModelerCli; }; #endif diff --git a/libpgmodeler/src/domain.cpp b/libpgmodeler/src/domain.cpp index fe5672dc5c..33900ef74f 100644 --- a/libpgmodeler/src/domain.cpp +++ b/libpgmodeler/src/domain.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,31 +20,31 @@ Domain::Domain(void) { - obj_type=OBJ_DOMAIN; + obj_type=ObjectType::Domain; not_null=false; - attributes[ParsersAttributes::DEFAULT_VALUE]=QString(); - attributes[ParsersAttributes::NOT_NULL]=QString(); - attributes[ParsersAttributes::TYPE]=QString(); - attributes[ParsersAttributes::CONSTRAINTS]=QString(); + attributes[Attributes::DefaultValue]=QString(); + attributes[Attributes::NotNull]=QString(); + attributes[Attributes::Type]=QString(); + attributes[Attributes::Constraints]=QString(); } void Domain::addCheckConstraint(const QString &name, const QString &expr) { //Raises an error if the constraint name is invalid if(!name.isEmpty() && !BaseObject::isValidName(name)) - throw Exception(ERR_ASG_INV_NAME_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidNameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); if(expr.isEmpty()) - throw Exception(ERR_ASG_INV_EXPR_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidExpressionObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); if(chk_constrs.count(name)) { - throw Exception(QString(Exception::getErrorMessage(ERR_ASG_DUPLIC_OBJECT)) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgDuplicatedObject) .arg(name) - .arg(BaseObject::getTypeName(OBJ_CONSTRAINT)) + .arg(BaseObject::getTypeName(ObjectType::Constraint)) .arg(this->getName(true)) .arg(this->getTypeName()), - ERR_ASG_DUPLIC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgDuplicatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); } chk_constrs[name] = expr; @@ -70,7 +70,7 @@ void Domain::setName(const QString &name) new_name=this->getName(true); //Renames the PostgreSQL type represented by the domain - PgSQLType::renameUserType(prev_name, this, new_name); + PgSqlType::renameUserType(prev_name, this, new_name); } void Domain::setSchema(BaseObject *schema) @@ -81,7 +81,7 @@ void Domain::setSchema(BaseObject *schema) BaseObject::setSchema(schema); //Renames the PostgreSQL type represented by the domain - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } void Domain::setDefaultValue(const QString &default_val) @@ -98,7 +98,7 @@ void Domain::setNotNull(bool value) not_null=value; } -void Domain::setType(PgSQLType type) +void Domain::setType(PgSqlType type) { setCodeInvalidated(this->type != type); this->type=type; @@ -114,7 +114,7 @@ bool Domain::isNotNull(void) return(not_null); } -PgSQLType Domain::getType(void) +PgSqlType Domain::getType(void) { return(type); } @@ -126,20 +126,20 @@ QString Domain::getCodeDefinition(unsigned def_type) attribs_map aux_attribs; - attributes[ParsersAttributes::NOT_NULL]=(not_null ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::DEFAULT_VALUE]=default_value; + attributes[Attributes::NotNull]=(not_null ? Attributes::True : QString()); + attributes[Attributes::DefaultValue]=default_value; for(auto itr : chk_constrs) { - aux_attribs[ParsersAttributes::NAME] = itr.first; - aux_attribs[ParsersAttributes::EXPRESSION] = itr.second; - attributes[ParsersAttributes::CONSTRAINTS]+=schparser.getCodeDefinition(ParsersAttributes::DOM_CONSTRAINT, aux_attribs, def_type); + aux_attribs[Attributes::Name] = itr.first; + aux_attribs[Attributes::Expression] = itr.second; + attributes[Attributes::Constraints]+=schparser.getCodeDefinition(Attributes::DomConstraint, aux_attribs, def_type); } - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::TYPE]=(*type); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Type]=(*type); else - attributes[ParsersAttributes::TYPE]=type.getCodeDefinition(def_type); + attributes[Attributes::Type]=type.getCodeDefinition(def_type); return(BaseObject::__getCodeDefinition(def_type)); } @@ -153,7 +153,7 @@ void Domain::operator = (Domain &domain) this->default_value=domain.default_value; this->type=domain.type; this->chk_constrs=domain.chk_constrs; - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } QString Domain::getAlterDefinition(BaseObject *object) @@ -161,7 +161,7 @@ QString Domain::getAlterDefinition(BaseObject *object) Domain *domain=dynamic_cast(object); if(!domain) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { @@ -169,23 +169,23 @@ QString Domain::getAlterDefinition(BaseObject *object) attribs_map orig_constrs, aux_constrs, aux_attribs; QString orig_expr, aux_expr; - attributes[ParsersAttributes::DEFAULT_VALUE]=QString(); - attributes[ParsersAttributes::NOT_NULL]=QString(); - attributes[ParsersAttributes::CONSTRAINTS]=QString(); - attributes[ParsersAttributes::EXPRESSION]=QString(); - attributes[ParsersAttributes::OLD_NAME]=QString(); - attributes[ParsersAttributes::NEW_NAME]=QString(); + attributes[Attributes::DefaultValue]=QString(); + attributes[Attributes::NotNull]=QString(); + attributes[Attributes::Constraints]=QString(); + attributes[Attributes::Expression]=QString(); + attributes[Attributes::OldName]=QString(); + attributes[Attributes::NewName]=QString(); if(this->default_value!=domain->default_value) - attributes[ParsersAttributes::DEFAULT_VALUE]=(!domain->default_value.isEmpty() ? domain->default_value : ParsersAttributes::UNSET); + attributes[Attributes::DefaultValue]=(!domain->default_value.isEmpty() ? domain->default_value : Attributes::Unset); if(this->not_null!=domain->not_null) - attributes[ParsersAttributes::NOT_NULL]=(domain->not_null ? ParsersAttributes::_TRUE_ : ParsersAttributes::UNSET); + attributes[Attributes::NotNull]=(domain->not_null ? Attributes::True : Attributes::Unset); orig_constrs = this->chk_constrs; aux_constrs = domain->chk_constrs; - aux_attribs[ParsersAttributes::SQL_OBJECT] = this->getSQLName(); - aux_attribs[ParsersAttributes::SIGNATURE] = this->getSignature(); + aux_attribs[Attributes::SqlObject] = this->getSQLName(); + aux_attribs[Attributes::Signature] = this->getSignature(); //Generating the DROP for check constraints that does not exists anymore for(auto constr : orig_constrs) @@ -197,17 +197,17 @@ QString Domain::getAlterDefinition(BaseObject *object) if(aux_constrs.count(constr.first) == 0 || (aux_constrs.count(constr.first) && orig_expr != aux_expr)) { - aux_attribs[ParsersAttributes::NAME]=constr.first; - aux_attribs[ParsersAttributes::EXPRESSION]=ParsersAttributes::UNSET; - attributes[ParsersAttributes::CONSTRAINTS]+=BaseObject::getAlterDefinition(ParsersAttributes::DOM_CONSTRAINT, aux_attribs, false, true); + aux_attribs[Attributes::Name]=constr.first; + aux_attribs[Attributes::Expression]=Attributes::Unset; + attributes[Attributes::Constraints]+=BaseObject::getAlterDefinition(Attributes::DomConstraint, aux_attribs, false, true); } //We should include a command to recreate the check constraint with the new expression if(aux_constrs.count(constr.first) && orig_expr != aux_expr) { - aux_attribs[ParsersAttributes::NAME]=constr.first; - aux_attribs[ParsersAttributes::EXPRESSION]=aux_constrs[constr.first]; - attributes[ParsersAttributes::CONSTRAINTS]+=BaseObject::getAlterDefinition(ParsersAttributes::DOM_CONSTRAINT, aux_attribs, false, true); + aux_attribs[Attributes::Name]=constr.first; + aux_attribs[Attributes::Expression]=aux_constrs[constr.first]; + attributes[Attributes::Constraints]+=BaseObject::getAlterDefinition(Attributes::DomConstraint, aux_attribs, false, true); } } @@ -216,9 +216,9 @@ QString Domain::getAlterDefinition(BaseObject *object) { if(orig_constrs.count(constr.first) == 0) { - aux_attribs[ParsersAttributes::NAME]=constr.first; - aux_attribs[ParsersAttributes::EXPRESSION]=constr.second; - attributes[ParsersAttributes::CONSTRAINTS]+=BaseObject::getAlterDefinition(ParsersAttributes::DOM_CONSTRAINT, aux_attribs, false, true); + aux_attribs[Attributes::Name]=constr.first; + aux_attribs[Attributes::Expression]=constr.second; + attributes[Attributes::Constraints]+=BaseObject::getAlterDefinition(Attributes::DomConstraint, aux_attribs, false, true); } } @@ -227,6 +227,6 @@ QString Domain::getAlterDefinition(BaseObject *object) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } diff --git a/libpgmodeler/src/domain.h b/libpgmodeler/src/domain.h index 8ca4b9e3b9..7ccc7a625d 100644 --- a/libpgmodeler/src/domain.h +++ b/libpgmodeler/src/domain.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -38,7 +38,7 @@ class Domain: public BaseObject{ bool not_null; //! \brief Domain data type - PgSQLType type; + PgSqlType type; //! \brief Store the check constraint expressions (key:name value:expression) attribs_map chk_constrs; @@ -59,7 +59,7 @@ class Domain: public BaseObject{ void setNotNull(bool value); //! \brief Defines the domain data type - void setType(PgSQLType type); + void setType(PgSqlType type); /*! \brief Overloaded BaseObject name definition method. Updates the reference of the domain as a PostgreSQL data type */ @@ -74,7 +74,7 @@ class Domain: public BaseObject{ QString getExpression(void); QString getDefaultValue(void); bool isNotNull(void); - PgSQLType getType(void); + PgSqlType getType(void); //! \brief Returns the SQL / XML code definition for the domain virtual QString getCodeDefinition(unsigned def_type) final; diff --git a/libpgmodeler/src/element.cpp b/libpgmodeler/src/element.cpp index 9cdb024074..7af30819d8 100644 --- a/libpgmodeler/src/element.cpp +++ b/libpgmodeler/src/element.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -22,8 +22,8 @@ Element::Element(void) { column=nullptr; operator_class=nullptr; - sorting_attibs[NULLS_FIRST]=false; - sorting_attibs[ASC_ORDER]=true; + sorting_attibs[NullsFirst]=false; + sorting_attibs[AscOrder]=true; sorting_enabled=false; } @@ -52,8 +52,8 @@ void Element::setOperatorClass(OperatorClass *oper_class) void Element::setSortingAttribute(unsigned attrib, bool value) { - if(attrib > NULLS_FIRST) - throw Exception(ERR_REF_ATTRIB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(attrib > NullsFirst) + throw Exception(ErrorCode::RefAttributeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); sorting_attibs[attrib]=value; } @@ -70,8 +70,8 @@ bool Element::isSortingEnabled(void) bool Element::getSortingAttribute(unsigned attrib) { - if(attrib > NULLS_FIRST) - throw Exception(ERR_REF_ATTRIB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(attrib > NullsFirst) + throw Exception(ErrorCode::RefAttributeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(sorting_attibs[attrib]); } @@ -93,34 +93,44 @@ OperatorClass *Element::getOperatorClass(void) void Element::configureAttributes(attribs_map &attributes, unsigned def_type) { - attributes[ParsersAttributes::COLUMN]=QString(); - attributes[ParsersAttributes::EXPRESSION]=QString(); - attributes[ParsersAttributes::OP_CLASS]=QString(); - attributes[ParsersAttributes::USE_SORTING]=(this->sorting_enabled ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::NULLS_FIRST]=(this->sorting_enabled && this->sorting_attibs[NULLS_FIRST] ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::ASC_ORDER]=(this->sorting_enabled && this->sorting_attibs[ASC_ORDER] ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::Column]=QString(); + attributes[Attributes::Expression]=QString(); + attributes[Attributes::OpClass]=QString(); + attributes[Attributes::UseSorting]=(this->sorting_enabled ? Attributes::True : QString()); + attributes[Attributes::NullsFirst]=(this->sorting_enabled && this->sorting_attibs[NullsFirst] ? Attributes::True : QString()); + attributes[Attributes::AscOrder]=(this->sorting_enabled && this->sorting_attibs[AscOrder] ? Attributes::True : QString()); if(column) - attributes[ParsersAttributes::COLUMN]=column->getName(true); + attributes[Attributes::Column]=column->getName(true); else - attributes[ParsersAttributes::EXPRESSION]=expression; + attributes[Attributes::Expression]=expression; if(operator_class) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::OP_CLASS]=operator_class->getName(true); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::OpClass]=operator_class->getName(true); else - attributes[ParsersAttributes::OP_CLASS]=operator_class->getCodeDefinition(def_type, true); + attributes[Attributes::OpClass]=operator_class->getCodeDefinition(def_type, true); } } +bool Element::isEqualsTo(Element &elem) +{ + return(this->column == elem.column && + this->expression == elem.expression && + this->operator_class == elem.operator_class && + this->sorting_enabled == elem.sorting_enabled && + this->sorting_attibs[AscOrder] == elem.sorting_attibs[AscOrder] && + this->sorting_attibs[NullsFirst] == elem.sorting_attibs[NullsFirst]); +} + bool Element::operator == (Element &elem) { - return(this->column == elem.column && - this->expression == elem.expression && - this->operator_class == elem.operator_class && - this->sorting_enabled == elem.sorting_enabled && - this->sorting_attibs[ASC_ORDER] == elem.sorting_attibs[ASC_ORDER] && - this->sorting_attibs[NULLS_FIRST] == elem.sorting_attibs[NULLS_FIRST]); + return(isEqualsTo(elem)); +} + +bool Element::operator == (const Element &elem) +{ + return(isEqualsTo(const_cast(elem))); } diff --git a/libpgmodeler/src/element.h b/libpgmodeler/src/element.h index 181161a8bb..bbaab3582d 100644 --- a/libpgmodeler/src/element.h +++ b/libpgmodeler/src/element.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -26,6 +26,7 @@ #include "column.h" #include "operatorclass.h" +#include "collation.h" class Element { private: @@ -45,9 +46,13 @@ class Element { /*! \brief Sorting attributes of the element (ASC|DESC, NULLS [FIRST|LAST]) This attibutes can be configured used the constants ASC_ORDER and nullptrS_FIRST */ bool sorting_attibs[2], + //! \brief Enable the use of the sort attributes sorting_enabled; + //! \brief Compares the attributes of provided element against this returning true/false if the match or not + bool isEqualsTo(Element &elem); + protected: SchemaParser schparser; @@ -55,16 +60,18 @@ class Element { public: //! \brief Constants used to reference the sorting method of the element - static const unsigned ASC_ORDER=0, - NULLS_FIRST=1; + static constexpr unsigned AscOrder=0, + NullsFirst=1; Element(void); virtual ~Element(void) {} //! \brief Element configuration methods - void setColumn(Column *column); - void setExpression(const QString &expression); - void setOperatorClass(OperatorClass *oper_class); + virtual void setColumn(Column *column); + virtual void setExpression(const QString &expression); + virtual void setOperatorClass(OperatorClass *oper_class); + virtual void setCollation(Collation *){} + virtual void setOperator(Operator *){} void setSortingEnabled(bool value); //! \brief Sets the state of one of the element sorting method @@ -76,10 +83,14 @@ class Element { Column *getColumn(void); QString getExpression(void); OperatorClass *getOperatorClass(void); + virtual Collation *getCollation(void){ return(nullptr); } + virtual Operator *getOperator(void){ return(nullptr); } + bool isSortingEnabled(void); - virtual QString getCodeDefinition(unsigned) = 0; + virtual QString getCodeDefinition(unsigned) { return(QString()); } bool operator == (Element &elem); + bool operator ==(const Element &elem); }; #endif diff --git a/libpgmodeler/src/eventtrigger.cpp b/libpgmodeler/src/eventtrigger.cpp index 7d5edd7a81..e2662e5fb8 100644 --- a/libpgmodeler/src/eventtrigger.cpp +++ b/libpgmodeler/src/eventtrigger.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,11 +20,11 @@ EventTrigger::EventTrigger(void) { - obj_type=OBJ_EVENT_TRIGGER; + obj_type=ObjectType::EventTrigger; function=nullptr; - attributes[ParsersAttributes::EVENT]=QString(); - attributes[ParsersAttributes::FILTER]=QString(); - attributes[ParsersAttributes::FUNCTION]=QString(); + attributes[Attributes::Event]=QString(); + attributes[Attributes::Filter]=QString(); + attributes[Attributes::Function]=QString(); } void EventTrigger::setEvent(EventTriggerType evnt_type) @@ -36,22 +36,22 @@ void EventTrigger::setEvent(EventTriggerType evnt_type) void EventTrigger::setFunction(Function *func) { if(!func) - throw Exception(Exception::getErrorMessage(ERR_ASG_NOT_ALOC_FUNCTION) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgNotAllocatedFunction) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_EVENT_TRIGGER)), - ERR_ASG_NOT_ALOC_FUNCTION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::EventTrigger)), + ErrorCode::AsgNotAllocatedFunction,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Functions with return type other that event_trigger are not accepted else if(func->getReturnType()!=QString("event_trigger")) - throw Exception(Exception::getErrorMessage(ERR_ASG_INV_TRIGGER_FUNCTION).arg(QString("event_trigger")),__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidTriggerFunction).arg(QString("event_trigger")),__PRETTY_FUNCTION__,__FILE__,__LINE__); //Functions with one or more parameters are not accepted else if(func->getParameterCount()!=0) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNC_INV_PARAM_COUNT) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidParamCount) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_EVENT_TRIGGER)), - ERR_ASG_FUNC_INV_PARAM_COUNT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::EventTrigger)), + ErrorCode::AsgFunctionInvalidParamCount,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Functions coded in SQL lang. is not accepted by event triggers - else if(func->getLanguage()->getName()==~LanguageType(LanguageType::sql)) - throw Exception(ERR_ASG_EVNT_TRIG_FUNC_INV_LANG,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(func->getLanguage()->getName()==~LanguageType(LanguageType::Sql)) + throw Exception(ErrorCode::AsgEventTriggerFuncInvalidLang,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(function != func); function=func; @@ -59,8 +59,8 @@ void EventTrigger::setFunction(Function *func) void EventTrigger::setFilter(const QString &variable, const QStringList &values) { - if(variable.toLower()!=ParsersAttributes::TAG) - throw Exception(Exception::getErrorMessage(ERR_ASG_INV_EVENT_TRIGGER_VARIABLE).arg(variable),__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(variable.toLower()!=Attributes::Tag) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidEventTriggerVariable).arg(variable),__PRETTY_FUNCTION__,__FILE__,__LINE__); if(!values.isEmpty()) { @@ -109,31 +109,31 @@ QString EventTrigger::getCodeDefinition(unsigned def_type) QString code_def=getCachedCode(def_type, false); if(!code_def.isEmpty()) return(code_def); - attributes[ParsersAttributes::EVENT]=~event; + attributes[Attributes::Event]=~event; - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) { QStringList str_list; if(function) - attributes[ParsersAttributes::FUNCTION]=function->getSignature(); + attributes[Attributes::Function]=function->getSignature(); for(auto &flt : filter) str_list.push_back(QString("%1 IN ('%2')").arg(flt.first).arg(flt.second.join(QString("','")))); - attributes[ParsersAttributes::FILTER]=str_list.join(QString("\n\t AND ")); + attributes[Attributes::Filter]=str_list.join(QString("\n\t AND ")); } else { if(function) - attributes[ParsersAttributes::FUNCTION]=function->getCodeDefinition(def_type, true); + attributes[Attributes::Function]=function->getCodeDefinition(def_type, true); for(auto &flt : filter) //Creating an element - attributes[ParsersAttributes::FILTER]+=QString("\t<%1 %2=\"%3\" %4=\"%5\"/>\n") - .arg(ParsersAttributes::FILTER) - .arg(ParsersAttributes::VARIABLE).arg(flt.first) - .arg(ParsersAttributes::VALUES).arg(flt.second.join(',')); + attributes[Attributes::Filter]+=QString("\t<%1 %2=\"%3\" %4=\"%5\"/>\n") + .arg(Attributes::Filter) + .arg(Attributes::Variable).arg(flt.first) + .arg(Attributes::Values).arg(flt.second.join(',')); } return(BaseObject::__getCodeDefinition(def_type)); @@ -143,11 +143,11 @@ QString EventTrigger::getAlterDefinition(BaseObject *object) { try { - attributes[ParsersAttributes::ALTER_CMDS]=BaseObject::getAlterDefinition(object); + attributes[Attributes::AlterCmds]=BaseObject::getAlterDefinition(object); return(BaseObject::getAlterDefinition(this->getSchemaName(), attributes, false, false)); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } diff --git a/libpgmodeler/src/eventtrigger.h b/libpgmodeler/src/eventtrigger.h index 0e81d04524..e6e7ada71e 100644 --- a/libpgmodeler/src/eventtrigger.h +++ b/libpgmodeler/src/eventtrigger.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libpgmodeler/src/excludeelement.cpp b/libpgmodeler/src/excludeelement.cpp index 5234f20c02..620e9eab06 100644 --- a/libpgmodeler/src/excludeelement.cpp +++ b/libpgmodeler/src/excludeelement.cpp @@ -20,18 +20,18 @@ QString ExcludeElement::getCodeDefinition(unsigned def_type) attribs_map attributes; schparser.setPgSQLVersion(BaseObject::getPgSQLVersion()); - attributes[ParsersAttributes::OPERATOR]=QString(); + attributes[Attributes::Operator]=QString(); configureAttributes(attributes, def_type); if(_operator) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::OPERATOR]=_operator->getName(true); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Operator]=_operator->getName(true); else - attributes[ParsersAttributes::OPERATOR]=_operator->getCodeDefinition(def_type, true); + attributes[Attributes::Operator]=_operator->getCodeDefinition(def_type, true); } - return(schparser.getCodeDefinition(ParsersAttributes::EXCLUDE_ELEMENT, attributes, def_type)); + return(schparser.getCodeDefinition(Attributes::ExcludeElement, attributes, def_type)); } bool ExcludeElement::operator == (ExcludeElement &elem) diff --git a/libpgmodeler/src/excludeelement.h b/libpgmodeler/src/excludeelement.h index 8f362b8d8f..9bc86cfac8 100644 --- a/libpgmodeler/src/excludeelement.h +++ b/libpgmodeler/src/excludeelement.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libpgmodeler/src/extension.cpp b/libpgmodeler/src/extension.cpp index d4ef4246b3..7093023cc6 100644 --- a/libpgmodeler/src/extension.cpp +++ b/libpgmodeler/src/extension.cpp @@ -2,11 +2,11 @@ Extension::Extension(void) { - obj_type=OBJ_EXTENSION; + obj_type=ObjectType::Extension; handles_type=false; - attributes[ParsersAttributes::HANDLES_TYPE]=QString(); - attributes[ParsersAttributes::CUR_VERSION]=QString(); - attributes[ParsersAttributes::OLD_VERSION]=QString(); + attributes[Attributes::HandlesType]=QString(); + attributes[Attributes::CurVersion]=QString(); + attributes[Attributes::OldVersion]=QString(); } void Extension::setName(const QString &name) @@ -22,7 +22,7 @@ void Extension::setName(const QString &name) new_name=this->getName(true); //Renames the PostgreSQL type represented by the extension - PgSQLType::renameUserType(prev_name, this, new_name); + PgSqlType::renameUserType(prev_name, this, new_name); } } @@ -40,7 +40,7 @@ void Extension::setSchema(BaseObject *schema) prev_name=this->getName(true); //Renames the PostgreSQL type represented by the extension - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } } } @@ -50,18 +50,18 @@ void Extension::setHandlesType(bool value) /* Raises an error if the extension is already registered as a data type and the try to change the attribute value. This cannot be done to avoid cascade reference breaking on table columns/functions or any other objects that references PgSQLType */ - if(!value && PgSQLType::getUserTypeIndex(this->getName(true), this) != BaseType::null) - throw Exception(Exception::getErrorMessage(ERR_REG_EXT_NOT_HANDLING_TYPE) + if(!value && PgSqlType::getUserTypeIndex(this->getName(true), this) != BaseType::Null) + throw Exception(Exception::getErrorMessage(ErrorCode::ExtensionHandlingTypeImmutable) .arg(this->getName(true)), - ERR_REG_EXT_NOT_HANDLING_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::ExtensionHandlingTypeImmutable,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->handles_type=value; } void Extension::setVersion(unsigned ver, const QString &value) { - if(ver > OLD_VERSION) - throw Exception(ERR_REF_ATTRIB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(ver > OldVersion) + throw Exception(ErrorCode::RefAttributeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(versions[ver] != value); versions[ver]=value; @@ -74,8 +74,8 @@ bool Extension::handlesType(void) QString Extension::getVersion(unsigned ver) { - if(ver > OLD_VERSION) - throw Exception(ERR_REF_ATTRIB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(ver > OldVersion) + throw Exception(ErrorCode::RefAttributeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(versions[ver]); } @@ -85,11 +85,11 @@ QString Extension::getCodeDefinition(unsigned def_type) QString code_def=getCachedCode(def_type, false); if(!code_def.isEmpty()) return(code_def); - attributes[ParsersAttributes::NAME]=this->getName(true, false); - attributes[ParsersAttributes::HANDLES_TYPE]=(handles_type ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::CUR_VERSION]=versions[CUR_VERSION]; - attributes[ParsersAttributes::OLD_VERSION]=versions[OLD_VERSION]; - attributes[ParsersAttributes::NAME]=this->getName(def_type==SchemaParser::SQL_DEFINITION, false); + attributes[Attributes::Name]=this->getName(def_type==SchemaParser::SqlDefinition, false); + attributes[Attributes::HandlesType]=(handles_type ? Attributes::True : QString()); + attributes[Attributes::CurVersion]=versions[CurVersion]; + attributes[Attributes::OldVersion]=versions[OldVersion]; + return(BaseObject::__getCodeDefinition(def_type)); } @@ -98,28 +98,28 @@ QString Extension::getAlterDefinition(BaseObject *object) Extension *ext=dynamic_cast(object); if(!ext) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { - attributes[ParsersAttributes::ALTER_CMDS]=BaseObject::getAlterDefinition(object); - attributes[ParsersAttributes::NEW_VERSION]=QString(); + attributes[Attributes::AlterCmds]=BaseObject::getAlterDefinition(object); + attributes[Attributes::NewVersion]=QString(); - if(!this->versions[CUR_VERSION].isEmpty() && !ext->versions[CUR_VERSION].isEmpty() && - this->versions[CUR_VERSION].isEmpty() < ext->versions[CUR_VERSION].isEmpty()) - attributes[ParsersAttributes::NEW_VERSION]=ext->versions[CUR_VERSION]; + if(!this->versions[CurVersion].isEmpty() && !ext->versions[CurVersion].isEmpty() && + this->versions[CurVersion].isEmpty() < ext->versions[CurVersion].isEmpty()) + attributes[Attributes::NewVersion]=ext->versions[CurVersion]; return(BaseObject::getAlterDefinition(this->getSchemaName(), attributes, false, true)); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } QString Extension::getDropDefinition(bool cascade) { - attributes[ParsersAttributes::NAME] = this->getName(); + attributes[Attributes::Name] = this->getName(true); return(BaseObject::getDropDefinition(cascade)); } @@ -138,10 +138,10 @@ void Extension::operator = (Extension &ext) QString prev_name=this->getName(true); *(dynamic_cast(this))=dynamic_cast(ext); - this->versions[CUR_VERSION]=ext.versions[CUR_VERSION]; - this->versions[OLD_VERSION]=ext.versions[OLD_VERSION]; + this->versions[CurVersion]=ext.versions[CurVersion]; + this->versions[OldVersion]=ext.versions[OldVersion]; this->handles_type=ext.handles_type; if(this->handles_type) - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } diff --git a/libpgmodeler/src/extension.h b/libpgmodeler/src/extension.h index 2ca77f871b..43e0dbee15 100644 --- a/libpgmodeler/src/extension.h +++ b/libpgmodeler/src/extension.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -40,8 +40,8 @@ class Extension: public BaseObject { QString versions[2]; public: - static const unsigned CUR_VERSION=0, - OLD_VERSION=1; + static constexpr unsigned CurVersion=0, + OldVersion=1; Extension(void); void setName(const QString &name); diff --git a/libpgmodeler/src/foreigndatawrapper.cpp b/libpgmodeler/src/foreigndatawrapper.cpp new file mode 100644 index 0000000000..86b620e8a1 --- /dev/null +++ b/libpgmodeler/src/foreigndatawrapper.cpp @@ -0,0 +1,144 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "foreigndatawrapper.h" + +ForeignDataWrapper::ForeignDataWrapper(void) : ForeignObject() +{ + obj_type=ObjectType::ForeignDataWrapper; + validator_func = handler_func = nullptr; + + attributes[Attributes::HandlerFunc] = QString(); + attributes[Attributes::ValidatorFunc] = QString(); +} + +void ForeignDataWrapper::setHandlerFunction(Function *func) +{ + if(func) + { + if(func->getReturnType() != PgSqlType("fdw_handler")) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidReturnType) + .arg(this->getName(true)) + .arg(this->getTypeName()), + ErrorCode::AsgFunctionInvalidReturnType, __PRETTY_FUNCTION__, __FILE__, __LINE__); + + if(func->getParameterCount() != 0) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidParamCount) + .arg(this->getName(true)) + .arg(this->getTypeName()), + ErrorCode::AsgFunctionInvalidParamCount, __PRETTY_FUNCTION__, __FILE__, __LINE__); + } + + handler_func = func; +} + +void ForeignDataWrapper::setValidatorFunction(Function *func) +{ + if(func) + { + if(func->getParameterCount() != 2) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidParamCount) + .arg(this->getName(true)) + .arg(this->getTypeName()), + ErrorCode::AsgFunctionInvalidParamCount, __PRETTY_FUNCTION__, __FILE__, __LINE__); + + if(!func->getParameter(0).getType().isExactTo(PgSqlType("text", 1)) || + !func->getParameter(1).getType().isExactTo(PgSqlType("oid"))) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidParameters) + .arg(this->getName(true)) + .arg(this->getTypeName()), + ErrorCode::AsgFunctionInvalidParameters, __PRETTY_FUNCTION__, __FILE__, __LINE__); + } + + validator_func = func; +} + +Function *ForeignDataWrapper::getHandlerFunction(void) +{ + return(handler_func); +} + +Function *ForeignDataWrapper::getValidatorFunction(void) +{ + return(validator_func); +} + +QString ForeignDataWrapper::getCodeDefinition(unsigned def_type) +{ + return(getCodeDefinition(def_type, false)); +} + +QString ForeignDataWrapper::getCodeDefinition(unsigned def_type, bool reduced_form) +{ + QString code_def=getCachedCode(def_type, reduced_form); + if(!code_def.isEmpty()) return(code_def); + + QStringList fmt_options; + bool is_sql_def = (def_type == SchemaParser::SqlDefinition); + + if(handler_func) + { + handler_func->setAttribute(Attributes::RefType, Attributes::HandlerFunc); + attributes[Attributes::HandlerFunc] = is_sql_def ? handler_func->getName(true) : handler_func->getCodeDefinition(def_type, true); + } + + if(validator_func) + { + validator_func->setAttribute(Attributes::RefType, Attributes::ValidatorFunc); + attributes[Attributes::ValidatorFunc] = is_sql_def ? validator_func->getName(true) : validator_func->getCodeDefinition(def_type, true); + } + + setOptionsAttribute(def_type); + return(this->BaseObject::getCodeDefinition(def_type, reduced_form)); +} + +QString ForeignDataWrapper::getAlterDefinition(BaseObject *object) +{ + try + { + ForeignDataWrapper *fdw=dynamic_cast(object); + attribs_map attribs; + QStringList func_attribs = { Attributes::ValidatorFunc, Attributes::HandlerFunc }; + Function *this_funcs[2] = { this->getValidatorFunction(), this->getHandlerFunction() }, + *fdw_funcs[2] = { fdw->getValidatorFunction(), fdw->getHandlerFunction() }, + *this_func = nullptr, *fdw_func = nullptr; + + attributes[Attributes::AlterCmds] = ForeignObject::getAlterDefinition(fdw); + + // Comparing FDW functions + for(int i = 0; i < 2; i++) + { + this_func = this_funcs[i]; + fdw_func = fdw_funcs[i]; + + if(!fdw_func && this_func) + attribs[func_attribs[i]] = Attributes::Unset; + else if(fdw_func && + (!this_func || + (this_func && this_func->getSignature() != fdw_func->getSignature()))) + attribs[func_attribs[i]] = fdw_func->getName(true); + } + + copyAttributes(attribs); + return(BaseObject::getAlterDefinition(this->getSchemaName(), attributes, false, true)); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + } +} diff --git a/libpgmodeler/src/foreigndatawrapper.h b/libpgmodeler/src/foreigndatawrapper.h new file mode 100644 index 0000000000..120a28fbda --- /dev/null +++ b/libpgmodeler/src/foreigndatawrapper.h @@ -0,0 +1,54 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +/** +\ingroup libpgmodeler +\class ForeignDataWrapper +\brief Implements the operations to manipulate foreign data wrappers on the database. +*/ + +#ifndef FOREIGN_DATA_WRAPPER_H +#define FOREIGN_DATA_WRAPPER_H + +#include "baseobject.h" +#include "function.h" +#include "foreignobject.h" + +class ForeignDataWrapper: public ForeignObject { + private: + //! \brief Function that executes the functions related to the foreign data wrapper + Function *handler_func, + + //! \brief Function that validates the options passed to the foreign data wrapper + *validator_func; + + public: + ForeignDataWrapper(void); + + void setHandlerFunction(Function *func); + void setValidatorFunction(Function *func); + + Function *getHandlerFunction(void); + Function *getValidatorFunction(void); + + virtual QString getCodeDefinition(unsigned def_type); + virtual QString getCodeDefinition(unsigned def_type, bool reduced_form); + virtual QString getAlterDefinition(BaseObject *object); +}; + +#endif diff --git a/libpgmodeler/src/foreignobject.cpp b/libpgmodeler/src/foreignobject.cpp new file mode 100644 index 0000000000..97b2bbe760 --- /dev/null +++ b/libpgmodeler/src/foreignobject.cpp @@ -0,0 +1,111 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "foreignobject.h" + +const QString ForeignObject::OptionsSeparator = QString(","); +const QString ForeignObject::OptionValueSeparator = QString("="); + +ForeignObject::ForeignObject(void) : BaseObject() +{ + attributes[Attributes::Options] = QString(); +} + +void ForeignObject::setOption(const QString &opt, const QString &value) +{ + if(opt.isEmpty()) + throw Exception(ErrorCode::AsgOptionInvalidName,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + options[opt] = value; +} + +void ForeignObject::setOptions(const attribs_map &options) +{ + for(auto &itr : options) + { + if(itr.first.isEmpty()) + throw Exception(ErrorCode::AsgOptionInvalidName,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + + this->options = options; +} + +void ForeignObject::removeOption(const QString &opt) +{ + options.erase(opt); +} + +void ForeignObject::removeOptions(void) +{ + options.clear(); +} + +attribs_map ForeignObject::getOptions(void) +{ + return(options); +} + +QString ForeignObject::getAlterDefinition(BaseObject *object) +{ + try + { + attribs_map attribs; + ForeignObject *fobj = dynamic_cast(object); + QStringList opts; + + if(!fobj) + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + // Comparing options (to be modified or added) + for(auto &opt : fobj->options) + { + if(this->options.count(opt.first) == 0) + opts.push_back(QString("ADD %1 '%2'").arg(opt.first).arg(opt.second)); + else if(this->options[opt.first] != opt.second) + opts.push_back(QString("SET %1 '%3'").arg(opt.first).arg(opt.second)); + } + + // Comparing options (to be removed) + for(auto &opt : this->options) + { + if(fobj->options.count(opt.first) == 0) + opts.push_back(QString("DROP %1").arg(opt.first)); + } + + attribs[Attributes::Options] = opts.join(OptionsSeparator); + copyAttributes(attribs); + + return(BaseObject::getAlterDefinition(object)); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__, __FILE__, __LINE__, &e); + } +} + +void ForeignObject::setOptionsAttribute(unsigned def_type) +{ + QStringList fmt_options; + + for(auto &itr : options) + fmt_options += def_type == SchemaParser::SqlDefinition ? + QString("%1 '%2'").arg(itr.first).arg(itr.second) : + QString("%1%2%3").arg(itr.first).arg(OptionValueSeparator).arg(itr.second); + + attributes[Attributes::Options] = fmt_options.join(OptionsSeparator); +} diff --git a/libpgmodeler/src/foreignobject.h b/libpgmodeler/src/foreignobject.h new file mode 100644 index 0000000000..4ef9fe3c66 --- /dev/null +++ b/libpgmodeler/src/foreignobject.h @@ -0,0 +1,54 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +/** +\ingroup libpgmodeler +\class ForeignObject +\brief Implements the basic operations to handle common attributes of foreign data wrapper, foreign servers and foreign tables. +*/ + +#ifndef FOREIGN_OBJECT_H +#define FOREIGN_OBJECT_H + +#include "baseobject.h" + +class ForeignObject: public BaseObject { + protected: + //! \brief A set of key/value options associated to the foreign object + attribs_map options; + + void setOptionsAttribute(unsigned def_type); + + public: + //! \brief Store the character used to separate options/values in the XML code + static const QString OptionsSeparator; + static const QString OptionValueSeparator; + + ForeignObject(void); + + void setOption(const QString &opt, const QString &value); + void setOptions(const attribs_map &options); + void removeOption(const QString &opt); + void removeOptions(void); + attribs_map getOptions(void); + + virtual QString getCodeDefinition(unsigned) = 0; + virtual QString getAlterDefinition(BaseObject *object); +}; + +#endif diff --git a/libpgmodeler/src/foreignserver.cpp b/libpgmodeler/src/foreignserver.cpp new file mode 100644 index 0000000000..1ccfa145d6 --- /dev/null +++ b/libpgmodeler/src/foreignserver.cpp @@ -0,0 +1,107 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "foreignserver.h" + +ForeignServer::ForeignServer(void) : ForeignObject() +{ + obj_type = ObjectType::ForeignServer; + fdata_wrapper = nullptr; + + attributes[Attributes::Options] = QString(); + attributes[Attributes::Version] = QString(); + attributes[Attributes::Type] = QString(); + attributes[Attributes::Object] = QString(); +} + +void ForeignServer::setType(const QString &type) +{ + this->type = type; +} + +void ForeignServer::setVersion(const QString &version) +{ + this->version = version; +} + +void ForeignServer::setForeignDataWrapper(ForeignDataWrapper *fdw) +{ + fdata_wrapper = fdw; +} + +QString ForeignServer::getType(void) +{ + return(type); +} + +QString ForeignServer::getVersion(void) +{ + return(version); +} + +ForeignDataWrapper *ForeignServer::getForeignDataWrapper(void) +{ + return(fdata_wrapper); +} + +QString ForeignServer::getCodeDefinition(unsigned def_type) +{ + return(getCodeDefinition(def_type, false)); +} + +QString ForeignServer::getCodeDefinition(unsigned def_type, bool reduced_form) +{ + QString code_def=getCachedCode(def_type, reduced_form); + if(!code_def.isEmpty()) return(code_def); + + attributes[Attributes::Version] = version; + attributes[Attributes::Type] = type; + attributes[Attributes::Fdw] = QString(); + + if(fdata_wrapper) + { + if(def_type == SchemaParser::SqlDefinition) + attributes[Attributes::Fdw] = fdata_wrapper->getName(true); + else + attributes[Attributes::Fdw] = fdata_wrapper->getCodeDefinition(def_type, true); + } + + setOptionsAttribute(def_type); + return(this->BaseObject::getCodeDefinition(def_type, reduced_form)); +} + +QString ForeignServer::getAlterDefinition(BaseObject *object) +{ + try + { + ForeignServer *server=dynamic_cast(object); + attribs_map attribs; + + attributes[Attributes::AlterCmds] = ForeignObject::getAlterDefinition(server); + + if(this->version != server->version) + attribs[Attributes::Version] = server->version; + + copyAttributes(attribs); + return(BaseObject::getAlterDefinition(this->getSchemaName(), attributes, false, true)); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + } +} diff --git a/libpgmodeler/src/foreignserver.h b/libpgmodeler/src/foreignserver.h new file mode 100644 index 0000000000..856df6ebe5 --- /dev/null +++ b/libpgmodeler/src/foreignserver.h @@ -0,0 +1,54 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +/** +\ingroup libpgmodeler +\class Server +\brief Implements the operations to manipulate foreign servers on the database. +*/ + +#ifndef FOREIGN_SERVER_H +#define FOREIGN_SERVER_H + +#include "baseobject.h" +#include "foreigndatawrapper.h" + +class ForeignServer: public ForeignObject { + private: + //! \brief The foreign data wrapper which manages the server + ForeignDataWrapper *fdata_wrapper; + + QString type, version; + + public: + ForeignServer(void); + + void setType(const QString &type); + void setVersion(const QString &version); + void setForeignDataWrapper(ForeignDataWrapper *fdw); + + QString getType(void); + QString getVersion(void); + ForeignDataWrapper *getForeignDataWrapper(void); + + virtual QString getCodeDefinition(unsigned def_type); + virtual QString getCodeDefinition(unsigned def_type, bool reduced_form); + virtual QString getAlterDefinition(BaseObject *object); +}; + +#endif diff --git a/libpgmodeler/src/function.cpp b/libpgmodeler/src/function.cpp index b7ef235a6b..1471d021a6 100644 --- a/libpgmodeler/src/function.cpp +++ b/libpgmodeler/src/function.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,33 +20,33 @@ Function::Function(void) { - return_type=PgSQLType(QString("void")); + return_type=PgSqlType(QString("void")); language=nullptr; returns_setof=false; is_wnd_function=false; is_leakproof=false; - obj_type=OBJ_FUNCTION; + obj_type=ObjectType::Function; execution_cost=100; row_amount=1000; - attributes[ParsersAttributes::PARAMETERS]=QString(); - attributes[ParsersAttributes::EXECUTION_COST]=QString(); - attributes[ParsersAttributes::ROW_AMOUNT]=QString(); - attributes[ParsersAttributes::RETURN_TYPE]=QString(); - attributes[ParsersAttributes::FUNCTION_TYPE]=QString(); - attributes[ParsersAttributes::LANGUAGE]=QString(); - attributes[ParsersAttributes::RETURNS_SETOF]=QString(); - attributes[ParsersAttributes::SECURITY_TYPE]=QString(); - attributes[ParsersAttributes::BEHAVIOR_TYPE]=QString(); - attributes[ParsersAttributes::DEFINITION]=QString(); - attributes[ParsersAttributes::SIGNATURE]=QString(); - attributes[ParsersAttributes::REF_TYPE]=QString(); - attributes[ParsersAttributes::WINDOW_FUNC]=QString(); - attributes[ParsersAttributes::RETURN_TABLE]=QString(); - attributes[ParsersAttributes::LIBRARY]=QString(); - attributes[ParsersAttributes::SYMBOL]=QString(); - attributes[ParsersAttributes::LEAKPROOF]=QString(); + attributes[Attributes::Parameters]=QString(); + attributes[Attributes::ExecutionCost]=QString(); + attributes[Attributes::RowAmount]=QString(); + attributes[Attributes::ReturnType]=QString(); + attributes[Attributes::FunctionType]=QString(); + attributes[Attributes::Language]=QString(); + attributes[Attributes::ReturnsSetOf]=QString(); + attributes[Attributes::SecurityType]=QString(); + attributes[Attributes::BehaviorType]=QString(); + attributes[Attributes::Definition]=QString(); + attributes[Attributes::Signature]=QString(); + attributes[Attributes::RefType]=QString(); + attributes[Attributes::WindowFunc]=QString(); + attributes[Attributes::ReturnTable]=QString(); + attributes[Attributes::Library]=QString(); + attributes[Attributes::Symbol]=QString(); + attributes[Attributes::LeakProof]=QString(); } void Function::setName(const QString &name) @@ -80,21 +80,21 @@ void Function::addParameter(Parameter param) //If a duplicated parameter is found an error is raised if(found) - throw Exception(Exception::getErrorMessage(ERR_ASG_DUPLIC_PARAM_FUNCTION) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgDuplicatedParameterFunction) .arg(param.getName()) .arg(this->signature), - ERR_ASG_DUPLIC_PARAM_FUNCTION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgDuplicatedParameterFunction,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Inserts the parameter in the function parameters.push_back(param); createSignature(); } -void Function::addReturnedTableColumn(const QString &name, PgSQLType type) +void Function::addReturnedTableColumn(const QString &name, PgSqlType type) { //Raises an error if the column name is empty if(name.isEmpty()) - throw Exception(ERR_ASG_EMPTY_NAME_RET_TABLE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgEmptyNameTableReturnType,__PRETTY_FUNCTION__,__FILE__,__LINE__); vector::iterator itr,itr_end; bool found=false; @@ -113,10 +113,10 @@ void Function::addReturnedTableColumn(const QString &name, PgSQLType type) //Raises an error if the column is duplicated if(found) - throw Exception(Exception::getErrorMessage(ERR_INS_DUPLIC_RET_TAB_TYPE) + throw Exception(Exception::getErrorMessage(ErrorCode::InsDuplicatedTableReturnType) .arg(name) .arg(this->signature), - ERR_INS_DUPLIC_RET_TAB_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InsDuplicatedTableReturnType,__PRETTY_FUNCTION__,__FILE__,__LINE__); Parameter p; p.setName(name); @@ -136,10 +136,10 @@ void Function::setParametersAttribute(unsigned def_type) str_param+=parameters[i].getCodeDefinition(def_type); } - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) str_param.remove(str_param.size()-2,2); - attributes[ParsersAttributes::PARAMETERS]=str_param; + attributes[Attributes::Parameters]=str_param; } void Function::setTableReturnTypeAttribute(unsigned def_type) @@ -153,10 +153,10 @@ void Function::setTableReturnTypeAttribute(unsigned def_type) str_type+=ret_table_columns[i].getCodeDefinition(def_type); } - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) str_type.remove(str_type.size()-2,2); - attributes[ParsersAttributes::RETURN_TABLE]=str_type; + attributes[Attributes::ReturnTable]=str_type; } void Function::setExecutionCost(unsigned exec_cost) @@ -174,9 +174,9 @@ void Function::setRowAmount(unsigned row_amount) void Function::setLibrary(const QString &library) { if(language->getName().toLower()!=~LanguageType("c")) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNC_REFLIB_LANG_NOT_C) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgRefLibraryFuncLanguageNotC) .arg(this->getSignature()), - ERR_ASG_FUNC_REFLIB_LANG_NOT_C,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgRefLibraryFuncLanguageNotC,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->library != library); this->library=library; @@ -185,15 +185,15 @@ void Function::setLibrary(const QString &library) void Function::setSymbol(const QString &symbol) { if(language->getName().toLower()!=~LanguageType("c")) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNC_REFLIB_LANG_NOT_C) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgRefLibraryFuncLanguageNotC) .arg(this->getSignature()), - ERR_ASG_FUNC_REFLIB_LANG_NOT_C,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgRefLibraryFuncLanguageNotC,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->symbol != symbol); this->symbol=symbol; } -void Function::setReturnType(PgSQLType type) +void Function::setReturnType(PgSqlType type) { setCodeInvalidated(return_type != type); return_type=type; @@ -209,10 +209,10 @@ void Function::setLanguage(BaseObject *language) { //Raises an error if the language is not allocated if(!language) - throw Exception(ERR_ASG_NOT_ALOC_LANGUAGE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocatedLanguage,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the language object is invalid - else if(language->getObjectType()!=OBJ_LANGUAGE) - throw Exception(ERR_ASG_INV_LANGUAGE_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(language->getObjectType()!=ObjectType::Language) + throw Exception(ErrorCode::AsgInvalidLanguageObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->language != language); this->language=language; @@ -251,15 +251,15 @@ void Function::setBehaviorType(BehaviorType behav_type) void Function::setSourceCode(const QString &src_code) { if(language && language->getName().toLower()==~LanguageType("c")) - throw Exception(Exception::getErrorMessage(ERR_ASG_CODE_FUNC_C_LANGUAGE) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgSourceCodeFuncCLanguage) .arg(this->getSignature()), - ERR_ASG_CODE_FUNC_C_LANGUAGE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgSourceCodeFuncCLanguage,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->source_code != src_code); this->source_code=src_code; } -PgSQLType Function::getReturnType(void) +PgSqlType Function::getReturnType(void) { return(return_type); } @@ -323,7 +323,7 @@ Parameter Function::getParameter(unsigned param_idx) { //Raises an error if the parameter index is out of bound if(param_idx>=parameters.size()) - throw Exception(ERR_REF_PARAM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefParameterInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(parameters[param_idx]); } @@ -332,7 +332,7 @@ Parameter Function::getReturnedTableColumn(unsigned column_idx) { //Raises an error if the column index is out of bound if(column_idx>=ret_table_columns.size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(ret_table_columns[column_idx]); } @@ -369,7 +369,7 @@ void Function::removeReturnedTableColumns(void) setCodeInvalidated(true); } -void Function::removeParameter(const QString &name, PgSQLType type) +void Function::removeParameter(const QString &name, PgSqlType type) { vector::iterator itr,itr_end; @@ -395,7 +395,7 @@ void Function::removeParameter(unsigned param_idx) { //Raises an error if parameter index is out of bound if(param_idx>=parameters.size()) - throw Exception(ERR_REF_PARAM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefParameterInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); vector::iterator itr; itr=parameters.begin()+param_idx; @@ -407,7 +407,7 @@ void Function::removeParameter(unsigned param_idx) void Function::removeReturnedTableColumn(unsigned column_idx) { if(column_idx>=ret_table_columns.size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); vector::iterator itr; itr=ret_table_columns.begin()+column_idx; @@ -433,7 +433,7 @@ void Function::createSignature(bool format, bool prepend_schema) (parameters[i].isIn() && parameters[i].isOut()) || (parameters[i].isIn() && !parameters[i].isOut())) { - str_param+=parameters[i].getCodeDefinition(SchemaParser::SQL_DEFINITION, true).trimmed(); + str_param+=parameters[i].getCodeDefinition(SchemaParser::SqlDefinition, true).trimmed(); parameters[i].setCodeInvalidated(true); } } @@ -457,40 +457,40 @@ QString Function::getCodeDefinition(unsigned def_type, bool reduced_form) setParametersAttribute(def_type); - attributes[ParsersAttributes::EXECUTION_COST]=QString("%1").arg(execution_cost); - attributes[ParsersAttributes::ROW_AMOUNT]=QString("%1").arg(row_amount); - attributes[ParsersAttributes::FUNCTION_TYPE]=(~function_type); + attributes[Attributes::ExecutionCost]=QString("%1").arg(execution_cost); + attributes[Attributes::RowAmount]=QString("%1").arg(row_amount); + attributes[Attributes::FunctionType]=(~function_type); if(language) { - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) { - attributes[ParsersAttributes::LANGUAGE]=language->getName(false); - attributes[ParsersAttributes::RETURN_TYPE]=(*return_type); + attributes[Attributes::Language]=language->getName(false); + attributes[Attributes::ReturnType]=(*return_type); } else { - attributes[ParsersAttributes::LANGUAGE]=language->getCodeDefinition(def_type,true); - attributes[ParsersAttributes::RETURN_TYPE]=return_type.getCodeDefinition(def_type); + attributes[Attributes::Language]=language->getCodeDefinition(def_type,true); + attributes[Attributes::ReturnType]=return_type.getCodeDefinition(def_type); + } + + if(language->getName()==~LanguageType(LanguageType::C)) + { + attributes[Attributes::Symbol]=symbol; + attributes[Attributes::Library]=library; } } setTableReturnTypeAttribute(def_type); - attributes[ParsersAttributes::RETURNS_SETOF]=(returns_setof ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::WINDOW_FUNC]=(is_wnd_function ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::LEAKPROOF]=(is_leakproof ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::SECURITY_TYPE]=(~security_type); - attributes[ParsersAttributes::BEHAVIOR_TYPE]=(~behavior_type); - attributes[ParsersAttributes::DEFINITION]=source_code; - - if(language->getName()==~LanguageType(LanguageType::c)) - { - attributes[ParsersAttributes::SYMBOL]=symbol; - attributes[ParsersAttributes::LIBRARY]=library; - } + attributes[Attributes::ReturnsSetOf]=(returns_setof ? Attributes::True : QString()); + attributes[Attributes::WindowFunc]=(is_wnd_function ? Attributes::True : QString()); + attributes[Attributes::LeakProof]=(is_leakproof ? Attributes::True : QString()); + attributes[Attributes::SecurityType]=(~security_type); + attributes[Attributes::BehaviorType]=(~behavior_type); + attributes[Attributes::Definition]=source_code; - attributes[ParsersAttributes::SIGNATURE]=signature; + attributes[Attributes::Signature]=signature; return(BaseObject::getCodeDefinition(def_type, reduced_form)); } @@ -499,46 +499,46 @@ QString Function::getAlterDefinition(BaseObject *object) Function *func=dynamic_cast(object); if(!func) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { attribs_map attribs; - attributes[ParsersAttributes::ALTER_CMDS]=BaseObject::getAlterDefinition(object); + attributes[Attributes::AlterCmds]=BaseObject::getAlterDefinition(object); if(this->source_code.simplified()!=func->source_code.simplified() || this->library!=func->library || this->symbol!=func->symbol) { - attribs[ParsersAttributes::DEFINITION]=func->getCodeDefinition(SchemaParser::SQL_DEFINITION); - attribs[ParsersAttributes::DEFINITION].replace(QString("CREATE FUNCTION"), QString("CREATE OR REPLACE FUNCTION")); + attribs[Attributes::Definition]=func->getCodeDefinition(SchemaParser::SqlDefinition); + attribs[Attributes::Definition].replace(QString("CREATE FUNCTION"), QString("CREATE OR REPLACE FUNCTION")); } else { if(this->execution_cost!=func->execution_cost) - attribs[ParsersAttributes::EXECUTION_COST]=QString::number(func->execution_cost); + attribs[Attributes::ExecutionCost]=QString::number(func->execution_cost); if(this->returns_setof && func->returns_setof && this->row_amount!=func->row_amount) { - attribs[ParsersAttributes::RETURNS_SETOF]=ParsersAttributes::_TRUE_; - attribs[ParsersAttributes::ROW_AMOUNT]=QString::number(row_amount); + attribs[Attributes::ReturnsSetOf]=Attributes::True; + attribs[Attributes::RowAmount]=QString::number(row_amount); } if(this->function_type!=func->function_type) - attribs[ParsersAttributes::FUNCTION_TYPE]=~func->function_type; + attribs[Attributes::FunctionType]=~func->function_type; if(this->is_leakproof!=func->is_leakproof) - attribs[ParsersAttributes::LEAKPROOF]=(func->is_leakproof ? ParsersAttributes::_TRUE_ : ParsersAttributes::UNSET); + attribs[Attributes::LeakProof]=(func->is_leakproof ? Attributes::True : Attributes::Unset); if(this->security_type!=func->security_type) - attribs[ParsersAttributes::SECURITY_TYPE]=~func->security_type; + attribs[Attributes::SecurityType]=~func->security_type; if((this->behavior_type!=func->behavior_type) && - ((this->behavior_type==BehaviorType::called_on_null_input) || - ((this->behavior_type==BehaviorType::strict || this->behavior_type==BehaviorType::returns_null_on_null_input) && - func->function_type==BehaviorType::called_on_null_input))) - attribs[ParsersAttributes::BEHAVIOR_TYPE]=~func->behavior_type; + ((this->behavior_type==BehaviorType::CalledOnNullInput) || + ((this->behavior_type==BehaviorType::Strict || this->behavior_type==BehaviorType::ReturnsNullOnNullInput) && + func->function_type==BehaviorType::CalledOnNullInput))) + attribs[Attributes::BehaviorType]=~func->behavior_type; } copyAttributes(attribs); @@ -547,6 +547,19 @@ QString Function::getAlterDefinition(BaseObject *object) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } + +void Function::configureSearchAttributes(void) +{ + QStringList param_types; + + BaseObject::configureSearchAttributes(); + search_attribs[Attributes::ReturnType] = ret_table_columns.empty() ? *return_type : QString(); + + for(auto ¶m : parameters) + param_types += *param.getType(); + + search_attribs[Attributes::Type] = param_types.join("; "); +} diff --git a/libpgmodeler/src/function.h b/libpgmodeler/src/function.h index 53930e5ff1..10283a11ef 100644 --- a/libpgmodeler/src/function.h +++ b/libpgmodeler/src/function.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -65,7 +65,7 @@ class Function: public BaseObject { FunctionType function_type; //! \brief Function return type - PgSQLType return_type; + PgSqlType return_type; /*! \brief Stores the table columns returned by the clause RETURNS TABLE. This clause instead of return a specific element returns a whole table. This structure is available @@ -87,6 +87,9 @@ class Function: public BaseObject { //! \brief Formats the function return type to be used by the SchemaParser void setTableReturnTypeAttribute(unsigned def_type); + protected: + virtual void configureSearchAttributes(void); + public: Function(void); @@ -100,7 +103,7 @@ class Function: public BaseObject { void addParameter(Parameter param); //! \brief Adds a column to the function returned table - void addReturnedTableColumn(const QString &name, PgSQLType type); + void addReturnedTableColumn(const QString &name, PgSqlType type); //! \brief Defines the function source code (if its not use the C language) void setSourceCode(const QString &src_code); @@ -136,7 +139,7 @@ class Function: public BaseObject { void setFunctionType(FunctionType func_type); //! \brief Defines the function return type - void setReturnType(PgSQLType type); + void setReturnType(PgSqlType type); //! \brief Defines the security type of the function void setSecurityType(SecurityType sec_type); @@ -184,7 +187,7 @@ class Function: public BaseObject { FunctionType getFunctionType(void); //! \brief Returns the function returned type - PgSQLType getReturnType(void); + PgSqlType getReturnType(void); //! \brief Returns the security type used by the function SecurityType getSecurityType(void); @@ -196,7 +199,7 @@ class Function: public BaseObject { unsigned getRowAmount(void); //! \brief Removes a parameter using its name and type - void removeParameter(const QString &name, PgSQLType type); + void removeParameter(const QString &name, PgSqlType type); //! \brief Removes a parameter using its index void removeParameter(unsigned param_idx); diff --git a/libpgmodeler/src/genericsql.cpp b/libpgmodeler/src/genericsql.cpp index bdff78407b..30ac105088 100644 --- a/libpgmodeler/src/genericsql.cpp +++ b/libpgmodeler/src/genericsql.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -17,11 +17,13 @@ */ #include "genericsql.h" +#include "tableobject.h" GenericSQL::GenericSQL(void) { - obj_type=OBJ_GENERIC_SQL; - attributes[ParsersAttributes::DEFINITION] = QString(); + obj_type = ObjectType::GenericSql; + attributes[Attributes::Definition] = QString(); + attributes[Attributes::Objects] = QString(); } void GenericSQL::setDefinition(const QString &def) @@ -35,16 +37,202 @@ QString GenericSQL::getDefinition(void) return(definition); } +vector GenericSQL::getObjectsReferences(void) +{ + return(objects_refs); +} + +int GenericSQL::getObjectRefNameIndex(const QString &ref_name) +{ + int idx = -1; + vector::iterator itr = objects_refs.begin(), + itr_end = objects_refs.end(); + + if(ref_name.isEmpty()) + return(-1); + + while(itr != itr_end) + { + if((*itr).ref_name == ref_name) + { + idx = itr - objects_refs.begin(); + break; + } + + itr++; + } + + return(idx); +} + +bool GenericSQL::isObjectReferenced(BaseObject *object) +{ + bool found = false; + vector::iterator itr = objects_refs.begin(), + itr_end = objects_refs.end(); + + if(!object) + return(false); + + while(itr != itr_end && !found) + { + found = ((*itr).object == object); + itr++; + } + + return(found); +} + +bool GenericSQL::isReferRelationshipAddedObject(void) +{ + bool found = false; + vector::iterator itr = objects_refs.begin(), + itr_end = objects_refs.end(); + TableObject *tab_obj = nullptr; + + while(itr != itr_end && !found) + { + tab_obj = dynamic_cast(itr->object); + found = (tab_obj && tab_obj->isAddedByRelationship()); + itr++; + } + + return(found); +} + +vector GenericSQL::getReferencedObjects(void) +{ + vector ref_objs; + + for(auto &ref : objects_refs) + ref_objs.push_back(ref.object); + + return(ref_objs); +} + +void GenericSQL::validateObjectReference(ObjectRefConfig ref, bool ignore_duplic) +{ + if(!ref.object) + throw Exception(ErrorCode::AsgNotAllocatedObjectReference,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + if(!BaseObject::isValidName(ref.ref_name)) + throw Exception(ErrorCode::AsgInvalidNameObjReference,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + if(!ignore_duplic && getObjectRefNameIndex(ref.ref_name) >= 0) + throw Exception(Exception::getErrorMessage(ErrorCode::InsDuplicatedObjectReference).arg(ref.ref_name), + ErrorCode::InsDuplicatedObjectReference,__PRETTY_FUNCTION__,__FILE__,__LINE__); +} + +void GenericSQL::addObjectReference(BaseObject *object, const QString &ref_name, bool use_signature, bool format_name) +{ + try + { + ObjectRefConfig ref = ObjectRefConfig(ref_name, object, use_signature, format_name); + validateObjectReference(ref, false); + objects_refs.push_back(ref); + setCodeInvalidated(true); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + } +} + +void GenericSQL::updateObjectReference(const QString &ref_name, BaseObject *object, const QString &new_ref_name, bool use_signature, bool format_name) +{ + int idx = getObjectRefNameIndex(ref_name); + + if(idx < 0) + return; + + try + { + ObjectRefConfig ref = ObjectRefConfig(new_ref_name, object, use_signature, format_name); + vector::iterator itr = objects_refs.begin() + idx; + int idx_aux = getObjectRefNameIndex(new_ref_name); + + if(idx_aux != idx) + throw Exception(Exception::getErrorMessage(ErrorCode::InsDuplicatedObjectReference).arg(new_ref_name), + ErrorCode::InsDuplicatedObjectReference,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + validateObjectReference(ref, true); + (*itr) = ref; + setCodeInvalidated(true); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + } +} + +void GenericSQL::removeObjectReference(const QString &ref_name) +{ + int idx = getObjectRefNameIndex(ref_name); + + if(idx >= 0) + objects_refs.erase(objects_refs.begin() + idx); + + setCodeInvalidated(true); +} + +void GenericSQL::removeObjectReferences(void) +{ + objects_refs.clear(); + setCodeInvalidated(true); +} + QString GenericSQL::getCodeDefinition(unsigned def_type) { QString code_def=getCachedCode(def_type, false); if(!code_def.isEmpty()) return(code_def); - attributes[ParsersAttributes::DEFINITION] = definition; - return(this->BaseObject::__getCodeDefinition(def_type)); -} + QString fmt_definition = definition, + name_attr = QString("%1%2%3").arg(SchemaParser::CharIniAttribute) + .arg(Attributes::Name) + .arg(SchemaParser::CharEndAttribute); -void GenericSQL::operator = (GenericSQL &genericsql) -{ - (*dynamic_cast(this))=reinterpret_cast(genericsql); + if(!objects_refs.empty()) + { + QString ref_name, ref_value; + attribs_map obj_attrs; + + for(auto &ref : objects_refs) + { + if(def_type == SchemaParser::XmlDefinition) + { + obj_attrs[Attributes::Name] = ref.object->getSignature(); + obj_attrs[Attributes::Type] = ref.object->getSchemaName(); + obj_attrs[Attributes::RefName] = ref.ref_name; + obj_attrs[Attributes::FormatName] = ref.format_name ? Attributes::True : QString(); + obj_attrs[Attributes::UseSignature] = ref.use_signature ? Attributes::True : QString(); + + schparser.ignoreUnkownAttributes(true); + attributes[Attributes::Objects] += schparser.getCodeDefinition(Attributes::Object, obj_attrs, SchemaParser::XmlDefinition); + } + else + { + /* In order to use a reference name in the object's SQL code, the reference should be writter in the for + * {ref_name} so it can be replaced by the corresponding value in the SQL code */ + ref_name = QString("%1%2%3").arg(SchemaParser::CharIniAttribute) + .arg(ref.ref_name) + .arg(SchemaParser::CharEndAttribute); + + // Configuring the value of the reference + ref_value = ref.use_signature ? + ref.object->getSignature(ref.format_name) : + ref.object->getName(ref.format_name); + + fmt_definition = fmt_definition.replace(ref_name, ref_value); + } + } + } + + // Special case for the {name} attribute which is created automatically when there's no one defined by the user + if(def_type == SchemaParser::SqlDefinition && + fmt_definition.contains(name_attr) && getObjectRefNameIndex(Attributes::Name) < 0) + fmt_definition = fmt_definition.replace(name_attr, this->getName(true)); + + attributes[Attributes::Definition] = fmt_definition; + + return(this->BaseObject::__getCodeDefinition(def_type)); } diff --git a/libpgmodeler/src/genericsql.h b/libpgmodeler/src/genericsql.h index b21d0ce506..6f44bfc22f 100644 --- a/libpgmodeler/src/genericsql.h +++ b/libpgmodeler/src/genericsql.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -26,21 +26,69 @@ #define GENERIC_SQL_H #include "baseobject.h" +#include class GenericSQL: public BaseObject{ + protected: + + //! \brief This is a internal structure used to hold object references configuration + struct ObjectRefConfig { + QString ref_name; // Name of the reference (in SQL it be used between {} in order to be parsed) + BaseObject *object; // The object being referenced + bool use_signature, // Indicates that the signature of the object should be used instead of the name + format_name; // Indicates that the name of the object need to be automatically quoted or the schema name appended + ObjectRefConfig(const QString &_ref_name, BaseObject *_object, bool _use_signature, bool _format_name) : + ref_name(_ref_name), object(_object), use_signature(_use_signature), format_name(_format_name) {} + }; + + //! \brief Returns a copy of the objects references list + vector getObjectsReferences(void); + private: + //! \brief The SQL definition of the generic object QString definition; + //! \brief The list of references to other object in the model + vector objects_refs; + + /*! \brief Returns the index of a object reference searching by its name. + * A negative return value indicates the reference doens't exist */ + int getObjectRefNameIndex(const QString &ref_name); + + /*! \brief Check if the provided object reference is correclty configured. + * The method will raise exceptions if any validation rule is broken. + * The parameter ignore_duplic makes the method ignore duplicated references names */ + void validateObjectReference(ObjectRefConfig ref, bool ignore_duplic); + public: GenericSQL(void); void setDefinition(const QString &def); QString getDefinition(void); - //! \brief Copies the attributes between generic sql objects - void operator = (GenericSQL &genericsql); + void addObjectReference(BaseObject *object, const QString &ref_name, bool use_signature, bool format_name); + void updateObjectReference(const QString &ref_name, BaseObject *object, const QString &new_ref_name, bool use_signature, bool format_name); + void removeObjectReference(const QString &ref_name); + void removeObjectReferences(void); + + //! \brief Returns true when the provided object is being referenced by the generic SQL object + bool isObjectReferenced(BaseObject *object); + + /*! \brief Returns whether the object references columns or constraints added + * by relationship to their parent tables. This method is used as auxiliary + * to control which generic SQL object references objects added by the + * relationship in order to avoid referece breaking due constants + * connections and disconnections of relationships */ + bool isReferRelationshipAddedObject(void); + + /*! \brief Returns a list of objectes being referenced by the generic object. + * For performance reasons this method doesn't eliminate duplicated values in + * the retunring list*/ + vector getReferencedObjects(void); virtual QString getCodeDefinition(unsigned def_type); + + friend class GenericSQLWidget; }; #endif diff --git a/libpgmodeler/src/index.cpp b/libpgmodeler/src/index.cpp index 242e61b5bc..cdfb5843bb 100644 --- a/libpgmodeler/src/index.cpp +++ b/libpgmodeler/src/index.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,26 +20,26 @@ Index::Index(void) { - obj_type=OBJ_INDEX; - index_attribs[UNIQUE]=index_attribs[CONCURRENT]= - index_attribs[FAST_UPDATE]=index_attribs[BUFFERING]=false; + obj_type=ObjectType::Index; + index_attribs[Unique]=index_attribs[Concurrent]= + index_attribs[FastUpdate]=index_attribs[Buffering]=false; fill_factor=90; - attributes[ParsersAttributes::UNIQUE]=QString(); - attributes[ParsersAttributes::CONCURRENT]=QString(); - attributes[ParsersAttributes::TABLE]=QString(); - attributes[ParsersAttributes::INDEX_TYPE]=QString(); - attributes[ParsersAttributes::COLUMNS]=QString(); - attributes[ParsersAttributes::EXPRESSION]=QString(); - attributes[ParsersAttributes::FACTOR]=QString(); - attributes[ParsersAttributes::PREDICATE]=QString(); - attributes[ParsersAttributes::OP_CLASS]=QString(); - attributes[ParsersAttributes::NULLS_FIRST]=QString(); - attributes[ParsersAttributes::ASC_ORDER]=QString(); - attributes[ParsersAttributes::DECL_IN_TABLE]=QString(); - attributes[ParsersAttributes::ELEMENTS]=QString(); - attributes[ParsersAttributes::FAST_UPDATE]=QString(); - attributes[ParsersAttributes::BUFFERING]=QString(); - attributes[ParsersAttributes::STORAGE_PARAMS]=QString(); + attributes[Attributes::Unique]=QString(); + attributes[Attributes::Concurrent]=QString(); + attributes[Attributes::Table]=QString(); + attributes[Attributes::IndexType]=QString(); + attributes[Attributes::Columns]=QString(); + attributes[Attributes::Expression]=QString(); + attributes[Attributes::Factor]=QString(); + attributes[Attributes::Predicate]=QString(); + attributes[Attributes::OpClass]=QString(); + attributes[Attributes::NullsFirst]=QString(); + attributes[Attributes::AscOrder]=QString(); + attributes[Attributes::DeclInTable]=QString(); + attributes[Attributes::Elements]=QString(); + attributes[Attributes::FastUpdate]=QString(); + attributes[Attributes::Buffering]=QString(); + attributes[Attributes::StorageParams]=QString(); } void Index::setIndexElementsAttribute(unsigned def_type) @@ -51,10 +51,10 @@ void Index::setIndexElementsAttribute(unsigned def_type) for(i=0; i < count; i++) { str_elem+=idx_elements[i].getCodeDefinition(def_type); - if(i < (count-1) && def_type==SchemaParser::SQL_DEFINITION) str_elem+=','; + if(i < (count-1) && def_type==SchemaParser::SqlDefinition) str_elem+=','; } - attributes[ParsersAttributes::ELEMENTS]=str_elem; + attributes[Attributes::Elements]=str_elem; } int Index::getElementIndex(IndexElement elem) @@ -74,9 +74,9 @@ int Index::getElementIndex(IndexElement elem) void Index::addIndexElement(IndexElement elem) { if(getElementIndex(elem) >= 0) - throw Exception(ERR_INS_DUPLIC_ELEMENT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InsDuplicatedElement,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(elem.getExpression().isEmpty() && !elem.getColumn()) - throw Exception(ERR_ASG_INV_EXPR_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidExpressionObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); idx_elements.push_back(elem); setCodeInvalidated(true); @@ -91,18 +91,18 @@ void Index::addIndexElement(const QString &expr, Collation *coll, OperatorClass //Raises an error if the expression is empty if(expr.isEmpty()) - throw Exception(ERR_ASG_INV_EXPR_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidExpressionObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Configures the element elem.setExpression(expr); elem.setOperatorClass(op_class); elem.setCollation(coll); elem.setSortingEnabled(use_sorting); - elem.setSortingAttribute(IndexElement::NULLS_FIRST, nulls_first); - elem.setSortingAttribute(IndexElement::ASC_ORDER, asc_order); + elem.setSortingAttribute(IndexElement::NullsFirst, nulls_first); + elem.setSortingAttribute(IndexElement::AscOrder, asc_order); if(getElementIndex(elem) >= 0) - throw Exception(ERR_INS_DUPLIC_ELEMENT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InsDuplicatedElement,__PRETTY_FUNCTION__,__FILE__,__LINE__); idx_elements.push_back(elem); setCodeInvalidated(true); @@ -110,7 +110,7 @@ void Index::addIndexElement(const QString &expr, Collation *coll, OperatorClass } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -122,21 +122,21 @@ void Index::addIndexElement(Column *column, Collation *coll, OperatorClass *op_c //Case the column is not allocated raises an error if(!column) - throw Exception(Exception::getErrorMessage(ERR_ASG_NOT_ALOC_COLUMN) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgNotAllocatedColumn) .arg(this->getName()) .arg(this->getTypeName()), - ERR_ASG_NOT_ALOC_COLUMN, __PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgNotAllocatedColumn, __PRETTY_FUNCTION__,__FILE__,__LINE__); //Configures the element elem.setColumn(column); elem.setOperatorClass(op_class); elem.setCollation(coll); elem.setSortingEnabled(use_sorting); - elem.setSortingAttribute(IndexElement::NULLS_FIRST, nulls_first); - elem.setSortingAttribute(IndexElement::ASC_ORDER, asc_order); + elem.setSortingAttribute(IndexElement::NullsFirst, nulls_first); + elem.setSortingAttribute(IndexElement::AscOrder, asc_order); if(getElementIndex(elem) >= 0) - throw Exception(ERR_INS_DUPLIC_ELEMENT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InsDuplicatedElement,__PRETTY_FUNCTION__,__FILE__,__LINE__); idx_elements.push_back(elem); setCodeInvalidated(true); @@ -144,7 +144,7 @@ void Index::addIndexElement(Column *column, Collation *coll, OperatorClass *op_c } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -162,14 +162,14 @@ void Index::addIndexElements(vector &elems) catch(Exception &e) { idx_elements = elems_bkp; - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void Index::removeIndexElement(unsigned idx_elem) { if(idx_elem >= idx_elements.size()) - throw Exception(ERR_REF_ELEM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); idx_elements.erase(idx_elements.begin() + idx_elem); setCodeInvalidated(true); @@ -184,7 +184,7 @@ void Index::removeIndexElements(void) IndexElement Index::getIndexElement(unsigned elem_idx) { if(elem_idx >= idx_elements.size()) - throw Exception(ERR_REF_ELEM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(idx_elements[elem_idx]); } @@ -201,8 +201,8 @@ unsigned Index::getIndexElementCount(void) void Index::setIndexAttribute(unsigned attrib_id, bool value) { - if(attrib_id > BUFFERING) - throw Exception(ERR_REF_ATTRIB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(attrib_id > Buffering) + throw Exception(ErrorCode::RefAttributeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(index_attribs[attrib_id] != value); index_attribs[attrib_id]=value; @@ -234,8 +234,8 @@ unsigned Index::getFillFactor(void) bool Index::getIndexAttribute(unsigned attrib_id) { - if(attrib_id > BUFFERING) - throw Exception(ERR_REF_ATTRIB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(attrib_id > Buffering) + throw Exception(ErrorCode::RefAttributeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(index_attribs[attrib_id]); } @@ -331,38 +331,38 @@ QString Index::getCodeDefinition(unsigned def_type) if(!code_def.isEmpty()) return(code_def); setIndexElementsAttribute(def_type); - attributes[ParsersAttributes::UNIQUE]=(index_attribs[UNIQUE] ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::CONCURRENT]=(index_attribs[CONCURRENT] ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::INDEX_TYPE]=(~indexing_type); - attributes[ParsersAttributes::PREDICATE]=predicate; - attributes[ParsersAttributes::STORAGE_PARAMS]=QString(); + attributes[Attributes::Unique]=(index_attribs[Unique] ? Attributes::True : QString()); + attributes[Attributes::Concurrent]=(index_attribs[Concurrent] ? Attributes::True : QString()); + attributes[Attributes::IndexType]=(~indexing_type); + attributes[Attributes::Predicate]=predicate; + attributes[Attributes::StorageParams]=QString(); if(getParentTable()) { - attributes[ParsersAttributes::TABLE]=getParentTable()->getName(true); + attributes[Attributes::Table]=getParentTable()->getName(true); - if(def_type==SchemaParser::SQL_DEFINITION && getParentTable()->getSchema()) - attributes[ParsersAttributes::SCHEMA]=getParentTable()->getSchema()->getName(true); + if(def_type==SchemaParser::SqlDefinition && getParentTable()->getSchema()) + attributes[Attributes::Schema]=getParentTable()->getSchema()->getName(true); } - if(this->indexing_type==IndexingType::gin) - attributes[ParsersAttributes::STORAGE_PARAMS]=attributes[ParsersAttributes::FAST_UPDATE]=(index_attribs[FAST_UPDATE] ? ParsersAttributes::_TRUE_ : QString()); + if(this->indexing_type==IndexingType::Gin) + attributes[Attributes::StorageParams]=attributes[Attributes::FastUpdate]=(index_attribs[FastUpdate] ? Attributes::True : QString()); - if(this->indexing_type==IndexingType::gist) - attributes[ParsersAttributes::STORAGE_PARAMS]=attributes[ParsersAttributes::BUFFERING]=(index_attribs[BUFFERING] ? ParsersAttributes::_TRUE_ : QString()); + if(this->indexing_type==IndexingType::Gist) + attributes[Attributes::StorageParams]=attributes[Attributes::Buffering]=(index_attribs[Buffering] ? Attributes::True : QString()); - if(/*this->indexing_type==IndexingType::btree && */fill_factor >= 10) + if(this->indexing_type!=IndexingType::Gin && fill_factor >= 10) { - attributes[ParsersAttributes::FACTOR]=QString("%1").arg(fill_factor); - attributes[ParsersAttributes::STORAGE_PARAMS]=ParsersAttributes::_TRUE_; + attributes[Attributes::Factor]=QString("%1").arg(fill_factor); + attributes[Attributes::StorageParams]=Attributes::True; } - else if(def_type==SchemaParser::XML_DEFINITION) - attributes[ParsersAttributes::FACTOR]=QString("0"); + else if(def_type==SchemaParser::XmlDefinition) + attributes[Attributes::Factor]=QString("0"); /* Case the index doesn't referece some column added by relationship it will be declared inside the parent table construction by the use of 'decl-in-table' schema attribute */ if(!isReferRelationshipAddedColumn()) - attributes[ParsersAttributes::DECL_IN_TABLE]=ParsersAttributes::_TRUE_; + attributes[Attributes::DeclInTable]=Attributes::True; return(BaseObject::__getCodeDefinition(def_type)); } @@ -380,25 +380,26 @@ QString Index::getAlterDefinition(BaseObject *object) Index *index=dynamic_cast(object); if(!index) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { attribs_map attribs; - attributes[ParsersAttributes::ALTER_CMDS]=BaseObject::getAlterDefinition(object); + attributes[Attributes::AlterCmds]=BaseObject::getAlterDefinition(object); if(this->indexing_type==index->indexing_type) { - if(this->fill_factor!=index->fill_factor && index->fill_factor >= 10) - attribs[ParsersAttributes::FACTOR]=QString::number(index->fill_factor); + if(this->indexing_type != IndexingType::Gin && + this->fill_factor!=index->fill_factor && index->fill_factor >= 10) + attribs[Attributes::Factor]=QString::number(index->fill_factor); - if(this->indexing_type==IndexingType::gin && - this->index_attribs[FAST_UPDATE] != index->index_attribs[FAST_UPDATE]) - attribs[ParsersAttributes::FAST_UPDATE]=(index->index_attribs[FAST_UPDATE] ? ParsersAttributes::_TRUE_ : ParsersAttributes::UNSET); + if(this->indexing_type==IndexingType::Gin && + this->index_attribs[FastUpdate] != index->index_attribs[FastUpdate]) + attribs[Attributes::FastUpdate]=(index->index_attribs[FastUpdate] ? Attributes::True : Attributes::Unset); - if(this->indexing_type==IndexingType::gist && - this->index_attribs[BUFFERING] != index->index_attribs[BUFFERING]) - attribs[ParsersAttributes::BUFFERING]=(index->index_attribs[BUFFERING] ? ParsersAttributes::_TRUE_ : ParsersAttributes::UNSET); + if(this->indexing_type==IndexingType::Gist && + this->index_attribs[Buffering] != index->index_attribs[Buffering]) + attribs[Attributes::Buffering]=(index->index_attribs[Buffering] ? Attributes::True : Attributes::Unset); } copyAttributes(attribs); @@ -406,13 +407,13 @@ QString Index::getAlterDefinition(BaseObject *object) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } void Index::validateElements(void) { - if(indexing_type!=IndexingType::btree) + if(indexing_type!=IndexingType::Btree) { for(unsigned i=0; i < idx_elements.size(); i++) { diff --git a/libpgmodeler/src/index.h b/libpgmodeler/src/index.h index d372b739be..596d1f7962 100644 --- a/libpgmodeler/src/index.h +++ b/libpgmodeler/src/index.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -54,10 +54,10 @@ class Index: public TableObject{ void validateElements(void); public: - static const unsigned UNIQUE=0, - CONCURRENT=1, - FAST_UPDATE=2, - BUFFERING=3; + static constexpr unsigned Unique=0, + Concurrent=1, + FastUpdate=2, + Buffering=3; Index(void); diff --git a/libpgmodeler/src/indexelement.cpp b/libpgmodeler/src/indexelement.cpp index 95a93d0970..a4a7297294 100644 --- a/libpgmodeler/src/indexelement.cpp +++ b/libpgmodeler/src/indexelement.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -38,17 +38,17 @@ QString IndexElement::getCodeDefinition(unsigned def_type) attribs_map attributes; schparser.setPgSQLVersion(BaseObject::getPgSQLVersion()); - attributes[ParsersAttributes::COLLATION]=QString(); + attributes[Attributes::Collation]=QString(); configureAttributes(attributes, def_type); if(collation) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::COLLATION]=collation->getName(true); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Collation]=collation->getName(true); else - attributes[ParsersAttributes::COLLATION]=collation->getCodeDefinition(def_type, true); + attributes[Attributes::Collation]=collation->getCodeDefinition(def_type, true); } - return(schparser.getCodeDefinition(ParsersAttributes::INDEX_ELEMENT,attributes, def_type)); + return(schparser.getCodeDefinition(Attributes::IndexElement,attributes, def_type)); } diff --git a/libpgmodeler/src/indexelement.h b/libpgmodeler/src/indexelement.h index c472a6bc8a..48a05a50da 100644 --- a/libpgmodeler/src/indexelement.h +++ b/libpgmodeler/src/indexelement.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libpgmodeler/src/language.cpp b/libpgmodeler/src/language.cpp index 050e3a8eae..a2a53ae77d 100644 --- a/libpgmodeler/src/language.cpp +++ b/libpgmodeler/src/language.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,26 +20,26 @@ Language::Language(void) { - obj_type=OBJ_LANGUAGE; + obj_type=ObjectType::Language; is_trusted=false; - for(unsigned i=VALIDATOR_FUNC; i <= INLINE_FUNC; i++) + for(unsigned i=ValidatorFunc; i <= InlineFunc; i++) functions[i]=nullptr; - attributes[ParsersAttributes::TRUSTED]=QString(); - attributes[ParsersAttributes::HANDLER_FUNC]=QString(); - attributes[ParsersAttributes::VALIDATOR_FUNC]=QString(); - attributes[ParsersAttributes::INLINE_FUNC]=QString(); + attributes[Attributes::Trusted]=QString(); + attributes[Attributes::HandlerFunc]=QString(); + attributes[Attributes::ValidatorFunc]=QString(); + attributes[Attributes::InlineFunc]=QString(); } void Language::setName(const QString &name) { //Raises an error if the user try to set an system reserved language name (C, SQL) if(name.toLower()==~LanguageType("c") || name.toLower()==~LanguageType("sql")) - throw Exception(Exception::getErrorMessage(ERR_ASG_RESERVED_NAME) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgReservedName) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_LANGUAGE)), - ERR_ASG_RESERVED_NAME,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Language)), + ErrorCode::AsgReservedName,__PRETTY_FUNCTION__,__FILE__,__LINE__); BaseObject::setName(name); } @@ -52,26 +52,26 @@ void Language::setTrusted(bool value) void Language::setFunction(Function *func, unsigned func_type) { - LanguageType lang=LanguageType::c; + LanguageType lang=LanguageType::C; if(!func || (func && /* The handler function must be written in C and have 'language_handler' as return type */ - ((func_type==HANDLER_FUNC && + ((func_type==HandlerFunc && func->getReturnType()==QString("language_handler") && func->getParameterCount()==0 && func->getLanguage()->getName()==(~lang)) || /* The validator function must be written in C and return 'void' also must have only one parameter of the type 'oid' */ - (func_type==VALIDATOR_FUNC && + (func_type==ValidatorFunc && func->getReturnType()==QString("void") && func->getParameterCount()==1 && func->getParameter(0).getType() == QString("oid") && func->getLanguage()->getName()==(~lang)) || /* The inline function must be written in C and return 'void' also must have only one parameter of the type 'internal' */ - (func_type==INLINE_FUNC && + (func_type==InlineFunc && func->getReturnType()==QString("void") && func->getParameterCount()==1 && func->getParameter(0).getType() == QString("internal") && @@ -81,21 +81,21 @@ void Language::setFunction(Function *func, unsigned func_type) this->functions[func_type]=func; } //Raises an error in case the function return type doesn't matches the required by each rule - else if((func_type==HANDLER_FUNC && func->getReturnType()!=QString("language_handler")) || - ((func_type==VALIDATOR_FUNC || func_type==INLINE_FUNC) && func->getReturnType()!=QString("void"))) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNCTION_INV_RET_TYPE) + else if((func_type==HandlerFunc && func->getReturnType()!=QString("language_handler")) || + ((func_type==ValidatorFunc || func_type==InlineFunc) && func->getReturnType()!=QString("void"))) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidReturnType) .arg(this->getName(true)) - .arg(BaseObject::getTypeName(OBJ_LANGUAGE)), - ERR_ASG_FUNCTION_INV_RET_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Language)), + ErrorCode::AsgFunctionInvalidReturnType,__PRETTY_FUNCTION__,__FILE__,__LINE__); else //Raises an error in case the function has invalid parameters (count and types) - throw Exception(ERR_ASG_FUNCTION_INV_PARAMS,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgFunctionInvalidParameters,__PRETTY_FUNCTION__,__FILE__,__LINE__); } Function * Language::getFunction(unsigned func_type) { - if(func_type > INLINE_FUNC) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(func_type > InlineFunc) + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(functions[func_type]); } @@ -116,24 +116,24 @@ QString Language::getCodeDefinition(unsigned def_type, bool reduced_form) if(!code_def.isEmpty()) return(code_def); unsigned i; - QString attribs_func[3]={ParsersAttributes::VALIDATOR_FUNC, - ParsersAttributes::HANDLER_FUNC, - ParsersAttributes::INLINE_FUNC}; + QString attribs_func[3]={Attributes::ValidatorFunc, + Attributes::HandlerFunc, + Attributes::InlineFunc}; - attributes[ParsersAttributes::TRUSTED]=(is_trusted ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::Trusted]=(is_trusted ? Attributes::True : QString()); - if(!reduced_form && def_type==SchemaParser::XML_DEFINITION) - reduced_form=(!functions[VALIDATOR_FUNC] && !functions[HANDLER_FUNC] && !functions[INLINE_FUNC] && !this->getOwner()); + if(!reduced_form && def_type==SchemaParser::XmlDefinition) + reduced_form=(!functions[ValidatorFunc] && !functions[HandlerFunc] && !functions[InlineFunc] && !this->getOwner()); for(i=0; i < 3; i++) { if(functions[i]) { - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) attributes[attribs_func[i]]=functions[i]->getName(true); else { - functions[i]->setAttribute(ParsersAttributes::REF_TYPE, attribs_func[i]); + functions[i]->setAttribute(Attributes::RefType, attribs_func[i]); attributes[attribs_func[i]]=functions[i]->getCodeDefinition(def_type, true); } } diff --git a/libpgmodeler/src/language.h b/libpgmodeler/src/language.h index c76b41ce48..52b07a6cfd 100644 --- a/libpgmodeler/src/language.h +++ b/libpgmodeler/src/language.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -45,9 +45,9 @@ class Language: public BaseObject{ > VALIDATOR: Function that validates the code written in the language's syntax > HANDLER: Function that executes the functions written in the language's syntax > INLINE: Function that executes inline instructions (DO's) (only on PostgreSQL 9.x) */ - static const unsigned VALIDATOR_FUNC=0, - HANDLER_FUNC=1, - INLINE_FUNC=2; + static constexpr unsigned ValidatorFunc=0, + HandlerFunc=1, + InlineFunc=2; Language(void); diff --git a/libpgmodeler/src/operation.cpp b/libpgmodeler/src/operation.cpp index 21bc64a67a..2f20bff6e0 100644 --- a/libpgmodeler/src/operation.cpp +++ b/libpgmodeler/src/operation.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -24,8 +24,8 @@ Operation::Operation(void) pool_obj=nullptr; original_obj=nullptr; object_idx=-1; - chain_type=NO_CHAIN; - op_type=NO_OPERATION; + chain_type=NoChain; + op_type=NoOperation; } QString Operation::generateOperationId(void) @@ -51,12 +51,12 @@ void Operation::setObjectIndex(int idx) void Operation::setChainType(unsigned type) { - chain_type=(type > CHAIN_END ? NO_CHAIN : type); + chain_type=(type > ChainEnd ? NoChain : type); } void Operation::setOperationType(unsigned type) { - op_type=(type > OBJECT_MOVED ? NO_OPERATION : type); + op_type=(type > ObjectMoved ? NoOperation : type); } void Operation::setOriginalObject(BaseObject *object) diff --git a/libpgmodeler/src/operation.h b/libpgmodeler/src/operation.h index f8fc51e5f0..f488ebc446 100644 --- a/libpgmodeler/src/operation.h +++ b/libpgmodeler/src/operation.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -70,21 +70,21 @@ class Operation { public: //! \brief Constants used to reference the type of operations - static const unsigned NO_OPERATION=0, - OBJECT_MODIFIED=1, - OBJECT_CREATED=2, - OBJECT_REMOVED=3, + static constexpr unsigned NoOperation=0, + ObjectModified=1, + ObjectCreated=2, + ObjectRemoved=3, /*! \brief This type of operation has the same effect of operation OBJECT_MODIFIED except that it not (re)validate relationships as happens with operations. This type of operation (OBJECT_MOVED) is useful to undo position changes of graphical objects without executing unnecessary revalidations of relationships */ - OBJECT_MOVED=4; + ObjectMoved=4; //! \brief Operation chain types - static const unsigned NO_CHAIN=0, //! \brief The operation is not part of a chain - CHAIN_START=1, //! \brief The operation is the head of the chain - CHAIN_MIDDLE=2, //! \brief The operation is in the middle of the chain - CHAIN_END=3; //! \brief The operation is the last on the chain + static constexpr unsigned NoChain=0, //! \brief The operation is not part of a chain + ChainStart=1, //! \brief The operation is the head of the chain + ChainMiddle=2, //! \brief The operation is in the middle of the chain + ChainEnd=3; //! \brief The operation is the last on the chain Operation(void); diff --git a/libpgmodeler/src/operationlist.cpp b/libpgmodeler/src/operationlist.cpp index f5e2d5e758..38ddfdbb70 100644 --- a/libpgmodeler/src/operationlist.cpp +++ b/libpgmodeler/src/operationlist.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -25,13 +25,14 @@ OperationList::OperationList(DatabaseModel *model) /* Raises an error if the user tries to allocate an operation list linked to to an unallocated model */ if(!model) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->model=model; xmlparser=model->getXMLParser(); current_index=0; - next_op_chain=Operation::NO_CHAIN; + next_op_chain=Operation::NoChain; ignore_chain=false; + operations.reserve(max_size); } OperationList::~OperationList(void) @@ -58,12 +59,12 @@ void OperationList::startOperationChain(void) { /* If the chaining is started and the user try it initializes again, the earlier chaining is finished */ - if(next_op_chain!=Operation::NO_CHAIN) + if(next_op_chain!=Operation::NoChain) finishOperationChain(); /* The next operation inserted on the list will be the start of the chaining */ - next_op_chain=Operation::CHAIN_START; + next_op_chain=Operation::ChainStart; } void OperationList::finishOperationChain(void) @@ -71,11 +72,11 @@ void OperationList::finishOperationChain(void) /* If the chain is not ignored indicates that the next element of the list no longer will be part of chaining */ if(!ignore_chain) - next_op_chain=Operation::NO_CHAIN; + next_op_chain=Operation::NoChain; else if(ignore_chain) /* If the chain is canceled indicates that the next element of the list still part of the chaining */ - next_op_chain=Operation::CHAIN_MIDDLE; + next_op_chain=Operation::ChainMiddle; if(operations.size() > 0 && !ignore_chain) { @@ -83,15 +84,15 @@ void OperationList::finishOperationChain(void) /* Marks the last operatin as being the end of chaining in case it is on the middle of chain */ - if(operations[idx]->getChainType()==Operation::CHAIN_MIDDLE) - operations[idx]->setChainType(Operation::CHAIN_END); + if(operations[idx]->getChainType()==Operation::ChainMiddle) + operations[idx]->setChainType(Operation::ChainEnd); /* If the last operation is marked as CHAIN_START indicates that the chaining was open but only one operation is recorded and thus the operation is marked as NO_CHAIN because as it is only one operation there is no need to treat it as chaining */ - else if(operations[idx]->getChainType()==Operation::CHAIN_START) - operations[idx]->setChainType(Operation::NO_CHAIN); + else if(operations[idx]->getChainType()==Operation::ChainStart) + operations[idx]->setChainType(Operation::NoChain); } } @@ -102,8 +103,8 @@ void OperationList::ignoreOperationChain(bool value) bool OperationList::isOperationChainStarted(void) { - return(next_op_chain==Operation::CHAIN_START || - next_op_chain==Operation::CHAIN_MIDDLE); + return(next_op_chain==Operation::ChainStart || + next_op_chain==Operation::ChainMiddle); } bool OperationList::isObjectRegistered(BaseObject *object, unsigned op_type) @@ -139,7 +140,7 @@ void OperationList::setMaximumSize(unsigned max) { //Raises an error if a zero max size is assigned to the list if(max==0) - throw Exception(ERR_ASG_INV_MAX_SIZE_OP_LIST,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidMaxSizeOpList,__PRETTY_FUNCTION__,__FILE__,__LINE__); max_size=max; } @@ -153,24 +154,24 @@ void OperationList::addToPool(BaseObject *object, unsigned op_type) //Raises an error if the object to be added is not allocated if(!object) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); obj_type=object->getObjectType(); //Stores a copy of the object if its about to be moved or modified - if(op_type==Operation::OBJECT_MODIFIED || - op_type==Operation::OBJECT_MOVED) + if(op_type==Operation::ObjectModified || + op_type==Operation::ObjectMoved) { BaseObject *copy_obj=nullptr; - if(obj_type!=BASE_OBJECT && obj_type!=OBJ_DATABASE) - PgModelerNS::copyObject(©_obj, object, obj_type); + if(obj_type!=ObjectType::BaseObject && obj_type!=ObjectType::Database) + PgModelerNs::copyObject(©_obj, object, obj_type); else - throw Exception(ERR_ASG_OBJECT_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the copy fails (returning a null object) if(!copy_obj) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else //Inserts the copy on the pool object_pool.push_back(copy_obj); @@ -181,7 +182,7 @@ void OperationList::addToPool(BaseObject *object, unsigned op_type) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -227,7 +228,7 @@ void OperationList::removeOperations(void) if(unallocated_objs.count(object)==0 && (!tab_obj && model->getObjectIndex(object) < 0)) { - if(object->getObjectType()==OBJ_TABLE) + if(object->getObjectType()==ObjectType::Table) { vector list=dynamic_cast
(object)->getObjects(); @@ -296,7 +297,7 @@ bool OperationList::isObjectOnPool(BaseObject *object) vector::iterator itr, itr_end; if(!object) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); itr=object_pool.begin(); itr_end=object_pool.end(); @@ -314,9 +315,9 @@ void OperationList::removeFromPool(unsigned obj_idx) BaseObject *object=nullptr; vector::iterator itr; - //Raises an error if the object index is invalid (out of bound) + //Avoiding the removal of an object in invalid index (out of bound) if(obj_idx >= object_pool.size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + return; //Gets the element to bo removed through its index itr=object_pool.begin() + obj_idx; @@ -347,18 +348,18 @@ int OperationList::registerObject(BaseObject *object, unsigned op_type, int obje { //Raises an error if the user tries to register an operation with null object if(!object) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); obj_type=object->getObjectType(); if(tab_obj && !parent_obj) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(parent_obj && - (((obj_type==OBJ_COLUMN || obj_type==OBJ_CONSTRAINT) && - (parent_obj->getObjectType()!=OBJ_RELATIONSHIP && parent_obj->getObjectType()!=OBJ_TABLE)) || + (((obj_type==ObjectType::Column || obj_type==ObjectType::Constraint) && + (parent_obj->getObjectType()!=ObjectType::Relationship && parent_obj->getObjectType()!=ObjectType::Table)) || - ((obj_type==OBJ_TRIGGER || obj_type==OBJ_RULE || obj_type==OBJ_INDEX) && !dynamic_cast(parent_obj)))) - throw Exception(ERR_OPR_OBJ_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ((obj_type==ObjectType::Trigger || obj_type==ObjectType::Rule || obj_type==ObjectType::Index) && !dynamic_cast(parent_obj)))) + throw Exception(ErrorCode::OprObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); //If the operations list is full makes the automatic cleaning before inserting a new operation if(current_index == static_cast(max_size-1)) @@ -397,15 +398,15 @@ int OperationList::registerObject(BaseObject *object, unsigned op_type, int obje operation->setPoolObject(object_pool.back()); //Stores the object's permission befor its removal - if(op_type==Operation::OBJECT_REMOVED) + if(op_type==Operation::ObjectRemoved) { vector perms; model->getPermissions(object, perms); operation->setPermissions(perms); } - if(next_op_chain==Operation::CHAIN_START) - next_op_chain=Operation::CHAIN_MIDDLE; + if(next_op_chain==Operation::ChainStart) + next_op_chain=Operation::ChainMiddle; /* Performing specific operations according to the type of object. If the object has a parent object, it must be discovered @@ -413,29 +414,29 @@ int OperationList::registerObject(BaseObject *object, unsigned op_type, int obje in the list on the parent object */ if(tab_obj) { - if(parent_obj->getObjectType()==OBJ_RELATIONSHIP) + if(parent_obj->getObjectType()==ObjectType::Relationship) parent_rel=dynamic_cast(parent_obj); else parent_tab=dynamic_cast(parent_obj); - if(((obj_type==OBJ_TRIGGER && dynamic_cast(tab_obj)->isReferRelationshipAddedColumn()) || - (obj_type==OBJ_INDEX && dynamic_cast(tab_obj)->isReferRelationshipAddedColumn()) || - (obj_type==OBJ_CONSTRAINT && dynamic_cast(tab_obj)->isReferRelationshipAddedColumn()))) + if(((obj_type==ObjectType::Trigger && dynamic_cast(tab_obj)->isReferRelationshipAddedColumn()) || + (obj_type==ObjectType::Index && dynamic_cast(tab_obj)->isReferRelationshipAddedColumn()) || + (obj_type==ObjectType::Constraint && dynamic_cast(tab_obj)->isReferRelationshipAddedColumn()))) { - if(op_type==Operation::OBJECT_REMOVED) + if(op_type==Operation::ObjectRemoved) tab_obj->setParentTable(parent_tab); - if(tab_obj->getObjectType()==OBJ_CONSTRAINT) - operation->setXMLDefinition(dynamic_cast(tab_obj)->getCodeDefinition(SchemaParser::XML_DEFINITION, true)); + if(tab_obj->getObjectType()==ObjectType::Constraint) + operation->setXMLDefinition(dynamic_cast(tab_obj)->getCodeDefinition(SchemaParser::XmlDefinition, true)); else - operation->setXMLDefinition(tab_obj->getCodeDefinition(SchemaParser::XML_DEFINITION)); + operation->setXMLDefinition(tab_obj->getCodeDefinition(SchemaParser::XmlDefinition)); } operation->setParentObject(parent_obj); /* If there is a parent relationship will get the index of the object. Only columns and constraints are handled case the parent is a relationship */ - if(parent_rel && (obj_type==OBJ_COLUMN || obj_type==OBJ_CONSTRAINT)) + if(parent_rel && (obj_type==ObjectType::Column || obj_type==ObjectType::Constraint)) { //Case a specific index wasn't specified if(object_idx < 0) @@ -456,13 +457,14 @@ int OperationList::registerObject(BaseObject *object, unsigned op_type, int obje } //Raises an error if both parent table / relationship isn't allocated else - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); } else { - if((obj_type==OBJ_SEQUENCE && dynamic_cast(object)->isReferRelationshipAddedColumn()) || - (obj_type==OBJ_VIEW && dynamic_cast(object)->isReferRelationshipAddedColumn())) - operation->setXMLDefinition(object->getCodeDefinition(SchemaParser::XML_DEFINITION)); + if((obj_type==ObjectType::Sequence && dynamic_cast(object)->isReferRelationshipAddedColumn()) || + (obj_type==ObjectType::View && dynamic_cast(object)->isReferRelationshipAddedColumn()) || + (obj_type==ObjectType::GenericSql && dynamic_cast(object)->isReferRelationshipAddedObject())) + operation->setXMLDefinition(object->getCodeDefinition(SchemaParser::XmlDefinition)); //Case a specific index wasn't specified if(object_idx < 0) @@ -473,8 +475,8 @@ int OperationList::registerObject(BaseObject *object, unsigned op_type, int obje obj_idx=object_idx; } - if(obj_type==OBJ_COLUMN && dynamic_cast(object)->getType().isUserType()) - operation->setXMLDefinition(object->getCodeDefinition(SchemaParser::XML_DEFINITION)); + if(obj_type==ObjectType::Column && dynamic_cast(object)->getType().isUserType()) + operation->setXMLDefinition(object->getCodeDefinition(SchemaParser::XmlDefinition)); operation->setObjectIndex(obj_idx); operations.push_back(operation); @@ -490,7 +492,7 @@ int OperationList::registerObject(BaseObject *object, unsigned op_type, int obje removeFromPool(object_pool.size()-1); delete(operation); } - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -500,7 +502,7 @@ void OperationList::getOperationData(unsigned oper_idx, unsigned &oper_type, QSt BaseObject *pool_obj=nullptr; if(oper_idx >= operations.size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); operation=operations[oper_idx]; oper_type=operation->getOperationType(); @@ -516,7 +518,7 @@ void OperationList::getOperationData(unsigned oper_idx, unsigned &oper_type, QSt } else { - obj_type=BASE_OBJECT; + obj_type=ObjectType::BaseObject; obj_name=trUtf8("(invalid object)"); } } @@ -531,21 +533,21 @@ unsigned OperationList::getChainSize(void) //Checks if the current operations is chained if(!operations.empty() && - operations[i]->getChainType()!=Operation::NO_CHAIN) + operations[i]->getChainType()!=Operation::NoChain) { - unsigned chain_type=Operation::NO_CHAIN; + unsigned chain_type=Operation::NoChain; int inc=0; //Case the operation is the end of a chain runs the list in reverse order (from end to start) - if(operations[i]->getChainType()==Operation::CHAIN_END) + if(operations[i]->getChainType()==Operation::ChainEnd) { - chain_type=Operation::CHAIN_START; + chain_type=Operation::ChainStart; inc=-1; } //Case the operation is the start of a chain runs the list in normal order (from start to end) - else if(operations[i]->getChainType()==Operation::CHAIN_START) + else if(operations[i]->getChainType()==Operation::ChainStart) { - chain_type=Operation::CHAIN_END; + chain_type=Operation::ChainEnd; inc=1; } @@ -585,14 +587,14 @@ void OperationList::undoOperation(void) and active chaining flag is cleared marks the flag to start the execution several operations at once */ if(!ignore_chain && !chain_active && - operation->getChainType()!=Operation::NO_CHAIN) + operation->getChainType()!=Operation::NoChain) chain_active=true; /* If the chaining is active and the current operation is not part of chain, aborts execution of the operation */ else if(chain_active && - (operation->getChainType()==Operation::CHAIN_END || - operation->getChainType()==Operation::NO_CHAIN)) + (operation->getChainType()==Operation::ChainEnd || + operation->getChainType()==Operation::NoChain)) break; try @@ -614,10 +616,10 @@ void OperationList::undoOperation(void) /* Performs the operations while the current operation is part of chain or the undo option is available */ while(!ignore_chain && isUndoAvailable() && - operation->getChainType()!=Operation::NO_CHAIN); + operation->getChainType()!=Operation::NoChain); - if(error.getErrorType()!=ERR_CUSTOM) - throw Exception(ERR_UNDO_REDO_OPR_INV_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__, &error); + if(error.getErrorCode()!=ErrorCode::Custom) + throw Exception(ErrorCode::UndoRedoOperationInvalidObject,__PRETTY_FUNCTION__,__FILE__,__LINE__, &error); } } @@ -641,14 +643,14 @@ void OperationList::redoOperation(void) and active chaining flag is cleared marks the flag to start the execution several operations at once */ if(!ignore_chain && !chain_active && - operation->getChainType()!=Operation::NO_CHAIN) + operation->getChainType()!=Operation::NoChain) chain_active=true; /* If the chaining is active and the current operation is not part of chain or it is at the start of chain, aborts execution of the operation */ else if(chain_active && - (operation->getChainType()==Operation::CHAIN_START || - operation->getChainType()==Operation::NO_CHAIN)) + (operation->getChainType()==Operation::ChainStart || + operation->getChainType()==Operation::NoChain)) break; try @@ -669,10 +671,10 @@ void OperationList::redoOperation(void) /* Performs the operations while the current operation is part of chain or the redo option is available */ while(!ignore_chain && isRedoAvailable() && - operation->getChainType()!=Operation::NO_CHAIN); + operation->getChainType()!=Operation::NoChain); - if(error.getErrorType()!=ERR_CUSTOM) - throw Exception(ERR_UNDO_REDO_OPR_INV_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__, &error); + if(error.getErrorCode()!=ErrorCode::Custom) + throw Exception(ErrorCode::UndoRedoOperationInvalidObject,__PRETTY_FUNCTION__,__FILE__,__LINE__, &error); } } @@ -686,7 +688,7 @@ void OperationList::executeOperation(Operation *oper, bool redo) BaseTable *parent_tab=nullptr; Relationship *parent_rel=nullptr; QString xml_def; - unsigned op_type=Operation::NO_OPERATION; + unsigned op_type=Operation::NoOperation; int obj_idx=-1; object=oper->getPoolObject(); @@ -697,13 +699,13 @@ void OperationList::executeOperation(Operation *oper, bool redo) obj_idx=oper->getObjectIndex(); /* Converting the parent object, if any, to the correct class according - to the type of the parent object. If OBJ_TABLE|OBJ_VIEW, the pointer + to the type of the parent object. If ObjectType::Table|ObjectType::View, the pointer 'parent_tab' get the reference to table/view and will be used as referential in the operations below. If the parent object is a relationship, the pointer 'parent_rel' get the reference to the relationship */ if(parent_obj) { - if(parent_obj->getObjectType()==OBJ_RELATIONSHIP) + if(parent_obj->getObjectType()==ObjectType::Relationship) parent_rel=dynamic_cast(parent_obj); else parent_tab=dynamic_cast(parent_obj); @@ -712,35 +714,36 @@ void OperationList::executeOperation(Operation *oper, bool redo) /* If the XML definition of object is set indicates that it is referencing a column included by relationship (special object) */ if(!xml_def.isEmpty() && - ((op_type==Operation::OBJECT_REMOVED && !redo) || - (op_type==Operation::OBJECT_CREATED && redo) || - (op_type==Operation::OBJECT_MODIFIED || - op_type==Operation::OBJECT_MOVED))) + ((op_type==Operation::ObjectRemoved && !redo) || + (op_type==Operation::ObjectCreated && redo) || + (op_type==Operation::ObjectModified || + op_type==Operation::ObjectMoved))) { //Resets the XML parser and loads the buffer xml from the operation xmlparser->restartParser(); xmlparser->loadXMLBuffer(xml_def); - if(obj_type==OBJ_TRIGGER) + if(obj_type==ObjectType::Trigger) aux_obj=model->createTrigger(); - else if(obj_type==OBJ_INDEX) + else if(obj_type==ObjectType::Index) aux_obj=model->createIndex(); - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) aux_obj=model->createConstraint(parent_obj); - else if(obj_type==OBJ_SEQUENCE) + else if(obj_type==ObjectType::Sequence) aux_obj=model->createSequence(); - else if(obj_type==OBJ_VIEW) + else if(obj_type==ObjectType::View) aux_obj=model->createView(); - else if(obj_type==OBJ_COLUMN) + else if(obj_type==ObjectType::Column) aux_obj=model->createColumn(); + else if(obj_type==ObjectType::GenericSql) + aux_obj=model->createGenericSQL(); } /* If the operation is a modified/moved object, the object copy stored in the pool will be restored */ - if(op_type==Operation::OBJECT_MODIFIED || - op_type==Operation::OBJECT_MOVED) + if(op_type==Operation::ObjectModified || op_type==Operation::ObjectMoved) { - if(obj_type==OBJ_RELATIONSHIP) + if(obj_type==ObjectType::Relationship) { /* Due to the complexity of the class Relationship and the strong link between all relationships of the model it is necessary to store XML for special objects and @@ -759,27 +762,27 @@ void OperationList::executeOperation(Operation *oper, bool redo) orig_obj=model->getObject(obj_idx, obj_type); if(aux_obj) - oper->setXMLDefinition(orig_obj->getCodeDefinition(SchemaParser::XML_DEFINITION)); + oper->setXMLDefinition(orig_obj->getCodeDefinition(SchemaParser::XmlDefinition)); //For pk constraint, before restore the previous configuration, uncheck the not-null flag of the source columns - if(obj_type==OBJ_CONSTRAINT) + if(obj_type==ObjectType::Constraint) dynamic_cast(orig_obj)->setColumnsNotNull(false); /* The original object (obtained from the table, relationship or model) will have its previous values restored with the existing copy on the pool. After restoring the object on the pool will have the same attributes as the object before being restored to enable redo operations */ - PgModelerNS::copyObject(reinterpret_cast(&bkp_obj), orig_obj, obj_type); - PgModelerNS::copyObject(reinterpret_cast(&orig_obj), object, obj_type); - PgModelerNS::copyObject(reinterpret_cast(&object), bkp_obj, obj_type); + PgModelerNs::copyObject(reinterpret_cast(&bkp_obj), orig_obj, obj_type); + PgModelerNs::copyObject(reinterpret_cast(&orig_obj), object, obj_type); + PgModelerNs::copyObject(reinterpret_cast(&object), bkp_obj, obj_type); object=orig_obj; if(aux_obj) - PgModelerNS::copyObject(reinterpret_cast(&object), aux_obj, obj_type); + PgModelerNs::copyObject(reinterpret_cast(&object), aux_obj, obj_type); //For pk constraint, after restore the previous configuration, check the not-null flag of the new source columns - if(obj_type==OBJ_CONSTRAINT) + if(obj_type==ObjectType::Constraint) dynamic_cast(orig_obj)->setColumnsNotNull(true); } @@ -787,35 +790,35 @@ void OperationList::executeOperation(Operation *oper, bool redo) if the object was previously created and wants to redo the operation the existing pool object will be inserted into table or in your relationship on its original index */ - else if((op_type==Operation::OBJECT_REMOVED && !redo) || - (op_type==Operation::OBJECT_CREATED && redo)) + else if((op_type==Operation::ObjectRemoved && !redo) || + (op_type==Operation::ObjectCreated && redo)) { if(aux_obj) - PgModelerNS::copyObject(reinterpret_cast(&object), aux_obj, obj_type); + PgModelerNs::copyObject(reinterpret_cast(&object), aux_obj, obj_type); if(parent_tab) { parent_tab->addObject(dynamic_cast(object), obj_idx); - if(object->getObjectType()==OBJ_CONSTRAINT && - dynamic_cast(object)->getConstraintType()==ConstraintType::foreign_key) + if(object->getObjectType()==ObjectType::Constraint && + dynamic_cast(object)->getConstraintType()==ConstraintType::ForeignKey) model->updateTableFKRelationships(dynamic_cast
(parent_tab)); } else if(parent_rel) parent_rel->addObject(dynamic_cast(object), obj_idx); - else if(object->getObjectType()==OBJ_TABLE) - dynamic_cast
(object)->getCodeDefinition(SchemaParser::SQL_DEFINITION); + else if(object->getObjectType()==ObjectType::Table) + dynamic_cast
(object)->getCodeDefinition(SchemaParser::SqlDefinition); model->addObject(object, obj_idx); - if(op_type==Operation::OBJECT_REMOVED) + if(op_type==Operation::ObjectRemoved) model->addPermissions(oper->getPermissions()); } /* If the operation is a previously created object or if the object was removed and wants to redo the operation it'll be excluded from the table or relationship */ - else if((op_type==Operation::OBJECT_CREATED && !redo) || - (op_type==Operation::OBJECT_REMOVED && redo)) + else if((op_type==Operation::ObjectCreated && !redo) || + (op_type==Operation::ObjectRemoved && redo)) { if(parent_tab) parent_tab->removeObject(object); @@ -837,14 +840,16 @@ void OperationList::executeOperation(Operation *oper, bool redo) if(parent_tab->getSchema()) dynamic_cast(parent_tab->getSchema())->setModified(true); - if(object->getObjectType()==OBJ_COLUMN || - object->getObjectType()==OBJ_CONSTRAINT) + if(object->getObjectType()==ObjectType::Column || + object->getObjectType()==ObjectType::Constraint) { model->validateRelationships(dynamic_cast(object), dynamic_cast
(parent_tab)); - if(object->getObjectType()==OBJ_CONSTRAINT && - dynamic_cast(object)->getConstraintType()==ConstraintType::foreign_key) + if(object->getObjectType()==ObjectType::Constraint && + dynamic_cast(object)->getConstraintType()==ConstraintType::ForeignKey) model->updateTableFKRelationships(dynamic_cast
(parent_tab)); + else if(object->getObjectType() == ObjectType::Column) + model->updateViewsReferencingTable(dynamic_cast
(parent_tab)); } } else if(parent_rel) @@ -857,43 +862,43 @@ void OperationList::executeOperation(Operation *oper, bool redo) /* If the object in question is graphical it has the modified flag marked to force the redraw at the time of its restoration */ - else if(obj_type==OBJ_TABLE || obj_type==OBJ_VIEW || - obj_type==BASE_RELATIONSHIP || obj_type==OBJ_RELATIONSHIP || - obj_type==OBJ_TEXTBOX || obj_type==OBJ_SCHEMA) + else if(obj_type==ObjectType::Table || obj_type==ObjectType::View || + obj_type==ObjectType::BaseRelationship || obj_type==ObjectType::Relationship || + obj_type==ObjectType::Textbox || obj_type==ObjectType::Schema) { BaseGraphicObject *graph_obj=dynamic_cast(object); - if(op_type==Operation::OBJECT_MODIFIED || - op_type==Operation::OBJECT_MOVED) + if(op_type==Operation::ObjectModified || + op_type==Operation::ObjectMoved) graph_obj->setModified(true); //Case the object is a view is necessary to update the table-view relationships on the model - if(obj_type==OBJ_VIEW && op_type==Operation::OBJECT_MODIFIED) + if(obj_type==ObjectType::View && op_type==Operation::ObjectModified) model->updateViewRelationships(dynamic_cast(graph_obj)); - else if((obj_type==OBJ_RELATIONSHIP || - (obj_type==OBJ_TABLE && model->getRelationship(dynamic_cast(object), nullptr))) && - op_type==Operation::OBJECT_MODIFIED) + else if((obj_type==ObjectType::Relationship || + (obj_type==ObjectType::Table && model->getRelationship(dynamic_cast(object), nullptr))) && + op_type==Operation::ObjectModified) model->validateRelationships(); //If a object had its schema restored is necessary to update the envolved schemas - if((obj_type==OBJ_TABLE || obj_type==OBJ_VIEW) && - ((bkp_obj && graph_obj->getSchema()!=bkp_obj->getSchema() && op_type==Operation::OBJECT_MODIFIED) || - op_type==Operation::OBJECT_MOVED)) + if((obj_type==ObjectType::Table || obj_type==ObjectType::View) && + ((bkp_obj && graph_obj->getSchema()!=bkp_obj->getSchema() && op_type==Operation::ObjectModified) || + op_type==Operation::ObjectMoved)) { dynamic_cast(graph_obj->getSchema())->setModified(true); if(bkp_obj) - dynamic_cast(bkp_obj->getSchema())->setModified(op_type==Operation::OBJECT_MODIFIED); + dynamic_cast(bkp_obj->getSchema())->setModified(op_type==Operation::ObjectModified); } } - else if(op_type==Operation::OBJECT_MODIFIED) + else if(op_type==Operation::ObjectModified) { - if(obj_type==OBJ_SCHEMA) + if(obj_type==ObjectType::Schema) { model->validateSchemaRenaming(dynamic_cast(object), bkp_obj->getName()); dynamic_cast(object)->setModified(true); } - else if(obj_type==OBJ_TAG) + else if(obj_type==ObjectType::Tag) { vector refs; model->getObjectReferences(object, refs); @@ -907,17 +912,17 @@ void OperationList::executeOperation(Operation *oper, bool redo) } //Case the object is a type update the tables that are referencing it - if(op_type==Operation::OBJECT_MODIFIED && - (object->getObjectType()==OBJ_TYPE || object->getObjectType()==OBJ_DOMAIN || - object->getObjectType()==OBJ_TABLE || object->getObjectType()==OBJ_VIEW || - object->getObjectType()==OBJ_EXTENSION)) + if(op_type==Operation::ObjectModified && + (object->getObjectType()==ObjectType::Type || object->getObjectType()==ObjectType::Domain || + object->getObjectType()==ObjectType::Table || object->getObjectType()==ObjectType::View || + object->getObjectType()==ObjectType::Extension)) { vector ref_objs; model->getObjectReferences(object, ref_objs); for(auto &obj : ref_objs) { - if(obj->getObjectType()==OBJ_COLUMN) + if(obj->getObjectType()==ObjectType::Column) dynamic_cast(obj)->getParentTable()->setModified(true); } } @@ -951,8 +956,8 @@ void OperationList::removeLastOperation(void) is removed the iteration is stopped.*/ end=(ignore_chain || (!ignore_chain && - (oper->getChainType()==Operation::NO_CHAIN || - oper->getChainType()==Operation::CHAIN_START))); + (oper->getChainType()==Operation::NoChain || + oper->getChainType()==Operation::ChainStart))); itr++; oper_idx--; } @@ -960,8 +965,8 @@ void OperationList::removeLastOperation(void) /* If the head of chaining is removed (CHAIN_START) marks that the next element in the list is the new start of chain */ - if(oper && oper->getChainType()==Operation::CHAIN_START) - next_op_chain=Operation::CHAIN_START; + if(oper && oper->getChainType()==Operation::ChainStart) + next_op_chain=Operation::ChainStart; //Erasing the excluded operations for(int i=operations.size()-1; i > oper_idx ; i--) @@ -983,7 +988,7 @@ void OperationList::updateObjectIndex(BaseObject *object, unsigned new_idx) Operation *oper=nullptr; if(!object) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); itr=operations.begin(); itr_end=operations.end(); diff --git a/libpgmodeler/src/operationlist.h b/libpgmodeler/src/operationlist.h index 3896d65edf..8760ee4a3e 100644 --- a/libpgmodeler/src/operationlist.h +++ b/libpgmodeler/src/operationlist.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -39,7 +39,7 @@ class OperationList: public QObject { //! \brief Inidcates that operation chaining is ignored temporarily bool ignore_chain; - XMLParser *xmlparser; + XmlParser *xmlparser; //! \brief List of objects that were removed / modified on the model vector object_pool; diff --git a/libpgmodeler/src/operator.cpp b/libpgmodeler/src/operator.cpp index 276ab253f7..14864ee028 100644 --- a/libpgmodeler/src/operator.cpp +++ b/libpgmodeler/src/operator.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -22,29 +22,29 @@ Operator::Operator(void) { unsigned i; - obj_type=OBJ_OPERATOR; + obj_type=ObjectType::Operator; - for(i=FUNC_OPERATOR; i <= FUNC_RESTRICT; i++) + for(i=FuncOperator; i <= FuncRestrict; i++) functions[i]=nullptr; - for(i=Operator::OPER_COMMUTATOR; i <= OPER_NEGATOR; i++) + for(i=Operator::OperCommutator; i <= OperNegator; i++) operators[i]=nullptr; hashes=merges=false; - argument_types[LEFT_ARG]=PgSQLType(QString("\"any\"")); - argument_types[RIGHT_ARG]=PgSQLType(QString("\"any\"")); - - attributes[ParsersAttributes::LEFT_TYPE]=QString(); - attributes[ParsersAttributes::RIGHT_TYPE]=QString(); - attributes[ParsersAttributes::COMMUTATOR_OP]=QString(); - attributes[ParsersAttributes::NEGATOR_OP]=QString(); - attributes[ParsersAttributes::RESTRICTION_FUNC]=QString(); - attributes[ParsersAttributes::JOIN_FUNC]=QString(); - attributes[ParsersAttributes::OPERATOR_FUNC]=QString(); - attributes[ParsersAttributes::HASHES]=QString(); - attributes[ParsersAttributes::MERGES]=QString(); - attributes[ParsersAttributes::SIGNATURE]=QString(); - attributes[ParsersAttributes::REF_TYPE]=QString(); + argument_types[LeftArg]=PgSqlType(QString("\"any\"")); + argument_types[RightArg]=PgSqlType(QString("\"any\"")); + + attributes[Attributes::LeftType]=QString(); + attributes[Attributes::RightType]=QString(); + attributes[Attributes::CommutatorOp]=QString(); + attributes[Attributes::NegatorOp]=QString(); + attributes[Attributes::RestrictionFunc]=QString(); + attributes[Attributes::JoinFunc]=QString(); + attributes[Attributes::OperatorFunc]=QString(); + attributes[Attributes::Hashes]=QString(); + attributes[Attributes::Merges]=QString(); + attributes[Attributes::Signature]=QString(); + attributes[Attributes::RefType]=QString(); } bool Operator::isValidName(const QString &name) @@ -55,7 +55,7 @@ bool Operator::isValidName(const QString &name) bool valid=true; //Checks if the size of the name is valid - valid=(name.size() <= static_cast(OBJECT_NAME_MAX_LENGTH)); + valid=(name.size() <= static_cast(ObjectNameMaxLength)); /* Checking if the name is valid according the conditions: 1) The name has only the chars defined in 'valid_chars' */ @@ -82,9 +82,9 @@ bool Operator::isValidName(const QString &name) void Operator::setName(const QString &name) { if(name.isEmpty()) - throw Exception(ERR_ASG_EMPTY_NAME_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgEmptyNameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(!isValidName(name)) - throw Exception(ERR_ASG_INV_NAME_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidNameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->obj_name=name; } @@ -92,27 +92,27 @@ void Operator::setName(const QString &name) void Operator::setFunction(Function *func, unsigned func_type) { //Raises an error if the function type is invalid - if(func_type > FUNC_RESTRICT) - throw Exception(ERR_REF_FUNCTION_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); - else if(func_type==FUNC_OPERATOR) + if(func_type > FuncRestrict) + throw Exception(ErrorCode::RefFunctionInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(func_type==FuncOperator) { //Raises an error if the function is not allocated if(!func) - throw Exception(Exception::getErrorMessage(ERR_ASG_NOT_ALOC_FUNCTION) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgNotAllocatedFunction) .arg(this->getName(true)) - .arg(BaseObject::getTypeName(OBJ_OPERATOR)), - ERR_ASG_NOT_ALOC_FUNCTION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Operator)), + ErrorCode::AsgNotAllocatedFunction,__PRETTY_FUNCTION__,__FILE__,__LINE__); /* Raises an error if the parameter count is invalid. To be used by the operator the function must own 1 or 2 parameters */ else if(func->getParameterCount()==0 || func->getParameterCount() > 2) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNC_INV_PARAM_COUNT) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidParamCount) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_OPERATOR)), - ERR_ASG_FUNC_INV_PARAM_COUNT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Operator)), + ErrorCode::AsgFunctionInvalidParamCount,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { unsigned param_count=func->getParameterCount(); - PgSQLType param_type1=PgSQLType(QString("\"any\"")), param_type2=PgSQLType(QString("\"any\"")); + PgSqlType param_type1=PgSqlType(QString("\"any\"")), param_type2=PgSqlType(QString("\"any\"")); //Get the function parameter to make validations param_type1=func->getParameter(0).getType(); @@ -140,10 +140,10 @@ void Operator::setFunction(Function *func, unsigned func_type) (param_count==1 && ((argument_types[0]!=QString("\"any\"") && argument_types[0]!=param_type1) || (argument_types[1]!=QString("\"any\"") && argument_types[1]!=param_type1)))) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNCTION_INV_PARAMS) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidParameters) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_OPERATOR)), - ERR_ASG_FUNCTION_INV_PARAMS,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Operator)), + ErrorCode::AsgFunctionInvalidParameters,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } @@ -151,11 +151,11 @@ void Operator::setFunction(Function *func, unsigned func_type) functions[func_type]=func; } -void Operator::setArgumentType(PgSQLType arg_type, unsigned arg_id) +void Operator::setArgumentType(PgSqlType arg_type, unsigned arg_id) { //Raises an error if the argument id is invalid - if(arg_id > RIGHT_ARG) - throw Exception( ERR_REF_OPER_ARG_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(arg_id > RightArg) + throw Exception(ErrorCode::RefOperatorArgumentInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(argument_types[arg_id] != arg_type); argument_types[arg_id]=arg_type; @@ -164,8 +164,8 @@ void Operator::setArgumentType(PgSQLType arg_type, unsigned arg_id) void Operator::setOperator(Operator *oper, unsigned op_type) { //Raises an error if the operator type is invalid - if(op_type > OPER_NEGATOR) - throw Exception(ERR_REF_OPER_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(op_type > OperNegator) + throw Exception(ErrorCode::RefOperatorInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { /* Validating the Commutator OP: According to the PostgreSQL documentation @@ -174,26 +174,26 @@ void Operator::setOperator(Operator *oper, unsigned op_type) is being defined and its commutator operator is +*+ then the signature of the latter should be +*+ (typeB, typeA). Raises an error when this condition is not satisfied. */ - if(oper && op_type==OPER_COMMUTATOR && argument_types[LEFT_ARG]!=oper->argument_types[RIGHT_ARG]) + if(oper && op_type==OperCommutator && argument_types[LeftArg]!=oper->argument_types[RightArg]) { - throw Exception(Exception::getErrorMessage(ERR_ASG_INV_COM_OPEERATOR) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidCommutatorOperator) .arg(oper->getSignature(true)) .arg(this->getSignature(true)), - ERR_ASG_FUNC_INV_PARAM_COUNT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgFunctionInvalidParamCount,__PRETTY_FUNCTION__,__FILE__,__LINE__); } /* Validating Negator OP: According to the PostgreSQL documentation the negator operator must have its arguments as the same type of arguments from the operator to be defined. That is, if the operator !!(typeA) is being set and its negator is !*! then the signature of the latter should be !*! (typeA). Raises an error when this condition is not satisfied. */ - else if(oper && op_type==OPER_NEGATOR && - (argument_types[LEFT_ARG]!=oper->argument_types[LEFT_ARG] && - argument_types[RIGHT_ARG]!=oper->argument_types[RIGHT_ARG])) + else if(oper && op_type==OperNegator && + (argument_types[LeftArg]!=oper->argument_types[LeftArg] && + argument_types[RightArg]!=oper->argument_types[RightArg])) { - throw Exception(Exception::getErrorMessage(ERR_ASG_INV_NEG_OPERATOR) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidNegatorOperator) .arg(oper->getSignature(true)) .arg(this->getSignature(true)), - ERR_ASG_FUNC_INV_PARAM_COUNT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgFunctionInvalidParamCount,__PRETTY_FUNCTION__,__FILE__,__LINE__); } setCodeInvalidated(operators[op_type] != oper); @@ -216,25 +216,25 @@ void Operator::setMerges(bool value) Function *Operator::getFunction(unsigned func_type) { //Raises an error if the function type is invalid - if(func_type > FUNC_RESTRICT) - throw Exception(ERR_REF_OPER_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(func_type > FuncRestrict) + throw Exception(ErrorCode::RefOperatorInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(functions[func_type]); } -PgSQLType Operator::getArgumentType(unsigned arg_id) +PgSqlType Operator::getArgumentType(unsigned arg_id) { //Raises an error if the argument id is invalid - if(arg_id > RIGHT_ARG) - throw Exception( ERR_REF_OPER_ARG_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(arg_id > RightArg) + throw Exception(ErrorCode::RefOperatorArgumentInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(argument_types[arg_id]); } Operator *Operator::getOperator(unsigned op_type) { //Raises an error if the operator type is invalid - if(op_type > OPER_NEGATOR) - throw Exception(ERR_REF_FUNCTION_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(op_type > OperNegator) + throw Exception(ErrorCode::RefFunctionInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(operators[op_type]); } @@ -280,17 +280,17 @@ QString Operator::getCodeDefinition(unsigned def_type, bool reduced_form) if(!code_def.isEmpty()) return(code_def); unsigned i; - QString type_attribs[]={ParsersAttributes::LEFT_TYPE, ParsersAttributes::RIGHT_TYPE}, - op_attribs[]={ ParsersAttributes::COMMUTATOR_OP, - ParsersAttributes::NEGATOR_OP }, + QString type_attribs[]={Attributes::LeftType, Attributes::RightType}, + op_attribs[]={ Attributes::CommutatorOp, + Attributes::NegatorOp }, - func_attribs[]={ParsersAttributes::OPERATOR_FUNC, - ParsersAttributes::JOIN_FUNC, - ParsersAttributes::RESTRICTION_FUNC}; + func_attribs[]={Attributes::OperatorFunc, + Attributes::JoinFunc, + Attributes::RestrictionFunc}; - for(i=Operator::LEFT_ARG; i <= Operator::RIGHT_ARG; i++) + for(i=Operator::LeftArg; i <= Operator::RightArg; i++) { - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) { if(argument_types[i]!=QString("\"any\"")) attributes[type_attribs[i]]=~argument_types[i]; @@ -298,42 +298,52 @@ QString Operator::getCodeDefinition(unsigned def_type, bool reduced_form) else { attributes[type_attribs[i]]=argument_types[i]. - getCodeDefinition(SchemaParser::XML_DEFINITION,type_attribs[i]); + getCodeDefinition(SchemaParser::XmlDefinition,type_attribs[i]); } } - for(i=Operator::OPER_COMMUTATOR; i <= Operator::OPER_NEGATOR; i++) + for(i=Operator::OperCommutator; i <= Operator::OperNegator; i++) { if(operators[i]) { - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) attributes[op_attribs[i]]=operators[i]->getName(true); else { - operators[i]->attributes[ParsersAttributes::REF_TYPE]=op_attribs[i]; + operators[i]->attributes[Attributes::RefType]=op_attribs[i]; attributes[op_attribs[i]]=operators[i]->getCodeDefinition(def_type, true); } } } - for(i=Operator::FUNC_OPERATOR; i <= Operator::FUNC_RESTRICT; i++) + for(i=Operator::FuncOperator; i <= Operator::FuncRestrict; i++) { if(functions[i]) { - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) attributes[func_attribs[i]]=functions[i]->getName(true); else { - functions[i]->setAttribute(ParsersAttributes::REF_TYPE, func_attribs[i]); + functions[i]->setAttribute(Attributes::RefType, func_attribs[i]); attributes[func_attribs[i]]=functions[i]->getCodeDefinition(def_type, true); } } } - attributes[ParsersAttributes::HASHES]=(hashes ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::MERGES]=(merges ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::SIGNATURE]=getSignature(); + attributes[Attributes::Hashes]=(hashes ? Attributes::True : QString()); + attributes[Attributes::Merges]=(merges ? Attributes::True : QString()); + attributes[Attributes::Signature]=getSignature(); return(BaseObject::getCodeDefinition(def_type, reduced_form)); } +void Operator::configureSearchAttributes(void) +{ + QStringList arg_types; + + BaseObject::configureSearchAttributes(); + + arg_types += *argument_types[0]; + arg_types += *argument_types[1]; + search_attribs[Attributes::Type] = arg_types.join("; "); +} diff --git a/libpgmodeler/src/operator.h b/libpgmodeler/src/operator.h index aa5685e5fc..aa73ef18d0 100644 --- a/libpgmodeler/src/operator.h +++ b/libpgmodeler/src/operator.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -36,7 +36,7 @@ class Operator: public BaseObject { Function *functions[3]; //! \brief Stores the arguments types (left and right) used by the operator - PgSQLType argument_types[2]; + PgSqlType argument_types[2]; //! \brief Stores the auxiliary operators Operator *operators[2]; @@ -44,14 +44,17 @@ class Operator: public BaseObject { bool hashes, //! \brief Indicates that the operator can execute a hash join merges; //! \brief Indicates that the operator can execute a merge join + protected: + virtual void configureSearchAttributes(void); + public: - static const unsigned FUNC_OPERATOR=0, - FUNC_JOIN=1, - FUNC_RESTRICT=2, - LEFT_ARG=0, - RIGHT_ARG=1, - OPER_COMMUTATOR=0, - OPER_NEGATOR=1; + static constexpr unsigned FuncOperator=0, + FuncJoin=1, + FuncRestrict=2, + LeftArg=0, + RightArg=1, + OperCommutator=0, + OperNegator=1; Operator(void); @@ -62,7 +65,7 @@ class Operator: public BaseObject { void setFunction(Function *func, unsigned func_type); //! \brief Defines the argument data type for operator (constants ARG_[LEFT | RIGHT]) - void setArgumentType(PgSQLType arg_type, unsigned arg_id); + void setArgumentType(PgSqlType arg_type, unsigned arg_id); //! \brief Defines the auxiliary operators (constants OPER_[COMMUTATOR | NEGATOR]) void setOperator(Operator *oper, unsigned op_type); @@ -77,7 +80,7 @@ class Operator: public BaseObject { Function *getFunction(unsigned func_type); //! \brief Returns the type of the passed argument id - PgSQLType getArgumentType(unsigned arg_id); + PgSqlType getArgumentType(unsigned arg_id); //! \brief Returns on of the auxiliary operators Operator *getOperator(unsigned op_type); diff --git a/libpgmodeler/src/operatorclass.cpp b/libpgmodeler/src/operatorclass.cpp index 514f421b82..fbb251f243 100644 --- a/libpgmodeler/src/operatorclass.cpp +++ b/libpgmodeler/src/operatorclass.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,14 +20,14 @@ OperatorClass::OperatorClass(void) { - obj_type=OBJ_OPCLASS; + obj_type=ObjectType::OpClass; family=nullptr; is_default=false; - attributes[ParsersAttributes::FAMILY]=QString(); - attributes[ParsersAttributes::ELEMENTS]=QString(); - attributes[ParsersAttributes::INDEX_TYPE]=QString(); - attributes[ParsersAttributes::TYPE]=QString(); - attributes[ParsersAttributes::DEFAULT]=QString(); + attributes[Attributes::Family]=QString(); + attributes[Attributes::Elements]=QString(); + attributes[Attributes::IndexType]=QString(); + attributes[Attributes::Type]=QString(); + attributes[Attributes::Default]=QString(); } OperatorClass::~OperatorClass(void) @@ -35,11 +35,11 @@ OperatorClass::~OperatorClass(void) elements.clear(); } -void OperatorClass::setDataType(PgSQLType data_type) +void OperatorClass::setDataType(PgSqlType data_type) { //A null datatype is not accepted by the operator class - if(data_type==PgSQLType::null) - throw Exception(ERR_ASG_INV_TYPE_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(data_type==PgSqlType::Null) + throw Exception(ErrorCode::AsgInvalidTypeObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->data_type != data_type); this->data_type=data_type; @@ -74,11 +74,11 @@ void OperatorClass::setElementsAttribute(unsigned def_type) for(i=0; i < count; i++) { str_elems+=elements[i].getCodeDefinition(def_type); - if(def_type==SchemaParser::SQL_DEFINITION && + if(def_type==SchemaParser::SqlDefinition && i < count-1) str_elems+=QString(",\n"); } - attributes[ParsersAttributes::ELEMENTS]=str_elems; + attributes[Attributes::Elements]=str_elems; } void OperatorClass::addElement(OperatorClassElement elem) @@ -94,7 +94,7 @@ void OperatorClass::removeElement(unsigned elem_idx) { //Raises an error in case the element index is out of bound if(elem_idx >= elements.size()) - throw Exception(ERR_REF_ELEM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Removes the item from the elements list elements.erase(elements.begin() + elem_idx); @@ -111,7 +111,7 @@ OperatorClassElement OperatorClass::getElement(unsigned elem_idx) { //Raises an error in case the element index is out of bound if(elem_idx >= elements.size()) - throw Exception(ERR_REF_ELEM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Returns the element on the specified index return(elements[elem_idx]); @@ -141,7 +141,7 @@ unsigned OperatorClass::getElementCount(void) return(elements.size()); } -PgSQLType OperatorClass::getDataType(void) +PgSqlType OperatorClass::getDataType(void) { return(data_type); } @@ -172,23 +172,23 @@ QString OperatorClass::getCodeDefinition(unsigned def_type, bool reduced_form) if(!code_def.isEmpty()) return(code_def); setElementsAttribute(def_type); - attributes[ParsersAttributes::INDEX_TYPE]=(~indexing_type); - attributes[ParsersAttributes::DEFAULT]=(is_default ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::IndexType]=(~indexing_type); + attributes[Attributes::Default]=(is_default ? Attributes::True : QString()); - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::TYPE]=(*data_type); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Type]=(*data_type); else - attributes[ParsersAttributes::TYPE]=data_type.getCodeDefinition(def_type); + attributes[Attributes::Type]=data_type.getCodeDefinition(def_type); if(family) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::FAMILY]=family->getName(true); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Family]=family->getName(true); else - attributes[ParsersAttributes::FAMILY]=family->getSignature(); + attributes[Attributes::Family]=family->getSignature(); } - attributes[ParsersAttributes::SIGNATURE]=getSignature(); + attributes[Attributes::Signature]=getSignature(); return(BaseObject::getCodeDefinition(def_type, reduced_form)); } diff --git a/libpgmodeler/src/operatorclass.h b/libpgmodeler/src/operatorclass.h index f2b89625dd..167a5dee48 100644 --- a/libpgmodeler/src/operatorclass.h +++ b/libpgmodeler/src/operatorclass.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -35,7 +35,7 @@ can be used in a particular indexing method. class OperatorClass: public BaseObject { private: //! \brief Data type witch the operator class acts on - PgSQLType data_type; + PgSqlType data_type; //! \brief Operator family that the operator class is part OperatorFamily *family; @@ -59,7 +59,7 @@ class OperatorClass: public BaseObject { ~OperatorClass(void); //! \brief Sets the data type that the operator class works on - void setDataType(PgSQLType data_type); + void setDataType(PgSqlType data_type); //! \brief Sets the operator family that the operator class is part void setFamily(OperatorFamily *family); @@ -78,7 +78,7 @@ class OperatorClass: public BaseObject { void removeElements(void); //! \brief Methods used to obtain the class attributes - PgSQLType getDataType(void); + PgSqlType getDataType(void); OperatorFamily *getFamily(void); IndexingType getIndexingType(void); bool isDefault(void); diff --git a/libpgmodeler/src/operatorclasselement.cpp b/libpgmodeler/src/operatorclasselement.cpp index 1c2b1922f1..ba0dbbcc36 100644 --- a/libpgmodeler/src/operatorclasselement.cpp +++ b/libpgmodeler/src/operatorclasselement.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,7 +20,7 @@ OperatorClassElement::OperatorClassElement(void) { - element_type=OPERATOR_ELEM; + element_type=OperatorElem; function=nullptr; _operator=nullptr; strategy_number=0; @@ -31,11 +31,11 @@ void OperatorClassElement::setFunction(Function *func, unsigned stg_number) { //Raises an exception case the function is not allocated if(!func) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error case the stratagy number is zero (invalid) else if(stg_number==0) - throw Exception(ERR_ASG_INV_SUPSTG_NUMBER,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidSupportStrategyNumber,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Clear the attributes not related to the FUNCTION element type this->_operator=nullptr; @@ -44,18 +44,18 @@ void OperatorClassElement::setFunction(Function *func, unsigned stg_number) //Configure the attributes that belongs to the element type this->function=func; this->strategy_number=stg_number; - this->element_type=FUNCTION_ELEM; + this->element_type=FunctionElem; } void OperatorClassElement::setOperator(Operator *oper, unsigned stg_number) { //Raises an error in case the operator is not allocated if(!oper) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error case the stratagy number is zero (invalid) else if(stg_number==0) - throw Exception(ERR_ASG_INV_SUPSTG_NUMBER,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidSupportStrategyNumber,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Clear the attributes not related to the OPERATOR element type this->function=nullptr; @@ -63,21 +63,21 @@ void OperatorClassElement::setOperator(Operator *oper, unsigned stg_number) //Configure the attributes that belongs to the element type this->_operator=oper; this->strategy_number=stg_number; - this->element_type=OPERATOR_ELEM; + this->element_type=OperatorElem; } void OperatorClassElement::setOperatorFamily(OperatorFamily *op_family) { - if(this->element_type==OPERATOR_ELEM) + if(this->element_type==OperatorElem) { - if(op_family && op_family->getIndexingType()!=IndexingType::btree) - throw Exception(ERR_ASG_INV_OPFAM_OPCLSELEM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(op_family && op_family->getIndexingType()!=IndexingType::Btree) + throw Exception(ErrorCode::AsgInvalidOpFamilyOpClassElem,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->op_family=op_family; } } -void OperatorClassElement::setStorage(PgSQLType storage) +void OperatorClassElement::setStorage(PgSqlType storage) { //Clear the attributes not related to the STORAGE element type this->function=nullptr; @@ -87,7 +87,7 @@ void OperatorClassElement::setStorage(PgSQLType storage) //Configure the attributes that belongs to the element type this->storage=storage; - this->element_type=STORAGE_ELEM; + this->element_type=StorageElem; } unsigned OperatorClassElement::getElementType(void) @@ -110,7 +110,7 @@ OperatorFamily *OperatorClassElement::getOperatorFamily(void) return(op_family); } -PgSQLType OperatorClassElement::getStorage(void) +PgSqlType OperatorClassElement::getStorage(void) { return(storage); } @@ -125,57 +125,57 @@ QString OperatorClassElement::getCodeDefinition(unsigned def_type) SchemaParser schparser; attribs_map attributes; - attributes[ParsersAttributes::TYPE]=QString(); - attributes[ParsersAttributes::STRATEGY_NUM]=QString(); - attributes[ParsersAttributes::SIGNATURE]=QString(); - attributes[ParsersAttributes::FUNCTION]=QString(); - attributes[ParsersAttributes::OPERATOR]=QString(); - attributes[ParsersAttributes::STORAGE]=QString(); - attributes[ParsersAttributes::OP_FAMILY]=QString(); - attributes[ParsersAttributes::DEFINITION]=QString(); + attributes[Attributes::Type]=QString(); + attributes[Attributes::StrategyNum]=QString(); + attributes[Attributes::Signature]=QString(); + attributes[Attributes::Function]=QString(); + attributes[Attributes::Operator]=QString(); + attributes[Attributes::Storage]=QString(); + attributes[Attributes::OpFamily]=QString(); + attributes[Attributes::Definition]=QString(); - if(element_type==FUNCTION_ELEM && function && strategy_number > 0) + if(element_type==FunctionElem && function && strategy_number > 0) { //FUNCTION support_number [ ( op_type [ , op_type ] ) ] funcname ( argument_type [, ...] ) - attributes[ParsersAttributes::FUNCTION]=ParsersAttributes::_TRUE_; - attributes[ParsersAttributes::STRATEGY_NUM]=QString("%1").arg(strategy_number); + attributes[Attributes::Function]=Attributes::True; + attributes[Attributes::StrategyNum]=QString("%1").arg(strategy_number); - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::SIGNATURE]=function->getSignature(); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Signature]=function->getSignature(); else - attributes[ParsersAttributes::DEFINITION]=function->getCodeDefinition(def_type,true); + attributes[Attributes::Definition]=function->getCodeDefinition(def_type,true); } - else if(element_type==OPERATOR_ELEM && _operator && strategy_number > 0) + else if(element_type==OperatorElem && _operator && strategy_number > 0) { //OPERATOR strategy_number operator_name [ ( op_type, op_type ) ] [ FOR SEARCH | FOR ORDER BY sort_family_name ] - attributes[ParsersAttributes::OPERATOR]=ParsersAttributes::_TRUE_; - attributes[ParsersAttributes::STRATEGY_NUM]=QString("%1").arg(strategy_number); + attributes[Attributes::Operator]=Attributes::True; + attributes[Attributes::StrategyNum]=QString("%1").arg(strategy_number); - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::SIGNATURE]=_operator->getSignature(); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Signature]=_operator->getSignature(); else - attributes[ParsersAttributes::DEFINITION]=_operator->getCodeDefinition(def_type,true); + attributes[Attributes::Definition]=_operator->getCodeDefinition(def_type,true); if(op_family) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::OP_FAMILY]=op_family->getName(true); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::OpFamily]=op_family->getName(true); else - attributes[ParsersAttributes::DEFINITION]+=op_family->getCodeDefinition(def_type,true); + attributes[Attributes::Definition]+=op_family->getCodeDefinition(def_type,true); } } - else if(element_type==STORAGE_ELEM && storage!=PgSQLType::null) + else if(element_type==StorageElem && storage!=PgSqlType::Null) { //STORAGE storage_type - attributes[ParsersAttributes::STORAGE]=ParsersAttributes::_TRUE_; + attributes[Attributes::Storage]=Attributes::True; - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::TYPE]=(*storage); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Type]=(*storage); else - attributes[ParsersAttributes::DEFINITION]=storage.getCodeDefinition(def_type); + attributes[Attributes::Definition]=storage.getCodeDefinition(def_type); } - return(schparser.getCodeDefinition(ParsersAttributes::ELEMENT,attributes, def_type)); + return(schparser.getCodeDefinition(Attributes::Element,attributes, def_type)); } bool OperatorClassElement::operator == (OperatorClassElement &elem) diff --git a/libpgmodeler/src/operatorclasselement.h b/libpgmodeler/src/operatorclasselement.h index 07463ad465..29956bbf86 100644 --- a/libpgmodeler/src/operatorclasselement.h +++ b/libpgmodeler/src/operatorclasselement.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -52,7 +52,7 @@ class OperatorClassElement { /*! \brief PostgreSQL type used in the indexing method of operator class. (only for type STORAGE_ELEM) */ - PgSQLType storage; + PgSqlType storage; /*! \brief Strategy number (or support number for functions). This attribute must have a value greater than 0 (only for OPERATOR_ELEM and FUNCTION_ELEM) */ @@ -60,9 +60,9 @@ class OperatorClassElement { public: //! \brief Constants used to reference the element types - static const unsigned OPERATOR_ELEM=0, - FUNCTION_ELEM=1, - STORAGE_ELEM=2; + static constexpr unsigned OperatorElem=0, + FunctionElem=1, + StorageElem=2; OperatorClassElement(void); virtual ~OperatorClassElement(void){} @@ -77,7 +77,7 @@ class OperatorClassElement { void setOperatorFamily(OperatorFamily *op_family); //! \brief Defines the element as a storage clause - void setStorage(PgSQLType storage); + void setStorage(PgSqlType storage); //! \brief Returns the element type unsigned getElementType(void); @@ -95,7 +95,7 @@ class OperatorClassElement { OperatorFamily *getOperatorFamily(void); //! \brief Storage type of the element - PgSQLType getStorage(void); + PgSqlType getStorage(void); //! \brief Returns the strategy (support) number of the element unsigned getStrategyNumber(void); diff --git a/libpgmodeler/src/operatorfamily.cpp b/libpgmodeler/src/operatorfamily.cpp index 3a3cbde953..ecfbaa9e97 100644 --- a/libpgmodeler/src/operatorfamily.cpp +++ b/libpgmodeler/src/operatorfamily.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,8 +20,8 @@ OperatorFamily::OperatorFamily(void) { - obj_type=OBJ_OPFAMILY; - attributes[ParsersAttributes::INDEX_TYPE]=QString(); + obj_type=ObjectType::OpFamily; + attributes[Attributes::IndexType]=QString(); } void OperatorFamily::setIndexingType(IndexingType idx_type) @@ -45,8 +45,8 @@ QString OperatorFamily::getCodeDefinition(unsigned def_type, bool reduced_form) QString code_def=getCachedCode(def_type, reduced_form); if(!code_def.isEmpty()) return(code_def); - attributes[ParsersAttributes::SIGNATURE]=getSignature(); - attributes[ParsersAttributes::INDEX_TYPE]=(~indexing_type); + attributes[Attributes::Signature]=getSignature(); + attributes[Attributes::IndexType]=(~indexing_type); return(BaseObject::getCodeDefinition(def_type,reduced_form)); } diff --git a/libpgmodeler/src/operatorfamily.h b/libpgmodeler/src/operatorfamily.h index 709ef31c61..97cd10e002 100644 --- a/libpgmodeler/src/operatorfamily.h +++ b/libpgmodeler/src/operatorfamily.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libpgmodeler/src/parameter.cpp b/libpgmodeler/src/parameter.cpp index 580ad98c4d..b2d13a2f3b 100644 --- a/libpgmodeler/src/parameter.cpp +++ b/libpgmodeler/src/parameter.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,14 +20,23 @@ Parameter::Parameter(void) { - obj_type=OBJ_PARAMETER; + obj_type=ObjectType::Parameter; is_in=is_out=is_variadic=false; } -void Parameter::setType(PgSQLType type) +Parameter::Parameter(const QString &name, PgSqlType type, bool in, bool out, bool variadic) : Parameter() +{ + setName(name); + setType(type); + setIn(in); + setOut(out); + setVariadic(variadic); +} + +void Parameter::setType(PgSqlType type) { if(!type.isArrayType() && !type.isPolymorphicType() && is_variadic) - throw Exception(ERR_INV_USE_VARIADIC_PARAM_MODE ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InvUsageVariadicParamMode ,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->type != type); this->type=type; @@ -50,7 +59,7 @@ void Parameter::setOut(bool value) void Parameter::setVariadic(bool value) { if(value && !type.isArrayType() && !type.isPolymorphicType()) - throw Exception(ERR_INV_USE_VARIADIC_PARAM_MODE ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InvUsageVariadicParamMode ,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(is_variadic != value); is_variadic=value; @@ -93,16 +102,16 @@ QString Parameter::getCodeDefinition(unsigned def_type) QString Parameter::getCodeDefinition(unsigned def_type, bool reduced_form) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::NAME]=BaseObject::formatName(obj_name); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Name]=BaseObject::formatName(obj_name); else - attributes[ParsersAttributes::NAME]=obj_name; + attributes[Attributes::Name]=obj_name; - attributes[ParsersAttributes::PARAM_IN]=(is_in ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::PARAM_OUT]=(is_out ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::PARAM_VARIADIC]=(is_variadic ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::DEFAULT_VALUE]=default_value; - attributes[ParsersAttributes::TYPE]=type.getCodeDefinition(def_type); + attributes[Attributes::ParamIn]=(is_in ? Attributes::True : QString()); + attributes[Attributes::ParamOut]=(is_out ? Attributes::True : QString()); + attributes[Attributes::ParamVariadic]=(is_variadic ? Attributes::True : QString()); + attributes[Attributes::DefaultValue]=default_value; + attributes[Attributes::Type]=type.getCodeDefinition(def_type); return(BaseObject::getCodeDefinition(def_type, reduced_form)); } diff --git a/libpgmodeler/src/parameter.h b/libpgmodeler/src/parameter.h index 36d7e3c903..d8f9672a4e 100644 --- a/libpgmodeler/src/parameter.h +++ b/libpgmodeler/src/parameter.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -34,8 +34,9 @@ class Parameter: public Column { public: Parameter(void); + Parameter(const QString &name, PgSqlType type, bool in = false, bool out = false, bool variadic = false); - void setType(PgSQLType type); + void setType(PgSqlType type); void setIn(bool value); void setOut(bool value); void setVariadic(bool value); diff --git a/libpgmodeler/src/partitionkey.cpp b/libpgmodeler/src/partitionkey.cpp new file mode 100644 index 0000000000..b40a61c4f4 --- /dev/null +++ b/libpgmodeler/src/partitionkey.cpp @@ -0,0 +1,53 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "partitionkey.h" + +PartitionKey::PartitionKey(void) +{ + collation = nullptr; +} + +void PartitionKey::setCollation(Collation *collation) +{ + this->collation=collation; +} + +Collation *PartitionKey::getCollation(void) +{ + return(collation); +} + +QString PartitionKey::getCodeDefinition(unsigned def_type) +{ + attribs_map attribs; + schparser.setPgSQLVersion(BaseObject::getPgSQLVersion()); + + attribs[Attributes::Collation]=QString(); + configureAttributes(attribs, def_type); + + if(collation) + { + if(def_type==SchemaParser::SqlDefinition) + attribs[Attributes::Collation]=collation->getName(true); + else + attribs[Attributes::Collation]=collation->getCodeDefinition(def_type, true); + } + + return(schparser.getCodeDefinition(Attributes::PartitionKey, attribs, def_type)); +} diff --git a/libpgmodeler/src/partitionkey.h b/libpgmodeler/src/partitionkey.h new file mode 100644 index 0000000000..407bd577cc --- /dev/null +++ b/libpgmodeler/src/partitionkey.h @@ -0,0 +1,47 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +/** +\ingroup libpgmodeler +\brief Implements the operations to manipulate partition key elements. +*/ + +#ifndef PARTITION_KEY_H +#define PARTITION_KEY_H + +#include "element.h" + +class PartitionKey: public Element { + private: + //! \brief Collation referenced by the element + Collation *collation; + + public: + PartitionKey(void); + + //! \brief Defines the collation referenced by the element + void setCollation(Collation *collation); + + //! \brief Get the collation referenced by the element + Collation *getCollation(void); + + //! \brief Returns the SQL / XML code definition for the partition key + virtual QString getCodeDefinition(unsigned def_type) final; +}; + +#endif diff --git a/libpgmodeler/src/permission.cpp b/libpgmodeler/src/permission.cpp index 82b59ec762..36d55aa09a 100644 --- a/libpgmodeler/src/permission.cpp +++ b/libpgmodeler/src/permission.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -25,47 +25,47 @@ Permission::Permission(BaseObject *obj) unsigned priv_id; //Initializes all the privileges as unchecked - for(priv_id=PRIV_SELECT; priv_id<=PRIV_USAGE; priv_id++) + for(priv_id=PrivSelect; priv_id<=PrivUsage; priv_id++) privileges[priv_id]=grant_option[priv_id]=false; //Raises an error if the object associated to the permission is no allocated if(!obj) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); /* Raises an error if the object type to be associated to the permission is invalid according to the rule (see class definition) */ - if(!objectAcceptsPermission(obj->getObjectType())) - throw Exception(ERR_ASG_OBJECT_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(!acceptsPermission(obj->getObjectType())) + throw Exception(ErrorCode::AsgObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->object=obj; - this->obj_type=OBJ_PERMISSION; + this->obj_type=ObjectType::Permission; revoke=cascade=false; - attributes[ParsersAttributes::OBJECT]=QString(); - attributes[ParsersAttributes::TYPE]=QString(); - attributes[ParsersAttributes::PARENT]=QString(); - attributes[ParsersAttributes::GRANT_OP]=QString(); - attributes[ParsersAttributes::ROLES]=QString(); - attributes[ParsersAttributes::PRIVILEGES]=QString(); - attributes[ParsersAttributes::CASCADE]=QString(); - attributes[ParsersAttributes::PRIVILEGES_GOP]=QString(); + attributes[Attributes::Object]=QString(); + attributes[Attributes::Type]=QString(); + attributes[Attributes::Parent]=QString(); + attributes[Attributes::GrantOp]=QString(); + attributes[Attributes::Roles]=QString(); + attributes[Attributes::Privileges]=QString(); + attributes[Attributes::Cascade]=QString(); + attributes[Attributes::PrivilegesGop]=QString(); } -bool Permission::objectAcceptsPermission(ObjectType obj_type, int privilege) +bool Permission::acceptsPermission(ObjectType obj_type, int privilege) { bool result=false; unsigned priv_id=static_cast(privilege); - result=(obj_type==OBJ_TABLE || obj_type==OBJ_COLUMN || obj_type==OBJ_VIEW || - obj_type==OBJ_SEQUENCE || obj_type==OBJ_DATABASE || obj_type==OBJ_FUNCTION || - obj_type==OBJ_AGGREGATE || obj_type==OBJ_LANGUAGE || obj_type==OBJ_SCHEMA || - obj_type==OBJ_TABLESPACE || obj_type==OBJ_DOMAIN || obj_type==OBJ_TYPE); + result=(obj_type==ObjectType::Table || obj_type==ObjectType::Column || obj_type==ObjectType::View || + obj_type==ObjectType::Sequence || obj_type==ObjectType::Database || obj_type==ObjectType::Function || + obj_type==ObjectType::Aggregate || obj_type==ObjectType::Language || obj_type==ObjectType::Schema || + obj_type==ObjectType::Tablespace || obj_type==ObjectType::Domain || obj_type==ObjectType::Type || + obj_type==ObjectType::ForeignDataWrapper || obj_type==ObjectType::ForeignServer); //Validating privilege - if(result && priv_id <= PRIV_USAGE) + if(result && priv_id <= PrivUsage) { - /* Some privileges are valid only for certain types of objects. If the user try to assign a privilege P for an object that does not accept this privilege the same @@ -81,33 +81,36 @@ bool Permission::objectAcceptsPermission(ObjectType obj_type, int privilege) Linguage: USAGE Schema: CREATE | USAGE Tablespace: CREATE - View: SELECT | INSERT | UPDATE | DELETE | REFERENCES | TRIGGER */ + View: SELECT | INSERT | UPDATE | DELETE | REFERENCES | TRIGGER + Foreign Data Wrapper: USAGE + Foreign Server: USAGE */ result=result && + (((obj_type==ObjectType::Table || obj_type==ObjectType::View) && + (priv_id==PrivSelect || priv_id==PrivInsert || + priv_id==PrivUpdate || priv_id==PrivDelete || + priv_id==PrivReferences || priv_id==PrivTrigger)) || - (((obj_type==OBJ_TABLE || obj_type==OBJ_VIEW) && - (priv_id==PRIV_SELECT || priv_id==PRIV_INSERT || - priv_id==PRIV_UPDATE || priv_id==PRIV_DELETE || - priv_id==PRIV_REFERENCES || priv_id==PRIV_TRIGGER)) || + ((obj_type==ObjectType::Table || obj_type==ObjectType::View) && priv_id==PrivTruncate) || - ((obj_type==OBJ_TABLE || obj_type==OBJ_VIEW) && priv_id==PRIV_TRUNCATE) || + (obj_type==ObjectType::Column && + (priv_id==PrivSelect ||priv_id==PrivInsert || + priv_id==PrivUpdate || priv_id==PrivReferences)) || - (obj_type==OBJ_COLUMN && - (priv_id==PRIV_SELECT ||priv_id==PRIV_INSERT || - priv_id==PRIV_UPDATE || priv_id==PRIV_REFERENCES)) || + (obj_type==ObjectType::Sequence && + (priv_id==PrivUsage || priv_id==PrivSelect || priv_id==PrivUpdate)) || - (obj_type==OBJ_SEQUENCE && - (priv_id==PRIV_USAGE || priv_id==PRIV_SELECT || priv_id==PRIV_UPDATE)) || + (obj_type==ObjectType::Database && + (priv_id==PrivCreate || priv_id==PrivConnect || priv_id==PrivTemporary)) || - (obj_type==OBJ_DATABASE && - (priv_id==PRIV_CREATE || priv_id==PRIV_CONNECT || priv_id==PRIV_TEMPORARY)) || + ((obj_type==ObjectType::Function || obj_type==ObjectType::Aggregate) && priv_id==PrivExecute) || - ((obj_type==OBJ_FUNCTION || obj_type==OBJ_AGGREGATE) && priv_id==PRIV_EXECUTE) || + ((obj_type==ObjectType::Language || obj_type==ObjectType::Type || obj_type==ObjectType::Domain) && priv_id==PrivUsage) || - ((obj_type==OBJ_LANGUAGE || obj_type==OBJ_TYPE || obj_type==OBJ_DOMAIN) && priv_id==PRIV_USAGE) || + (obj_type==ObjectType::Schema && (priv_id==PrivUsage || priv_id==PrivCreate)) || - (obj_type==OBJ_SCHEMA && (priv_id==PRIV_USAGE || priv_id==PRIV_CREATE)) || + (obj_type==ObjectType::Tablespace && priv_id==PrivCreate) || - (obj_type==OBJ_TABLESPACE && priv_id==PRIV_CREATE)); + ((obj_type==ObjectType::ForeignDataWrapper || obj_type==ObjectType::ForeignServer) && priv_id==PrivUsage)); } return(result); @@ -123,11 +126,11 @@ void Permission::addRole(Role *role) { //Raises an error if the role is not allocated if(!role) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the role already exists in the permission if(isRoleExists(role)) - throw Exception(ERR_INS_DUP_ROLE_PERMISSION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InsDuplicatedRolePermission,__PRETTY_FUNCTION__,__FILE__,__LINE__); roles.push_back(role); setCodeInvalidated(true); @@ -139,12 +142,12 @@ void Permission::addRole(Role *role) void Permission::setPrivilege(unsigned priv_id, bool value, bool grant_op) { //Caso o tipo de privilégio sejá inválido dispara uma exceção - if(priv_id > PRIV_USAGE) - throw Exception(ERR_REF_INV_PRIVILEGE_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(priv_id > PrivUsage) + throw Exception(ErrorCode::RefInvalidPrivilegeType,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(!objectAcceptsPermission(object->getObjectType(), priv_id)) + if(!acceptsPermission(object->getObjectType(), priv_id)) //Raises an error if the privilege is invalid according to the object type - throw Exception(ERR_ASG_INCOMP_PRIV_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidPrivilegeObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated((privileges[priv_id] != value) || grant_option[priv_id] != grant_op); privileges[priv_id]=value; @@ -205,7 +208,7 @@ bool Permission::isSimilarTo(Permission *perm) void Permission::removeRole(unsigned role_idx) { if(role_idx > roles.size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); roles.erase(roles.begin() + role_idx); generatePermissionId(); @@ -222,7 +225,7 @@ void Permission::removeRoles(void) Role *Permission::getRole(unsigned role_idx) { if(role_idx > roles.size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(roles[role_idx]); } @@ -245,8 +248,8 @@ BaseObject *Permission::getObject(void) bool Permission::getPrivilege(unsigned priv_id) { //Raises an error if the privilege is invalid - if(priv_id > PRIV_USAGE) - throw Exception(ERR_REF_INV_PRIVILEGE_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(priv_id > PrivUsage) + throw Exception(ErrorCode::RefInvalidPrivilegeType,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(privileges[priv_id]); } @@ -254,8 +257,8 @@ bool Permission::getPrivilege(unsigned priv_id) bool Permission::getGrantOption(unsigned priv_id) { //Raises an error if the privilege is invalid - if(priv_id > PRIV_USAGE) - throw Exception(ERR_REF_INV_PRIVILEGE_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(priv_id > PrivUsage) + throw Exception(ErrorCode::RefInvalidPrivilegeType,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(grant_option[priv_id]); } @@ -411,43 +414,47 @@ QString Permission::getCodeDefinition(unsigned def_type) unsigned i, count; ObjectType obj_type; - QString priv_vect[12]={ ParsersAttributes::SELECT_PRIV, ParsersAttributes::INSERT_PRIV, - ParsersAttributes::UPDATE_PRIV, ParsersAttributes::DELETE_PRIV, - ParsersAttributes::TRUNCATE_PRIV, ParsersAttributes::REFERENCES_PRIV, - ParsersAttributes::TRIGGER_PRIV, ParsersAttributes::CREATE_PRIV, - ParsersAttributes::CONNECT_PRIV, ParsersAttributes::TEMPORARY_PRIV, - ParsersAttributes::EXECUTE_PRIV, ParsersAttributes::USAGE_PRIV }; + QString priv_vect[12]={ Attributes::SelectPriv, Attributes::InsertPriv, + Attributes::UpdatePriv, Attributes::DeletePriv, + Attributes::TruncatePriv, Attributes::ReferencesPriv, + Attributes::TriggerPriv, Attributes::CreatePriv, + Attributes::ConnectPriv, Attributes::TemporaryPriv, + Attributes::ExecutPriv, Attributes::UsagePriv }; obj_type=object->getObjectType(); - attributes[ParsersAttributes::REVOKE]=(revoke ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::CASCADE]=(cascade ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::Revoke]=(revoke ? Attributes::True : QString()); + attributes[Attributes::Cascade]=(cascade ? Attributes::True : QString()); - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) { - //Views and Tables uses the same key word when setting permission (TABLE) - attributes[ParsersAttributes::TYPE]= - (object->getObjectType()==OBJ_VIEW ? BaseObject::getSQLName(OBJ_TABLE): BaseObject::getSQLName(object->getObjectType())); + if(obj_type == ObjectType::View) + //Views and Tables uses the same key word when setting permission (TABLE) + attributes[Attributes::Type] = BaseObject::getSQLName(ObjectType::Table); + else if(obj_type == ObjectType::ForeignServer) + attributes[Attributes::Type] = QString("FOREIGN ") + object->getSQLName(); + else + attributes[Attributes::Type] = BaseObject::getSQLName(obj_type); } else - attributes[ParsersAttributes::TYPE]=BaseObject::getSchemaName(object->getObjectType()); + attributes[Attributes::Type]=BaseObject::getSchemaName(obj_type); - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) { - attributes[ParsersAttributes::OBJECT]=object->getName(true); - attributes[ParsersAttributes::PARENT]=dynamic_cast(object)->getParentTable()->getName(true); + attributes[Attributes::Object]=object->getName(true); + attributes[Attributes::Parent]=dynamic_cast(object)->getParentTable()->getName(true); } else - attributes[ParsersAttributes::OBJECT]=object->getSignature(); + attributes[Attributes::Object]=object->getSignature(); - if(def_type==SchemaParser::XML_DEFINITION) + if(def_type==SchemaParser::XmlDefinition) { for(i=0; i < 12; i++) { if(privileges[i] && grant_option[i]) - attributes[priv_vect[i]]=ParsersAttributes::GRANT_OP; + attributes[priv_vect[i]]=Attributes::GrantOp; else if(privileges[i]) - attributes[priv_vect[i]]=ParsersAttributes::_TRUE_; + attributes[priv_vect[i]]=Attributes::True; else attributes[priv_vect[i]]=QString(); } @@ -459,21 +466,21 @@ QString Permission::getCodeDefinition(unsigned def_type) for(i=0; i < 12; i++) { if(privileges[i] && !grant_option[i]) - priv_list.push_back(object->getObjectType() == OBJ_COLUMN ? QString("%1(%2)").arg(priv_vect[i].toUpper()).arg(object->getName(true)) : priv_vect[i].toUpper()); + priv_list.push_back(object->getObjectType() == ObjectType::Column ? QString("%1(%2)").arg(priv_vect[i].toUpper()).arg(object->getName(true)) : priv_vect[i].toUpper()); else if(grant_option[i]) - gop_priv_list.push_back(object->getObjectType() == OBJ_COLUMN ? QString("%1(%2)").arg(priv_vect[i].toUpper()).arg(object->getName(true)) : priv_vect[i].toUpper()); + gop_priv_list.push_back(object->getObjectType() == ObjectType::Column ? QString("%1(%2)").arg(priv_vect[i].toUpper()).arg(object->getName(true)) : priv_vect[i].toUpper()); } - attributes[ParsersAttributes::PRIVILEGES] = priv_list.join(QChar(',')); - attributes[ParsersAttributes::PRIVILEGES_GOP] = gop_priv_list.join(QChar(',')); + attributes[Attributes::Privileges] = priv_list.join(QChar(',')); + attributes[Attributes::PrivilegesGop] = gop_priv_list.join(QChar(',')); } count=roles.size(); for(i=0; i < count; i++) - attributes[ParsersAttributes::ROLES]+=roles[i]->getName(true) + QString(","); + attributes[Attributes::Roles]+=roles[i]->getName(true) + QString(","); - attributes[ParsersAttributes::ROLES].remove(attributes[ParsersAttributes::ROLES].size()-1,1); + attributes[Attributes::Roles].remove(attributes[Attributes::Roles].size()-1,1); return(BaseObject::__getCodeDefinition(def_type)); } @@ -507,7 +514,7 @@ QString Permission::getDropDefinition(bool cascade) this->setRevoke(!revoke); this->setCascade(cascade); - def=this->getCodeDefinition(SchemaParser::SQL_DEFINITION); + def=this->getCodeDefinition(SchemaParser::SqlDefinition); this->setRevoke(revoke); this->setCascade(this->cascade); @@ -515,6 +522,6 @@ QString Permission::getDropDefinition(bool cascade) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } diff --git a/libpgmodeler/src/permission.h b/libpgmodeler/src/permission.h index e0198fa492..658d474ded 100644 --- a/libpgmodeler/src/permission.h +++ b/libpgmodeler/src/permission.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -43,8 +43,8 @@ class Permission: public BaseObject { * view * sequence * database - * foreign-data wrapper (not implemented) - * foreign server (not implemented) + * foreign-data wrapper + * foreign server * large objects (not implemented) * function * aggregate @@ -84,18 +84,18 @@ class Permission: public BaseObject { public: //! \brief Constants used to reference the privileges - static const unsigned PRIV_SELECT=0, - PRIV_INSERT=1, - PRIV_UPDATE=2, - PRIV_DELETE=3, - PRIV_TRUNCATE=4, - PRIV_REFERENCES=5, - PRIV_TRIGGER=6, - PRIV_CREATE=7, - PRIV_CONNECT=8, - PRIV_TEMPORARY=9, - PRIV_EXECUTE=10, - PRIV_USAGE=11; + static constexpr unsigned PrivSelect=0, + PrivInsert=1, + PrivUpdate=2, + PrivDelete=3, + PrivTruncate=4, + PrivReferences=5, + PrivTrigger=6, + PrivCreate=7, + PrivConnect=8, + PrivTemporary=9, + PrivExecute=10, + PrivUsage=11; /*! \brief In the constructor is required to specify which object will receive the permissions this can not be changed after the object instance of @@ -154,7 +154,7 @@ class Permission: public BaseObject { bool isSimilarTo(Permission *perm); //! \brief Returns if the passed object type accepts permission - static bool objectAcceptsPermission(ObjectType obj_type, int privilege=-1); + static bool acceptsPermission(ObjectType obj_type, int privilege=-1); //! \brief Returns the SQL / XML definition for the permission virtual QString getCodeDefinition(unsigned def_type) final; diff --git a/libpgmodeler/src/pgmodelerns.cpp b/libpgmodeler/src/pgmodelerns.cpp index 84e933a0ae..f91bf74e47 100644 --- a/libpgmodeler/src/pgmodelerns.cpp +++ b/libpgmodeler/src/pgmodelerns.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -21,7 +21,7 @@ #include #include -namespace PgModelerNS { +namespace PgModelerNs { template void copyObject(BaseObject **psrc_obj, Class *copy_obj) @@ -33,7 +33,7 @@ namespace PgModelerNS { //Raises an error if the copy object is not allocated if(!copy_obj) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Allocates the source object if its not allocated if(!orig_obj) @@ -50,7 +50,7 @@ namespace PgModelerNS { { switch(obj_type) { - case OBJ_RELATIONSHIP: + case ObjectType::Relationship: Relationship *rel1; rel1=new Relationship(dynamic_cast(copy_obj)); if(!(*psrc_obj)) @@ -58,7 +58,7 @@ namespace PgModelerNS { else (*(dynamic_cast(*psrc_obj)))=(*rel1); break; - case BASE_RELATIONSHIP: + case ObjectType::BaseRelationship: BaseRelationship *rel; rel=new BaseRelationship(dynamic_cast(copy_obj)); if(!(*psrc_obj)) @@ -66,93 +66,101 @@ namespace PgModelerNS { else (*(dynamic_cast(*psrc_obj)))=(*rel); break; - case OBJ_COLUMN: + case ObjectType::Column: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_CONSTRAINT: + case ObjectType::Constraint: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_TRIGGER: + case ObjectType::Trigger: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_RULE: + case ObjectType::Rule: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_INDEX: + case ObjectType::Index: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_POLICY: + case ObjectType::Policy: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_TABLE: + case ObjectType::Table: copyObject(psrc_obj, dynamic_cast
(copy_obj)); break; - case OBJ_TEXTBOX: + case ObjectType::Textbox: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_OPCLASS: + case ObjectType::OpClass: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_CONVERSION: + case ObjectType::Conversion: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_CAST: + case ObjectType::Cast: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_DOMAIN: + case ObjectType::Domain: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_TABLESPACE: + case ObjectType::Tablespace: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_SCHEMA: + case ObjectType::Schema: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_OPFAMILY: + case ObjectType::OpFamily: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_FUNCTION: + case ObjectType::Function: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_AGGREGATE: + case ObjectType::Aggregate: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_LANGUAGE: + case ObjectType::Language: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_OPERATOR: + case ObjectType::Operator: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_ROLE: + case ObjectType::Role: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_SEQUENCE: + case ObjectType::Sequence: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_TYPE: + case ObjectType::Type: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_VIEW: + case ObjectType::View: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_COLLATION: + case ObjectType::Collation: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_EXTENSION: + case ObjectType::Extension: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_TAG: + case ObjectType::Tag: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_EVENT_TRIGGER: + case ObjectType::EventTrigger: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - case OBJ_GENERIC_SQL: + case ObjectType::GenericSql: copyObject(psrc_obj, dynamic_cast(copy_obj)); break; - default: - throw Exception(ERR_OPR_OBJ_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + case ObjectType::ForeignDataWrapper: + copyObject(psrc_obj, dynamic_cast(copy_obj)); + break; + case ObjectType::ForeignServer: + copyObject(psrc_obj, dynamic_cast(copy_obj)); break; + case ObjectType::UserMapping: + copyObject(psrc_obj, dynamic_cast(copy_obj)); + break; + default: + throw Exception(ErrorCode::OprObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } @@ -161,57 +169,57 @@ namespace PgModelerNS { { static QHash keywords={ {QChar('A'), {QString("ALL"), QString("ANALYSE"), QString("ANALYZE"), QString("AND"), - QString("ANY"), QString("AS"), QString("ASC"), QString("AUTHORIZATION")}}, + QString("ANY"), QString("AS"), QString("ASC"), QString("AUTHORIZATION")}}, {QChar('B'), {QString("BETWEEN"), QString("BIGINT"), QString("BINARY"), QString("BIT"), - QString("BOOLEAN"), QString("BOTH")}}, + QString("BOOLEAN"), QString("BOTH")}}, {QChar('C'), {QString("CASE"), QString("CAST"), QString("CHAR"), QString("CHARACTER"), - QString("CHECK"), QString("COALESCE"), QString("COLLATE"), QString("COLUMN"), - QString("CONSTRAINT"), QString("CONVERT"), QString("CREATE"), QString("CROSS"), - QString("CURRENT_DATE"), QString("CURRENT_TIME"), QString("CURRENT_TIMESTAMP"), QString("CURRENT_USER")}}, + QString("CHECK"), QString("COALESCE"), QString("COLLATE"), QString("COLUMN"), + QString("CONSTRAINT"), QString("CONVERT"), QString("CREATE"), QString("CROSS"), + QString("CURRENT_DATE"), QString("CURRENT_TIME"), QString("CURRENT_TIMESTAMP"), QString("CURRENT_USER")}}, {QChar('D'), {QString("DEC"), QString("DECIMAL"), QString("DEFAULT"), QString("DEFERRABLE"), - QString("DESC"), QString("DISTINCT"), QString("DO")}}, + QString("DESC"), QString("DISTINCT"), QString("DO")}}, {QChar('E'), {QString("ELSE"), QString("END"), QString("EXCEPT"), QString("EXISTS"), - QString("EXTRACT")}}, + QString("EXTRACT")}}, {QChar('F'), {QString("FALSE"), QString("FLOAT"), QString("FOR"), QString("FOREIGN"), - QString("FREEZE"), QString("FROM"), QString("FULL")}}, + QString("FREEZE"), QString("FROM"), QString("FULL")}}, {QChar('G'), {QString("GRANT"), QString("GROUP")}}, {QChar('H'), {QString("HAVING")}}, {QChar('I'), {QString("ILIKE"), QString("IN"), QString("INITIALLY"), QString("INNER"), - QString("INT"), QString("INTEGER"), QString("INTERSECT"), QString("INTERVAL"), - QString("INTO"), QString("IS"), QString("ISNULL")}}, + QString("INT"), QString("INTEGER"), QString("INTERSECT"), QString("INTERVAL"), + QString("INTO"), QString("IS"), QString("ISNULL")}}, {QChar('J'), {QString("JOIN")}}, {QChar('L'), {QString("LEADING"), QString("LEFT"), QString("LIKE"), QString("LIMIT"), - QString("LOCALTIME"), QString("LOCALTIMESTAMP")}}, + QString("LOCALTIME"), QString("LOCALTIMESTAMP")}}, {QChar('N'), {QString("NATURAL"), QString("NCHAR"), QString("NEW"), QString("NOCREATEDB"), - QString("NOCREATEUSER"), QString("NONE"), QString("NOT"), QString("NOTHING"), - QString("NOTIFY"), QString("NOTNULL"), QString("NULL"), QString("NULLIF"), - QString("NUMERIC")}}, + QString("NOCREATEUSER"), QString("NONE"), QString("NOT"), QString("NOTHING"), + QString("NOTIFY"), QString("NOTNULL"), QString("NULL"), QString("NULLIF"), + QString("NUMERIC")}}, {QChar('O'), {QString("OFF"), QString("OFFSET"), QString("OLD"), QString("ON"), - QString("ONLY"), QString("OR"), QString("ORDER"), QString("OUTER"), - QString("OVERLAPS"), QString("OVERLAY")}}, + QString("ONLY"), QString("OR"), QString("ORDER"), QString("OUTER"), + QString("OVERLAPS"), QString("OVERLAY")}}, {QChar('P'), {QString("PLACING"), QString("POSITION"), QString("PRIMARY")}}, {QChar('R'), {QString("REAL"), QString("REFERENCES"), QString("RIGHT"), QString("ROW")}}, {QChar('S'), {QString("SELECT"), QString("SESSION_USER"), QString("SETOF"), QString("SIMILAR"), - QString("SMALLINT"), QString("SOME"), QString("SUBSTRING")}}, + QString("SMALLINT"), QString("SOME"), QString("SUBSTRING")}}, {QChar('T'), {QString("TABLE"), QString("THEN"), QString("TIME"), QString("TIMESTAMP"), - QString("TO"), QString("TRAILING"), QString("TREAT"), QString("TRIM"), - QString("TRUE")}}, + QString("TO"), QString("TRAILING"), QString("TREAT"), QString("TRIM"), + QString("TRUE")}}, {QChar('U'), {QString("UNION"), QString("UNIQUE"), QString("USER"), QString("USING")}}, diff --git a/libpgmodeler/src/pgmodelerns.h b/libpgmodeler/src/pgmodelerns.h index 109ddca216..73629d65fd 100644 --- a/libpgmodeler/src/pgmodelerns.h +++ b/libpgmodeler/src/pgmodelerns.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -27,12 +27,12 @@ #include "baseobject.h" -namespace PgModelerNS { +namespace PgModelerNs { //! \brief Default char used as unescaped value start delimiter - const static QChar UNESC_VALUE_START='/'; + static const QChar UnescValueStart='/'; //! \brief Default char used as unescaped value end delimiter - const static QChar UNESC_VALUE_END='/'; + static const QChar UnescValueEnd='/'; /*! \brief Template function that makes a copy from 'copy_obj' to 'psrc_obj' doing the cast to the correct object type. If the source object (psrc_obj) is not allocated the function allocates the attributes @@ -65,27 +65,27 @@ namespace PgModelerNS { if(!obj) return(""); //Cast objects will not have the name changed since their name are automatically generated - else if(obj->getObjectType()==OBJ_CAST || obj->getObjectType()==OBJ_DATABASE) + else if(obj->getObjectType()==ObjectType::Cast || obj->getObjectType()==ObjectType::Database) return(obj->getName()); obj_name=obj->getName(fmt_name); obj_type=obj->getObjectType(); - if(!use_suf_on_conflict && obj_type!=OBJ_OPERATOR) + if(!use_suf_on_conflict && obj_type!=ObjectType::Operator) obj_name += suffix; - counter = (use_suf_on_conflict && obj_type!= OBJ_OPERATOR? 0 : 1); + counter = (use_suf_on_conflict && obj_type!= ObjectType::Operator? 0 : 1); id=QString::number(obj->getObjectId()); len=obj_name.size() + id.size(); //If the name length exceeds the maximum size - if(len > BaseObject::OBJECT_NAME_MAX_LENGTH) + if(len > BaseObject::ObjectNameMaxLength) { //Remove the last chars in the count of 3 + length of id obj_name.chop(id.size() + 3); //Append the id of the object on its name (this is not applied to operators) - if(obj_type!=OBJ_OPERATOR) + if(obj_type!=ObjectType::Operator) obj_name+=QString("_") + id; } @@ -101,7 +101,7 @@ namespace PgModelerNS { if(/*aux_obj!=obj &&*/ aux_obj->getName(fmt_name)==aux_name) { //For operators is appended a '?' on the name - if(obj_type==OBJ_OPERATOR) + if(obj_type==ObjectType::Operator) aux_name=QString("%1%2").arg(obj_name).arg(QString("").leftJustified(counter++, oper_uniq_chr)); else { diff --git a/libpgmodeler/src/pgsqltypes.cpp b/libpgmodeler/src/pgsqltypes.cpp index 745cea71cd..cafb9c8dff 100644 --- a/libpgmodeler/src/pgsqltypes.cpp +++ b/libpgmodeler/src/pgsqltypes.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -21,7 +21,7 @@ /******************** * CLASS: BaseType * ********************/ -QString BaseType::type_list[types_count]= +QString BaseType::type_list[BaseType::TypesCount]= { /* Tipo vazio, quando se instância a classe TipoBase ao usar o operador ~ este será o único tipo retornado */ @@ -73,7 +73,7 @@ QString BaseType::type_list[types_count]= "brin", //Types used by the class PgSQLType - //offsets 27 to 86 + //offsets 27 to 88 //Note: the type char is different from "char" (with quotes) //Reference: http://www.postgresql.org/docs/9.2/static/datatype-character.html @@ -85,13 +85,13 @@ QString BaseType::type_list[types_count]= "interval", "boolean", "bool", "point", "line", "lseg", "box", "path", "polygon", "circle", "cidr", "inet", - "macaddr", "bit", "bit varying", "varbit", "uuid", "xml", "json", "jsonb", + "macaddr", "macaddr8", "bit", "bit varying", "varbit", "uuid", "xml", "json", "jsonb", "smallserial", "int2vector", "int2", "int4", "int8", "float4", "float8", "bpchar", "name", "abstime", "aclitem", "gtsvector", "refcursor", "reltime", "tinterval", "tsquery", "tsvector", "txid_snapshot", //Spatial type specifics for the PostGiS extension - //offsets 88 to 101 + //offsets 89 to 102 "box2d","box3d","geometry", "geometry_dump","geography", "geomval", "addbandarg", "rastbandarg", @@ -101,12 +101,12 @@ QString BaseType::type_list[types_count]= "validatetopology_returntype", //Range-types - //offsets 102 to 107 + //offsets 103 to 108 "int4range", "int8range", "numrange", "tsrange","tstzrange","daterange", //Object Identification type (OID) - //offsets 108 to 122 + //offsets 109 to 123 "oid", "regproc", "regprocedure", "regoper", "regoperator", "regclass", "regrole", "regnamespace", "regtype", @@ -114,31 +114,31 @@ QString BaseType::type_list[types_count]= "tid", "oidvector", //Pseudo-types - //offsets 123 to 137 + //offsets 124 to 138 "\"any\"","anyarray","anyelement","anyenum", "anynonarray", "anyrange", "cstring","internal","language_handler", "record","trigger","void","opaque", "fdw_handler", "event_trigger", //Interval types - //offsets 138 to 150 + //offsets 139 to 151 "YEAR", "MONTH", "DAY", "HOUR", "MINUTE", "SECOND","YEAR TO MONTH", "DAY TO HOUR","DAY TO MINUTE","DAY TO SECOND", "HOUR TO MINUTE","HOUR TO SECOND","MINUTE TO SECOND", //Types used by the class BehaviorType - //offsets 151 to 153 + //offsets 152 to 154 "CALLED ON NULL INPUT", "RETURNS NULL ON NULL INPUT", "STRICT", //Types used by the class SecurityType - //offsets 154 to 155 + //offsets 155 to 156 "SECURITY INVOKER", "SECURITY DEFINER", //Types used by the class LanguageType - //offsets 156 to 162 + //offsets 157 to 163 "sql", "c", "plpgsql", @@ -148,7 +148,7 @@ QString BaseType::type_list[types_count]= "internal", //Types used by the class EncodingType - //offsets 163 to 204 + //offsets 164 to 205 "UTF8", "BIG5", "EUC_CN", "EUC_JP", "EUC_JIS_2004", "EUC_KR", "EUC_TW", "GB18030", "GBK", "ISO_8859_5", "ISO_8859_6", "ISO_8859_7", "ISO_8859_8", @@ -161,25 +161,25 @@ QString BaseType::type_list[types_count]= "WIN1254", "WIN1255", "WIN1256", "WIN1257", "WIN1258", //Types used by the class StorageType - //offsets 205 to 208 + //offsets 206 to 209 "plain", "external", "extended", "main", //Types used by the class MatchType - //offsets 209 to 211 + //offsets 210 to 212 "MATCH FULL", "MATCH PARTIAL", "MATCH SIMPLE", //Types used by the class DeferralType - //offsets 212 to 213 + //offsets 213 to 214 "INITIALLY IMMEDIATE", "INITIALLY DEFERRED", //Types used by the class CategoryType - //offsets 214 to 227 - See table 44-43 on PostgreSQL 8.4 documentation + //offsets 215 to 228 - See table 44-43 on PostgreSQL 8.4 documentation "U", //User-defined types "A", //Array types "B", //Boolean types @@ -196,7 +196,7 @@ QString BaseType::type_list[types_count]= "X", //Unknown type //Types used by the class FiringType - //offsets 228 to 230 + //offsets 229 to 231 "BEFORE", "AFTER", "INSTEAD OF", @@ -205,7 +205,7 @@ QString BaseType::type_list[types_count]= These types accepts variations Z, M e ZM. > Example: POINT, POINTZ, POINTM, POINTZM Reference: http://postgis.refractions.net/documentation/manual-2.0/using_postgis_dbmanagement.html */ - //offsets 231 to 246 + //offsets 232 to 247 "POINT", "LINESTRING", "POLYGON", @@ -224,35 +224,41 @@ QString BaseType::type_list[types_count]= "MULTISURFACE", //Types used by the class EventTriggerType - //offsets 247 to 250 + //offsets 248 to 251 "ddl_command_start", "ddl_command_end", "sql_drop", "table_rewrite", //Types used by the class IdentityType - //offsets 251 to 252 + //offsets 252 to 253 "ALWAYS", "BY DEFAULT", //Types used by the class PolicyCmdType - //offsets 253 to 257 + //offsets 254 to 258 "ALL", "SELECT", "INSERT", "DELETE", - "UPDATE" + "UPDATE", + + //Types used by the class PartitioningType + //offsets 259 to 261 + "RANGE", + "LIST", + "HASH", }; BaseType::BaseType(void) { - type_idx=BaseType::null; + type_idx=BaseType::Null; } QString BaseType::getTypeString(unsigned type_id) { - if(type_id > types_count) - throw Exception(ERR_REF_TYPE_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(type_id > TypesCount) + throw Exception(ErrorCode::RefTypeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(type_list[type_id]); } @@ -260,11 +266,11 @@ QString BaseType::getTypeString(unsigned type_id) void BaseType::setType(unsigned type_id,unsigned offset,unsigned count) { //Raises an error if the type count is invalid - if(count==0 || count > this->types_count) - throw Exception(ERR_OBT_TYPES_INV_QUANTITY,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(count==0 || count > this->TypesCount) + throw Exception(ErrorCode::ObtTypesInvalidQuantity,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the type id is invalid else if(!isTypeValid(type_id,offset,count)) - throw Exception(ERR_ASG_INV_TYPE_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidTypeObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else type_idx=type_id; } @@ -272,14 +278,14 @@ void BaseType::setType(unsigned type_id,unsigned offset,unsigned count) bool BaseType::isTypeValid(unsigned type_id,unsigned offset,unsigned count) { //Returns if the type id is valid according to the specified interval (offset-count) - return((type_id>=offset && type_id<=(offset+count-1)) || type_id==BaseType::null); + return((type_id>=offset && type_id<=(offset+count-1)) || type_id==BaseType::Null); } void BaseType::getTypes(QStringList &types,unsigned offset,unsigned count) { //Raises an error if the type count is invalid - if(count==0 || count > BaseType::types_count) - throw Exception(ERR_OBT_TYPES_INV_QUANTITY,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(count==0 || count > BaseType::TypesCount) + throw Exception(ErrorCode::ObtTypesInvalidQuantity,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { unsigned idx,total; @@ -298,7 +304,7 @@ unsigned BaseType::getType(const QString &type_name,unsigned offset,unsigned cou bool found=false; if(type_name.isEmpty()) - return(BaseType::null); + return(BaseType::Null); else { QString aux_name, tp_name=type_name; @@ -316,7 +322,7 @@ unsigned BaseType::getType(const QString &type_name,unsigned offset,unsigned cou if(found) { idx--; return(idx); } else - return(BaseType::null); + return(BaseType::Null); } } @@ -375,17 +381,17 @@ ActionType::ActionType(const QString &type_name) ActionType::ActionType(void) { - type_idx=offset; + type_idx=Offset; } void ActionType::getTypes(QStringList &type_list) { - BaseType::getTypes(type_list,offset,types_count); + BaseType::getTypes(type_list,Offset,TypesCount); } unsigned ActionType::operator = (unsigned type_id) { - BaseType::setType(type_id,offset,types_count); + BaseType::setType(type_id,Offset,TypesCount); return(type_idx); } @@ -393,8 +399,8 @@ unsigned ActionType::operator = (const QString &type_name) { unsigned type_idx; - type_idx=BaseType::getType(type_name, offset, types_count); - BaseType::setType(type_idx,offset,types_count); + type_idx=BaseType::getType(type_name, Offset, TypesCount); + BaseType::setType(type_idx,Offset,TypesCount); return(type_idx); } @@ -413,17 +419,17 @@ ConstraintType::ConstraintType(const QString &type_name) ConstraintType::ConstraintType(void) { - type_idx=offset; + type_idx=Offset; } void ConstraintType::getTypes(QStringList &type_list) { - BaseType::getTypes(type_list,offset,types_count); + BaseType::getTypes(type_list,Offset,TypesCount); } unsigned ConstraintType::operator = (unsigned type_id) { - BaseType::setType(type_id,offset,types_count); + BaseType::setType(type_id,Offset,TypesCount); return(type_idx); } @@ -431,8 +437,8 @@ unsigned ConstraintType::operator = (const QString &type_name) { unsigned type_id; - type_id=BaseType::getType(type_name, offset, types_count); - BaseType::setType(type_id,offset,types_count); + type_id=BaseType::getType(type_name, Offset, TypesCount); + BaseType::setType(type_id,Offset,TypesCount); return(type_id); } @@ -441,7 +447,7 @@ unsigned ConstraintType::operator = (const QString &type_name) ********************/ EventType::EventType(void) { - type_idx=offset; + type_idx=Offset; } EventType::EventType(const QString &type_name) @@ -456,12 +462,12 @@ EventType::EventType(unsigned type_id) void EventType::getTypes(QStringList &type_list) { - BaseType::getTypes(type_list,offset,types_count); + BaseType::getTypes(type_list,Offset,TypesCount); } unsigned EventType::operator = (unsigned type_id) { - BaseType::setType(type_id,offset,types_count); + BaseType::setType(type_id,Offset,TypesCount); return(type_idx); } @@ -469,8 +475,8 @@ unsigned EventType::operator = (const QString &type_name) { unsigned type_id; - type_id=BaseType::getType(type_name, offset, types_count); - BaseType::setType(type_id,offset,types_count); + type_id=BaseType::getType(type_name, Offset, TypesCount); + BaseType::setType(type_id,Offset,TypesCount); return(type_id); } @@ -489,7 +495,7 @@ bool EventType::operator < (unsigned type_id) const ************************/ ExecutionType::ExecutionType(void) { - type_idx=offset; + type_idx=Offset; } ExecutionType::ExecutionType(unsigned type_id) @@ -504,12 +510,12 @@ ExecutionType::ExecutionType(const QString &type_name) void ExecutionType::getTypes(QStringList &type_list) { - BaseType::getTypes(type_list,offset,types_count); + BaseType::getTypes(type_list,Offset,TypesCount); } unsigned ExecutionType::operator = (unsigned type_id) { - BaseType::setType(type_id,offset,types_count); + BaseType::setType(type_id,Offset,TypesCount); return(type_idx); } @@ -517,8 +523,8 @@ unsigned ExecutionType::operator = (const QString &type_name) { unsigned type_id; - type_id=BaseType::getType(type_name, offset, types_count); - BaseType::setType(type_id,offset,types_count); + type_id=BaseType::getType(type_name, Offset, TypesCount); + BaseType::setType(type_id,Offset,TypesCount); return(type_id); } @@ -532,7 +538,7 @@ FunctionType::FunctionType(unsigned type_id) FunctionType::FunctionType(void) { - type_idx=offset; + type_idx=Offset; } FunctionType::FunctionType(const QString &type_name) @@ -542,12 +548,12 @@ FunctionType::FunctionType(const QString &type_name) void FunctionType::getTypes(QStringList &tipos) { - BaseType::getTypes(tipos,offset,types_count); + BaseType::getTypes(tipos,Offset,TypesCount); } unsigned FunctionType::operator = (unsigned type_id) { - BaseType::setType(type_id,offset,types_count); + BaseType::setType(type_id,Offset,TypesCount); return(type_idx); } @@ -555,8 +561,8 @@ unsigned FunctionType::operator = (const QString &type_name) { unsigned type_id; - type_id=BaseType::getType(type_name, offset, types_count); - BaseType::setType(type_id,offset,types_count); + type_id=BaseType::getType(type_name, Offset, TypesCount); + BaseType::setType(type_id,Offset,TypesCount); return(type_id); } @@ -570,7 +576,7 @@ IndexingType::IndexingType(unsigned type_id) IndexingType::IndexingType(void) { - type_idx=offset; + type_idx=Offset; } IndexingType::IndexingType(const QString &type_name) @@ -580,12 +586,12 @@ IndexingType::IndexingType(const QString &type_name) void IndexingType::getTypes(QStringList &type_list) { - BaseType::getTypes(type_list,offset,types_count); + BaseType::getTypes(type_list,Offset,TypesCount); } unsigned IndexingType::operator = (unsigned type_id) { - BaseType::setType(type_id,offset,types_count); + BaseType::setType(type_id,Offset,TypesCount); return(type_idx); } @@ -593,8 +599,8 @@ unsigned IndexingType::operator = (const QString &type_name) { unsigned type_id; - type_id=BaseType::getType(type_name, offset, types_count); - BaseType::setType(type_id,offset,types_count); + type_id=BaseType::getType(type_name, Offset, TypesCount); + BaseType::setType(type_id,Offset,TypesCount); return(type_id); } @@ -608,7 +614,7 @@ IntervalType::IntervalType(unsigned type_id) IntervalType::IntervalType(void) { - type_idx=BaseType::null; + type_idx=BaseType::Null; } IntervalType::IntervalType(const QString &type_name) @@ -618,12 +624,12 @@ IntervalType::IntervalType(const QString &type_name) void IntervalType::getTypes(QStringList &type_list) { - BaseType::getTypes(type_list,offset,types_count); + BaseType::getTypes(type_list,Offset,TypesCount); } unsigned IntervalType::operator = (unsigned type_id) { - BaseType::setType(type_id,offset,types_count); + BaseType::setType(type_id,Offset,TypesCount); return(type_idx); } @@ -631,8 +637,8 @@ unsigned IntervalType::operator = (const QString &type_name) { unsigned type_id; - type_id=BaseType::getType(type_name, offset, types_count); - BaseType::setType(type_id,offset,types_count); + type_id=BaseType::getType(type_name, Offset, TypesCount); + BaseType::setType(type_id,Offset,TypesCount); return(type_id); } @@ -645,44 +651,44 @@ SpatialType::SpatialType(const QString &type_name, int srid, unsigned variation_ if(name.endsWith(QString("ZM"))) { - variation_id=var_zm; + variation_id=VarZm; name.remove(QString("ZM")); } else if(name.endsWith(QString("M"))) { - variation_id=var_m; + variation_id=VarM; name.remove(QString("M")); } else if(name.endsWith(QString("Z"))) { - variation_id=var_z; + variation_id=VarZ; name.remove(QString("Z")); } - BaseType::setType(BaseType::getType(name, offset, types_count), - offset, types_count); + BaseType::setType(BaseType::getType(name, Offset, TypesCount), + Offset, TypesCount); setVariation(variation_id); setSRID(srid); } SpatialType::SpatialType(unsigned type_id, int srid, unsigned var_id) { - BaseType::setType(type_id,offset,types_count); + BaseType::setType(type_id,Offset,TypesCount); setVariation(var_id); setSRID(srid); } SpatialType::SpatialType(void) { - type_idx=BaseType::null; - variation=no_var; + type_idx=BaseType::Null; + variation=NoVar; srid=0; } void SpatialType::setVariation(unsigned var) { - if(var > var_zm) - variation=var_zm; + if(var > VarZm) + variation=VarZm; else variation=var; } @@ -694,7 +700,7 @@ unsigned SpatialType::getVariation(void) void SpatialType::getTypes(QStringList &type_list) { - BaseType::getTypes(type_list,offset,types_count); + BaseType::getTypes(type_list,Offset,TypesCount); } void SpatialType::setSRID(int srid) @@ -710,15 +716,15 @@ int SpatialType::getSRID(void) QString SpatialType::operator * (void) { - if(this->type_idx!=BaseType::null) + if(this->type_idx!=BaseType::Null) { QString var_str; switch(variation) { - case var_z: var_str+=QString("Z"); break; - case var_m: var_str+=QString("M"); break; - case var_zm: var_str+=QString("ZM"); break; + case VarZ: var_str+=QString("Z"); break; + case VarM: var_str+=QString("M"); break; + case VarZm: var_str+=QString("ZM"); break; default: var_str=QString(); break; } @@ -734,61 +740,61 @@ QString SpatialType::operator * (void) /******************** * CLASS: PgSQLType * ********************/ -vector PgSQLType::user_types; +vector PgSqlType::user_types; -PgSQLType::PgSQLType(void) +PgSqlType::PgSqlType(void) { - type_idx=offset; + type_idx=Offset; length=0; precision=-1; dimension=0; with_timezone=false; } -PgSQLType::PgSQLType(const QString &type_name) : PgSQLType() +PgSqlType::PgSqlType(const QString &type_name) : PgSqlType() { (*this)=type_name; } -PgSQLType::PgSQLType(void *ptype) : PgSQLType() +PgSqlType::PgSqlType(void *ptype) : PgSqlType() { (*this) << ptype; } -PgSQLType::PgSQLType(void *ptype, unsigned length, unsigned dimension, int precision, bool with_timezone, IntervalType interv_type, SpatialType spatial_type) : PgSQLType() +PgSqlType::PgSqlType(void *ptype, unsigned dimension, unsigned length, int precision, bool with_timezone, IntervalType interv_type, SpatialType spatial_type) : PgSqlType() { (*this) << ptype; - setLength(length); setDimension(dimension); + setLength(length); setPrecision(precision); setWithTimezone(with_timezone); setIntervalType(interv_type); setSpatialType(spatial_type); } -PgSQLType::PgSQLType(const QString &type_name, unsigned length, unsigned dimension, int precision, bool with_timezone, IntervalType interv_type, SpatialType spatial_type) : PgSQLType() +PgSqlType::PgSqlType(const QString &type_name, unsigned dimension, unsigned length, int precision, bool with_timezone, IntervalType interv_type, SpatialType spatial_type) : PgSqlType() { (*this)=type_name; - setLength(length); setDimension(dimension); + setLength(length); setPrecision(precision); setWithTimezone(with_timezone); setIntervalType(interv_type); setSpatialType(spatial_type); } -PgSQLType::PgSQLType(unsigned type_id, unsigned length, unsigned dimension, int precision, bool with_timezone, IntervalType interv_type, SpatialType spatial_type) : PgSQLType() +PgSqlType::PgSqlType(unsigned type_id, unsigned dimension, unsigned length, int precision, bool with_timezone, IntervalType interv_type, SpatialType spatial_type) : PgSqlType() { (*this)=type_id; - setLength(length); setDimension(dimension); + setLength(length); setPrecision(precision); setWithTimezone(with_timezone); setIntervalType(interv_type); setSpatialType(spatial_type); } -PgSQLType PgSQLType::parseString(const QString &str) +PgSqlType PgSqlType::parseString(const QString &str) { QString type_str=str.toLower().simplified(), sptype, interv; bool with_tz=false; @@ -796,7 +802,7 @@ PgSQLType PgSQLType::parseString(const QString &str) int prec=-1, len = -1; int start=-1, end=-1; QStringList value, intervals; - PgSQLType type; + PgSqlType type; //Checking if the string contains one of interval types IntervalType::getTypes(intervals); @@ -867,7 +873,7 @@ PgSQLType PgSQLType::parseString(const QString &str) try { //Creates the type based on the extracted values - type=PgSQLType(type_str); + type=PgSqlType(type_str); } catch(Exception &) { @@ -876,12 +882,12 @@ PgSQLType PgSQLType::parseString(const QString &str) QStringList typname=type_str.split('.'); if(typname.size()==2) - type=PgSQLType(typname[1]); + type=PgSqlType(typname[1]); else { /* One last try it to check if the type has an entry on user defined types as pg_catalog.[type name] */ - type=PgSQLType(QString("pg_catalog.") + type_str); + type=PgSqlType(QString("pg_catalog.") + type_str); } } @@ -907,39 +913,39 @@ PgSQLType PgSQLType::parseString(const QString &str) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, str); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, str); } } -void PgSQLType::getTypes(QStringList &type_list, bool oids, bool pseudos) +void PgSqlType::getTypes(QStringList &type_list, bool oids, bool pseudos) { unsigned idx,total; type_list.clear(); - total=offset+types_count; + total=Offset+TypesCount; - for(idx=offset; idx=oid_start && idx<=oid_end) || - (pseudos && idx>=pseudo_start && idx<=pseudo_end)) + if(idx=OidStart && idx<=OidEnd) || + (pseudos && idx>=PseudoStart && idx<=PseudoEnd)) type_list.push_back(BaseType::type_list[idx]); } } -unsigned PgSQLType::operator = (unsigned type_id) +unsigned PgSqlType::operator = (unsigned type_id) { - if(type_id>=offset) + if(type_id>=Offset) setUserType(type_id); else if(type_id > 0) - BaseType::setType(type_id,offset,types_count); + BaseType::setType(type_id,Offset,TypesCount); else if(type_id==0) - throw Exception(ERR_ASG_INV_TYPE_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidTypeObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(type_idx); } -unsigned PgSQLType::operator = (const QString &type_name) +unsigned PgSqlType::operator = (const QString &type_name) { unsigned type_idx, usr_type_idx; @@ -947,10 +953,10 @@ unsigned PgSQLType::operator = (const QString &type_name) usr_type_idx=getUserTypeIndex(type_name, nullptr); if(type_idx==0 && usr_type_idx==0) - throw Exception(ERR_ASG_INV_TYPE_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidTypeObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(type_idx!=0) { - BaseType::setType(type_idx,offset,types_count); + BaseType::setType(type_idx,Offset,TypesCount); return(type_idx); } else @@ -960,28 +966,28 @@ unsigned PgSQLType::operator = (const QString &type_name) } } -void *PgSQLType::getUserTypeReference(void) +void *PgSqlType::getUserTypeReference(void) { if(this->isUserType()) - return(user_types[this->type_idx - (pseudo_end + 1)].ptype); + return(user_types[this->type_idx - (PseudoEnd + 1)].ptype); else return(nullptr); } -unsigned PgSQLType::getUserTypeConfig(void) +unsigned PgSqlType::getUserTypeConfig(void) { if(this->isUserType()) - return(user_types[this->type_idx - (pseudo_end + 1)].type_conf); + return(user_types[this->type_idx - (PseudoEnd + 1)].type_conf); else return(0); } -unsigned PgSQLType::getTypeId(void) +unsigned PgSqlType::getTypeId(void) { return(!(*this)); } -QString PgSQLType::getTypeName(bool incl_dimension) +QString PgSqlType::getTypeName(bool incl_dimension) { if(incl_dimension) { @@ -998,32 +1004,32 @@ QString PgSQLType::getTypeName(bool incl_dimension) return(~(*this)); } -QString PgSQLType::getSQLTypeName(void) +QString PgSqlType::getSQLTypeName(void) { return(*(*this)); } -bool PgSQLType::isRegistered(const QString &type, void *pmodel) +bool PgSqlType::isRegistered(const QString &type, void *pmodel) { - if(getBaseTypeIndex(type)!=BaseType::null) + if(getBaseTypeIndex(type)!=BaseType::Null) return(true); else - return(getUserTypeIndex(type, nullptr, pmodel)!=BaseType::null); + return(getUserTypeIndex(type, nullptr, pmodel)!=BaseType::Null); } -bool PgSQLType::operator == (unsigned type_id) +bool PgSqlType::operator == (unsigned type_id) { return(this->type_idx==type_id); } -bool PgSQLType::operator == (const QString &type_name) +bool PgSqlType::operator == (const QString &type_name) { unsigned idx,total; bool found=false; - total=offset + types_count; + total=Offset + TypesCount; - for(idx=offset; idxtype_idx!=type.type_idx); } -bool PgSQLType::operator != (unsigned type_id) +bool PgSqlType::operator != (unsigned type_id) { return(this->type_idx!=type_id); } -bool PgSQLType::operator == (PgSQLType type) +bool PgSqlType::operator == (PgSqlType type) { return(this->type_idx==type.type_idx); } -bool PgSQLType::operator == (void *ptype) +bool PgSqlType::operator == (void *ptype) { int idx; idx=getUserTypeIndex(QString(),ptype); return(static_cast(type_idx) == idx); } -IntervalType PgSQLType::getIntervalType(void) +IntervalType PgSqlType::getIntervalType(void) { return(interval_type); } -SpatialType PgSQLType::getSpatialType(void) +SpatialType PgSqlType::getSpatialType(void) { return(spatial_type); } -bool PgSQLType::isWithTimezone(void) +bool PgSqlType::isWithTimezone(void) { return(with_timezone); } -bool PgSQLType::isOIDType(void) +bool PgSqlType::isOIDType(void) { - return(type_idx>=oid_start && type_idx<=oid_end); + return(type_idx>=OidStart && type_idx<=OidEnd); } -bool PgSQLType::isPseudoType(void) +bool PgSqlType::isPseudoType(void) { - return(type_idx>=pseudo_start && type_idx<=pseudo_end); + return(type_idx>=PseudoStart && type_idx<=PseudoEnd); } -unsigned PgSQLType::operator << (void *ptype) +unsigned PgSqlType::operator << (void *ptype) { setUserType(ptype); return(type_idx); } -void PgSQLType::setIntervalType(IntervalType interv_type) +void PgSqlType::setIntervalType(IntervalType interv_type) { interval_type=interv_type; } -void PgSQLType::setSpatialType(SpatialType spat_type) +void PgSqlType::setSpatialType(SpatialType spat_type) { spatial_type=spat_type; } -void PgSQLType::setWithTimezone(bool with_tz) +void PgSqlType::setWithTimezone(bool with_tz) { this->with_timezone=with_tz; } -void PgSQLType::setUserType(unsigned type_id) +void PgSqlType::setUserType(unsigned type_id) { unsigned lim1, lim2; - lim1=pseudo_end + 1; - lim2=lim1 + PgSQLType::user_types.size(); + lim1=PseudoEnd + 1; + lim2=lim1 + PgSqlType::user_types.size(); - if(PgSQLType::user_types.size() > 0 && + if(PgSqlType::user_types.size() > 0 && (type_id >= lim1 && type_id < lim2)) type_idx=type_id; else - throw Exception(ERR_ASG_INV_TYPE_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidTypeObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); } -void PgSQLType::setUserType(void *ptype) +void PgSqlType::setUserType(void *ptype) { int idx; idx=getUserTypeIndex(QString(),ptype); if(idx <= 0) - throw Exception(ERR_ASG_INV_TYPE_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidTypeObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else type_idx=idx; } -void PgSQLType::addUserType(const QString &type_name, void *ptype, void *pmodel, unsigned type_conf) +void PgSqlType::addUserType(const QString &type_name, void *ptype, void *pmodel, unsigned type_conf) { if(!type_name.isEmpty() && ptype && pmodel && - (type_conf==UserTypeConfig::DOMAIN_TYPE || - type_conf==UserTypeConfig::SEQUENCE_TYPE || - type_conf==UserTypeConfig::TABLE_TYPE || - type_conf==UserTypeConfig::VIEW_TYPE || - type_conf==UserTypeConfig::EXTENSION_TYPE || - type_conf==UserTypeConfig::BASE_TYPE) && + (type_conf==UserTypeConfig::DomainType || + type_conf==UserTypeConfig::SequenceType || + type_conf==UserTypeConfig::TableType || + type_conf==UserTypeConfig::ViewType || + type_conf==UserTypeConfig::ExtensionType || + type_conf==UserTypeConfig::BaseType) && getUserTypeIndex(type_name,ptype,pmodel)==0) { UserTypeConfig cfg; @@ -1146,19 +1152,19 @@ void PgSQLType::addUserType(const QString &type_name, void *ptype, void *pmodel, cfg.ptype=ptype; cfg.pmodel=pmodel; cfg.type_conf=type_conf; - PgSQLType::user_types.push_back(cfg); + PgSqlType::user_types.push_back(cfg); } } -void PgSQLType::removeUserType(const QString &type_name, void *ptype) +void PgSqlType::removeUserType(const QString &type_name, void *ptype) { - if(PgSQLType::user_types.size() > 0 && + if(PgSqlType::user_types.size() > 0 && !type_name.isEmpty() && ptype) { vector::iterator itr, itr_end; - itr=PgSQLType::user_types.begin(); - itr_end=PgSQLType::user_types.end(); + itr=PgSqlType::user_types.begin(); + itr_end=PgSqlType::user_types.end(); while(itr!=itr_end) { @@ -1175,15 +1181,15 @@ void PgSQLType::removeUserType(const QString &type_name, void *ptype) } } -void PgSQLType::renameUserType(const QString &type_name, void *ptype,const QString &new_name) +void PgSqlType::renameUserType(const QString &type_name, void *ptype,const QString &new_name) { - if(PgSQLType::user_types.size() > 0 && + if(PgSqlType::user_types.size() > 0 && !type_name.isEmpty() && ptype && type_name!=new_name) { vector::iterator itr, itr_end; - itr=PgSQLType::user_types.begin(); - itr_end=PgSQLType::user_types.end(); + itr=PgSqlType::user_types.begin(); + itr_end=PgSqlType::user_types.end(); while(itr!=itr_end) { @@ -1197,7 +1203,7 @@ void PgSQLType::renameUserType(const QString &type_name, void *ptype,const QStri } } -void PgSQLType::removeUserTypes(void *pmodel) +void PgSqlType::removeUserTypes(void *pmodel) { if(pmodel) { @@ -1221,25 +1227,25 @@ void PgSQLType::removeUserTypes(void *pmodel) } } -unsigned PgSQLType::getBaseTypeIndex(const QString &type_name) +unsigned PgSqlType::getBaseTypeIndex(const QString &type_name) { QString aux_name=type_name; aux_name.remove(QString("[]")); aux_name.remove(QRegExp(QString("( )(with)(out)?(.)*"))); aux_name=aux_name.trimmed(); - return(getType(aux_name,offset,types_count)); + return(getType(aux_name,Offset,TypesCount)); } -unsigned PgSQLType::getUserTypeIndex(const QString &type_name, void *ptype, void *pmodel) +unsigned PgSqlType::getUserTypeIndex(const QString &type_name, void *ptype, void *pmodel) { - if(PgSQLType::user_types.size() > 0 && (!type_name.isEmpty() || ptype)) + if(PgSqlType::user_types.size() > 0 && (!type_name.isEmpty() || ptype)) { vector::iterator itr, itr_end; int idx=0; - itr=PgSQLType::user_types.begin(); - itr_end=PgSQLType::user_types.end(); + itr=PgSqlType::user_types.begin(); + itr_end=PgSqlType::user_types.end(); while(itr!=itr_end) { @@ -1253,34 +1259,34 @@ unsigned PgSQLType::getUserTypeIndex(const QString &type_name, void *ptype, void } if(itr!=itr_end) - return(pseudo_end + 1 + idx); + return(PseudoEnd + 1 + idx); else - return(BaseType::null); + return(BaseType::Null); } - else return(BaseType::null); + else return(BaseType::Null); } -QString PgSQLType::getUserTypeName(unsigned type_id) +QString PgSqlType::getUserTypeName(unsigned type_id) { unsigned lim1, lim2; - lim1=pseudo_end + 1; - lim2=lim1 + PgSQLType::user_types.size(); + lim1=PseudoEnd + 1; + lim2=lim1 + PgSqlType::user_types.size(); - if(PgSQLType::user_types.size() > 0 && + if(PgSqlType::user_types.size() > 0 && (type_id >= lim1 && type_id < lim2)) - return(PgSQLType::user_types[type_id - lim1].name); + return(PgSqlType::user_types[type_id - lim1].name); else return(QString()); } -void PgSQLType::getUserTypes(QStringList &type_list, void *pmodel, unsigned inc_usr_types) +void PgSqlType::getUserTypes(QStringList &type_list, void *pmodel, unsigned inc_usr_types) { unsigned idx,total; type_list.clear(); - total=PgSQLType::user_types.size(); + total=PgSqlType::user_types.size(); for(idx=0; idx < total; idx++) { @@ -1291,12 +1297,12 @@ void PgSQLType::getUserTypes(QStringList &type_list, void *pmodel, unsigned inc_ } } -void PgSQLType::getUserTypes(vector &ptypes, void *pmodel, unsigned inc_usr_types) +void PgSqlType::getUserTypes(vector &ptypes, void *pmodel, unsigned inc_usr_types) { unsigned idx, total; ptypes.clear(); - total=PgSQLType::user_types.size(); + total=PgSqlType::user_types.size(); for(idx=0; idx < total; idx++) { @@ -1307,10 +1313,10 @@ void PgSQLType::getUserTypes(vector &ptypes, void *pmodel, unsigned inc_ } } -QString PgSQLType::operator ~ (void) +QString PgSqlType::operator ~ (void) { - if(type_idx >= pseudo_end + 1) - return(user_types[type_idx - (pseudo_end + 1)].name); + if(type_idx >= PseudoEnd + 1) + return(user_types[type_idx - (PseudoEnd + 1)].name); else { QString name=BaseType::type_list[type_idx]; @@ -1322,26 +1328,28 @@ QString PgSQLType::operator ~ (void) } } -bool PgSQLType::isArrayType(void) +bool PgSqlType::isArrayType(void) { return(dimension > 0); } -bool PgSQLType::isUserType(void) +bool PgSqlType::isUserType(void) { - return(type_idx > pseudo_end); + return(type_idx > PseudoEnd); } -bool PgSQLType::isNetworkType(void) +bool PgSqlType::isNetworkType(void) { QString curr_type=(!isUserType() ? type_list[this->type_idx] : QString()); return(!isUserType() && (curr_type==QString("cidr") || - curr_type==QString("inet"))); + curr_type==QString("inet") || + curr_type==QString("macaddr") || + curr_type==QString("macaddr8"))); } -bool PgSQLType::isGiSType(void) +bool PgSqlType::isGiSType(void) { QString curr_type=(!isUserType() ? type_list[this->type_idx] : QString()); @@ -1351,7 +1359,7 @@ bool PgSQLType::isGiSType(void) curr_type==QString("geometry_dump"))); } -bool PgSQLType::isRangeType(void) +bool PgSqlType::isRangeType(void) { QString curr_type=(!isUserType() ? type_list[this->type_idx] : QString()); @@ -1361,7 +1369,7 @@ bool PgSQLType::isRangeType(void) curr_type==QString("tstzrange") || curr_type==QString("daterange"))); } -bool PgSQLType::isSerialType(void) +bool PgSqlType::isSerialType(void) { QString curr_type=(!isUserType() ? type_list[this->type_idx] : QString()); @@ -1371,7 +1379,7 @@ bool PgSQLType::isSerialType(void) curr_type==QString("bigserial"))); } -bool PgSQLType::isDateTimeType(void) +bool PgSqlType::isDateTimeType(void) { QString curr_type=(!isUserType() ? type_list[this->type_idx] : QString()); @@ -1381,7 +1389,7 @@ bool PgSQLType::isDateTimeType(void) curr_type==QString("timetz") || curr_type==QString("timestamptz"))); } -bool PgSQLType::isNumericType(void) +bool PgSqlType::isNumericType(void) { QString curr_type=(!isUserType() ? type_list[this->type_idx] : QString()); @@ -1389,7 +1397,7 @@ bool PgSQLType::isNumericType(void) (curr_type==QString("numeric") || curr_type==QString("decimal"))); } -bool PgSQLType::isIntegerType(void) +bool PgSqlType::isIntegerType(void) { QString curr_type=(!isUserType() ? type_list[this->type_idx] : QString()); @@ -1399,7 +1407,7 @@ bool PgSQLType::isIntegerType(void) curr_type==QString("int8") || curr_type==QString("int2"))); } -bool PgSQLType::hasVariableLength(void) +bool PgSqlType::hasVariableLength(void) { QString curr_type=(!isUserType() ? type_list[this->type_idx] : QString()); @@ -1411,7 +1419,7 @@ bool PgSQLType::hasVariableLength(void) curr_type==QString("varbit"))); } -bool PgSQLType::isCharacterType(void) +bool PgSqlType::isCharacterType(void) { QString curr_type=(!isUserType() ? type_list[this->type_idx] : QString()); @@ -1420,7 +1428,7 @@ bool PgSQLType::isCharacterType(void) curr_type==QString("character varying") || curr_type==QString("text")); } -bool PgSQLType::isPolymorphicType(void) +bool PgSqlType::isPolymorphicType(void) { QString curr_type=(!isUserType() ? type_list[this->type_idx] : QString()); @@ -1429,13 +1437,13 @@ bool PgSQLType::isPolymorphicType(void) curr_type==QString("anyrange") || curr_type==QString("\"any\"")); } -bool PgSQLType::acceptsPrecision(void) +bool PgSqlType::acceptsPrecision(void) { return(isNumericType() || (!isUserType() && type_list[this->type_idx]!=QString("date") && isDateTimeType())); } -bool PgSQLType::canCastTo(PgSQLType type) +bool PgSqlType::canCastTo(PgSqlType type) { // If the types are the same of belongs to the same category they naturally can be casted if(this->type_idx==type.type_idx || @@ -1465,7 +1473,7 @@ bool PgSQLType::canCastTo(PgSQLType type) return(false); } -bool PgSQLType::isEquivalentTo(PgSQLType type) +bool PgSqlType::isEquivalentTo(PgSqlType type) { unsigned this_idx=0, type_idx=0; static vector types={{QString("int2"),QString("smallint")}, @@ -1478,8 +1486,8 @@ bool PgSQLType::isEquivalentTo(PgSQLType type) {QString("bit varying"),QString("varbit")}, {QString("oid"),QString("regproc"),QString("regprocedure"), QString("regoper"),QString("regoperator"),QString("regclass"), - QString("regtype"),QString("regconfig"),QString("regdictionary")}}; - + QString("regtype"),QString("regconfig"),QString("regdictionary")}, + {QString("timestamptz"),QString("timestamp with time zone")}}; //If the types are equal there is no need to perform further operations if(*this==type) @@ -1501,124 +1509,134 @@ bool PgSQLType::isEquivalentTo(PgSQLType type) return(this_idx < types.size() && type_idx < types.size() && this_idx==type_idx && - this->isArrayType()==type.isArrayType()); + this->isArrayType()==type.isArrayType()); } -PgSQLType PgSQLType::getAliasType(void) +bool PgSqlType::isExactTo(PgSqlType type) +{ + return(this->type_idx == type.type_idx && + this->dimension == type.dimension && + this->length == type.length && + this->precision == type.precision && + this->with_timezone == type.with_timezone && + this->interval_type == type.interval_type && + this->spatial_type == type.spatial_type); +} + +PgSqlType PgSqlType::getAliasType(void) { if(!isUserType()) { if(type_list[this->type_idx]==QString("serial")) - return(PgSQLType(QString("integer"))); + return(PgSqlType(QString("integer"))); else if(type_list[this->type_idx]==QString("smallserial")) - return(PgSQLType(QString("smallint"))); + return(PgSqlType(QString("smallint"))); else if(type_list[this->type_idx]==QString("bigserial")) - return(PgSQLType(QString("bigint"))); + return(PgSqlType(QString("bigint"))); else - return(PgSQLType(type_list[this->type_idx])); + return(PgSqlType(type_list[this->type_idx])); } else return(*this); } -void PgSQLType::setDimension(unsigned dim) +void PgSqlType::setDimension(unsigned dim) { if(dim > 0 && this->isUserType()) { - int idx=getUserTypeIndex(~(*this), nullptr) - (pseudo_end + 1); + int idx=getUserTypeIndex(~(*this), nullptr) - (PseudoEnd + 1); if(static_cast(idx) < user_types.size() && - (user_types[idx].type_conf==UserTypeConfig::DOMAIN_TYPE || - user_types[idx].type_conf==UserTypeConfig::SEQUENCE_TYPE)) - throw Exception(ERR_ASG_INV_DOMAIN_ARRAY,__PRETTY_FUNCTION__,__FILE__,__LINE__); + user_types[idx].type_conf==UserTypeConfig::SequenceType) + throw Exception(ErrorCode::AsgInvalidSequenceTypeArray,__PRETTY_FUNCTION__,__FILE__,__LINE__); } dimension=dim; } -void PgSQLType::setLength(unsigned len) +void PgSqlType::setLength(unsigned len) { this->length=len; } -void PgSQLType::setPrecision(int prec) +void PgSqlType::setPrecision(int prec) { if(!isUserType()) { //Raises an error if the user tries to specify a precision > length if(((BaseType::type_list[type_idx]==QString("numeric") || BaseType::type_list[type_idx]==QString("decimal")) && prec > static_cast(length))) - throw Exception(ERR_ASG_INV_PRECISION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidPrecision,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the precision is greater thant 6 else if(((BaseType::type_list[type_idx]==QString("time") || BaseType::type_list[type_idx]==QString("timestamp") || BaseType::type_list[type_idx]==QString("interval")) && prec > 6)) - throw Exception(ERR_ASG_INV_PREC_TIMESTAMP,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidPrecisionTimestamp,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->precision=prec; } } -unsigned PgSQLType::getDimension(void) +unsigned PgSqlType::getDimension(void) { return(dimension); } -unsigned PgSQLType::getLength(void) +unsigned PgSqlType::getLength(void) { return(length); } -int PgSQLType::getPrecision(void) +int PgSqlType::getPrecision(void) { return(precision); } -QString PgSQLType::getCodeDefinition(unsigned def_type,QString ref_type) +QString PgSqlType::getCodeDefinition(unsigned def_type,QString ref_type) { - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) return(*(*this)); else { attribs_map attribs; SchemaParser schparser; - attribs[ParsersAttributes::LENGTH]=QString(); - attribs[ParsersAttributes::DIMENSION]=QString(); - attribs[ParsersAttributes::PRECISION]=QString(); - attribs[ParsersAttributes::WITH_TIMEZONE]=QString(); - attribs[ParsersAttributes::INTERVAL_TYPE]=QString(); - attribs[ParsersAttributes::SPATIAL_TYPE]=QString(); - attribs[ParsersAttributes::VARIATION]=QString(); - attribs[ParsersAttributes::SRID]=QString(); - attribs[ParsersAttributes::REF_TYPE]=ref_type; + attribs[Attributes::Length]=QString(); + attribs[Attributes::Dimension]=QString(); + attribs[Attributes::Precision]=QString(); + attribs[Attributes::WithTimezone]=QString(); + attribs[Attributes::IntervalType]=QString(); + attribs[Attributes::SpatialType]=QString(); + attribs[Attributes::Variation]=QString(); + attribs[Attributes::Srid]=QString(); + attribs[Attributes::RefType]=ref_type; - attribs[ParsersAttributes::NAME]=(~(*this)); - attribs[ParsersAttributes::LENGTH]=QString("%1").arg(this->length); + attribs[Attributes::Name]=(~(*this)); + attribs[Attributes::Length]=QString("%1").arg(this->length); if(dimension > 0) - attribs[ParsersAttributes::DIMENSION]=QString("%1").arg(this->dimension); + attribs[Attributes::Dimension]=QString("%1").arg(this->dimension); if(precision >= 0) - attribs[ParsersAttributes::PRECISION]=QString("%1").arg(this->precision); + attribs[Attributes::Precision]=QString("%1").arg(this->precision); - if(interval_type != BaseType::null) - attribs[ParsersAttributes::INTERVAL_TYPE]=(~interval_type); + if(interval_type != BaseType::Null) + attribs[Attributes::IntervalType]=(~interval_type); if(isGiSType()) { - attribs[ParsersAttributes::SPATIAL_TYPE]=(~spatial_type); - attribs[ParsersAttributes::VARIATION]=QString("%1").arg(spatial_type.getVariation()); - attribs[ParsersAttributes::SRID]=QString("%1").arg(spatial_type.getSRID()); + attribs[Attributes::SpatialType]=(~spatial_type); + attribs[Attributes::Variation]=QString("%1").arg(spatial_type.getVariation()); + attribs[Attributes::Srid]=QString("%1").arg(spatial_type.getSRID()); } if(with_timezone) - attribs[ParsersAttributes::WITH_TIMEZONE]=ParsersAttributes::_TRUE_; + attribs[Attributes::WithTimezone]=Attributes::True; - return(schparser.getCodeDefinition(ParsersAttributes::PGSQL_BASE_TYPE, attribs, def_type)); + return(schparser.getCodeDefinition(Attributes::PgSqlBaseType, attribs, def_type)); } } -QString PgSQLType::operator * (void) +QString PgSqlType::operator * (void) { QString fmt_type, type, aux; unsigned idx; @@ -1657,7 +1675,7 @@ QString PgSQLType::operator * (void) { aux=BaseType::type_list[type_idx]; - if(interval_type!=BaseType::null) + if(interval_type!=BaseType::Null) aux+=QString(" %1 ").arg(~interval_type); if(precision >= 0) @@ -1689,7 +1707,7 @@ BehaviorType::BehaviorType(unsigned type_id) BehaviorType::BehaviorType(void) { - type_idx=offset; + type_idx=Offset; } BehaviorType::BehaviorType(const QString &type_name) @@ -1699,12 +1717,12 @@ BehaviorType::BehaviorType(const QString &type_name) void BehaviorType::getTypes(QStringList &type_list) { - BaseType::getTypes(type_list,offset,types_count); + BaseType::getTypes(type_list,Offset,TypesCount); } unsigned BehaviorType::operator = (unsigned type_id) { - BaseType::setType(type_id,offset,types_count); + BaseType::setType(type_id,Offset,TypesCount); return(type_idx); } @@ -1712,8 +1730,8 @@ unsigned BehaviorType::operator = (const QString &type_name) { unsigned type_id; - type_id=BaseType::getType(type_name, offset, types_count); - BaseType::setType(type_id,offset,types_count); + type_id=BaseType::getType(type_name, Offset, TypesCount); + BaseType::setType(type_id,Offset,TypesCount); return(type_id); } @@ -1722,7 +1740,7 @@ unsigned BehaviorType::operator = (const QString &type_name) ***********************/ SecurityType::SecurityType(void) { - type_idx=offset; + type_idx=Offset; } SecurityType::SecurityType(const QString &type_name) @@ -1737,12 +1755,12 @@ SecurityType::SecurityType(unsigned type_id) void SecurityType::getTypes(QStringList &tipos) { - BaseType::getTypes(tipos,offset,types_count); + BaseType::getTypes(tipos,Offset,TypesCount); } unsigned SecurityType::operator = (unsigned type_id) { - BaseType::setType(type_id,offset,types_count); + BaseType::setType(type_id,Offset,TypesCount); return(type_idx); } @@ -1750,8 +1768,8 @@ unsigned SecurityType::operator = (const QString &type_name) { unsigned type_id; - type_id=BaseType::getType(type_name, offset, types_count); - BaseType::setType(type_id,offset,types_count); + type_id=BaseType::getType(type_name, Offset, TypesCount); + BaseType::setType(type_id,Offset,TypesCount); return(type_id); } @@ -1760,7 +1778,7 @@ unsigned SecurityType::operator = (const QString &type_name) ***********************/ LanguageType::LanguageType(void) { - type_idx=offset; + type_idx=Offset; } LanguageType::LanguageType(unsigned type_id) @@ -1775,12 +1793,12 @@ LanguageType::LanguageType(const QString &type_name) void LanguageType::getTypes(QStringList &tipos) { - BaseType::getTypes(tipos,offset,types_count); + BaseType::getTypes(tipos,Offset,TypesCount); } unsigned LanguageType::operator = (unsigned tipo_id) { - BaseType::setType(tipo_id,offset,types_count); + BaseType::setType(tipo_id,Offset,TypesCount); return(type_idx); } @@ -1788,8 +1806,8 @@ unsigned LanguageType::operator = (const QString &type_name) { unsigned type_id; - type_id=BaseType::getType(type_name, offset, types_count); - BaseType::setType(type_id,offset,types_count); + type_id=BaseType::getType(type_name, Offset, TypesCount); + BaseType::setType(type_id,Offset,TypesCount); return(type_id); } @@ -1798,7 +1816,7 @@ unsigned LanguageType::operator = (const QString &type_name) ***********************/ EncodingType::EncodingType(void) { - type_idx=offset; + type_idx=Offset; } EncodingType::EncodingType(const QString &type) @@ -1813,12 +1831,12 @@ EncodingType::EncodingType(const unsigned type_id) void EncodingType::getTypes(QStringList &tipos) { - BaseType::getTypes(tipos,offset,types_count); + BaseType::getTypes(tipos,Offset,TypesCount); } unsigned EncodingType::operator = (unsigned type_id) { - BaseType::setType(type_id,offset,types_count); + BaseType::setType(type_id,Offset,TypesCount); return(type_idx); } @@ -1826,8 +1844,8 @@ unsigned EncodingType::operator = (const QString &type_name) { unsigned type_id; - type_id=BaseType::getType(type_name, offset, types_count); - BaseType::setType(type_id,offset,types_count); + type_id=BaseType::getType(type_name, Offset, TypesCount); + BaseType::setType(type_id,Offset,TypesCount); return(type_id); } @@ -1841,9 +1859,9 @@ bool EncodingType::operator == (const QString &type_name) unsigned idx,total; bool found=false; - total=offset + types_count; + total=Offset + TypesCount; - for(idx=offset; idx +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -26,15 +26,15 @@ #define PGSQL_TYPES_H #include "exception.h" -#include "parsersattributes.h" +#include "attributes.h" #include "schemaparser.h" #include #include class BaseType{ protected: - static const unsigned types_count=258; - static QString type_list[types_count]; + static constexpr unsigned TypesCount=262; + static QString type_list[TypesCount]; //! \brief Index of the type on the type_list vector unsigned type_idx; @@ -53,7 +53,7 @@ class BaseType{ static unsigned getType(const QString &type_name, unsigned offset, unsigned count); public: - static const unsigned null=0; + static constexpr unsigned Null=0; BaseType(void); @@ -80,17 +80,17 @@ class BaseType{ class ActionType: public BaseType{ private: //! \brief Initial position of the names related to the class on BaseType::type_list - static const unsigned offset=1; + static constexpr unsigned Offset=1; //! \brief Type count for the class related to the list - static const unsigned types_count=5; + static constexpr unsigned TypesCount=5; public: - static const unsigned no_action=offset; - static const unsigned restrict=offset+1; - static const unsigned cascade=offset+2; - static const unsigned set_null=offset+3; - static const unsigned set_default=offset+4; + static constexpr unsigned NoAction=Offset; + static constexpr unsigned Restrict=Offset+1; + static constexpr unsigned Cascade=Offset+2; + static constexpr unsigned SetNull=Offset+3; + static constexpr unsigned SetDefault=Offset+4; ActionType(const QString &type_name); ActionType(unsigned type_id); @@ -104,15 +104,15 @@ class ActionType: public BaseType{ class ConstraintType: public BaseType{ private: - static const unsigned offset=6; - static const unsigned types_count=5; + static constexpr unsigned Offset=6; + static constexpr unsigned TypesCount=5; public: - static const unsigned primary_key=offset; - static const unsigned foreign_key=offset+1; - static const unsigned check=offset+2; - static const unsigned unique=offset+3; - static const unsigned exclude=offset+4; + static constexpr unsigned PrimaryKey=Offset; + static constexpr unsigned ForeignKey=Offset+1; + static constexpr unsigned Check=Offset+2; + static constexpr unsigned Unique=Offset+3; + static constexpr unsigned Exclude=Offset+4; ConstraintType(const QString &type_name); ConstraintType(unsigned type_id); @@ -125,15 +125,15 @@ class ConstraintType: public BaseType{ class EventType: public BaseType{ private: - static const unsigned offset=11; - static const unsigned types_count=5; + static constexpr unsigned Offset=11; + static constexpr unsigned TypesCount=5; public: - static const unsigned on_select=offset; - static const unsigned on_insert=offset+1; - static const unsigned on_delete=offset+2; - static const unsigned on_update=offset+3; - static const unsigned on_truncate=offset+4; + static constexpr unsigned OnSelect=Offset; + static constexpr unsigned OnInsert=Offset+1; + static constexpr unsigned OnDelete=Offset+2; + static constexpr unsigned OnUpdate=Offset+3; + static constexpr unsigned OnTruncate=Offset+4; EventType(const QString &type_name); EventType(unsigned type_id); @@ -151,12 +151,12 @@ class EventType: public BaseType{ class ExecutionType: public BaseType{ private: - static const unsigned offset=16; - static const unsigned types_count=2; + static constexpr unsigned Offset=16; + static constexpr unsigned TypesCount=2; public: - static const unsigned also=offset; - static const unsigned instead=offset+1; + static constexpr unsigned Also=Offset; + static constexpr unsigned Instead=Offset+1; ExecutionType(const QString &type_name); ExecutionType(unsigned type_id); @@ -169,13 +169,13 @@ class ExecutionType: public BaseType{ class FunctionType: public BaseType{ private: - static const unsigned offset=18; - static const unsigned types_count=3; + static constexpr unsigned Offset=18; + static constexpr unsigned TypesCount=3; public: - static const unsigned _volatile_=offset; - static const unsigned stable=offset+1; - static const unsigned immutable=offset+2; + static constexpr unsigned Volatile=Offset; + static constexpr unsigned Stable=Offset+1; + static constexpr unsigned Immutable=Offset+2; FunctionType(const QString &type_name); FunctionType(unsigned type_id); @@ -188,16 +188,16 @@ class FunctionType: public BaseType{ class IndexingType: public BaseType{ private: - static const unsigned offset=21; - static const unsigned types_count=6; + static constexpr unsigned Offset=21; + static constexpr unsigned TypesCount=6; public: - static const unsigned btree=offset; - static const unsigned gist=offset+1; - static const unsigned hash=offset+2; - static const unsigned gin=offset+3; - static const unsigned spgist=offset+4; - static const unsigned brin=offset+5; + static constexpr unsigned Btree=Offset; + static constexpr unsigned Gist=Offset+1; + static constexpr unsigned Hash=Offset+2; + static constexpr unsigned Gin=Offset+3; + static constexpr unsigned Spgist=Offset+4; + static constexpr unsigned Brin=Offset+5; IndexingType(const QString &type_name); IndexingType(unsigned type_id); @@ -210,23 +210,23 @@ class IndexingType: public BaseType{ class IntervalType: public BaseType{ private: - static const unsigned offset=138; - static const unsigned types_count=13; + static constexpr unsigned Offset=139; + static constexpr unsigned TypesCount=13; public: - static const unsigned year=offset; - static const unsigned month=offset+1; - static const unsigned day=offset+2; - static const unsigned hour=offset+3; - static const unsigned minute=offset+4; - static const unsigned second=offset+5; - static const unsigned year_to_month=offset+6; - static const unsigned day_to_hour=offset+7; - static const unsigned day_to_minute=offset+8; - static const unsigned day_to_second=offset+9; - static const unsigned hour_to_minute=offset+10; - static const unsigned hour_to_second=offset+11; - static const unsigned minute_to_second=offset+12; + static constexpr unsigned Year=Offset; + static constexpr unsigned Month=Offset+1; + static constexpr unsigned Day=Offset+2; + static constexpr unsigned Hour=Offset+3; + static constexpr unsigned Minute=Offset+4; + static constexpr unsigned Second=Offset+5; + static constexpr unsigned YearToMonth=Offset+6; + static constexpr unsigned DayToHour=Offset+7; + static constexpr unsigned DayToMinute=Offset+8; + static constexpr unsigned DayToSecond=Offset+9; + static constexpr unsigned HourToMinute=Offset+10; + static constexpr unsigned HourToSecond=Offset+11; + static constexpr unsigned MinuteToSecond=Offset+12; IntervalType(const QString &type_name); IntervalType(unsigned type_id); @@ -261,49 +261,49 @@ class UserTypeConfig { bool invalidated; public: - static const unsigned BASE_TYPE=1, //! \brief The type refers to a user-defined base type (class Type) - DOMAIN_TYPE=2, //! \brief The type refers to a domain - TABLE_TYPE=4, //! \brief The type refers to a table - SEQUENCE_TYPE=8, //! \brief The type refers to a sequence - VIEW_TYPE=16, //! \brief The type refers to a view - EXTENSION_TYPE=32, //! \brief The type refers to a extension used as datatype + static constexpr unsigned BaseType=1, //! \brief The type refers to a user-defined base type (class Type) + DomainType=2, //! \brief The type refers to a domain + TableType=4, //! \brief The type refers to a table + SequenceType=8, //! \brief The type refers to a sequence + ViewType=16, //! \brief The type refers to a view + ExtensionType=32, //! \brief The type refers to a extension used as datatype //! \brief This constant refers to all types above and must be used only on type searches - ALL_USER_TYPES=63; + AllUserTypes=63; UserTypeConfig(void) - { name=QString(); ptype=nullptr; pmodel=nullptr; invalidated=false; type_conf=BASE_TYPE; } + { name=QString(); ptype=nullptr; pmodel=nullptr; invalidated=false; type_conf=BaseType; } - friend class PgSQLType; + friend class PgSqlType; }; class SpatialType: public BaseType{ private: unsigned variation; - static const unsigned offset=231; - static const unsigned types_count=16; + static constexpr unsigned Offset=232; + static constexpr unsigned TypesCount=16; /*! \brief Used in conjunction with spatial_type, and denotes the SRID value for the spatial type. This value goes from -1 to n. */ int srid; public: - static const unsigned no_var=0; - static const unsigned var_z=1; - static const unsigned var_m=2; - static const unsigned var_zm=3; - - static const unsigned point=offset; - static const unsigned linestring=offset+1; - static const unsigned polygon=offset+2; - static const unsigned multipoint=offset+3; - static const unsigned multilinestring=offset+4; - static const unsigned multipolygon=offset+5; - static const unsigned geometry=offset+6; - static const unsigned geometrycollection=offset+7; - - SpatialType(const QString &type_name, int srid, unsigned variation_id=SpatialType::no_var); - SpatialType(unsigned type_id, int srid, unsigned var_id=SpatialType::no_var); + static constexpr unsigned NoVar=0; + static constexpr unsigned VarZ=1; + static constexpr unsigned VarM=2; + static constexpr unsigned VarZm=3; + + static constexpr unsigned Point=Offset; + static constexpr unsigned LineString=Offset+1; + static constexpr unsigned Polygon=Offset+2; + static constexpr unsigned MultiPoint=Offset+3; + static constexpr unsigned MultiLineString=Offset+4; + static constexpr unsigned MultiPolygon=Offset+5; + static constexpr unsigned Geometry=Offset+6; + static constexpr unsigned GeometryCollection=Offset+7; + + SpatialType(const QString &type_name, int srid, unsigned variation_id=SpatialType::NoVar); + SpatialType(unsigned type_id, int srid, unsigned var_id=SpatialType::NoVar); SpatialType(void); void setVariation(unsigned var); @@ -316,18 +316,18 @@ class SpatialType: public BaseType{ QString operator * (void); }; -class PgSQLType: public BaseType{ +class PgSqlType: public BaseType{ private: - static const unsigned offset=27; - static const unsigned types_count=111; + static constexpr unsigned Offset=27; + static constexpr unsigned TypesCount=112; //! \brief Offset for oid types - static const unsigned oid_start=108; - static const unsigned oid_end=122; + static constexpr unsigned OidStart=109; + static constexpr unsigned OidEnd=123; //! \brief Offset for pseudo types - static const unsigned pseudo_start=123; - static const unsigned pseudo_end=137; + static constexpr unsigned PseudoStart=124; + static constexpr unsigned PseudoEnd=138; //! \brief Configuration for user defined types static vector user_types; @@ -373,35 +373,47 @@ class PgSQLType: public BaseType{ void setUserType(void *ptype); public: - PgSQLType(void); + PgSqlType(void); /*! \brief Creates a type from a simple string containing the name of the type. \note This method works in different way than PgSQLType::parserString() */ - PgSQLType(const QString &type_name); + PgSqlType(const QString &type_name); //! \brief Creates a type from a pointer that references an user defined type (Type class) - PgSQLType(void *ptype); - - PgSQLType(const QString &type_name, unsigned length, - unsigned dimension, int precision, - bool with_timezone, IntervalType interv_type, - SpatialType spatial_type); - - PgSQLType(void *ptipo, unsigned length, - unsigned dimension, int precision, - bool with_timezone, IntervalType interv_type, - SpatialType spatial_type); - - PgSQLType(unsigned type_id, unsigned length, - unsigned dimension, int precision, - bool with_timezone, IntervalType interv_type, - SpatialType spatial_type); + PgSqlType(void *ptype); + + /*! \brief Creates a type from a type name and a series of data like + * dimension, length, precision, timezone option, interval type and spatial type. + * All parameters are optional except type_name and dimension which can be used to quicly create + * array of a certain type. */ + PgSqlType(const QString &type_name, unsigned dimension, + unsigned length = 0, int precision = -1, + bool with_timezone = false, IntervalType interv_type = IntervalType::Null, + SpatialType spatial_type = SpatialType()); + + /*! \brief Creates a type from a pointer to a data type (generally a user defined type, see UserTypeConfig class) + * and a series of data like dimension, length, precision, timezone option, interval type and spatial type. + * All parameters are optional except ptype and dimension which can be used to quickly create + * array of a certain type. */ + PgSqlType(void *ptype, unsigned dimension, + unsigned length = 0, int precision = -1, + bool with_timezone = false, IntervalType interv_type = IntervalType::Null, + SpatialType spatial_type = SpatialType()); + + /*! \brief Creates a type from a type id and a series of data like + * dimension, length, precision, timezone option, interval type and spatial type. + * All parameters are optional except type_id and dimension which can be used to quickly create + * array of a certain type. */ + PgSqlType(unsigned type_id, unsigned dimension, + unsigned length = 0, int precision = -1, + bool with_timezone = false, IntervalType interv_type = IntervalType::Null, + SpatialType spatial_type = SpatialType()); /*! \brief Creates a configured instance of PgSQLType from a string in SQL canonical form, e.g, varchar(255), timestamp with timezone, smallint[] and so on. If the string specifies arrays and length descriptors in wrong positions the method will try to return the correct type. The method will raise errors if the type could not be configured */ - static PgSQLType parseString(const QString &str); + static PgSqlType parseString(const QString &str); static unsigned getUserTypeIndex(const QString &type_name, void *ptype, void *pmodel=nullptr); static unsigned getBaseTypeIndex(const QString &type_name); @@ -445,15 +457,21 @@ class PgSQLType: public BaseType{ bool acceptsPrecision(void); //! \brief Indicates if the 'this' type can be casted to 'type' - bool canCastTo(PgSQLType type); + bool canCastTo(PgSqlType type); /*! \brief Returns if the "this" type is equivalent to the specified type. In order to be compatible the "this" and "type" must be an alias from each other, for instance, "varchar" is compatible with "character varying" and vice-versa, smallint is compatible with int2, and so on. */ - bool isEquivalentTo(PgSQLType type); + bool isEquivalentTo(PgSqlType type); - PgSQLType getAliasType(void); + /*! \brief Returns true if the provided type is exactly the same as the "this". + * This method compares ALL attributes of the type. Note that this method is + * different from the operatores == (PgSqlType) because this latter compares only + * the indexes of the types. This method is useful if one need to fully compare the types */ + bool isExactTo(PgSqlType type); + + PgSqlType getAliasType(void); QString getCodeDefinition(unsigned def_type, QString ref_type=QString()); QString operator ~ (void); @@ -463,12 +481,22 @@ class PgSQLType: public BaseType{ unsigned operator << (void *ptype); unsigned operator = (unsigned type_id); unsigned operator = (const QString &type_name); + + //! \brief Compares the index of the "this" with the provided type index. If an exact match is needed use isExactTo() bool operator == (unsigned type_idx); - bool operator == (PgSQLType type); + + //! \brief Compares the index of the "this" with the provided type. If an exact match is needed use isExactTo() + bool operator == (PgSqlType type); + + //! \brief Compares the index of the "this" with the provided type name index. If an exact match is needed use isExactTo() bool operator == (const QString &type_name); + + //! \brief Compares the index of the "this" with the provided type reference. If an exact match is needed use isExactTo() bool operator == (void *ptype); + + // The methods below are just the oposite of the == versions bool operator != (const QString &type_name); - bool operator != (PgSQLType type); + bool operator != (PgSqlType type); bool operator != (unsigned type_idx); /*! \brief Returns the pointer to the user defined type which denotes the @@ -500,13 +528,13 @@ class PgSQLType: public BaseType{ class BehaviorType: public BaseType{ private: - static const unsigned offset=151; - static const unsigned types_count=3; + static constexpr unsigned Offset=152; + static constexpr unsigned TypesCount=3; public: - static const unsigned called_on_null_input=offset; - static const unsigned returns_null_on_null_input=offset+1; - static const unsigned strict=offset+2; + static constexpr unsigned CalledOnNullInput=Offset; + static constexpr unsigned ReturnsNullOnNullInput=Offset+1; + static constexpr unsigned Strict=Offset+2; BehaviorType(const QString &type_name); BehaviorType(unsigned type_id); @@ -519,12 +547,12 @@ class BehaviorType: public BaseType{ class SecurityType: public BaseType{ private: - static const unsigned offset=154; - static const unsigned types_count=2; + static constexpr unsigned Offset=155; + static constexpr unsigned TypesCount=2; public: - static const unsigned invoker=offset; - static const unsigned definer=offset+1; + static constexpr unsigned Invoker=Offset; + static constexpr unsigned Definer=Offset+1; SecurityType(unsigned type_id); SecurityType(const QString &type_name); @@ -537,17 +565,17 @@ class SecurityType: public BaseType{ class LanguageType: public BaseType{ private: - static const unsigned offset=156; - static const unsigned types_count=7; + static constexpr unsigned Offset=157; + static constexpr unsigned TypesCount=7; public: - static const unsigned sql=offset; - static const unsigned c=offset+1; - static const unsigned plpgsql=offset+2; - static const unsigned pltcl=offset+3; - static const unsigned plperl=offset+4; - static const unsigned plpython=offset+5; - static const unsigned internal=offset+6; + static constexpr unsigned Sql=Offset; + static constexpr unsigned C=Offset+1; + static constexpr unsigned PlPgsql=Offset+2; + static constexpr unsigned PlTcl=Offset+3; + static constexpr unsigned PlPerl=Offset+4; + static constexpr unsigned PlPython=Offset+5; + static constexpr unsigned Internal=Offset+6; LanguageType(const QString &type_name); LanguageType(unsigned type_id); @@ -560,8 +588,8 @@ class LanguageType: public BaseType{ class EncodingType: public BaseType{ private: - static const unsigned offset=163; - static const unsigned types_count=42; + static constexpr unsigned Offset=164; + static constexpr unsigned TypesCount=42; public: EncodingType(void); @@ -580,14 +608,14 @@ class EncodingType: public BaseType{ class StorageType: public BaseType{ private: - static const unsigned offset=207; - static const unsigned types_count=4; + static constexpr unsigned Offset=206; + static constexpr unsigned TypesCount=4; public: - static const unsigned plain=offset; - static const unsigned external=offset+1; - static const unsigned extended=offset+2; - static const unsigned main=offset+3; + static constexpr unsigned Plain=Offset; + static constexpr unsigned External=Offset+1; + static constexpr unsigned Extended=Offset+2; + static constexpr unsigned Main=Offset+3; StorageType(void); StorageType(const QString &type_name); @@ -603,13 +631,13 @@ class StorageType: public BaseType{ class MatchType: public BaseType{ private: - static const unsigned offset=209; - static const unsigned types_count=3; + static constexpr unsigned Offset=210; + static constexpr unsigned TypesCount=3; public: - static const unsigned full=offset; - static const unsigned partial=offset+1; - static const unsigned simple=offset+2; + static constexpr unsigned Full=Offset; + static constexpr unsigned Partial=Offset+1; + static constexpr unsigned Simple=Offset+2; MatchType(unsigned type_id); MatchType(const QString &type_name); @@ -622,12 +650,12 @@ class MatchType: public BaseType{ class DeferralType: public BaseType{ private: - static const unsigned offset=212; - static const unsigned types_count=2; + static constexpr unsigned Offset=213; + static constexpr unsigned TypesCount=2; public: - static const unsigned immediate=offset; - static const unsigned deferred=offset+1; + static constexpr unsigned Immediate=Offset; + static constexpr unsigned Deferred=Offset+1; DeferralType(unsigned type_id); DeferralType(const QString &type_name); @@ -640,24 +668,24 @@ class DeferralType: public BaseType{ class CategoryType: public BaseType{ private: - static const unsigned offset=214; - static const unsigned types_count=14; + static constexpr unsigned Offset=215; + static constexpr unsigned TypesCount=14; public: - static const unsigned userdefined=offset; - static const unsigned array=offset+1; - static const unsigned boolean=offset+2; - static const unsigned composite=offset+3; - static const unsigned datetime=offset+4; - static const unsigned enumeration=offset+5; - static const unsigned geometric=offset+6; - static const unsigned networkaddr=offset+7; - static const unsigned numeric=offset+8; - static const unsigned pseudotypes=offset+9; - static const unsigned stringt=offset+10; - static const unsigned timespan=offset+11; - static const unsigned bitstring=offset+12; - static const unsigned unknown=offset+13; + static constexpr unsigned UserDefined=Offset; + static constexpr unsigned Array=Offset+1; + static constexpr unsigned Boolean=Offset+2; + static constexpr unsigned Composite=Offset+3; + static constexpr unsigned DateTime=Offset+4; + static constexpr unsigned Enumeration=Offset+5; + static constexpr unsigned Geometric=Offset+6; + static constexpr unsigned NetworkAddr=Offset+7; + static constexpr unsigned Numeric=Offset+8; + static constexpr unsigned PseudoTypes=Offset+9; + static constexpr unsigned Stringt=Offset+10; + static constexpr unsigned Timespan=Offset+11; + static constexpr unsigned BitString=Offset+12; + static constexpr unsigned Unknown=Offset+13; CategoryType(unsigned type_id); CategoryType(const QString &type_name); @@ -670,13 +698,13 @@ class CategoryType: public BaseType{ class FiringType: public BaseType{ private: - static const unsigned offset=228; - static const unsigned types_count=3; + static constexpr unsigned Offset=229; + static constexpr unsigned TypesCount=3; public: - static const unsigned before=offset; - static const unsigned after=offset+1; - static const unsigned instead_of=offset+2; + static constexpr unsigned Before=Offset; + static constexpr unsigned After=Offset+1; + static constexpr unsigned InsteadOf=Offset+2; FiringType(const QString &type_name); FiringType(unsigned type_id); @@ -689,14 +717,14 @@ class FiringType: public BaseType{ class EventTriggerType: public BaseType{ private: - static const unsigned offset=247; - static const unsigned types_count=4; + static constexpr unsigned Offset=248; + static constexpr unsigned TypesCount=4; public: - static const unsigned ddl_command_start=offset; - static const unsigned ddl_command_end=offset+1; - static const unsigned sql_drop=offset+2; - static const unsigned table_rewrite=offset+3; + static constexpr unsigned DdlCommandStart=Offset; + static constexpr unsigned DdlCommandEnd=Offset+1; + static constexpr unsigned SqlDrop=Offset+2; + static constexpr unsigned TableRewrite=Offset+3; EventTriggerType(const QString &type_name); EventTriggerType(unsigned type_id); @@ -709,12 +737,12 @@ class EventTriggerType: public BaseType{ class IdentityType: public BaseType{ private: - static const unsigned offset=251; - static const unsigned types_count=2; + static constexpr unsigned Offset=252; + static constexpr unsigned TypesCount=2; public: - static const unsigned always=offset; - static const unsigned by_default=offset+1; + static constexpr unsigned Always=Offset; + static constexpr unsigned ByDefault=Offset+1; IdentityType(const QString &type_name); IdentityType(unsigned type_id); @@ -727,15 +755,15 @@ class IdentityType: public BaseType{ class PolicyCmdType: public BaseType { private: - static const unsigned offset=253; - static const unsigned types_count=5; + static constexpr unsigned Offset=254; + static constexpr unsigned TypesCount=5; public: - static const unsigned all=offset; - static const unsigned select=offset+1; - static const unsigned insert=offset+2; - static const unsigned updated=offset+3; - static const unsigned delete_=offset+4; + static constexpr unsigned All=Offset; + static constexpr unsigned Select=Offset+1; + static constexpr unsigned Insert=Offset+2; + static constexpr unsigned Update=Offset+3; + static constexpr unsigned Delete=Offset+4; PolicyCmdType(const QString &type_name); PolicyCmdType(unsigned type_id); @@ -746,4 +774,23 @@ class PolicyCmdType: public BaseType { unsigned operator = (const QString &type_name); }; +class PartitioningType: public BaseType { + private: + static constexpr unsigned Offset=259; + static constexpr unsigned TypesCount=3; + + public: + static constexpr unsigned Range=Offset; + static constexpr unsigned List=Offset+1; + static constexpr unsigned Hash=Offset+2; + + PartitioningType(const QString &type_name); + PartitioningType(unsigned type_id); + PartitioningType(void); + + static void getTypes(QStringList&type_list); + unsigned operator = (unsigned type_id); + unsigned operator = (const QString &type_name); +}; + #endif diff --git a/libpgmodeler/src/policy.cpp b/libpgmodeler/src/policy.cpp index b01a3c5fdf..85ea6c705c 100644 --- a/libpgmodeler/src/policy.cpp +++ b/libpgmodeler/src/policy.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -19,26 +19,26 @@ Policy::Policy(void) : TableObject() { - obj_type=OBJ_POLICY; + obj_type=ObjectType::Policy; permissive = false; - policy_cmd = PolicyCmdType::all; + policy_cmd = PolicyCmdType::All; - attributes[ParsersAttributes::PERMISSIVE] = QString(); - attributes[ParsersAttributes::COMMAND] = QString(); - attributes[ParsersAttributes::USING_EXP] = QString(); - attributes[ParsersAttributes::CHECK_EXP] = QString(); - attributes[ParsersAttributes::ROLES] = QString(); + attributes[Attributes::Permissive] = QString(); + attributes[Attributes::Command] = QString(); + attributes[Attributes::UsingExp] = QString(); + attributes[Attributes::CheckExp] = QString(); + attributes[Attributes::Roles] = QString(); } void Policy::setParentTable(BaseTable *table) { - if(table && table->getObjectType() != OBJ_TABLE) + if(table && table->getObjectType() != ObjectType::Table) { - throw Exception(Exception::getErrorMessage(ERR_ASG_INV_OBJECT_TYPE) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidObjectType) .arg(this->obj_name) .arg(this->getTypeName()) - .arg(BaseObject::getTypeName(OBJ_TABLE)), - ERR_ASG_INV_OBJECT_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Table)), + ErrorCode::AsgInvalidObjectType,__PRETTY_FUNCTION__,__FILE__,__LINE__); } TableObject::setParentTable(table); @@ -91,7 +91,7 @@ QString Policy::getCheckExpression(void) void Policy::addRole(Role *role) { if(!role) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); if(std::find(roles.begin(), roles.end(), role) == roles.end()) roles.push_back(role); @@ -116,17 +116,17 @@ QString Policy::getCodeDefinition(unsigned def_type) QStringList rol_names; if(getParentTable()) - attributes[ParsersAttributes::TABLE]=getParentTable()->getName(true); + attributes[Attributes::Table]=getParentTable()->getName(true); - attributes[ParsersAttributes::COMMAND] = ~policy_cmd; + attributes[Attributes::Command] = ~policy_cmd; for(auto role : roles) rol_names.append(role->getName(true)); - attributes[ParsersAttributes::PERMISSIVE] = (permissive ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::USING_EXP] = using_expr; - attributes[ParsersAttributes::CHECK_EXP] = check_expr; - attributes[ParsersAttributes::ROLES] = rol_names.join(QString(", ")); + attributes[Attributes::Permissive] = (permissive ? Attributes::True : QString()); + attributes[Attributes::UsingExp] = using_expr; + attributes[Attributes::CheckExp] = check_expr; + attributes[Attributes::Roles] = rol_names.join(QString(", ")); return(BaseObject::__getCodeDefinition(def_type)); } @@ -144,20 +144,20 @@ QString Policy::getAlterDefinition(BaseObject *object) Policy *policy=dynamic_cast(object); if(!policy) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { QStringList rol_names, aux_rol_names; attribs_map attribs; - attributes[ParsersAttributes::ALTER_CMDS]=BaseObject::getAlterDefinition(object); + attributes[Attributes::AlterCmds]=BaseObject::getAlterDefinition(object); if(this->using_expr.simplified() != policy->using_expr.simplified()) - attribs[ParsersAttributes::USING_EXP] = policy->using_expr; + attribs[Attributes::UsingExp] = policy->using_expr; if(this->check_expr.simplified() != policy->check_expr.simplified()) - attribs[ParsersAttributes::CHECK_EXP] = policy->check_expr; + attribs[Attributes::CheckExp] = policy->check_expr; for(auto role : this->roles) rol_names.append(role->getName(true)); @@ -169,16 +169,16 @@ QString Policy::getAlterDefinition(BaseObject *object) aux_rol_names.sort(); if(!rol_names.isEmpty() && aux_rol_names.isEmpty()) - attribs[ParsersAttributes::ROLES] = ParsersAttributes::UNSET; + attribs[Attributes::Roles] = Attributes::Unset; else if(rol_names.join(QString(", ")) != aux_rol_names.join(QString(", "))) - attribs[ParsersAttributes::ROLES] = aux_rol_names.join(QString(", ")); + attribs[Attributes::Roles] = aux_rol_names.join(QString(", ")); copyAttributes(attribs); return(BaseObject::getAlterDefinition(this->getSchemaName(), attributes, false, true)); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } diff --git a/libpgmodeler/src/policy.h b/libpgmodeler/src/policy.h index cda7614ea7..63ee4825cc 100644 --- a/libpgmodeler/src/policy.h +++ b/libpgmodeler/src/policy.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libpgmodeler/src/reference.cpp b/libpgmodeler/src/reference.cpp index 68e3537f57..f8ae695d36 100644 --- a/libpgmodeler/src/reference.cpp +++ b/libpgmodeler/src/reference.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -29,16 +29,16 @@ Reference::Reference(Table *table, Column *column, const QString &tab_alias, con { //Raises an error if the table is not allocated if(!table) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the table/column alias has an invalid name else if((!tab_alias.isEmpty() && !BaseObject::isValidName(tab_alias)) || - (!col_alias.isEmpty() && !BaseObject::isValidName(col_alias))) - throw Exception(ERR_ASG_INV_NAME_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + (!col_alias.isEmpty() && !BaseObject::isValidName(col_alias))) + throw Exception(ErrorCode::AsgInvalidNameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the column parent table differs from the passed table else if(column && column->getParentTable()!=table) - throw Exception(ERR_ASG_OBJ_BELONGS_OTHER_TABLE ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgObjectBelongsAnotherTable ,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->table=table; this->column=column; @@ -51,10 +51,10 @@ Reference::Reference(const QString &expression, const QString &expr_alias) { //Raises an error if the user try to create an reference using an empty expression if(expression.isEmpty()) - throw Exception(ERR_ASG_INV_EXPR_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidExpressionObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the expression alias has an invalid name else if(!expr_alias.isEmpty() && !BaseObject::isValidName(expr_alias)) - throw Exception(ERR_ASG_INV_NAME_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidNameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); table=nullptr; column=nullptr; @@ -65,7 +65,38 @@ Reference::Reference(const QString &expression, const QString &expr_alias) void Reference::setDefinitionExpression(bool value) { - is_def_expr=value; + is_def_expr = value; + if(!value) clearReferencedTables(); +} + +void Reference::addReferencedTable(Table *ref_table) +{ + if(!ref_table) + return; + + if(std::find(ref_tables.begin(), ref_tables.end(), ref_table) == ref_tables.end()) + ref_tables.push_back(ref_table); +} + +int Reference::getReferencedTableIndex(Table *ref_table) +{ + int idx = -1; + vector
::iterator itr = std::find(ref_tables.begin(), ref_tables.end(), ref_table); + + if(itr != ref_tables.end()) + idx = itr - ref_tables.begin(); + + return(idx); +} + +void Reference::clearReferencedTables(void) +{ + ref_tables.clear(); +} + +vector
Reference::getReferencedTables(void) +{ + return(ref_tables); } bool Reference::isDefinitionExpression(void) @@ -73,6 +104,56 @@ bool Reference::isDefinitionExpression(void) return(is_def_expr); } +void Reference::addColumn(const QString &name, PgSqlType type, const QString &alias) +{ + QString aux_name = name; + + if(aux_name.startsWith(QChar('\"')) && + aux_name.endsWith(QChar('\"'))) + { + aux_name.remove(0, 1); + aux_name.remove(aux_name.length(), 1); + } + + // Validating the column name + if(!BaseObject::isValidName(name)) + { + if(aux_name.isEmpty()) + throw Exception(ErrorCode::AsgEmptyNameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(aux_name.size() > BaseObject::ObjectNameMaxLength) + throw Exception(ErrorCode::AsgLongNameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else + throw Exception(ErrorCode::AsgInvalidNameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + + // Checking if the column already exists + for(auto &col : columns) + { + if(col.name == name) + throw Exception(ErrorCode::InsDuplicatedElement,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + + columns.push_back(SimpleColumn(name, *type, alias)); +} + +void Reference::addColumn(Column *col) +{ + if(!col) + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + addColumn(col->getName(), col->getType(), col->getAlias()); +} + +void Reference::removeColumns(void) +{ + columns.clear(); +} + +vector Reference::getColumns(void) +{ + return(columns); +} + Table *Reference::getTable(void) { return(table); @@ -101,9 +182,22 @@ QString Reference::getExpression(void) unsigned Reference::getReferenceType(void) { if(expression.isEmpty()) - return(REFER_COLUMN); + return(ReferColumn); else - return(REFER_EXPRESSION); + return(ReferExpression); +} + +void Reference::setReferenceAlias(const QString &alias) +{ + if(alias.size() > BaseObject::ObjectNameMaxLength) + throw Exception(ErrorCode::AsgLongNameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + ref_alias = alias; +} + +QString Reference::getReferenceAlias(void) +{ + return(ref_alias); } QString Reference::getSQLDefinition(unsigned sql_type) @@ -114,10 +208,10 @@ QString Reference::getSQLDefinition(unsigned sql_type) refer_type=getReferenceType(); //Case the reference is between the SELECT-FROM keywords - if(sql_type==SQL_REFER_SELECT) + if(sql_type==SqlReferSelect) { //Case the reference is linked to a column - if(refer_type==REFER_COLUMN) + if(refer_type==ReferColumn) { /* Generated SQL definition: [TABLE_ALIAS.]{COLUMN_NAME | *} [AS COLUMN_ALIAS] */ @@ -153,14 +247,14 @@ QString Reference::getSQLDefinition(unsigned sql_type) sql_def+=QString(",\n"); } //Case the reference is between the FROM-[JOIN | WHERE] keywords - else if(sql_type==SQL_REFER_FROM) + else if(sql_type==SqlReferFrom) { /* Case the reference is linked to a column only the table name is used. For expression the complete code is used thus the generated code is: ... FROM {TABLE_NAME} [AS ALIAS] or ... FROM {EXPRESSION} */ - if(refer_type==REFER_COLUMN) + if(refer_type==ReferColumn) { sql_def+=table->getName(true); @@ -176,7 +270,7 @@ QString Reference::getSQLDefinition(unsigned sql_type) else { //Case the column is allocated - if(refer_type==REFER_COLUMN && column) + if(refer_type==ReferColumn && column) { /* Generated SQL definition: ... WHERE {TABLE_NAME | ALIAS}.{COLUMN_NAME} */ @@ -191,7 +285,7 @@ QString Reference::getSQLDefinition(unsigned sql_type) if(column) sql_def+=column->getName(true); } - else if(refer_type==REFER_EXPRESSION) + else if(refer_type==ReferExpression) sql_def=expression; } @@ -201,23 +295,45 @@ QString Reference::getSQLDefinition(unsigned sql_type) QString Reference::getXMLDefinition(void) { - attribs_map attribs; + attribs_map attribs, aux_attribs; SchemaParser schparser; + Column col_aux; + QStringList ref_tab_names; - attribs[ParsersAttributes::TABLE]=QString(); - attribs[ParsersAttributes::COLUMN]=QString(); + attribs[Attributes::Table]=QString(); + attribs[Attributes::Column]=QString(); if(table) - attribs[ParsersAttributes::TABLE]=table->getName(true); + attribs[Attributes::Table]=table->getName(true); if(column) - attribs[ParsersAttributes::COLUMN]=column->getName(); + attribs[Attributes::Column]=column->getName(); + + attribs[Attributes::RefAlias]=ref_alias; + attribs[Attributes::Expression]=expression; + attribs[Attributes::Alias]=alias; + attribs[Attributes::ColumnAlias]=column_alias; + attribs[Attributes::Columns]=QString(); + attribs[Attributes::RefTables]=QString(); - attribs[ParsersAttributes::EXPRESSION]=expression; - attribs[ParsersAttributes::ALIAS]=alias; - attribs[ParsersAttributes::COLUMN_ALIAS]=column_alias; + for(auto &col : columns) + { + col_aux.setName(col.name); + col_aux.setType(PgSqlType::parseString(col.type)); + col_aux.setAlias(col.alias); + attribs[Attributes::Columns]+=col_aux.getCodeDefinition(SchemaParser::XmlDefinition); + } + + if(is_def_expr) + { + for(auto &tab : ref_tables) + { + aux_attribs[Attributes::Name] = tab->getSignature(); + attribs[Attributes::RefTables] += schparser.getCodeDefinition(Attributes::RefTableTag, aux_attribs, SchemaParser::XmlDefinition); + } + } - return(schparser.getCodeDefinition(ParsersAttributes::REFERENCE, attribs, SchemaParser::XML_DEFINITION)); + return(schparser.getCodeDefinition(Attributes::Reference, attribs, SchemaParser::XmlDefinition)); } bool Reference::operator == (Reference &refer) @@ -228,7 +344,7 @@ bool Reference::operator == (Reference &refer) if(ref_type==refer.getReferenceType()) { - if(ref_type==REFER_COLUMN) + if(ref_type==ReferColumn) { return(this->table==refer.table && this->column==refer.column && diff --git a/libpgmodeler/src/reference.h b/libpgmodeler/src/reference.h index 0067a77590..b388f77813 100644 --- a/libpgmodeler/src/reference.h +++ b/libpgmodeler/src/reference.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -29,6 +29,14 @@ #include "table.h" #include "schema.h" +/*! \brief This simple struct acts like a rudimentary column used by Reference and Views to represent columns + * Note that, as intended, the struct expects that all received values are validated since they are immutable */ +struct SimpleColumn { + QString name, type, alias; + SimpleColumn(const QString &_name, const QString &_type, const QString &_alias) : + name(_name), type(_type), alias(_alias) {} +}; + class Reference { private: //! \brief Stores the table used by the reference @@ -39,25 +47,40 @@ class Reference { //! \brief Stores the expression that defines one reference QString expression, + //! \brief Stores the alias to the expression or table alias, + //! \brief Stores only the alias for the column - column_alias; + column_alias, + + //! \brief Stores the alias for the reference. This text will be displayed when the view is being show in compact mode + ref_alias; //! \brief Indicates if the expression is used as entire view definition bool is_def_expr; + /*! \brief Stores the columns that the reference (when being an expression [is_def_expr]) generates. + * These columns are used when drawing a view and that has only on definition expression. + * By having columns, instead of drawing the expression as a column of the view, the ones in + * this vector are displayed */ + vector columns; + + /*! \brief Stores the tables that the reference object is using within the expression which defines the view + * when is_def_expr is set. These tables are used to hint the user which tables the view is using. */ + vector
ref_tables; + public: //! \brief Constants used to define the reference type - static const unsigned REFER_COLUMN=0, //! \brief The reference is based on a table column - REFER_EXPRESSION=1; //! \brief The reference is based on an expression + static constexpr unsigned ReferColumn=0, //! \brief The reference is based on a table column + ReferExpression=1; //! \brief The reference is based on an expression //! \brief Constants used on the view code generation - static const unsigned SQL_REFER_WHERE=10, - SQL_REFER_SELECT=20, - SQL_REFER_FROM=30, - SQL_REFER_END_EXPR=40, - SQL_VIEW_DEFINITION=50; + static constexpr unsigned SqlReferWhere=1, + SqlReferSelect=2, + SqlReferFrom=4, + SqlReferEndExpr=8, + SqlViewDefinition=16; Reference(void); @@ -71,6 +94,11 @@ class Reference { reference to be used as the entire view SQL definition */ void setDefinitionExpression(bool value); + void addReferencedTable(Table *ref_table); + int getReferencedTableIndex(Table *ref_table); + void clearReferencedTables(void); + vector
getReferencedTables(void); + //! \brief Gets the referenced table Table *getTable(void); @@ -89,6 +117,10 @@ class Reference { //! \brief Returns the reference typ (see REFER_??? constants) unsigned getReferenceType(void); + void setReferenceAlias(const QString &alias); + + QString getReferenceAlias(void); + //! \brief Returns the SQL code definition QString getSQLDefinition(unsigned sql_type); @@ -98,6 +130,16 @@ class Reference { //! \brief Indicates if the reference when used as expression defines the entire view (raw sql definition) bool isDefinitionExpression(void); + //! \brief Adds a column as being generated by the reference (if it is an expression) + void addColumn(const QString &name, PgSqlType type, const QString &alias); + void addColumn(Column *col); + + //! \brief Clears the columns generated by the expression + void removeColumns(void); + + //! \brief Returns the columns which the reference generates + vector getColumns(void); + /*! \brief Compare the attributes of two references returning true when they have the same values */ bool operator == (Reference &refer); diff --git a/libpgmodeler/src/relationship.cpp b/libpgmodeler/src/relationship.cpp index bd244cd1d6..0a6608cf79 100644 --- a/libpgmodeler/src/relationship.cpp +++ b/libpgmodeler/src/relationship.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,24 +20,24 @@ #include "pgmodelerns.h" #include -const QString Relationship::SUFFIX_SEPARATOR=QString("_"); -const QString Relationship::SRC_TAB_TOKEN=QString("{st}"); -const QString Relationship::DST_TAB_TOKEN=QString("{dt}"); -const QString Relationship::GEN_TAB_TOKEN=QString("{gt}"); -const QString Relationship::SRC_COL_TOKEN=QString("{sc}"); +const QString Relationship::SuffixSeparator=QString("_"); +const QString Relationship::SrcTabToken=QString("{st}"); +const QString Relationship::DstTabToken=QString("{dt}"); +const QString Relationship::GenTabToken=QString("{gt}"); +const QString Relationship::SrcColToken=QString("{sc}"); -const unsigned Relationship::SRC_COL_PATTERN=0; -const unsigned Relationship::DST_COL_PATTERN=1; -const unsigned Relationship::PK_PATTERN=2; -const unsigned Relationship::UQ_PATTERN=3; -const unsigned Relationship::SRC_FK_PATTERN=4; -const unsigned Relationship::DST_FK_PATTERN=5; -const unsigned Relationship::PK_COL_PATTERN=6; +constexpr unsigned Relationship::SrcColPattern; +constexpr unsigned Relationship::DstColPattern; +constexpr unsigned Relationship::PkPattern; +constexpr unsigned Relationship::UqPattern; +constexpr unsigned Relationship::SrcFkPattern; +constexpr unsigned Relationship::DstFkPattern; +constexpr unsigned Relationship::PkColPattern; Relationship::Relationship(Relationship *rel) : BaseRelationship(rel) { if(!rel) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); (*(this))=(*rel); } @@ -50,29 +50,67 @@ Relationship::Relationship(unsigned rel_type, Table *src_tab, { try { - obj_type=OBJ_RELATIONSHIP; + obj_type=ObjectType::Relationship; QString str_aux; /* Raises an error if the user tries to create a relationship which some table doesn't has a primary key */ - if(((rel_type==RELATIONSHIP_11 || rel_type==RELATIONSHIP_1N) && + if(((rel_type==Relationship11 || rel_type==Relationship1n) && !this->getReferenceTable()->getPrimaryKey()) || - (rel_type==RELATIONSHIP_NN && (!src_tab->getPrimaryKey() || !dst_tab->getPrimaryKey()))) - throw Exception(Exception::getErrorMessage(ERR_LINK_TABLES_NO_PK) + (rel_type==RelationshipNn && (!src_tab->getPrimaryKey() || !dst_tab->getPrimaryKey()))) + throw Exception(Exception::getErrorMessage(ErrorCode::InvLinkTablesNoPrimaryKey) .arg(obj_name) .arg(src_tab->getName(true)) .arg(dst_tab->getName(true)), - ERR_LINK_TABLES_NO_PK,__PRETTY_FUNCTION__,__FILE__,__LINE__); - else if(rel_type==RELATIONSHIP_DEP && src_tab->getCopyTable()) - throw Exception(Exception::getErrorMessage(ERR_COPY_REL_TAB_DEFINED) + ErrorCode::InvLinkTablesNoPrimaryKey,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + // Raises an error if the user tries to create another copy relationship if the table already copies another table + if(rel_type==RelationshipDep && src_tab->getCopyTable()) + throw Exception(Exception::getErrorMessage(ErrorCode::InvCopyRelTableDefined) .arg(src_tab->getName(true)) .arg(dst_tab->getName(true)) .arg(src_tab->getCopyTable()->getName(true)), - ERR_COPY_REL_TAB_DEFINED,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvCopyRelTableDefined,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + /* If the relationship is partitioning the destination table (partitioned) shoud have + * a partitioning type defined otherwise and error is raised */ + if(rel_type == RelationshipPart && !dst_tab->isPartitioned()) + throw Exception(Exception::getErrorMessage(ErrorCode::InvPartitioningTypePartRel) + .arg(src_tab->getSignature()).arg(dst_tab->getSignature()), + ErrorCode::InvPartitioningTypePartRel, __PRETTY_FUNCTION__,__FILE__,__LINE__); + + // Raises an error if the user tries to create a partitioning relationship where one of the tables are already a partition table + if(rel_type==RelationshipPart && src_tab->getPartitionedTable()) + throw Exception(Exception::getErrorMessage(ErrorCode::InvPartRelPartitionedDefined) + .arg(src_tab->getName(true)) + .arg(dst_tab->getName(true)) + .arg(src_tab->getPartitionedTable()->getName(true)), + ErrorCode::InvPartRelPartitionedDefined,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + /* Raises an error if the user tries to create a relationship in the following configuration: + * 1) Many-to-many relationship where one of the tables is a partitioned one + * it will be created a fk in the intermediate table which references the partitioned table which + * is not allowed by partitioning rules. + * + * 2) One-to-many relationship which the reference table is partitioned and the received is a ordinary table, because + * a fk will be created on the ordinary table (receiver) which will be referencing the partitioned table, situation + * that is not allowed as too. + * + * 3) Generalization, copy relationship or one-to-many in which one of the tables is part of a partitioning hierarchy. + */ + if((rel_type == RelationshipNn && (src_tab->isPartitioned() || dst_tab->isPartitioned())) || + (rel_type == Relationship1n && getReferenceTable()->isPartitioned() && !getReceiverTable()->isPartitioned()) || + ((rel_type == RelationshipGen || rel_type == RelationshipDep || rel_type == Relationship11) && + (src_tab->isPartition() || src_tab->isPartitioned() || dst_tab->isPartition() || dst_tab->isPartitioned()))) + throw Exception(Exception::getErrorMessage(ErrorCode::InvRelTypeForPatitionTables) + .arg(src_tab->getName(true)) + .arg(dst_tab->getName(true)) + .arg(src_tab->isPartitioned() || src_tab->isPartition() ? src_tab->getName(true) : dst_tab->getName(true)), + ErrorCode::InvRelTypeForPatitionTables,__PRETTY_FUNCTION__,__FILE__,__LINE__); copy_options=copy_op; table_relnn=nullptr; - fk_rel1n=pk_relident=pk_special=uq_rel11=nullptr; + fk_rel1n=pk_relident=pk_special=uq_rel11=pk_original=nullptr; this->deferrable=deferrable; this->deferral_type=deferral_type; this->del_action=fk_del_act; @@ -81,54 +119,56 @@ Relationship::Relationship(unsigned rel_type, Table *src_tab, this->invalidated=true; this->single_pk_column=false; - if(rel_type==RELATIONSHIP_11) + if(rel_type==Relationship11) str_aux=QApplication::translate("Relationship","%1_has_one_%2",""); - else if(rel_type==RELATIONSHIP_1N) + else if(rel_type==Relationship1n) str_aux=QApplication::translate("Relationship","%1_has_many_%2",""); - else if(rel_type==RELATIONSHIP_NN) + else if(rel_type==RelationshipNn) str_aux=QApplication::translate("Relationship","many_%1_has_many_%2",""); - else if(rel_type==RELATIONSHIP_GEN) + else if(rel_type==RelationshipGen) str_aux=QApplication::translate("Relationship","%1_inherits_%2",""); + else if(rel_type==RelationshipPart) + str_aux=QApplication::translate("Relationship","%1_is_partition_of_%2",""); else str_aux=QApplication::translate("Relationship","%1_copies_%2",""); - if(rel_type==RELATIONSHIP_NN) + if(rel_type==RelationshipNn) str_aux=str_aux.arg(this->src_table->getName()) .arg(this->dst_table->getName()); - else if(rel_type==RELATIONSHIP_1N) + else if(rel_type==Relationship1n) str_aux=str_aux.arg(this->getReferenceTable()->getName()) .arg(this->getReceiverTable()->getName()); else str_aux=str_aux.arg(this->getReceiverTable()->getName()) .arg(this->getReferenceTable()->getName()); - if(str_aux.size() > BaseObject::OBJECT_NAME_MAX_LENGTH) - str_aux.resize(BaseObject::OBJECT_NAME_MAX_LENGTH); + if(str_aux.size() > BaseObject::ObjectNameMaxLength) + str_aux.resize(BaseObject::ObjectNameMaxLength); setName(str_aux); - if(rel_type==RELATIONSHIP_NN) + if(rel_type==RelationshipNn) { tab_name_relnn=this->obj_name; - if(tab_name_relnn.size() > BaseObject::OBJECT_NAME_MAX_LENGTH) - tab_name_relnn.resize(BaseObject::OBJECT_NAME_MAX_LENGTH); - - setNamePattern(PK_PATTERN, GEN_TAB_TOKEN + SUFFIX_SEPARATOR + QString("pk")); - setNamePattern(SRC_FK_PATTERN, SRC_TAB_TOKEN + SUFFIX_SEPARATOR + QString("fk")); - setNamePattern(DST_FK_PATTERN, DST_TAB_TOKEN + SUFFIX_SEPARATOR + QString("fk")); - setNamePattern(UQ_PATTERN, GEN_TAB_TOKEN + SUFFIX_SEPARATOR + QString("uq")); - setNamePattern(SRC_COL_PATTERN, SRC_COL_TOKEN + SUFFIX_SEPARATOR + SRC_TAB_TOKEN); - setNamePattern(DST_COL_PATTERN, SRC_COL_TOKEN + SUFFIX_SEPARATOR + DST_TAB_TOKEN); - setNamePattern(PK_COL_PATTERN, QString("id")); + if(tab_name_relnn.size() > BaseObject::ObjectNameMaxLength) + tab_name_relnn.resize(BaseObject::ObjectNameMaxLength); + + setNamePattern(PkPattern, GenTabToken + SuffixSeparator + QString("pk")); + setNamePattern(SrcFkPattern, SrcTabToken + SuffixSeparator + QString("fk")); + setNamePattern(DstFkPattern, DstTabToken + SuffixSeparator + QString("fk")); + setNamePattern(UqPattern, GenTabToken + SuffixSeparator + QString("uq")); + setNamePattern(SrcColPattern, SrcColToken + SuffixSeparator + SrcTabToken); + setNamePattern(DstColPattern, SrcColToken + SuffixSeparator + DstTabToken); + setNamePattern(PkColPattern, QString("id")); } - else if(rel_type==RELATIONSHIP_DEP || rel_type==RELATIONSHIP_GEN) - setNamePattern(PK_PATTERN, DST_TAB_TOKEN + SUFFIX_SEPARATOR + QString("pk")); + else if(rel_type==RelationshipDep || rel_type==RelationshipGen) + setNamePattern(PkPattern, DstTabToken + SuffixSeparator + QString("pk")); else { - setNamePattern(PK_PATTERN, DST_TAB_TOKEN + SUFFIX_SEPARATOR + QString("pk")); - setNamePattern(SRC_FK_PATTERN, SRC_TAB_TOKEN + SUFFIX_SEPARATOR + QString("fk")); - setNamePattern(UQ_PATTERN, DST_TAB_TOKEN + SUFFIX_SEPARATOR + QString("uq")); - setNamePattern(SRC_COL_PATTERN, SRC_COL_TOKEN + SUFFIX_SEPARATOR + SRC_TAB_TOKEN); + setNamePattern(PkPattern, DstTabToken + SuffixSeparator + QString("pk")); + setNamePattern(SrcFkPattern, SrcTabToken + SuffixSeparator + QString("fk")); + setNamePattern(UqPattern, DstTabToken + SuffixSeparator + QString("uq")); + setNamePattern(SrcColPattern, SrcColToken + SuffixSeparator + SrcTabToken); } rejected_col_count=0; @@ -136,7 +176,7 @@ Relationship::Relationship(unsigned rel_type, Table *src_tab, } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -145,18 +185,18 @@ void Relationship::setNamePattern(unsigned pat_id, const QString &pattern) if(!pattern.isEmpty()) { QString aux_name=pattern, - pat_tokens[]={ SRC_TAB_TOKEN, DST_TAB_TOKEN, - GEN_TAB_TOKEN, SRC_COL_TOKEN }; + pat_tokens[]={ SrcTabToken, DstTabToken, + GenTabToken, SrcColToken }; unsigned i, count=sizeof(pat_tokens)/sizeof(QString); for(i=0; i < count; i++) aux_name.replace(pat_tokens[i], QString("%1").arg(static_cast('a' + i))); - if(pat_id > PK_COL_PATTERN) - throw Exception(Exception::getErrorMessage(ERR_REF_INV_NAME_PATTERN_ID) + if(pat_id > PkColPattern) + throw Exception(Exception::getErrorMessage(ErrorCode::RefInvalidNamePatternId) .arg(this->getName()),__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(!BaseObject::isValidName(aux_name)) - throw Exception(Exception::getErrorMessage(ERR_ASG_INV_NAME_PATTERN) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidNamePattern) .arg(this->getName()),__PRETTY_FUNCTION__,__FILE__,__LINE__); name_patterns[pat_id]=pattern; @@ -166,38 +206,54 @@ void Relationship::setNamePattern(unsigned pat_id, const QString &pattern) QString Relationship::getNamePattern(unsigned pat_id) { - if(pat_id > PK_COL_PATTERN) - throw Exception(ERR_REF_INV_NAME_PATTERN_ID,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(pat_id > PkColPattern) + throw Exception(ErrorCode::RefInvalidNamePatternId,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(name_patterns[pat_id]); } -QString Relationship::generateObjectName(unsigned pat_id, Column *id_col) +QString Relationship::generateObjectName(unsigned pat_id, Column *id_col, bool use_alias) { - QString name; + QString name, aux_name; name=name_patterns[pat_id]; - name.replace(GEN_TAB_TOKEN, (rel_type==RELATIONSHIP_NN ? tab_name_relnn : QString())); + name.replace(GenTabToken, (rel_type==RelationshipNn ? tab_name_relnn : QString())); - if(rel_type==RELATIONSHIP_NN) + if(rel_type==RelationshipNn) { - name.replace(SRC_TAB_TOKEN, src_table->getName()); - name.replace(DST_TAB_TOKEN, dst_table->getName()); + aux_name = use_alias && !src_table->getAlias().isEmpty() ? src_table->getAlias() : src_table->getName(); + name.replace(SrcTabToken, aux_name); + + aux_name = use_alias && !dst_table->getAlias().isEmpty() ? dst_table->getAlias() : dst_table->getName(); + name.replace(DstTabToken, aux_name); } else { - name.replace(SRC_TAB_TOKEN, getReferenceTable()->getName()); - name.replace(DST_TAB_TOKEN, getReceiverTable()->getName()); + aux_name = use_alias && !getReferenceTable()->getAlias().isEmpty() ? getReferenceTable()->getAlias() : getReferenceTable()->getName(); + name.replace(SrcTabToken, aux_name); + + aux_name = use_alias && !getReceiverTable()->getAlias().isEmpty() ? getReceiverTable()->getAlias() : getReceiverTable()->getName(); + name.replace(DstTabToken, aux_name); } - name.replace(SRC_COL_TOKEN, (id_col ? id_col->getName() : QString())); + aux_name.clear(); + + if(id_col) + aux_name = use_alias && !id_col->getAlias().isEmpty() ? id_col->getAlias() : id_col->getName(); - if(name.size() > BaseObject::OBJECT_NAME_MAX_LENGTH) - name.remove(BaseObject::OBJECT_NAME_MAX_LENGTH, name.size()); + name.replace(SrcColToken, aux_name); + + if(name.size() > BaseObject::ObjectNameMaxLength) + name.remove(BaseObject::ObjectNameMaxLength, name.size()); return(name); } +void Relationship::setOriginalPrimaryKey(Constraint *pk) +{ + pk_original = pk; +} + void Relationship::setMandatoryTable(unsigned table_id, bool value) { BaseRelationship::setMandatoryTable(table_id, value); @@ -217,10 +273,10 @@ void Relationship::setIdentifier(bool value) set as identifier. */ if(value && (src_table==dst_table || - (rel_type==RELATIONSHIP_NN || - rel_type==RELATIONSHIP_GEN || - rel_type==RELATIONSHIP_DEP))) - throw Exception(ERR_INV_IDENT_RELATIOSHIP,__PRETTY_FUNCTION__,__FILE__,__LINE__); + (rel_type==RelationshipNn || + rel_type==RelationshipGen || + rel_type==RelationshipDep))) + throw Exception(ErrorCode::InvIdentifierRelationship,__PRETTY_FUNCTION__,__FILE__,__LINE__); identifier=value; this->invalidated=true; @@ -231,9 +287,9 @@ void Relationship::setSpecialPrimaryKeyCols(vector &cols) /* Raises an error if the user try to set columns for special primary key when the relationship type is identifier or self relationship */ if(!cols.empty() && (isSelfRelationship() || isIdentifier())) - throw Exception(Exception::getErrorMessage(ERR_INV_USE_ESPECIAL_PK) + throw Exception(Exception::getErrorMessage(ErrorCode::InvUseSpecialPrimaryKey) .arg(this->getName()), - ERR_INV_USE_ESPECIAL_PK,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvUseSpecialPrimaryKey,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->column_ids_pk_rel=cols; } @@ -249,6 +305,14 @@ void Relationship::createSpecialPrimaryKey(void) { unsigned i, count; vector gen_cols; + Table *table = getReceiverTable(); + + // First we need to remove the original primary key in order to use the special pk + if(table->getPrimaryKey()) + { + pk_original = table->getPrimaryKey(); + table->removeObject(pk_original); + } /* Allocates the primary key with the following feature: 1) Protected and included by linking in order to be easily identified @@ -256,14 +320,19 @@ void Relationship::createSpecialPrimaryKey(void) 2) Use the same tablespace as the receiver table */ pk_special=new Constraint; - pk_special->setName(generateObjectName(PK_PATTERN)); - pk_special->setConstraintType(ConstraintType::primary_key); + pk_special->setName(generateObjectName(PkPattern)); + pk_special->setAlias(generateObjectName(PkPattern, nullptr, true)); + pk_special->setConstraintType(ConstraintType::PrimaryKey); pk_special->setAddedByLinking(true); pk_special->setProtected(true); pk_special->setTablespace(dynamic_cast(getReceiverTable()->getTablespace())); //For generalization relationships generates the primary key in form of ALTER command - pk_special->setDeclaredInTable(this->getRelationshipType()!=RELATIONSHIP_GEN); + pk_special->setDeclaredInTable(this->getRelationshipType()!=RelationshipGen); + + // Adding the collumns of the original primary key to the special one + for(i=0; pk_original && i < pk_original->getColumnCount(Constraint::SourceCols); i++) + pk_special->addColumn(pk_original->getColumn(i, Constraint::SourceCols), Constraint::SourceCols); gen_cols=gen_columns; for(auto &attrib : rel_attributes) @@ -274,8 +343,8 @@ void Relationship::createSpecialPrimaryKey(void) for(i=0; i < count; i++) { if(column_ids_pk_rel[i] < gen_cols.size() && - !pk_special->isColumnExists(gen_cols[column_ids_pk_rel[i]], Constraint::SOURCE_COLS)) - pk_special->addColumn(gen_cols[column_ids_pk_rel[i]], Constraint::SOURCE_COLS); + !pk_special->isColumnExists(gen_cols[column_ids_pk_rel[i]], Constraint::SourceCols)) + pk_special->addColumn(gen_cols[column_ids_pk_rel[i]], Constraint::SourceCols); } try @@ -293,10 +362,10 @@ void Relationship::createSpecialPrimaryKey(void) void Relationship::setTableNameRelNN(const QString &name) { - if(rel_type==RELATIONSHIP_NN) + if(rel_type==RelationshipNn) { if(!BaseObject::isValidName(name)) - throw Exception(ERR_ASG_INV_NAME_TABLE_RELNN, __PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidNameTableRelNN, __PRETTY_FUNCTION__,__FILE__,__LINE__); tab_name_relnn=name; tab_name_relnn.remove('"'); @@ -309,6 +378,17 @@ QString Relationship::getTableNameRelNN(void) return(tab_name_relnn); } +void Relationship::setPartitionBoundingExpr(const QString &part_bound_expr) +{ + part_bounding_expr = part_bound_expr.toLower() == Attributes::Default.toLower() ? QString() : part_bound_expr; + this->invalidated = true; +} + +QString Relationship::getPartitionBoundingExpr(void) +{ + return(part_bounding_expr); +} + bool Relationship::isDeferrable(void) { return(deferrable); @@ -327,7 +407,7 @@ DeferralType Relationship::getDeferralType(void) void Relationship::setActionType(ActionType act_type, unsigned act_id) { - if(act_id==Constraint::DELETE_ACTION) + if(act_id==Constraint::DeleteAction) this->del_action=act_type; else this->upd_action=act_type; @@ -337,7 +417,7 @@ void Relationship::setActionType(ActionType act_type, unsigned act_id) ActionType Relationship::getActionType(unsigned act_id) { - if(act_id==Constraint::DELETE_ACTION) + if(act_id==Constraint::DeleteAction) return(del_action); else return(upd_action); @@ -353,17 +433,17 @@ int Relationship::getObjectIndex(TableObject *object) //Raises an error if the object is not allocated if(!object) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Selecting the correct list using the object type obj_type=object->getObjectType(); - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) list=&rel_attributes; - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) list=&rel_constraints; else //Raises an error if the object type isn't valid (not a column or constraint) - throw Exception(ERR_REF_OBJ_INV_TYPE, __PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidType, __PRETTY_FUNCTION__,__FILE__,__LINE__); itr=list->begin(); itr_end=list->end(); @@ -389,7 +469,7 @@ bool Relationship::isColumnExists(Column *column) //Raises an error if the column is not allocated if(!column) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); itr=gen_columns.begin(); itr_end=gen_columns.end(); @@ -411,12 +491,13 @@ void Relationship::addObject(TableObject *tab_obj, int obj_idx) /* Raises an error if the user try to add manually a special primary key on the relationship and the relationship type is not generalization or copy */ - if((rel_type==RELATIONSHIP_GEN || - rel_type==RELATIONSHIP_DEP) && + if((rel_type==RelationshipGen || + rel_type==RelationshipDep || + rel_type==RelationshipPart) && !(tab_obj->isAddedByRelationship() && tab_obj->isProtected() && - tab_obj->getObjectType()==OBJ_CONSTRAINT)) - throw Exception(ERR_ASG_OBJ_INV_REL_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + tab_obj->getObjectType()==ObjectType::Constraint)) + throw Exception(ErrorCode::AsgObjectInvalidRelationshipType,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { @@ -426,30 +507,30 @@ void Relationship::addObject(TableObject *tab_obj, int obj_idx) { //Gets the object list according the object type obj_type=tab_obj->getObjectType(); - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) obj_list=&rel_attributes; - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) obj_list=&rel_constraints; else //Raises an error if the object type isn't valid (not a column or constraint) - throw Exception(ERR_ASG_OBJECT_INV_TYPE, __PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgObjectInvalidType, __PRETTY_FUNCTION__,__FILE__,__LINE__); //Defines the parent table for the object only for validation tab_obj->setParentTable(src_table); //Generates the code for the object only for validation - if(obj_type==OBJ_COLUMN) - dynamic_cast(tab_obj)->getCodeDefinition(SchemaParser::SQL_DEFINITION); + if(obj_type==ObjectType::Column) + dynamic_cast(tab_obj)->getCodeDefinition(SchemaParser::SqlDefinition); else { Constraint *rest=nullptr; rest=dynamic_cast(tab_obj); //Raises an error if the user try to add as foreign key to relationship - if(rest->getConstraintType()==ConstraintType::foreign_key) - throw Exception(ERR_ASG_FOREIGN_KEY_REL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(rest->getConstraintType()==ConstraintType::ForeignKey) + throw Exception(ErrorCode::AsgForeignKeyRelationship,__PRETTY_FUNCTION__,__FILE__,__LINE__); - rest->getCodeDefinition(SchemaParser::SQL_DEFINITION); + rest->getCodeDefinition(SchemaParser::SqlDefinition); } //Switch back to null the object parent @@ -469,22 +550,22 @@ void Relationship::addObject(TableObject *tab_obj, int obj_idx) this->invalidated=true; } else - throw Exception(QString(Exception::getErrorMessage(ERR_ASG_DUPLIC_OBJECT)) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgDuplicatedObject) .arg(tab_obj->getName(true)) .arg(tab_obj->getTypeName()) .arg(this->getName(true)) .arg(this->getTypeName()), - ERR_ASG_DUPLIC_OBJECT, __PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgDuplicatedObject, __PRETTY_FUNCTION__,__FILE__,__LINE__); } catch(Exception &e) { - if(e.getErrorType()==ERR_UNDEF_ATTRIB_VALUE) - throw Exception(Exception::getErrorMessage(ERR_ASG_OBJ_INV_DEFINITION) + if(e.getErrorCode()==ErrorCode::UndefinedAttributeValue) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgObjectInvalidDefinition) .arg(tab_obj->getName()) .arg(tab_obj->getTypeName()), - ERR_ASG_OBJ_INV_DEFINITION,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + ErrorCode::AsgObjectInvalidDefinition,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -509,21 +590,21 @@ void Relationship::removeObject(unsigned obj_id, ObjectType obj_type) TableObject *tab_obj=nullptr; Table *recv_table=nullptr; - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) obj_list=&rel_attributes; - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) obj_list=&rel_constraints; else - throw Exception(ERR_REF_OBJ_INV_TYPE, __PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidType, __PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the object index is out of bound if(obj_id >= obj_list->size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); tab_obj=obj_list->at(obj_id); recv_table=this->getReceiverTable(); - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) { Column *col=nullptr; Constraint *constr=nullptr; @@ -540,21 +621,21 @@ void Relationship::removeObject(unsigned obj_id, ObjectType obj_type) { constr=dynamic_cast(*itr); //Check is the column is referenced by one relationship constraints - refer=(constr->getColumn(col->getName(), Constraint::SOURCE_COLS) || - constr->getColumn(col->getName(), Constraint::REFERENCED_COLS)); + refer=(constr->getColumn(col->getName(), Constraint::SourceCols) || + constr->getColumn(col->getName(), Constraint::ReferencedCols)); itr++; } //Raises an error if the column to be removed is referenced by a relationship constraint if(refer) - throw Exception(Exception::getErrorMessage(ERR_REM_INDIRECT_REFERENCE) + throw Exception(Exception::getErrorMessage(ErrorCode::RemInderectReference) .arg(col->getName()) .arg(col->getTypeName()) .arg(constr->getName()) .arg(constr->getTypeName()) .arg(this->getName(true)) .arg(this->getTypeName()), - ERR_REM_INDIRECT_REFERENCE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::RemInderectReference,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Generating the column index inside the special pk column list col_idx=getObjectIndex(col) + gen_columns.size(); @@ -582,19 +663,19 @@ void Relationship::removeObject(unsigned obj_id, ObjectType obj_type) void Relationship::removeObject(TableObject *object) { if(!object) - throw Exception(ERR_REM_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RemNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); removeObject(getObjectIndex(object),object->getObjectType()); } void Relationship::removeAttribute(unsigned attrib_idx) { - removeObject(attrib_idx, OBJ_COLUMN); + removeObject(attrib_idx, ObjectType::Column); } void Relationship::removeConstraint(unsigned constr_idx) { - removeObject(constr_idx, OBJ_CONSTRAINT); + removeObject(constr_idx, ObjectType::Constraint); } vector Relationship::getGeneratedColumns(void) @@ -627,15 +708,15 @@ TableObject *Relationship::getObject(unsigned obj_idx, ObjectType obj_type) { vector *list=nullptr; - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) list=&rel_attributes; - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) list=&rel_constraints; else - throw Exception(ERR_REF_OBJ_INV_TYPE, __PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidType, __PRETTY_FUNCTION__,__FILE__,__LINE__); if(obj_idx >= list->size()) - throw Exception(ERR_REF_OBJ_INV_INDEX, __PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex, __PRETTY_FUNCTION__,__FILE__,__LINE__); return(list->at(obj_idx)); } @@ -647,12 +728,12 @@ TableObject *Relationship::getObject(const QString &name, ObjectType obj_type) TableObject *obj_aux=nullptr; bool found=false; - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) list=&rel_attributes; - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) list=&rel_constraints; else - throw Exception(ERR_REF_OBJ_INV_TYPE, __PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidType, __PRETTY_FUNCTION__,__FILE__,__LINE__); itr=list->begin(); itr_end=list->end(); @@ -674,14 +755,14 @@ Column *Relationship::getAttribute(unsigned attrib_idx) { //Raises an error if the attribute index is out of bound if(attrib_idx >= rel_attributes.size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(dynamic_cast(rel_attributes[attrib_idx])); } Column *Relationship::getAttribute(const QString &name) { - return(dynamic_cast(getObject(name,OBJ_COLUMN))); + return(dynamic_cast(getObject(name,ObjectType::Column))); } vector Relationship::getAttributes(void) @@ -693,14 +774,14 @@ Constraint *Relationship::getConstraint(unsigned constr_idx) { //Raises an error if the constraint index is out of bound if(constr_idx >= rel_constraints.size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(dynamic_cast(rel_constraints[constr_idx])); } Constraint *Relationship::getConstraint(const QString &name) { - return(dynamic_cast(getObject(name,OBJ_CONSTRAINT))); + return(dynamic_cast(getObject(name,ObjectType::Constraint))); } vector Relationship::getConstraints(void) @@ -720,12 +801,12 @@ unsigned Relationship::getConstraintCount(void) unsigned Relationship::getObjectCount(ObjectType obj_type) { - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) return(rel_attributes.size()); - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) return(rel_constraints.size()); else - throw Exception(ERR_REF_OBJ_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); } void Relationship::addConstraints(Table *recv_tab) @@ -746,9 +827,9 @@ void Relationship::addConstraints(Table *recv_tab) if(constr->getParentTable()) break; - if(constr->getConstraintType()!=ConstraintType::primary_key) + if(constr->getConstraintType()!=ConstraintType::PrimaryKey) { - constr->setName(PgModelerNS::generateUniqueName(constr, (*recv_tab->getObjectList(OBJ_CONSTRAINT)))); + constr->setName(PgModelerNs::generateUniqueName(constr, (*recv_tab->getObjectList(ObjectType::Constraint)))); recv_tab->addConstraint(constr); } else @@ -761,12 +842,12 @@ void Relationship::addConstraints(Table *recv_tab) if(pk) { - count=constr->getColumnCount(Constraint::SOURCE_COLS); + count=constr->getColumnCount(Constraint::SourceCols); for(i=0; i < count; i++) //Adds the colums from the constraint into the table's primary key - pk->addColumn(constr->getColumn(i, Constraint::SOURCE_COLS), - Constraint::SOURCE_COLS); + pk->addColumn(constr->getColumn(i, Constraint::SourceCols), + Constraint::SourceCols); } else //Case the table doens't has a primary key the constraint will the be it @@ -790,11 +871,11 @@ void Relationship::addConstraints(Table *recv_tab) itr++; } - throw Exception(e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } -void Relationship::addColumnsRelGen(void) +void Relationship::addColumnsRelGenPart(void) { Table *src_tab=nullptr, *dst_tab=nullptr, *parent_tab=nullptr, *aux_tab=nullptr; @@ -804,30 +885,37 @@ void Relationship::addColumnsRelGen(void) i, i1, i2, id_tab, idx, tab_count; vector columns; - ObjectType types[2]={OBJ_TABLE, BASE_TABLE}; - ErrorType err_type=ERR_CUSTOM; + ObjectType types[2]={ObjectType::Table, ObjectType::BaseTable}; + ErrorCode err_code=ErrorCode::Custom; bool duplic=false, cond=false, /* 0 -> Column created by inheritance relationship 1 -> Column created by copy relationship */ src_flags[2]={false,false}, dst_flags[2]={false,false}; QString str_aux, msg; - PgSQLType src_type, dst_type; + PgSqlType src_type, dst_type; try { src_tab=dynamic_cast
(src_table); dst_tab=dynamic_cast
(dst_table); - + //Gets the column count from participant tables src_count=src_tab->getColumnCount(); dst_count=dst_tab->getColumnCount(); rejected_col_count=0; + /* If the relationship is partitioning the destination table (partitioned) shoud have + * a partitioning type defined otherwise and error is raised */ + if(rel_type == RelationshipPart && !dst_tab->isPartitioned()) + throw Exception(Exception::getErrorMessage(ErrorCode::InvPartitioningTypePartRel) + .arg(src_tab->getSignature()).arg(dst_tab->getSignature()), + ErrorCode::InvPartitioningTypePartRel, __PRETTY_FUNCTION__,__FILE__,__LINE__); + /* This for compares the columns of the receiver table with the columns of the reference table in order to resolve the conflicting names */ - for(i=0; i < dst_count && err_type==ERR_CUSTOM; i++) + for(i=0; i < dst_count && err_code==ErrorCode::Custom; i++) { //Gets the column from the receiver (destination) table dst_col=dst_tab->getColumn(i); @@ -891,14 +979,13 @@ void Relationship::addColumnsRelGen(void) for(i2=0; i2 < 2; i2++) { //Checking if the column came from a generalization relationship - if(types[i2]==OBJ_TABLE) + if(types[i2]==ObjectType::Table) { - tab_count=aux_tab->getObjectCount(OBJ_TABLE); + tab_count=aux_tab->getObjectCount(ObjectType::Table); for(idx=0; idx < tab_count; idx++) { - parent_tab=dynamic_cast
(aux_tab->getObject(idx, OBJ_TABLE)); - cond=(aux_col->getParentTable()==parent_tab && - aux_col->isAddedByGeneralization()); + parent_tab=dynamic_cast
(aux_tab->getObject(idx, ObjectType::Table)); + cond=(aux_col->getParentTable()==parent_tab && aux_col->isAddedByGeneralization()); } } @@ -906,9 +993,8 @@ void Relationship::addColumnsRelGen(void) else { parent_tab=aux_tab->getCopyTable(); - cond=(parent_tab && - aux_col->getParentTable()==parent_tab && - aux_col->isAddedByGeneralization()); + cond=(parent_tab && rel_type == RelationshipDep && + aux_col->getParentTable()==parent_tab && aux_col->isAddedByCopy()); } if(id_tab==0) @@ -922,7 +1008,7 @@ void Relationship::addColumnsRelGen(void) column is from the table itself or it came from a copy table and the destination column is from the destination table or came from a copy table of the destination table itself */ - if(rel_type==RELATIONSHIP_DEP && + if((rel_type==RelationshipDep) && ((!src_flags[0] && !src_flags[1]) || (!src_flags[0] && src_flags[1])) && @@ -930,18 +1016,17 @@ void Relationship::addColumnsRelGen(void) ((!dst_flags[0] && !dst_flags[1]) || (!dst_flags[0] && dst_flags[1]))) { - err_type=ERR_DUPLIC_COLS_COPY_REL; + err_code=ErrorCode::InvCopyRelationshipDuplicCols; } /* Error condition 2: The relationship type is generalization and the column - types is incompatible */ - else if(rel_type==RELATIONSHIP_GEN && - src_type!=dst_type) - err_type=ERR_INCOMP_COLS_INHERIT_REL; + * types is incompatible */ + else if((rel_type == RelationshipGen || rel_type==RelationshipPart) && src_type != dst_type) + err_code=ErrorCode::InvInheritRelationshipIncompCols; } } //In case that no error was detected (ERR_CUSTOM) - if(err_type==ERR_CUSTOM) + if(err_code==ErrorCode::Custom) { //In case there is no column duplicity if(!duplic) @@ -951,10 +1036,8 @@ void Relationship::addColumnsRelGen(void) (*column)=(*dst_col); - if(rel_type==RELATIONSHIP_GEN) - { + if(rel_type==RelationshipGen) column->setAddedByGeneralization(true); - } else column->setAddedByCopy(true); @@ -963,11 +1046,11 @@ void Relationship::addColumnsRelGen(void) //Converts the type if(column->getType()==QString("serial")) - column->setType(PgSQLType(QString("integer"))); + column->setType(PgSqlType(QString("integer"))); else if(column->getType()==QString("bigserial")) - column->setType(PgSQLType(QString("bigint"))); + column->setType(PgSqlType(QString("bigint"))); else if(column->getType()==QString("smallserial")) - column->setType(PgSQLType(QString("smallint"))); + column->setType(PgSqlType(QString("smallint"))); //Adds the new column to the temporary column list columns.push_back(column); @@ -981,8 +1064,11 @@ void Relationship::addColumnsRelGen(void) } } + if((src_tab->getColumnCount() + columns.size()) != dst_tab->getColumnCount() && rel_type == RelationshipPart) + err_code = ErrorCode::InvColumnCountPartRel; + //In case that no duplicity error is detected - if(err_type==ERR_CUSTOM) + if(err_code==ErrorCode::Custom) { vector::iterator itr, itr_end; @@ -1008,25 +1094,31 @@ void Relationship::addColumnsRelGen(void) columns.pop_back(); } - str_aux=Exception::getErrorMessage(err_type); + str_aux=Exception::getErrorMessage(err_code); - if(err_type==ERR_DUPLIC_COLS_COPY_REL) + if(err_code==ErrorCode::InvCopyRelationshipDuplicCols) + { + msg=QString(str_aux) + .arg(dst_col->getName(true)) + .arg(dst_tab->getName(true)) + .arg(src_tab->getName(true)); + } + else if(err_code==ErrorCode::InvColumnCountPartRel) { msg=QString(str_aux) - .arg(dst_col->getName()) - .arg(dst_tab->getName()) - .arg(src_tab->getName()); + .arg(src_tab->getName(true)) + .arg(dst_tab->getName(true)); } else { msg=QString(str_aux) - .arg(dst_col->getName()) - .arg(dst_tab->getName()) - .arg(src_col->getName()) - .arg(src_tab->getName()); + .arg(dst_col->getName(true)) + .arg(dst_tab->getName(true)) + .arg(src_col->getName(true)) + .arg(src_tab->getName(true)); } - throw Exception(msg, err_type,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(msg, err_code,__PRETTY_FUNCTION__,__FILE__,__LINE__); } //Creates the special primary key if exists @@ -1041,15 +1133,15 @@ void Relationship::addColumnsRelGen(void) this->connected=true; this->disconnectRelationship(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } -void Relationship::addConstraintsRelGen(void) +void Relationship::addConstraintsRelGenPart(void) { Table *parent_tab=dynamic_cast
(getReferenceTable()), *child_tab=dynamic_cast
(getReceiverTable()); - vector *constrs=parent_tab->getObjectList(OBJ_CONSTRAINT); + vector *constrs=parent_tab->getObjectList(ObjectType::Constraint); Constraint *ck_constr=nullptr, *constr=nullptr, *aux_constr=nullptr; try @@ -1058,9 +1150,9 @@ void Relationship::addConstraintsRelGen(void) { constr=dynamic_cast(obj); - if(constr->getConstraintType()==ConstraintType::check && !constr->isNoInherit()) + if(constr->getConstraintType()==ConstraintType::Check && !constr->isNoInherit()) { - aux_constr=dynamic_cast(child_tab->getObject(constr->getName(), OBJ_CONSTRAINT)); + aux_constr=dynamic_cast(child_tab->getObject(constr->getName(), ObjectType::Constraint)); if(!aux_constr) { @@ -1071,18 +1163,18 @@ void Relationship::addConstraintsRelGen(void) child_tab->addConstraint(ck_constr); ck_constraints.push_back(ck_constr); } - else if(aux_constr->getConstraintType()!=ConstraintType::check || + else if(aux_constr->getConstraintType()!=ConstraintType::Check || aux_constr->getExpression().simplified()!=constr->getExpression().simplified()) - throw Exception(Exception::getErrorMessage(ERR_INCOMP_CONSTRS_INHERIT_REL) + throw Exception(Exception::getErrorMessage(ErrorCode::InvInheritRelationshipIncompConstrs) .arg(constr->getName()).arg(parent_tab->getName(false, true)) .arg(aux_constr->getName()).arg(child_tab->getName(false, true)), - ERR_INCOMP_CONSTRS_INHERIT_REL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvInheritRelationshipIncompConstrs,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1092,35 +1184,45 @@ void Relationship::connectRelationship(void) { if(!connected) { - if(rel_type==RELATIONSHIP_GEN) + if(rel_type==RelationshipGen) { //Copying the CHECK constraints before adding custom constraints like special pk - addConstraintsRelGen(); + addConstraintsRelGenPart(); //Creates the columns on the receiver table following the rules for generalization rules - addColumnsRelGen(); + addColumnsRelGenPart(); //The reference table is added as parent table on the receiver getReceiverTable()->addAncestorTable(dynamic_cast
(getReferenceTable())); } - else if(rel_type==RELATIONSHIP_DEP) + else if(rel_type==RelationshipDep) { //Creates the columns on the receiver table following the rules for copy rules - addColumnsRelGen(); + addColumnsRelGenPart(); //The reference table is added as copy table on the receiver getReceiverTable()->setCopyTable(dynamic_cast
(getReferenceTable())); getReceiverTable()->setCopyTableOptions(this->copy_options); } - else if(rel_type==RELATIONSHIP_11 || - rel_type==RELATIONSHIP_1N) + else if(rel_type == RelationshipPart) { - if(rel_type==RELATIONSHIP_11) + //Copying the CHECK constraints before adding custom constraints like special pk + addConstraintsRelGenPart(); + + //Creates the columns on the receiver table following the rules for copy rules + addColumnsRelGenPart(); + getReceiverTable()->setPartionedTable(dynamic_cast
(getReferenceTable())); + getReceiverTable()->setPartitionBoundingExpr(part_bounding_expr); + } + else if(rel_type==Relationship11 || + rel_type==Relationship1n) + { + if(rel_type==Relationship11) addColumnsRel11(); else addColumnsRel1n(); } - else if(rel_type==RELATIONSHIP_NN) + else if(rel_type==RelationshipNn) { if(!table_relnn) //Allocates the table that represents the Many-to-Many relationship @@ -1153,7 +1255,7 @@ void Relationship::connectRelationship(void) delete(table_relnn); table_relnn=nullptr; } - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1178,7 +1280,7 @@ void Relationship::configureIndentifierRel(Table *recv_tab) if(!pk_relident) { pk=new Constraint; - pk->setConstraintType(ConstraintType::primary_key); + pk->setConstraintType(ConstraintType::PrimaryKey); pk->setAddedByLinking(true); pk->setDeferrable(this->deferrable); pk->setDeferralType(this->deferral_type); @@ -1188,13 +1290,14 @@ void Relationship::configureIndentifierRel(Table *recv_tab) pk=this->pk_relident; new_pk=true; - pk->setName(generateObjectName(PK_PATTERN)); + pk->setName(generateObjectName(PkPattern)); + pk->setAlias(generateObjectName(PkPattern, nullptr, true)); } //Adds the columns from the strong entity primary key on the weak entity primary key count=gen_columns.size(); for(i=0; i < count; i++) - pk->addColumn(gen_columns[i], Constraint::SOURCE_COLS); + pk->addColumn(gen_columns[i], Constraint::SourceCols); //Inserts the configured primary key on the receiver table (if there is no pk on it) if(new_pk) @@ -1214,13 +1317,13 @@ void Relationship::configureIndentifierRel(Table *recv_tab) pk=recv_tab->getPrimaryKey(); count=gen_columns.size(); for(i=0; i < count; i++) - pk->removeColumn(gen_columns[i]->getName(), Constraint::SOURCE_COLS); + pk->removeColumn(gen_columns[i]->getName(), Constraint::SourceCols); } pk_relident=nullptr; } - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1237,7 +1340,7 @@ void Relationship::addUniqueKey(Table *recv_tab) uq=new Constraint; uq->setDeferrable(this->deferrable); uq->setDeferralType(this->deferral_type); - uq->setConstraintType(ConstraintType::unique); + uq->setConstraintType(ConstraintType::Unique); uq->setAddedByLinking(true); uq_rel11=uq; } @@ -1247,10 +1350,11 @@ void Relationship::addUniqueKey(Table *recv_tab) i=0; while(i < count) - uq->addColumn(gen_columns[i++], Constraint::SOURCE_COLS); + uq->addColumn(gen_columns[i++], Constraint::SourceCols); - uq->setName(generateObjectName(UQ_PATTERN)); - uq->setName(PgModelerNS::generateUniqueName(uq, (*recv_tab->getObjectList(OBJ_CONSTRAINT)))); + uq->setName(generateObjectName(UqPattern)); + uq->setAlias(generateObjectName(UqPattern, nullptr, true)); + uq->setName(PgModelerNs::generateUniqueName(uq, (*recv_tab->getObjectList(ObjectType::Constraint)))); recv_tab->addConstraint(uq); } catch(Exception &e) @@ -1262,7 +1366,7 @@ void Relationship::addUniqueKey(Table *recv_tab) uq_rel11=nullptr; } - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1271,18 +1375,18 @@ void Relationship::addForeignKey(Table *ref_tab, Table *recv_tab, ActionType del Constraint *pk=nullptr, *pk_aux=nullptr, *fk=nullptr; unsigned i, i1, qty; Column *column=nullptr, *column_aux=nullptr; - QString name, aux; + QString name, aux, fk_alias; try { //Alocates the foreign key - if((rel_type==RELATIONSHIP_NN) || - (!fk_rel1n && (rel_type==RELATIONSHIP_11 || rel_type==RELATIONSHIP_1N))) + if((rel_type==RelationshipNn) || + (!fk_rel1n && (rel_type==Relationship11 || rel_type==Relationship1n))) { fk=new Constraint; fk->setDeferrable(this->deferrable); fk->setDeferralType(this->deferral_type); - fk->setConstraintType(ConstraintType::foreign_key); + fk->setConstraintType(ConstraintType::ForeignKey); fk->setAddedByLinking(true); //The reference table is the table referenced by the foreign key @@ -1290,13 +1394,13 @@ void Relationship::addForeignKey(Table *ref_tab, Table *recv_tab, ActionType del /* The configured fk is assigned to the relatioship attibute in order to be manipulated more easily */ - if(rel_type==RELATIONSHIP_11 || rel_type==RELATIONSHIP_1N) + if(rel_type==Relationship11 || rel_type==Relationship1n) fk_rel1n=fk; } //Sets the ON DELETE and ON UPDATE actions for the foreign key - fk->setActionType(del_act, Constraint::DELETE_ACTION); - fk->setActionType(upd_act, Constraint::UPDATE_ACTION); + fk->setActionType(del_act, Constraint::DeleteAction); + fk->setActionType(upd_act, Constraint::UpdateAction); /* Gets the primary key from the reference table in order to reference its columns on the primary key */ @@ -1321,7 +1425,7 @@ void Relationship::addForeignKey(Table *ref_tab, Table *recv_tab, ActionType del of the target table. The first column related to the destination table column list always has its index starting at the existant columns count on the primary key on the source table because they is always inserted after this position. */ - if(rel_type==RELATIONSHIP_NN) + if(rel_type==RelationshipNn) { vector fks; @@ -1334,42 +1438,51 @@ void Relationship::addForeignKey(Table *ref_tab, Table *recv_tab, ActionType del if((!isSelfRelationship() && ref_tab==src_table) || //Condition to create the first fk on the self relationship (isSelfRelationship() && fks.size()==0)) - qty-=dynamic_cast
(dst_table)->getPrimaryKey()->getColumnCount(Constraint::SOURCE_COLS); + qty-=dynamic_cast
(dst_table)->getPrimaryKey()->getColumnCount(Constraint::SourceCols); //Case 2: shifiting the scan index else if(ref_tab==dst_table) { pk_aux=dynamic_cast
(src_table)->getPrimaryKey(); - i=pk_aux->getColumnCount(Constraint::SOURCE_COLS); + i=pk_aux->getColumnCount(Constraint::SourceCols); } } while(i < qty) { column=gen_columns[i]; - column_aux=pk->getColumn(i1, Constraint::SOURCE_COLS); + column_aux=pk->getColumn(i1, Constraint::SourceCols); //Link the two columns on the foreign key - fk->addColumn(column, Constraint::SOURCE_COLS); - fk->addColumn(column_aux, Constraint::REFERENCED_COLS); + fk->addColumn(column, Constraint::SourceCols); + fk->addColumn(column_aux, Constraint::ReferencedCols); i++; i1++; } //Configures the foreign key name - aux.clear(); - if(rel_type!=RELATIONSHIP_NN) - name=generateObjectName(SRC_FK_PATTERN); + if(rel_type!=RelationshipNn) + { + name=generateObjectName(SrcFkPattern); + fk_alias=generateObjectName(SrcFkPattern, nullptr, true); + } else { if(ref_tab==src_table) - name=generateObjectName(SRC_FK_PATTERN); + { + name=generateObjectName(SrcFkPattern); + fk_alias=generateObjectName(SrcFkPattern, nullptr, true); + } else - name=generateObjectName(DST_FK_PATTERN); + { + name=generateObjectName(DstFkPattern); + fk_alias=generateObjectName(DstFkPattern, nullptr, true); + } } fk->setName(name); - fk->setName(PgModelerNS::generateUniqueName(fk, (*recv_tab->getObjectList(OBJ_CONSTRAINT)))); + fk->setAlias(fk_alias); + fk->setName(PgModelerNs::generateUniqueName(fk, (*recv_tab->getObjectList(ObjectType::Constraint)))); recv_tab->addConstraint(fk); } catch(Exception &e) @@ -1381,7 +1494,7 @@ void Relationship::addForeignKey(Table *ref_tab, Table *recv_tab, ActionType del fk_rel1n=nullptr; } - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1403,7 +1516,7 @@ void Relationship::addAttributes(Table *recv_tab) if(column->getParentTable()) break; - column->setName(PgModelerNS::generateUniqueName(column, (*recv_tab->getObjectList(OBJ_COLUMN)))); + column->setName(PgModelerNs::generateUniqueName(column, (*recv_tab->getObjectList(ObjectType::Column)))); column->setAddedByLinking(true); column->setParentRelationship(this); recv_tab->addColumn(column); @@ -1419,7 +1532,7 @@ void Relationship::addAttributes(Table *recv_tab) itr++; } - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1428,7 +1541,7 @@ void Relationship::copyColumns(Table *ref_tab, Table *recv_tab, bool not_null, b Constraint *dst_pk=nullptr, *src_pk=nullptr, *pk=nullptr; unsigned i, count; Column *column=nullptr, *column_aux=nullptr; - QString name, prev_name; + QString name, prev_name, col_alias; try { @@ -1437,15 +1550,15 @@ void Relationship::copyColumns(Table *ref_tab, Table *recv_tab, bool not_null, b /* Raises an error if some table doesn't has a primary key if the relationship is 1-1, 1-n or n-n */ - if((!src_pk && (rel_type==RELATIONSHIP_1N || rel_type==RELATIONSHIP_11)) || - (!src_pk && !dst_pk && rel_type==RELATIONSHIP_NN)) - throw Exception(Exception::getErrorMessage(ERR_LINK_TABLES_NO_PK) + if((!src_pk && (rel_type==Relationship1n || rel_type==Relationship11)) || + (!src_pk && !dst_pk && rel_type==RelationshipNn)) + throw Exception(Exception::getErrorMessage(ErrorCode::InvLinkTablesNoPrimaryKey) .arg(this->obj_name) .arg(ref_tab->getName(true)) .arg(recv_tab->getName(true)), - ERR_LINK_TABLES_NO_PK,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvLinkTablesNoPrimaryKey,__PRETTY_FUNCTION__,__FILE__,__LINE__); - count=pk->getColumnCount(Constraint::SOURCE_COLS); + count=pk->getColumnCount(Constraint::SourceCols); /* Scans the primary key columns adding them to the referenced column list of the relationship */ @@ -1455,7 +1568,7 @@ void Relationship::copyColumns(Table *ref_tab, Table *recv_tab, bool not_null, b gen_columns.push_back(column); //Add the current primary key source column on the list - column_aux=pk->getColumn(i, Constraint::SOURCE_COLS); + column_aux=pk->getColumn(i, Constraint::SourceCols); pk_columns.push_back(column_aux); (*column)=(*column_aux); @@ -1465,16 +1578,27 @@ void Relationship::copyColumns(Table *ref_tab, Table *recv_tab, bool not_null, b prev_name=prev_ref_col_names[column_aux->getObjectId()]; - if(rel_type!=RELATIONSHIP_NN) - name=generateObjectName(SRC_COL_PATTERN, column_aux); + if(rel_type!=RelationshipNn) + { + name=generateObjectName(SrcColPattern, column_aux); + col_alias=generateObjectName(SrcColPattern, column_aux, true); + } else { if(ref_tab==src_table && (!isSelfRelationship() || (isSelfRelationship() && !is_dst_table))) - name=generateObjectName(SRC_COL_PATTERN, column_aux); + { + name=generateObjectName(SrcColPattern, column_aux); + col_alias=generateObjectName(SrcColPattern, column_aux, true); + } else - name=generateObjectName(DST_COL_PATTERN, column_aux); + { + name=generateObjectName(DstColPattern, column_aux); + col_alias=generateObjectName(DstColPattern, column_aux, true); + } } + column->setAlias(col_alias); + //Protects the column evicting that the user modifies it column->setAddedByLinking(true); @@ -1484,14 +1608,14 @@ void Relationship::copyColumns(Table *ref_tab, Table *recv_tab, bool not_null, b //Converting the serial like types if(column->getType()==QString("serial")) - column->setType(PgSQLType(QString("integer"))); + column->setType(PgSqlType(QString("integer"))); else if(column->getType()==QString("bigserial")) - column->setType(PgSQLType(QString("bigint"))); + column->setType(PgSqlType(QString("bigint"))); else if(column->getType()==QString("smallserial")) - column->setType(PgSQLType(QString("smallint"))); + column->setType(PgSqlType(QString("smallint"))); column->setName(name); - name=PgModelerNS::generateUniqueName(column, (*recv_tab->getObjectList(OBJ_COLUMN))); + name=PgModelerNs::generateUniqueName(column, (*recv_tab->getObjectList(ObjectType::Column))); column->setName(name); if(!prev_name.isEmpty()) @@ -1507,7 +1631,7 @@ void Relationship::copyColumns(Table *ref_tab, Table *recv_tab, bool not_null, b by the relationship. This operation is only performed for relationships 1-1, 1-n relationships to the n-n relationships columns are always recreated without the need to keep the history because the user can not reference the columns created by n-n relationships. */ - if(prev_name!=name && (rel_type==RELATIONSHIP_11 || rel_type==RELATIONSHIP_1N)) + if(prev_name!=name && (rel_type==Relationship11 || rel_type==Relationship1n)) prev_ref_col_names[column_aux->getObjectId()]=column->getName(); recv_tab->addColumn(column); @@ -1523,7 +1647,7 @@ void Relationship::copyColumns(Table *ref_tab, Table *recv_tab, bool not_null, b prev_ref_col_names.clear(); pk_columns.clear(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1538,25 +1662,25 @@ void Relationship::addColumnsRel11(void) ref_tab=dynamic_cast
(this->getReferenceTable()); recv_tab=dynamic_cast
(this->getReceiverTable()); - if(this->upd_action!=ActionType::null) + if(this->upd_action!=ActionType::Null) upd_action=this->upd_action; else - upd_action=ActionType::cascade; + upd_action=ActionType::Cascade; - if(this->del_action!=ActionType::null) + if(this->del_action!=ActionType::Null) del_action=this->del_action; else { if(identifier) - del_action=ActionType::cascade; + del_action=ActionType::Cascade; else { //Case the reference table is mandatory participation set as RESTRICT the delete action on the foreign key - if((ref_tab==this->src_table && this->isTableMandatory(SRC_TABLE)) || - (ref_tab==this->dst_table && this->isTableMandatory(DST_TABLE))) - del_action=ActionType::restrict; + if((ref_tab==this->src_table && this->isTableMandatory(SrcTable)) || + (ref_tab==this->dst_table && this->isTableMandatory(DstTable))) + del_action=ActionType::Restrict; else - del_action=ActionType::set_null; + del_action=ActionType::SetNull; } } @@ -1570,19 +1694,19 @@ void Relationship::addColumnsRel11(void) } else { - copyColumns(ref_tab, recv_tab, (!identifier && (this->isTableMandatory(SRC_TABLE) || this->isTableMandatory(DST_TABLE)))); + copyColumns(ref_tab, recv_tab, (!identifier && (this->isTableMandatory(SrcTable) || this->isTableMandatory(DstTable)))); if(identifier) { /* When the relationship is identifier, the cardinalities are ignored because the strong entity always is of mandatory participation. */ - this->setMandatoryTable(DST_TABLE, false); - this->setMandatoryTable(SRC_TABLE, false); + this->setMandatoryTable(DstTable, false); + this->setMandatoryTable(SrcTable, false); if(ref_tab==this->src_table) - this->setMandatoryTable(SRC_TABLE, true); + this->setMandatoryTable(SrcTable, true); else - this->setMandatoryTable(DST_TABLE, true); + this->setMandatoryTable(DstTable, true); configureIndentifierRel(recv_tab); } @@ -1603,7 +1727,7 @@ void Relationship::addColumnsRel11(void) this->connected=true; this->disconnectRelationship(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1611,19 +1735,19 @@ void Relationship::addColumnsRel1n(void) { Table *ref_tab=nullptr, *recv_tab=nullptr; bool not_null=false; - ActionType del_action=ActionType::set_null, upd_action; + ActionType del_action=ActionType::SetNull, upd_action; try { recv_tab=dynamic_cast
(this->getReceiverTable()); ref_tab=dynamic_cast
(this->getReferenceTable()); - if(this->upd_action!=ActionType::null) + if(this->upd_action!=ActionType::Null) upd_action=this->upd_action; else - upd_action=ActionType::cascade; + upd_action=ActionType::Cascade; - if(this->del_action!=ActionType::null) + if(this->del_action!=ActionType::Null) del_action=this->del_action; else { @@ -1633,9 +1757,9 @@ void Relationship::addColumnsRel1n(void) if(!identifier && src_mandatory) { if(!deferrable) - del_action=ActionType::restrict; + del_action=ActionType::Restrict; else - del_action=ActionType::no_action; + del_action=ActionType::NoAction; } /* Case the relationship is identifier configures the ON DELETE anda ON UPDATE action @@ -1643,7 +1767,7 @@ void Relationship::addColumnsRel1n(void) entity also exists, this means if the strong entity tuple is removed the weak entity tuple is also removed */ else if(identifier) - del_action=ActionType::cascade; + del_action=ActionType::Cascade; } if(!identifier && src_mandatory) @@ -1662,8 +1786,8 @@ void Relationship::addColumnsRel1n(void) if(identifier) { - this->setMandatoryTable(SRC_TABLE, true); - this->setMandatoryTable(DST_TABLE, false); + this->setMandatoryTable(SrcTable, true); + this->setMandatoryTable(DstTable, false); configureIndentifierRel(recv_tab); } else @@ -1680,7 +1804,7 @@ void Relationship::addColumnsRel1n(void) this->connected=true; this->disconnectRelationship(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1690,8 +1814,8 @@ void Relationship::addColumnsRelNn(void) Table *tab=nullptr, *tab1=nullptr; Constraint *pk_tabnn=nullptr; bool src_not_null=false, dst_not_null=false; - ActionType src_del_act=ActionType::restrict, dst_del_act=ActionType::restrict, - src_upd_act=ActionType::cascade, dst_upd_act=ActionType::cascade; + ActionType src_del_act=ActionType::Restrict, dst_del_act=ActionType::Restrict, + src_upd_act=ActionType::Cascade, dst_upd_act=ActionType::Cascade; try @@ -1699,15 +1823,15 @@ void Relationship::addColumnsRelNn(void) tab=dynamic_cast
(src_table); tab1=dynamic_cast
(dst_table); - if(this->upd_action!=ActionType::null) + if(this->upd_action!=ActionType::Null) src_upd_act=dst_upd_act=this->upd_action; else - src_upd_act=dst_upd_act=ActionType::cascade; + src_upd_act=dst_upd_act=ActionType::Cascade; - if(this->del_action!=ActionType::null) + if(this->del_action!=ActionType::Null) src_del_act=dst_del_act=this->del_action; else - src_del_act=dst_del_act=ActionType::restrict; + src_del_act=dst_del_act=ActionType::Restrict; /* Copy the columns from the primary keys of the source and destination tables to the table that represents the n-n relationship */ @@ -1717,16 +1841,18 @@ void Relationship::addColumnsRelNn(void) if(single_pk_column) { pk_col=new Column; - pk_col->setName(generateObjectName(PK_COL_PATTERN)); - pk_col->setType(PgSQLType(QString("serial"))); + pk_col->setName(generateObjectName(PkColPattern)); + pk_col->setAlias(generateObjectName(PkColPattern, nullptr, true)); + pk_col->setType(PgSqlType(QString("serial"))); pk_col->setAddedByLinking(true); table_relnn->addColumn(pk_col); } //Creates the primary key for the n-n relationship table pk_tabnn=new Constraint; - pk_tabnn->setName(generateObjectName(PK_PATTERN)); - pk_tabnn->setConstraintType(ConstraintType::primary_key); + pk_tabnn->setName(generateObjectName(PkPattern)); + pk_tabnn->setAlias(generateObjectName(PkPattern, nullptr, true)); + pk_tabnn->setConstraintType(ConstraintType::PrimaryKey); pk_tabnn->setAddedByLinking(true); if(!single_pk_column) @@ -1734,12 +1860,12 @@ void Relationship::addColumnsRelNn(void) for(auto &col : gen_columns) { col->setNotNull(true); - pk_tabnn->addColumn(col, Constraint::SOURCE_COLS); + pk_tabnn->addColumn(col, Constraint::SourceCols); } } else { - pk_tabnn->addColumn(pk_col, Constraint::SOURCE_COLS); + pk_tabnn->addColumn(pk_col, Constraint::SourceCols); for(auto &col : gen_columns) col->setNotNull(true); @@ -1748,7 +1874,7 @@ void Relationship::addColumnsRelNn(void) for(unsigned i : column_ids_pk_rel) { if(i < rel_attributes.size()) - pk_tabnn->addColumn(dynamic_cast(rel_attributes[i]), Constraint::SOURCE_COLS); + pk_tabnn->addColumn(dynamic_cast(rel_attributes[i]), Constraint::SourceCols); } table_relnn->addConstraint(pk_tabnn); @@ -1768,7 +1894,7 @@ void Relationship::addColumnsRelNn(void) //Forcing the relationship as connected to perform the disconnection operations this->connected=true; this->disconnectRelationship(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1776,7 +1902,7 @@ Table *Relationship::getReferenceTable(void) { /* Many to Many relationships doesn't has only one reference table so is returned nullptr */ - if(rel_type==RELATIONSHIP_NN) + if(rel_type==RelationshipNn) return(nullptr); else { @@ -1789,7 +1915,7 @@ Table *Relationship::getReferenceTable(void) void Relationship::setSiglePKColumn(bool value) { - if(rel_type==RELATIONSHIP_NN) + if(rel_type==RelationshipNn) { single_pk_column=value; this->invalidated=(single_pk_column!=value); @@ -1803,7 +1929,7 @@ bool Relationship::isSiglePKColumn(void) Table *Relationship::getReceiverTable(void) { - if(rel_type==RELATIONSHIP_11) + if(rel_type==Relationship11) { /* Case 1: (0,1) ---<>--- (0,1) Case 2: (1,1) ---<>--- (0,1) */ @@ -1821,12 +1947,13 @@ Table *Relationship::getReceiverTable(void) } /* For 1-n relationships, the table order is unchagned this means that the columns are always included in the destination table */ - else if(rel_type==RELATIONSHIP_1N) + else if(rel_type==Relationship1n) return(dynamic_cast
(dst_table)); /* For generalization / copy relationships the columns are always added in the source table */ - else if(rel_type==RELATIONSHIP_GEN || - rel_type==RELATIONSHIP_DEP) + else if(rel_type==RelationshipGen || + rel_type==RelationshipDep || + rel_type==RelationshipPart) return(dynamic_cast
(src_table)); //For n-n relationships, the columns are added in the table that represents the relationship (table_relnn) else @@ -1874,7 +2001,7 @@ void Relationship::removeTableObjectsRefCols(Table *table) { constr=table->getConstraint(i); if(!constr->isAddedByRelationship() && - constr->getConstraintType()!=ConstraintType::primary_key && + constr->getConstraintType()!=ConstraintType::PrimaryKey && constr->isReferRelationshipAddedColumn()) { table->removeObject(constr); @@ -1899,18 +2026,18 @@ void Relationship::removeColumnsFromTablePK(Table *table) if(pk) { - count=pk->getColumnCount(Constraint::SOURCE_COLS); + count=pk->getColumnCount(Constraint::SourceCols); for(i=0; i < count; i++) { - column=pk->getColumn(i, Constraint::SOURCE_COLS); + column=pk->getColumn(i, Constraint::SourceCols); //Case the column was added by relationship and it belongs to the relationship if(column->isAddedByRelationship() && (isColumnExists(column) || getObjectIndex(column) >= 0)) { //Removes the column from primary key - pk->removeColumn(column->getName(), Constraint::SOURCE_COLS); + pk->removeColumn(column->getName(), Constraint::SourceCols); i--; count--; } } @@ -1929,13 +2056,13 @@ void Relationship::removeColumnFromTablePK(Table *table, Column *column) if(pk) { - count=pk->getColumnCount(Constraint::SOURCE_COLS); + count=pk->getColumnCount(Constraint::SourceCols); for(i=0; i < count; i++) { - if(column==pk->getColumn(i, Constraint::SOURCE_COLS)) + if(column==pk->getColumn(i, Constraint::SourceCols)) { - pk->removeColumn(column->getName(), Constraint::SOURCE_COLS); + pk->removeColumn(column->getName(), Constraint::SourceCols); break; } } @@ -1963,7 +2090,7 @@ void Relationship::disconnectRelationship(bool rem_tab_objs) vector::iterator itr_atrib, itr_atrib_end; TableObject *tab_obj=nullptr; - if(rel_type==RELATIONSHIP_GEN || rel_type==RELATIONSHIP_DEP) + if(rel_type==RelationshipGen || rel_type==RelationshipDep || rel_type== RelationshipPart) { table=getReceiverTable(); @@ -1974,12 +2101,16 @@ void Relationship::disconnectRelationship(bool rem_tab_objs) //Removes the special primary key if(table->getObjectIndex(pk_special) >= 0) + { table->removeObject(pk_special); - if(rel_type==RELATIONSHIP_GEN) - { - table->removeObject(getReferenceTable()); + // Restoring the original primary key of the table + if(pk_original) + table->addObject(pk_original); + } + if(rel_type==RelationshipGen || rel_type==RelationshipPart) + { while(!ck_constraints.empty()) { table->removeObject(ck_constraints.back()); @@ -1987,6 +2118,11 @@ void Relationship::disconnectRelationship(bool rem_tab_objs) ck_constraints.pop_back(); } } + + if(rel_type==RelationshipGen) + table->removeObject(getReferenceTable()); + else if(rel_type == RelationshipPart) + table->setPartionedTable(nullptr); else table->setCopyTable(nullptr); } @@ -1998,7 +2134,7 @@ void Relationship::disconnectRelationship(bool rem_tab_objs) /* In case of relationship 1-1 and 1-n is necessary remove the foreign key that represents the relationship furthermore columns added to primary key (in case of a identifier relationship) must be removed */ - if(fk_rel1n && (rel_type==RELATIONSHIP_11 || rel_type==RELATIONSHIP_1N)) + if(fk_rel1n && (rel_type==Relationship11 || rel_type==Relationship1n)) { table=getReceiverTable(); @@ -2052,9 +2188,15 @@ void Relationship::disconnectRelationship(bool rem_tab_objs) pk_relident=nullptr; } else if(pk_special && table->getObjectIndex(pk_special) >= 0) + { table->removeObject(pk_special); + + // Restoring the original primary key of the table + if(pk_original) + table->addObject(pk_original); + } } - else if(rel_type==RELATIONSHIP_NN) + else if(rel_type==RelationshipNn) { //In case of n-n relationship destroy the added constraints count=table_relnn->getConstraintCount(); @@ -2130,12 +2272,13 @@ void Relationship::disconnectRelationship(bool rem_tab_objs) table_relnn=nullptr; } + pk_original = nullptr; BaseRelationship::disconnectRelationship(); } } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -2172,7 +2315,7 @@ bool Relationship::hasIndentifierAttribute(void) /* A relationship is considered to own a identifier attribute when a primary key is found among the constraints */ - found=(constr->getConstraintType()==ConstraintType::primary_key); + found=(constr->getConstraintType()==ConstraintType::PrimaryKey); itr++; } @@ -2190,7 +2333,7 @@ bool Relationship::isInvalidated(void) Table *table=nullptr, *table1=nullptr; Constraint *fk=nullptr, *fk1=nullptr, *constr=nullptr, *pk=nullptr; bool valid=false; - Column *rel_pk_col=nullptr, *gen_col=nullptr, *pk_col=nullptr; + Column *rel_pk_col=nullptr, *gen_col=nullptr, *col_aux=nullptr, *col_aux1 = nullptr, *pk_col=nullptr; QString col_name; if(invalidated) @@ -2210,7 +2353,7 @@ bool Relationship::isInvalidated(void) { /* Checking if the tables were renamed. For 1:1, 1:n and n:n this situation may cause the renaming of all generated objects */ - if((rel_type==RELATIONSHIP_11 || rel_type==RELATIONSHIP_1N || rel_type==RELATIONSHIP_NN) && + if((rel_type==Relationship11 || rel_type==Relationship1n || rel_type==RelationshipNn) && (src_tab_prev_name!=src_table->getName() || dst_tab_prev_name!=dst_table->getName())) return(true); @@ -2218,12 +2361,12 @@ bool Relationship::isInvalidated(void) invalidation of the relationship is based on the comparison of amount of foreign key columns and the number of columns of primary key from the source table */ - if(rel_type==RELATIONSHIP_11 || rel_type==RELATIONSHIP_1N) + if(rel_type==Relationship11 || rel_type==Relationship1n) { table=getReferenceTable(); //Gets the source columns from the foreign key that represents the relationship - rel_cols_count=fk_rel1n->getColumnCount(Constraint::SOURCE_COLS); + rel_cols_count=fk_rel1n->getColumnCount(Constraint::SourceCols); //The relationship is invalidated if the reference table doesn't has a primary key pk=table->getPrimaryKey(); @@ -2231,7 +2374,7 @@ bool Relationship::isInvalidated(void) if(pk) { //Gets the amount of columns from the primary key - tab_cols_count=pk->getColumnCount(Constraint::SOURCE_COLS); + tab_cols_count=pk->getColumnCount(Constraint::SourceCols); //Compares the column quantity valid=(rel_cols_count==tab_cols_count); @@ -2247,7 +2390,7 @@ bool Relationship::isInvalidated(void) /* This third columns is get from the table primary key and will be checked if the columns addresses is the same. If not the relationship is invalidated */ - pk_col=pk->getColumn(i, Constraint::SOURCE_COLS); + pk_col=pk->getColumn(i, Constraint::SourceCols); /* To validate the columns with each other the following rules are followed: @@ -2260,11 +2403,10 @@ bool Relationship::isInvalidated(void) 3) Check if the column (address) from the vector pk_columns is equal to the column obtained directly from the primary key */ - col_name=generateObjectName(SRC_COL_PATTERN, rel_pk_col); + col_name=generateObjectName(SrcColPattern, rel_pk_col); valid=(rel_pk_col==pk_col && - (gen_col->getName()==col_name || - gen_col->getName().contains(pk_col->getName())) && - (rel_pk_col->getType()==gen_col->getType() || + (gen_col->getName()==col_name ||gen_col->getName().contains(pk_col->getName())) && + (rel_pk_col->getType()==gen_col->getType() || (rel_pk_col->getType()==QString("serial") && gen_col->getType()==QString("integer")) || (rel_pk_col->getType()==QString("bigserial") && gen_col->getType()==QString("bigint")) || (rel_pk_col->getType()==QString("smallserial") && gen_col->getType()==QString("smallint")))); @@ -2274,8 +2416,7 @@ bool Relationship::isInvalidated(void) /* For copy / generalization relationships, is obtained the number of columns created when connecting it and comparing with the number of columns of the source table */ - else if(rel_type==RELATIONSHIP_DEP || - rel_type==RELATIONSHIP_GEN) + else if(rel_type==RelationshipDep || rel_type==RelationshipGen || rel_type==RelationshipPart) { table=getReferenceTable(); table1=getReceiverTable(); @@ -2291,23 +2432,49 @@ bool Relationship::isInvalidated(void) valid=(rel_cols_count == tab_cols_count); /* Checking if the columns created with inheritance / copy still exist - in reference table */ + in reference table, and their types are compatible */ for(i=0; i < gen_columns.size() && valid; i++) - valid=table->getColumn(gen_columns[i]->getName(true)); + { + gen_col = gen_columns[i]; + col_aux = table->getColumn(gen_col->getName(true)); + valid = col_aux && (col_aux->getType().isEquivalentTo(gen_col->getType()) || + col_aux->getType().getAliasType().isEquivalentTo(gen_col->getType())); + } + + // Specific for partition relatoinship: check if all the columns on the source table (partition) exist on the partitioned table + if(rel_type==RelationshipPart) + { + count = table1->getColumnCount(); + valid = table->isPartitioned(); + + for(i=0; i < count && valid; i++) + { + col_aux1 = table1->getColumn(i); + col_aux = table->getColumn(col_aux1->getName(true)); + valid = col_aux && col_aux1 && (col_aux->getType().isEquivalentTo(col_aux1->getType()) || + col_aux->getType().getAliasType().isEquivalentTo(col_aux1->getType())); + } + } /* Checking if the reference table columns are in the receiver table. In theory all columns must exist in the two table because one inherits another soon they will possess all the same columns. if this not happen indicates that a reference table column was renamed */ for(i=0; i < tab_cols_count && valid; i++) - valid=table1->getColumn(table->getColumn(i)->getName(true)); + { + col_aux = table->getColumn(i); + col_aux1 = table1->getColumn(col_aux->getName(true)); + valid = col_aux && col_aux1 && (col_aux->getType().isEquivalentTo(col_aux1->getType()) || + col_aux->getType().getAliasType().isEquivalentTo(col_aux1->getType())); + } //Checking if the check constraints were not renamed in the parent table for(i=0; i < ck_constraints.size() && valid; i++) { constr=table->getConstraint(ck_constraints[i]->getName(true)); - valid=(constr && !constr->isNoInherit() && constr->getConstraintType()==ConstraintType::check); + valid=(constr && !constr->isNoInherit() && constr->getConstraintType()==ConstraintType::Check); } + } /* For n-n relationships, it is necessary the comparisons: @@ -2319,7 +2486,7 @@ bool Relationship::isInvalidated(void) 2) It is necessary to validate if the names of the table columns generated matches the column names of the originating tables */ - else if(rel_type==RELATIONSHIP_NN) + else if(rel_type==RelationshipNn) { table=dynamic_cast
(src_table); table1=dynamic_cast
(dst_table); @@ -2332,7 +2499,7 @@ bool Relationship::isInvalidated(void) for(i=0; i < count; i++) { constr=table_relnn->getConstraint(i); - if(constr->getConstraintType()==ConstraintType::foreign_key) + if(constr->getConstraintType()==ConstraintType::ForeignKey) { if(!fk && constr->getReferencedTable()==table) fk=constr; @@ -2343,38 +2510,36 @@ bool Relationship::isInvalidated(void) /* The number of columns of relationship is calculated by summing quantities of foreign key columns obtained */ - rel_cols_count=fk->getColumnCount(Constraint::REFERENCED_COLS) + fk1->getColumnCount(Constraint::REFERENCED_COLS); + rel_cols_count=fk->getColumnCount(Constraint::ReferencedCols) + fk1->getColumnCount(Constraint::ReferencedCols); /* The number of columns in the table is obtained by summing the amount of primary keys columns involved in the relationship */ - tab_cols_count=table->getPrimaryKey()->getColumnCount(Constraint::SOURCE_COLS) + - table1->getPrimaryKey()->getColumnCount(Constraint::SOURCE_COLS); + tab_cols_count=table->getPrimaryKey()->getColumnCount(Constraint::SourceCols) + + table1->getPrimaryKey()->getColumnCount(Constraint::SourceCols); valid=(rel_cols_count == tab_cols_count); - /* Checking if the columns created with the connection still exists - in reference table */ - count=fk->getColumnCount(Constraint::SOURCE_COLS); + // Checking if the columns created with the connection still exists in reference table + count=fk->getColumnCount(Constraint::SourceCols); pk=table->getPrimaryKey(); for(i=0; i < count && valid; i++) { - gen_col=fk->getColumn(i, Constraint::SOURCE_COLS); - pk_col=pk->getColumn(i, Constraint::SOURCE_COLS); - valid=(gen_col->getName()==generateObjectName(SRC_COL_PATTERN, pk_col) || - gen_col->getName().contains(pk_col->getName())); + gen_col=fk->getColumn(i, Constraint::SourceCols); + pk_col=pk->getColumn(i, Constraint::SourceCols); + valid=(gen_col->getName()==generateObjectName(SrcColPattern, pk_col) || + gen_col->getName().contains(pk_col->getName())); } - /* Checking if the columns created with the connection still exists - in receiver table */ - count=fk1->getColumnCount(Constraint::SOURCE_COLS); + // Checking if the columns created with the connection still exists in receiver table + count=fk1->getColumnCount(Constraint::SourceCols); pk=table1->getPrimaryKey(); for(i=0; i < count && valid; i++) { - gen_col=fk1->getColumn(i, Constraint::SOURCE_COLS); - pk_col=pk->getColumn(i, Constraint::SOURCE_COLS); - valid=(gen_col->getName()==generateObjectName(DST_COL_PATTERN, pk_col) || + gen_col=fk1->getColumn(i, Constraint::SourceCols); + pk_col=pk->getColumn(i, Constraint::SourceCols); + valid=(gen_col->getName()==generateObjectName(DstColPattern, pk_col) || gen_col->getName().contains(pk_col->getName())); } } @@ -2390,50 +2555,50 @@ QString Relationship::getCodeDefinition(unsigned def_type) QString code_def=getCachedCode(def_type); if(!code_def.isEmpty()) return(code_def); - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) { - if(fk_rel1n && (rel_type==RELATIONSHIP_11 || rel_type==RELATIONSHIP_1N)) + if(fk_rel1n && (rel_type==Relationship11 || rel_type==Relationship1n)) { unsigned count, i; - attributes[ParsersAttributes::RELATIONSHIP_1N]=ParsersAttributes::_TRUE_; - attributes[ParsersAttributes::CONSTRAINTS]=fk_rel1n->getCodeDefinition(def_type); + attributes[Attributes::Relationship1n]=Attributes::True; + attributes[Attributes::Constraints]=fk_rel1n->getCodeDefinition(def_type); if(uq_rel11) - attributes[ParsersAttributes::CONSTRAINTS]+=uq_rel11->getCodeDefinition(def_type); + attributes[Attributes::Constraints]+=uq_rel11->getCodeDefinition(def_type); count=rel_constraints.size(); for(i=0; i < count; i++) { - if(dynamic_cast(rel_constraints[i])->getConstraintType()!=ConstraintType::primary_key) - attributes[ParsersAttributes::CONSTRAINTS]+=dynamic_cast(rel_constraints[i])->getCodeDefinition(def_type, false); + if(dynamic_cast(rel_constraints[i])->getConstraintType()!=ConstraintType::PrimaryKey) + attributes[Attributes::Constraints]+=dynamic_cast(rel_constraints[i])->getCodeDefinition(def_type, false); } - attributes[ParsersAttributes::TABLE]=getReceiverTable()->getName(true); + attributes[Attributes::Table]=getReceiverTable()->getName(true); } - else if(table_relnn && rel_type==RELATIONSHIP_NN) + else if(table_relnn && rel_type==RelationshipNn) { unsigned count, i; - attributes[ParsersAttributes::RELATIONSHIP_NN]=ParsersAttributes::_TRUE_; - attributes[ParsersAttributes::TABLE]=table_relnn->getCodeDefinition(def_type); + attributes[Attributes::RelationshipNn]=Attributes::True; + attributes[Attributes::Table]=table_relnn->getCodeDefinition(def_type); count=table_relnn->getConstraintCount(); for(i=0; i < count; i++) { - if(table_relnn->getConstraint(i)->getConstraintType()!=ConstraintType::primary_key && - table_relnn->getConstraint(i)->getConstraintType()!=ConstraintType::check) - attributes[ParsersAttributes::CONSTRAINTS]+=table_relnn->getConstraint(i)->getCodeDefinition(def_type, true); + if(table_relnn->getConstraint(i)->getConstraintType()!=ConstraintType::PrimaryKey && + table_relnn->getConstraint(i)->getConstraintType()!=ConstraintType::Check) + attributes[Attributes::Constraints]+=table_relnn->getConstraint(i)->getCodeDefinition(def_type, true); } } - else if(rel_type==RELATIONSHIP_GEN) + else if(rel_type==RelationshipGen) { - attributes[ParsersAttributes::RELATIONSHIP_GEN]=ParsersAttributes::_TRUE_; - attributes[ParsersAttributes::TABLE]=getReceiverTable()->getName(true); + attributes[Attributes::RelationshipGen]=Attributes::True; + attributes[Attributes::Table]=getReceiverTable()->getName(true); } - return(this->BaseObject::__getCodeDefinition(SchemaParser::SQL_DEFINITION)); + return(this->BaseObject::__getCodeDefinition(SchemaParser::SqlDefinition)); } else { @@ -2441,40 +2606,50 @@ QString Relationship::getCodeDefinition(unsigned def_type) bool reduced_form; setRelationshipAttributes(); - attributes[ParsersAttributes::IDENTIFIER]=(identifier ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::SINGLE_PK_COLUMN]=(single_pk_column ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::DEFERRABLE]=(deferrable ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::DEFER_TYPE]=~deferral_type; - attributes[ParsersAttributes::UPD_ACTION]=~upd_action; - attributes[ParsersAttributes::DEL_ACTION]=~del_action; - - attributes[ParsersAttributes::TABLE_NAME]=tab_name_relnn; - attributes[ParsersAttributes::RELATIONSHIP_GEN]=(rel_type==RELATIONSHIP_GEN ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::RELATIONSHIP_DEP]=(rel_type==RELATIONSHIP_DEP ? ParsersAttributes::_TRUE_ : QString()); - - attributes[ParsersAttributes::SRC_COL_PATTERN]=name_patterns[SRC_COL_PATTERN]; - attributes[ParsersAttributes::DST_COL_PATTERN]=name_patterns[DST_COL_PATTERN]; - attributes[ParsersAttributes::PK_PATTERN]=name_patterns[PK_PATTERN]; - attributes[ParsersAttributes::UQ_PATTERN]=name_patterns[UQ_PATTERN]; - attributes[ParsersAttributes::SRC_FK_PATTERN]=name_patterns[SRC_FK_PATTERN]; - attributes[ParsersAttributes::DST_FK_PATTERN]=name_patterns[DST_FK_PATTERN]; - attributes[ParsersAttributes::PK_COL_PATTERN]=name_patterns[PK_COL_PATTERN]; - - attributes[ParsersAttributes::COLUMNS]=QString(); + attributes[Attributes::Identifier]=(identifier ? Attributes::True : QString()); + attributes[Attributes::SinglePkColumn]=(single_pk_column ? Attributes::True : QString()); + attributes[Attributes::Deferrable]=(deferrable ? Attributes::True : QString()); + attributes[Attributes::DeferType]=~deferral_type; + attributes[Attributes::UpdAction]=~upd_action; + attributes[Attributes::DelAction]=~del_action; + + attributes[Attributes::TableName]=tab_name_relnn; + attributes[Attributes::RelationshipGen]=(rel_type==RelationshipGen ? Attributes::True : QString()); + attributes[Attributes::RelationshipDep]=(rel_type==RelationshipDep ? Attributes::True : QString()); + attributes[Attributes::RelationshipPart]=(rel_type==RelationshipPart ? Attributes::True : QString()); + + attributes[Attributes::SrcColPattern]=name_patterns[SrcColPattern]; + attributes[Attributes::DstColPattern]=name_patterns[DstColPattern]; + attributes[Attributes::PkPattern]=name_patterns[PkPattern]; + attributes[Attributes::UqPattern]=name_patterns[UqPattern]; + attributes[Attributes::SrcFkPattern]=name_patterns[SrcFkPattern]; + attributes[Attributes::DstFkPattern]=name_patterns[DstFkPattern]; + attributes[Attributes::PkColPattern]=name_patterns[PkColPattern]; + + attributes[Attributes::PartitionBoundExpr]=part_bounding_expr; + + attributes[Attributes::Columns]=QString(); count=rel_attributes.size(); for(i=0; i < count; i++) { - attributes[ParsersAttributes::COLUMNS]+=dynamic_cast(rel_attributes[i])-> - getCodeDefinition(SchemaParser::XML_DEFINITION); + attributes[Attributes::Columns]+=dynamic_cast(rel_attributes[i])-> + getCodeDefinition(SchemaParser::XmlDefinition); } - attributes[ParsersAttributes::CONSTRAINTS]=QString(); + attributes[Attributes::Constraints]=QString(); count=rel_constraints.size(); for(i=0; i < count; i++) { if(!rel_constraints[i]->isProtected()) - attributes[ParsersAttributes::CONSTRAINTS]+=dynamic_cast(rel_constraints[i])-> - getCodeDefinition(SchemaParser::XML_DEFINITION, true); + attributes[Attributes::Constraints]+=dynamic_cast(rel_constraints[i])-> + getCodeDefinition(SchemaParser::XmlDefinition, true); + } + + if(pk_original) + { + pk_original->setParentTable(getReceiverTable()); + attributes[Attributes::OriginalPk]=pk_original->getCodeDefinition(SchemaParser::XmlDefinition); + pk_original->setParentTable(nullptr); } count=column_ids_pk_rel.size(); @@ -2482,28 +2657,28 @@ QString Relationship::getCodeDefinition(unsigned def_type) { if(!gen_columns.empty() && i < gen_columns.size()) { - attributes[ParsersAttributes::SPECIAL_PK_COLS]+=QString("%1").arg(column_ids_pk_rel[i]); - if(i < count-1) attributes[ParsersAttributes::SPECIAL_PK_COLS]+=","; + attributes[Attributes::SpecialPkCols]+=QString("%1").arg(column_ids_pk_rel[i]); + if(i < count-1) attributes[Attributes::SpecialPkCols]+=","; } } if(copy_options.getCopyMode()!=0) { - attributes[ParsersAttributes::COPY_OPTIONS]=QString("%1").arg(copy_options.getCopyOptionsIds()); - attributes[ParsersAttributes::COPY_MODE]=QString("%1").arg(copy_options.getCopyMode());; + attributes[Attributes::CopyOptions]=QString("%1").arg(copy_options.getCopyOptionsIds()); + attributes[Attributes::CopyMode]=QString("%1").arg(copy_options.getCopyMode()); } - reduced_form=(attributes[ParsersAttributes::COLUMNS].isEmpty() && - attributes[ParsersAttributes::CONSTRAINTS].isEmpty() && - attributes[ParsersAttributes::POINTS].isEmpty() && - attributes[ParsersAttributes::SPECIAL_PK_COLS].isEmpty() && - attributes[ParsersAttributes::POINTS].isEmpty() && - attributes[ParsersAttributes::LABELS_POS].isEmpty()); + reduced_form=(attributes[Attributes::Columns].isEmpty() && + attributes[Attributes::Constraints].isEmpty() && + attributes[Attributes::Points].isEmpty() && + attributes[Attributes::SpecialPkCols].isEmpty() && + attributes[Attributes::Points].isEmpty() && + attributes[Attributes::LabelsPos].isEmpty()); if(!reduced_form) cached_reduced_code.clear(); - return(this->BaseObject::getCodeDefinition(SchemaParser::XML_DEFINITION, reduced_form)); + return(this->BaseObject::getCodeDefinition(SchemaParser::XmlDefinition, reduced_form)); } } @@ -2530,14 +2705,30 @@ void Relationship::operator = (Relationship &rel) this->single_pk_column=rel.single_pk_column; } -QString Relationship::getInheritDefinition(bool undo_inherit) +QString Relationship::getAlterRelationshipDefinition(bool undo_inh_part) { - if(rel_type!=RELATIONSHIP_GEN) + if(rel_type != RelationshipGen && rel_type != RelationshipPart) return(QString()); - attributes[ParsersAttributes::INHERIT]=(undo_inherit ? ParsersAttributes::UNSET : ParsersAttributes::_TRUE_); - attributes[ParsersAttributes::TABLE]=getReceiverTable()->getName(true); - attributes[ParsersAttributes::ANCESTOR_TABLE]=getReferenceTable()->getName(true); + attributes[Attributes::Inherit]=QString(); + attributes[Attributes::AncestorTable]=QString(); + attributes[Attributes::PartitionedTable]=QString(); + attributes[Attributes::PartitionBoundExpr]=QString(); + attributes[Attributes::Partitioning]=QString(); + + if(rel_type == RelationshipGen) + { + attributes[Attributes::Inherit]=(undo_inh_part ? Attributes::Unset : Attributes::True); + attributes[Attributes::Table]=getReceiverTable()->getName(true); + attributes[Attributes::AncestorTable]=getReferenceTable()->getName(true); + } + else + { + attributes[Attributes::Partitioning]=(undo_inh_part ? Attributes::Unset : Attributes::True); + attributes[Attributes::Table]=getReceiverTable()->getName(true); + attributes[Attributes::PartitionedTable]=getReferenceTable()->getName(true); + attributes[Attributes::PartitionBoundExpr]=getReceiverTable()->getPartitionBoundingExpr(); + } return(BaseObject::getAlterDefinition(this->getSchemaName(), attributes)); } @@ -2545,18 +2736,18 @@ QString Relationship::getInheritDefinition(bool undo_inherit) bool Relationship::isReferenceTableMandatory(void) { - if(rel_type == BaseRelationship::RELATIONSHIP_11 && getReferenceTable() == dst_table && !src_mandatory) + if(rel_type == BaseRelationship::Relationship11 && getReferenceTable() == dst_table && !src_mandatory) return(dst_mandatory); else - return((getReferenceTable() == src_table && isTableMandatory(SRC_TABLE)) || - (getReferenceTable() == dst_table && isTableMandatory(DST_TABLE))); + return((getReferenceTable() == src_table && isTableMandatory(SrcTable)) || + (getReferenceTable() == dst_table && isTableMandatory(DstTable))); } bool Relationship::isReceiverTableMandatory(void) { - if(rel_type == BaseRelationship::RELATIONSHIP_11 && getReferenceTable() == dst_table && !src_mandatory) + if(rel_type == BaseRelationship::Relationship11 && getReferenceTable() == dst_table && !src_mandatory) return(false); else - return((getReceiverTable() == src_table && isTableMandatory(SRC_TABLE)) || - (getReceiverTable() == dst_table && isTableMandatory(DST_TABLE))); + return((getReceiverTable() == src_table && isTableMandatory(SrcTable)) || + (getReceiverTable() == dst_table && isTableMandatory(DstTable))); } diff --git a/libpgmodeler/src/relationship.h b/libpgmodeler/src/relationship.h index 86d56a5528..4e776b5495 100644 --- a/libpgmodeler/src/relationship.h +++ b/libpgmodeler/src/relationship.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -172,6 +172,8 @@ class Relationship: public BaseRelationship { to generalization / copy relationships */ *pk_special, + *pk_original, + //! \brief Stores the unique key that represents the 1-1 relationship (including the fk_rel1n) *uq_rel11; @@ -206,6 +208,9 @@ class Relationship: public BaseRelationship { src_tab_prev_name, dst_tab_prev_name; + //! \brief The partition bounding expression + QString part_bounding_expr; + //! \brief Indicates if the column exists on the referenced column list bool isColumnExists(Column *column); @@ -221,12 +226,12 @@ class Relationship: public BaseRelationship { /*! \brief Copy columns from one table to another. This operation is done in relationships of type copy / generalization. It is necessary to check duplicate names and incompatible types of columns */ - void addColumnsRelGen(void); + void addColumnsRelGenPart(void); /*! \brief Copy constraints from the parent table to the child. Currently, only check constraints are copied only if the NO INHERIT attribute is not set and there are no conflicting constraints (name or expression) on the child table */ - void addConstraintsRelGen(void); + void addConstraintsRelGenPart(void); /*! \brief Creates the foreign key that represents the relationship and adds it to the receiver table. Must be specified the actions ON DELETE and UPDATE. */ @@ -268,7 +273,9 @@ class Relationship: public BaseRelationship { void removeColumnFromTablePK(Table *table, Column *column); //! \brief Generates the object name according to the specified name pattern - QString generateObjectName(unsigned pat_id, Column *id_col=nullptr); + QString generateObjectName(unsigned pat_id, Column *id_col=nullptr, bool use_alias=false); + + void setOriginalPrimaryKey(Constraint *pk); protected: //! \brief Destroy all the relationship attributes and constraints @@ -287,20 +294,20 @@ class Relationship: public BaseRelationship { public: //! \brief String used as the name suffix separator. Default '_' - static const QString SUFFIX_SEPARATOR, - SRC_TAB_TOKEN, //{st} - DST_TAB_TOKEN, //{dt} - GEN_TAB_TOKEN, //{gt} - SRC_COL_TOKEN; //{sc} + static const QString SuffixSeparator, + SrcTabToken, //{st} + DstTabToken, //{dt} + GenTabToken, //{gt} + SrcColToken; //{sc} //! \brief Patterns ids - static const unsigned SRC_COL_PATTERN, - DST_COL_PATTERN, - PK_PATTERN, - UQ_PATTERN, - SRC_FK_PATTERN, - DST_FK_PATTERN, - PK_COL_PATTERN; + static constexpr unsigned SrcColPattern=0, + DstColPattern=1, + PkPattern=2, + UqPattern=3, + SrcFkPattern=4, + DstFkPattern=5, + PkColPattern=6; Relationship(Relationship *rel); @@ -308,9 +315,9 @@ class Relationship: public BaseRelationship { Table *src_tab, Table *dst_tab, bool src_mdtry=false, bool dst_mdtry=false, bool identifier=false, bool deferrable=false, - DeferralType deferral_type=DeferralType::immediate, - ActionType fk_del_act=ActionType::null, - ActionType fk_upd_act=ActionType::null, + DeferralType deferral_type=DeferralType::Immediate, + ActionType fk_del_act=ActionType::Null, + ActionType fk_upd_act=ActionType::Null, CopyOptions copy_op = CopyOptions(0,0)); //! \brief Connects the relationship making the configuration according to its type @@ -347,6 +354,13 @@ class Relationship: public BaseRelationship { //! \brief Returns the name of the table auto generated by the n-n relationship QString getTableNameRelNN(void); + /*! \brief Defines the partition bounding expression associated to the partition table (receiver table) + * when the relationship is connected (only for partitioning relationship) */ + void setPartitionBoundingExpr(const QString &part_bound_expr); + + //! \brief Returns the partition bouding expression configured for the relationship (only for partitioning relationship) + QString getPartitionBoundingExpr(void); + //! \brief Defines if the created foreign key is deferrable (only for 1-1, 1-n relationships) void setDeferrable(bool value); @@ -357,7 +371,7 @@ class Relationship: public BaseRelationship { void setDeferralType(DeferralType defer_type); /*! \brief Defines the type of action for generated foreign keys (ON DELETE and ON UPDATE) - User must use Constraint::[DELETE_ACTION|UPDATE_ACTION] (only for 1-1, 1-n relationships) */ + User must use Constraint::[DELETE_ACTION|UPDATE_ACTION] (only for 1-1, 1-n relationships) */ void setActionType(ActionType act_type, unsigned act_id); //! \brief Returns the deferral tyep for the created foreign key (only for 1-1, 1-n relationships) @@ -474,6 +488,7 @@ class Relationship: public BaseRelationship { Table *getReferenceTable(void); void setSiglePKColumn(bool value); + bool isSiglePKColumn(void); //! \brief Returns SQL / XML definition for the relationship. @@ -482,7 +497,7 @@ class Relationship: public BaseRelationship { //! \brief Copies the attributes from one relationship to another void operator = (Relationship &rel); - QString getInheritDefinition(bool undo_inherit); + QString getAlterRelationshipDefinition(bool undo_inh_part); //! \brief Returns true when the reference table is mandatory in the relationship bool isReferenceTableMandatory(void); diff --git a/libpgmodeler/src/role.cpp b/libpgmodeler/src/role.cpp index 982ee2ca23..c6e18bb05a 100644 --- a/libpgmodeler/src/role.cpp +++ b/libpgmodeler/src/role.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -22,36 +22,36 @@ unsigned Role::role_id=0; Role::Role(void) { - obj_type=OBJ_ROLE; + obj_type=ObjectType::Role; object_id=Role::role_id++; - for(unsigned i=0; i <= OP_BYPASSRLS; i++) + for(unsigned i=0; i <= OpBypassRls; i++) options[i]=false; conn_limit=-1; - attributes[ParsersAttributes::SUPERUSER]=QString(); - attributes[ParsersAttributes::CREATEDB]=QString(); - attributes[ParsersAttributes::CREATEROLE]=QString(); - attributes[ParsersAttributes::INHERIT]=QString(); - attributes[ParsersAttributes::LOGIN]=QString(); - attributes[ParsersAttributes::CONN_LIMIT]=QString(); - attributes[ParsersAttributes::PASSWORD]=QString(); - attributes[ParsersAttributes::ENCRYPTED]=QString(); - attributes[ParsersAttributes::VALIDITY]=QString(); - attributes[ParsersAttributes::REF_ROLES]=QString(); - attributes[ParsersAttributes::MEMBER_ROLES]=QString(); - attributes[ParsersAttributes::ADMIN_ROLES]=QString(); - attributes[ParsersAttributes::REPLICATION]=QString(); - attributes[ParsersAttributes::GROUP]=QString(); - attributes[ParsersAttributes::BYPASSRLS]=QString(); + attributes[Attributes::Superuser]=QString(); + attributes[Attributes::CreateDb]=QString(); + attributes[Attributes::CreateRole]=QString(); + attributes[Attributes::Inherit]=QString(); + attributes[Attributes::Login]=QString(); + attributes[Attributes::ConnLimit]=QString(); + attributes[Attributes::Password]=QString(); + attributes[Attributes::Encrypted]=QString(); + attributes[Attributes::Validity]=QString(); + attributes[Attributes::RefRoles]=QString(); + attributes[Attributes::MemberRoles]=QString(); + attributes[Attributes::AdminRoles]=QString(); + attributes[Attributes::Replication]=QString(); + attributes[Attributes::Group]=QString(); + attributes[Attributes::BypassRls]=QString(); } void Role::setOption(unsigned op_type, bool value) { - if(op_type > OP_BYPASSRLS) + if(op_type > OpBypassRls) //Raises an error if the option type is invalid - throw Exception(ERR_ASG_VAL_INV_ROLE_OPT_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgValueInvalidRoleOptionType,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(options[op_type] != value); options[op_type]=value; @@ -61,36 +61,36 @@ void Role::addRole(unsigned role_type, Role *role) { //Raises an error if the role to be added is not allocated if(!role) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the role to be added is the 'this' role else if(role && this==role) - throw Exception(Exception::getErrorMessage(ERR_ROLE_MEMBER_ITSELF) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgRoleMemberItself) .arg(role->getName()), - ERR_ROLE_MEMBER_ITSELF,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgRoleMemberItself,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { bool role_ref, role_mem, role_adm, role_ref1, role_mem1, role_adm1; //Check if the role to be added already exists in one of the internal role list - role_ref=this->isRoleExists(REF_ROLE, role); - role_mem=this->isRoleExists(MEMBER_ROLE, role); - role_adm=this->isRoleExists(ADMIN_ROLE, role); + role_ref=this->isRoleExists(RefRole, role); + role_mem=this->isRoleExists(MemberRole, role); + role_adm=this->isRoleExists(AdminRole, role); /* Check if the role 'this' is referenced in one of the internal role list of the role to be added */ - role_ref1=role->isRoleExists(REF_ROLE, this); - role_mem1=role->isRoleExists(MEMBER_ROLE, this); - role_adm1=role->isRoleExists(ADMIN_ROLE, this); + role_ref1=role->isRoleExists(RefRole, this); + role_mem1=role->isRoleExists(MemberRole, this); + role_adm1=role->isRoleExists(AdminRole, this); //Raises an error if the role already exists in one of the internal list - if((role_type==REF_ROLE && role_ref) || - (role_type==MEMBER_ROLE && (role_mem || role_adm)) || - (role_type==ADMIN_ROLE && (role_adm || role_mem))) - throw Exception(Exception::getErrorMessage(ERR_INS_DUPLIC_ROLE) + if((role_type==RefRole && role_ref) || + (role_type==MemberRole && (role_mem || role_adm)) || + (role_type==AdminRole && (role_adm || role_mem))) + throw Exception(Exception::getErrorMessage(ErrorCode::InsDuplicatedRole) .arg(role->getName()) .arg(this->getName()), - ERR_INS_DUPLIC_ROLE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InsDuplicatedRole,__PRETTY_FUNCTION__,__FILE__,__LINE__); /* Checking for redundant reference between roles. A redundant reference can happen when: @@ -114,20 +114,20 @@ void Role::addRole(unsigned role_type, Role *role) 5) The role 'role' (from parameter) is already part of the 'ref_roles' list of role 'this' and the user try to add the object 'role' as an element of the 'member_roles' list of the role 'this' */ - else if((role_type==REF_ROLE && ((role_mem || role_adm) || role_ref1)) || - (role_type==MEMBER_ROLE && ((role_mem1 || role_adm1) || role_ref)) || - (role_type==ADMIN_ROLE && ((role_mem1 || role_adm1) || role_ref))) - throw Exception(Exception::getErrorMessage(ERR_ROLE_REF_REDUNDANCY) + else if((role_type==RefRole && ((role_mem || role_adm) || role_ref1)) || + (role_type==MemberRole && ((role_mem1 || role_adm1) || role_ref)) || + (role_type==AdminRole && ((role_mem1 || role_adm1) || role_ref))) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgRoleReferenceRedundancy) .arg(this->getName()) .arg(role->getName()), - ERR_ROLE_REF_REDUNDANCY,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgRoleReferenceRedundancy,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { switch(role_type) { - case MEMBER_ROLE: member_roles.push_back(role); break; - case ADMIN_ROLE: admin_roles.push_back(role); break; - case REF_ROLE: + case MemberRole: member_roles.push_back(role); break; + case AdminRole: admin_roles.push_back(role); break; + case RefRole: default: ref_roles.push_back(role); break; @@ -164,18 +164,18 @@ void Role::setRoleAttribute(unsigned role_type) switch(role_type) { - case MEMBER_ROLE: + case MemberRole: roles_vect=&member_roles; - attrib=ParsersAttributes::MEMBER_ROLES; + attrib=Attributes::MemberRoles; break; - case ADMIN_ROLE: + case AdminRole: roles_vect=&admin_roles; - attrib=ParsersAttributes::ADMIN_ROLES; + attrib=Attributes::AdminRoles; break; - case REF_ROLE: + case RefRole: default: roles_vect=&ref_roles; - attrib=ParsersAttributes::REF_ROLES; + attrib=Attributes::RefRoles; break; } @@ -196,17 +196,17 @@ void Role::removeRole(unsigned role_type, unsigned role_idx) switch(role_type) { - case REF_ROLE: list=&ref_roles; break; - case MEMBER_ROLE: list=&member_roles; break; - case ADMIN_ROLE: list=&admin_roles; break; + case RefRole: list=&ref_roles; break; + case MemberRole: list=&member_roles; break; + case AdminRole: list=&admin_roles; break; default: //Raises an error if the role type is invalid - throw Exception(ERR_REF_INV_ROLE_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefInvalidRoleType,__PRETTY_FUNCTION__,__FILE__,__LINE__); break; } if(role_idx >= list->size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); itr=list->begin() + role_idx; list->erase(itr); @@ -219,12 +219,12 @@ void Role::removeRoles(unsigned role_type) switch(role_type) { - case REF_ROLE: list=&ref_roles; break; - case MEMBER_ROLE: list=&member_roles; break; - case ADMIN_ROLE: list=&admin_roles; break; + case RefRole: list=&ref_roles; break; + case MemberRole: list=&member_roles; break; + case AdminRole: list=&admin_roles; break; default: //Raises an error if the role type is invalid - throw Exception(ERR_REF_INV_ROLE_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefInvalidRoleType,__PRETTY_FUNCTION__,__FILE__,__LINE__); break; } @@ -240,12 +240,12 @@ bool Role::isRoleExists(unsigned role_type, Role *role) switch(role_type) { - case REF_ROLE: list=&ref_roles; break; - case MEMBER_ROLE: list=&member_roles; break; - case ADMIN_ROLE: list=&admin_roles; break; + case RefRole: list=&ref_roles; break; + case MemberRole: list=&member_roles; break; + case AdminRole: list=&admin_roles; break; default: //Raises an error if the role type is invalid - throw Exception(ERR_REF_INV_ROLE_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefInvalidRoleType,__PRETTY_FUNCTION__,__FILE__,__LINE__); break; } @@ -262,8 +262,8 @@ bool Role::isRoleExists(unsigned role_type, Role *role) bool Role::getOption(unsigned op_type) { - if(op_type > OP_BYPASSRLS) - throw Exception(ERR_ASG_VAL_INV_ROLE_OPT_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(op_type > OpBypassRls) + throw Exception(ErrorCode::AsgValueInvalidRoleOptionType,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(options[op_type]); } @@ -274,18 +274,18 @@ Role *Role::getRole(unsigned role_type, unsigned role_idx) switch(role_type) { - case REF_ROLE: list=&ref_roles; break; - case MEMBER_ROLE: list=&member_roles; break; - case ADMIN_ROLE: list=&admin_roles; break; + case RefRole: list=&ref_roles; break; + case MemberRole: list=&member_roles; break; + case AdminRole: list=&admin_roles; break; default: //Raises an error if the role type is invalid - throw Exception(ERR_REF_INV_ROLE_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefInvalidRoleType,__PRETTY_FUNCTION__,__FILE__,__LINE__); break; } //Raises an error if the role index is invalid (out of bound) if(role_idx > list->size()) - throw Exception(ERR_REF_ROLE_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefRoleInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(list->at(role_idx)); } @@ -296,12 +296,12 @@ unsigned Role::getRoleCount(unsigned role_type) switch(role_type) { - case REF_ROLE: list=&ref_roles; break; - case MEMBER_ROLE: list=&member_roles; break; - case ADMIN_ROLE: list=&admin_roles; break; + case RefRole: list=&ref_roles; break; + case MemberRole: list=&member_roles; break; + case AdminRole: list=&admin_roles; break; default: //Raises an error if the role type is invalid - throw Exception(ERR_REF_INV_ROLE_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefInvalidRoleType,__PRETTY_FUNCTION__,__FILE__,__LINE__); break; } @@ -325,29 +325,34 @@ QString Role::getPassword(void) QString Role::getCodeDefinition(unsigned def_type) { - QString code_def=getCachedCode(def_type, false); + return(getCodeDefinition(def_type, false)); +} + +QString Role::getCodeDefinition(unsigned def_type, bool reduced_form) +{ + QString code_def=getCachedCode(def_type, reduced_form); if(!code_def.isEmpty()) return(code_def); unsigned i; - QString op_attribs[]={ ParsersAttributes::SUPERUSER, ParsersAttributes::CREATEDB, - ParsersAttributes::CREATEROLE, ParsersAttributes::INHERIT, - ParsersAttributes::LOGIN, ParsersAttributes::ENCRYPTED, - ParsersAttributes::REPLICATION, ParsersAttributes::BYPASSRLS }; + QString op_attribs[]={ Attributes::Superuser, Attributes::CreateDb, + Attributes::CreateRole, Attributes::Inherit, + Attributes::Login, Attributes::Encrypted, + Attributes::Replication, Attributes::BypassRls }; - setRoleAttribute(REF_ROLE); - setRoleAttribute(MEMBER_ROLE); - setRoleAttribute(ADMIN_ROLE); + setRoleAttribute(RefRole); + setRoleAttribute(MemberRole); + setRoleAttribute(AdminRole); - for(i=0; i <= OP_BYPASSRLS; i++) - attributes[op_attribs[i]]=(options[i] ? ParsersAttributes::_TRUE_ : QString()); + for(i=0; i <= OpBypassRls; i++) + attributes[op_attribs[i]]=(options[i] ? Attributes::True : QString()); - attributes[ParsersAttributes::PASSWORD]=password; - attributes[ParsersAttributes::VALIDITY]=validity; + attributes[Attributes::Password]=password; + attributes[Attributes::Validity]=validity; if(conn_limit >= 0) - attributes[ParsersAttributes::CONN_LIMIT]=QString("%1").arg(conn_limit); + attributes[Attributes::ConnLimit]=QString("%1").arg(conn_limit); - return(BaseObject::__getCodeDefinition(def_type)); + return(BaseObject::getCodeDefinition(def_type, reduced_form)); } QString Role::getAlterDefinition(BaseObject *object, bool ignore_name_diff) @@ -355,29 +360,29 @@ QString Role::getAlterDefinition(BaseObject *object, bool ignore_name_diff) Role *role=dynamic_cast(object); if(!role) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { attribs_map attribs; - QString op_attribs[]={ ParsersAttributes::SUPERUSER, ParsersAttributes::CREATEDB, - ParsersAttributes::CREATEROLE, ParsersAttributes::INHERIT, - ParsersAttributes::LOGIN, ParsersAttributes::ENCRYPTED, - ParsersAttributes::REPLICATION, ParsersAttributes::BYPASSRLS }; + QString op_attribs[]={ Attributes::Superuser, Attributes::CreateDb, + Attributes::CreateRole, Attributes::Inherit, + Attributes::Login, Attributes::Encrypted, + Attributes::Replication, Attributes::BypassRls }; - attributes[ParsersAttributes::ALTER_CMDS]=BaseObject::getAlterDefinition(object, ignore_name_diff); + attributes[Attributes::AlterCmds]=BaseObject::getAlterDefinition(object, ignore_name_diff); if(this->password!=role->password) - attribs[ParsersAttributes::PASSWORD]=role->password; + attribs[Attributes::Password]=role->password; if(this->validity!=role->validity) - attribs[ParsersAttributes::VALIDITY]=role->validity; + attribs[Attributes::Validity]=role->validity; - for(unsigned i=0; i <= OP_BYPASSRLS; i++) + for(unsigned i=0; i <= OpBypassRls; i++) { - if((attribs.count(ParsersAttributes::PASSWORD) && i==OP_ENCRYPTED) || + if((attribs.count(Attributes::Password) && i==OpEncrypted) || this->options[i]!=role->options[i]) - attribs[op_attribs[i]]=(role->options[i] ? ParsersAttributes::_TRUE_ : ParsersAttributes::UNSET); + attribs[op_attribs[i]]=(role->options[i] ? Attributes::True : Attributes::Unset); } copyAttributes(attribs); @@ -386,6 +391,6 @@ QString Role::getAlterDefinition(BaseObject *object, bool ignore_name_diff) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } diff --git a/libpgmodeler/src/role.h b/libpgmodeler/src/role.h index df8a486865..ec08b2a118 100644 --- a/libpgmodeler/src/role.h +++ b/libpgmodeler/src/role.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -59,19 +59,19 @@ class Role: public BaseObject { public: //! \brief Constants used to reference the available options for the role - static const unsigned OP_SUPERUSER=0, - OP_CREATEDB=1, - OP_CREATEROLE=2, - OP_INHERIT=3, - OP_LOGIN=4, - OP_ENCRYPTED=5, - OP_REPLICATION=6, - OP_BYPASSRLS=7; + static constexpr unsigned OpSuperuser=0, + OpCreateDb=1, + OpCreateRole=2, + OpInherit=3, + OpLogin=4, + OpEncrypted=5, + OpReplication=6, + OpBypassRls=7; //! \brief Constants used to reference the internal role lists of the class - static const unsigned REF_ROLE=10, - MEMBER_ROLE=20, - ADMIN_ROLE=30; + static constexpr unsigned RefRole=10, + MemberRole=20, + AdminRole=30; Role(void); @@ -120,6 +120,7 @@ class Role: public BaseObject { //! \brief Returns the SQL / XML definition for the role virtual QString getCodeDefinition(unsigned def_type) final; + virtual QString getCodeDefinition(unsigned def_type, bool reduced_form) final; virtual QString getAlterDefinition(BaseObject *object, bool ignore_name_diff=false) final; }; diff --git a/libpgmodeler/src/rule.cpp b/libpgmodeler/src/rule.cpp index f8364202ee..21b5b2f1dd 100644 --- a/libpgmodeler/src/rule.cpp +++ b/libpgmodeler/src/rule.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,13 +20,13 @@ Rule::Rule(void) { - execution_type=BaseType::null; - obj_type=OBJ_RULE; - attributes[ParsersAttributes::EVENT_TYPE]=QString(); - attributes[ParsersAttributes::TABLE]=QString(); - attributes[ParsersAttributes::CONDITION]=QString(); - attributes[ParsersAttributes::EXEC_TYPE]=QString(); - attributes[ParsersAttributes::COMMANDS]=QString(); + execution_type=BaseType::Null; + obj_type=ObjectType::Rule; + attributes[Attributes::EventType]=QString(); + attributes[Attributes::Table]=QString(); + attributes[Attributes::Condition]=QString(); + attributes[Attributes::ExecType]=QString(); + attributes[Attributes::Commands]=QString(); } void Rule::setCommandsAttribute(void) @@ -41,7 +41,7 @@ void Rule::setCommandsAttribute(void) if(i < (qtd-1)) str_cmds+=QString(";"); } - attributes[ParsersAttributes::COMMANDS]=str_cmds; + attributes[Attributes::Commands]=str_cmds; } void Rule::setEventType(EventType type) @@ -66,7 +66,7 @@ void Rule::addCommand(const QString &cmd) { //Raises an error if the command is empty if(cmd.isEmpty()) - throw Exception(ERR_INS_EMPTY_RULE_COMMAND,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InsEmptyRuleCommand,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { QString cmd_aux=cmd; @@ -95,7 +95,7 @@ QString Rule::getCommand(unsigned cmd_idx) { //Raises an error if the command index is out of bound if(cmd_idx >= commands.size()) - throw Exception(ERR_REF_RULE_CMD_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefRuleCommandInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(commands[cmd_idx]); } @@ -109,7 +109,7 @@ void Rule::removeCommand(unsigned cmd_idx) { //Raises an error if the command index is out of bound if(cmd_idx>=commands.size()) - throw Exception(ERR_REF_RULE_CMD_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefRuleCommandInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); commands.erase(commands.begin() + cmd_idx); setCodeInvalidated(true); @@ -127,12 +127,12 @@ QString Rule::getCodeDefinition(unsigned def_type) if(!code_def.isEmpty()) return(code_def); setCommandsAttribute(); - attributes[ParsersAttributes::CONDITION]=conditional_expr; - attributes[ParsersAttributes::EXEC_TYPE]=(~execution_type); - attributes[ParsersAttributes::EVENT_TYPE]=(~event_type); + attributes[Attributes::Condition]=conditional_expr; + attributes[Attributes::ExecType]=(~execution_type); + attributes[Attributes::EventType]=(~event_type); if(getParentTable()) - attributes[ParsersAttributes::TABLE]=getParentTable()->getName(true); + attributes[Attributes::Table]=getParentTable()->getName(true); return(BaseObject::__getCodeDefinition(def_type)); } diff --git a/libpgmodeler/src/rule.h b/libpgmodeler/src/rule.h index 90379857ee..56c9e7ac8c 100644 --- a/libpgmodeler/src/rule.h +++ b/libpgmodeler/src/rule.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libpgmodeler/src/schema.cpp b/libpgmodeler/src/schema.cpp index 9ee5d93d3b..257fa2d6fc 100644 --- a/libpgmodeler/src/schema.cpp +++ b/libpgmodeler/src/schema.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,11 +20,11 @@ Schema::Schema(void) { - obj_type=OBJ_SCHEMA; + obj_type=ObjectType::Schema; fill_color=QColor(225,225,225, 80); rect_visible=false; - attributes[ParsersAttributes::FILL_COLOR]=QString(); - attributes[ParsersAttributes::RECT_VISIBLE]=QString(); + attributes[Attributes::FillColor]=QString(); + attributes[Attributes::RectVisible]=QString(); } void Schema::setName(const QString &name) @@ -32,10 +32,10 @@ void Schema::setName(const QString &name) /* Schema names starting with pg_ is reserved to PostgreSQL if its the case raises an error */ if(name.mid(0,3)==QString("pg_")) - throw Exception(Exception::getErrorMessage(ERR_ASG_RESERVED_NAME) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgReservedName) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_SCHEMA)), - ERR_ASG_RESERVED_NAME,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Schema)), + ErrorCode::AsgReservedName,__PRETTY_FUNCTION__,__FILE__,__LINE__); BaseObject::setName(name); } @@ -67,8 +67,9 @@ QString Schema::getCodeDefinition(unsigned def_type) QString code_def=getCachedCode(def_type, false); if(!code_def.isEmpty()) return(code_def); - attributes[ParsersAttributes::FILL_COLOR]=fill_color.name(); - attributes[ParsersAttributes::RECT_VISIBLE]=(rect_visible ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::Layer]=QString::number(layer); + attributes[Attributes::FillColor]=fill_color.name(); + attributes[Attributes::RectVisible]=(rect_visible ? Attributes::True : QString()); setFadedOutAttribute(); return(BaseObject::__getCodeDefinition(def_type)); diff --git a/libpgmodeler/src/schema.h b/libpgmodeler/src/schema.h index 99174dcb27..79e1f19f8c 100644 --- a/libpgmodeler/src/schema.h +++ b/libpgmodeler/src/schema.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libpgmodeler/src/sequence.cpp b/libpgmodeler/src/sequence.cpp index 808df35f2a..d72250af4b 100644 --- a/libpgmodeler/src/sequence.cpp +++ b/libpgmodeler/src/sequence.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,53 +18,61 @@ #include "sequence.h" -const QString Sequence::MAX_POSITIVE_VALUE=QString("+2147483647"); -const QString Sequence::MAX_NEGATIVE_VALUE=QString("-2147483648"); -const QString Sequence::MAX_SMALL_POSITIVE_VALUE=QString("+32767"); -const QString Sequence::MAX_SMALL_NEGATIVE_VALUE=QString("-32768"); -const QString Sequence::MAX_BIG_POSITIVE_VALUE=QString("+9223372036854775807"); -const QString Sequence::MAX_BIG_NEGATIVE_VALUE=QString("-9223372036854775808"); +const QString Sequence::MaxPositiveValue=QString("+2147483647"); +const QString Sequence::MaxNegativeValue=QString("-2147483648"); +const QString Sequence::MaxSmallPositiveValue=QString("+32767"); +const QString Sequence::MaxSmallNegativeValue=QString("-32768"); +const QString Sequence::MaxBigPositiveValue=QString("+9223372036854775807"); +const QString Sequence::MaxBigNegativeValue=QString("-9223372036854775808"); Sequence::Sequence(void) { - obj_type=OBJ_SEQUENCE; + obj_type=ObjectType::Sequence; cycle=false; - setDefaultValues(PgSQLType(QString("serial"))); + setDefaultValues(PgSqlType(QString("serial"))); owner_col=nullptr; - attributes[ParsersAttributes::INCREMENT]=QString(); - attributes[ParsersAttributes::MIN_VALUE]=QString(); - attributes[ParsersAttributes::MAX_VALUE]=QString(); - attributes[ParsersAttributes::START]=QString(); - attributes[ParsersAttributes::CACHE]=QString(); - attributes[ParsersAttributes::CYCLE]=QString(); - attributes[ParsersAttributes::OWNER_COLUMN]=QString(); - attributes[ParsersAttributes::TABLE]=QString(); - attributes[ParsersAttributes::COLUMN]=QString(); - attributes[ParsersAttributes::COL_IS_IDENTITY]=QString(); + attributes[Attributes::Increment]=QString(); + attributes[Attributes::MinValue]=QString(); + attributes[Attributes::MaxValue]=QString(); + attributes[Attributes::Start]=QString(); + attributes[Attributes::Cache]=QString(); + attributes[Attributes::Cycle]=QString(); + attributes[Attributes::OwnerColumn]=QString(); + attributes[Attributes::Table]=QString(); + attributes[Attributes::Column]=QString(); + attributes[Attributes::ColIsIdentity]=QString(); } -bool Sequence::isNullValue(const QString &value) +bool Sequence::isZeroValue(const QString &value) { + if(value.isEmpty()) + return(false); + unsigned i, count; - bool is_null; + bool is_zero; i=0; - is_null=true; + is_zero=true; count=value.size(); - while(i < count && is_null) + + while(i < count && is_zero) { - is_null=(value[i]=='0' || value[i]=='+' || value[i]=='-'); + is_zero=(value[i]=='0' || value[i]=='+' || value[i]=='-'); i++; } - return(is_null); + + return(is_zero); } bool Sequence::isValidValue(const QString &value) { + if(value.isEmpty()) + return(false); + /* To be valid the value can be start with + or -, have only numbers and it's length must not exceed the MAX_POSITIVE_VALUE length */ - if(value.size() > MAX_BIG_POSITIVE_VALUE.size()) + if(value.size() > MaxBigPositiveValue.size()) return(false); else { @@ -122,7 +130,7 @@ QString Sequence::formatValue(const QString &value) int Sequence::compareValues(QString value1, QString value2) { - if(value1==value2) + if(value1==value2 || value1.isEmpty() || value2.isEmpty()) return(0); else { @@ -170,24 +178,26 @@ int Sequence::compareValues(QString value1, QString value2) } } -void Sequence::setDefaultValues(PgSQLType serial_type) +void Sequence::setDefaultValues(PgSqlType serial_type) { QString min, max; - if(serial_type==QString("smallserial")) + if(serial_type==QString("smallserial") || + serial_type.isEquivalentTo(QString("smallint"))) { - min=MAX_SMALL_NEGATIVE_VALUE; - max=MAX_SMALL_POSITIVE_VALUE; + min=MaxSmallNegativeValue; + max=MaxSmallPositiveValue; } - else if(serial_type==QString("bigserial")) + else if(serial_type==QString("bigserial") || + serial_type.isEquivalentTo(QString("bigint"))) { - min=MAX_BIG_NEGATIVE_VALUE; - max=MAX_BIG_POSITIVE_VALUE; + min=MaxBigNegativeValue; + max=MaxBigPositiveValue; } else { - min=MAX_NEGATIVE_VALUE; - max=MAX_POSITIVE_VALUE; + min=MaxNegativeValue; + max=MaxPositiveValue; } setValues(min, max, QString("1"), QString("1"), QString("1")); @@ -199,7 +209,7 @@ void Sequence::setName(const QString &name) QString prev_name=this->getName(true); BaseObject::setName(name); - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } void Sequence::setSchema(BaseObject *schema) @@ -214,11 +224,11 @@ void Sequence::setSchema(BaseObject *schema) //Raises an error when the passed schema differs from the table schema if(table && table->getSchema()!=schema) - throw Exception(ERR_ASG_SEQ_DIF_TABLE_SCHEMA,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgSchemaSequenceDiffersTableSchema,__PRETTY_FUNCTION__,__FILE__,__LINE__); } BaseObject::setSchema(schema); - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } void Sequence::setCycle(bool value) @@ -235,23 +245,17 @@ void Sequence::setValues(QString minv, QString maxv, QString inc, QString start, start=formatValue(start); cache=formatValue(cache); - //Raises an error when some values are empty - if(minv.isEmpty() || maxv.isEmpty() || inc.isEmpty() || - start.isEmpty() || cache.isEmpty()) - throw Exception(ERR_ASG_INV_VALUE_SEQ_ATTRIBS,__PRETTY_FUNCTION__,__FILE__,__LINE__); - //Raises an error when the min value is greater than max value - else if(compareValues(minv,maxv) > 0) - throw Exception(ERR_ASG_INV_SEQ_MIN_VALUE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(compareValues(minv,maxv) > 0) + throw Exception(ErrorCode::AsgInvalidSequenceMinValue,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error when the start value is less that min value or grater than max value - else if(compareValues(start, minv) < 0 || - compareValues(start, maxv) > 0) - throw Exception(ERR_ASG_INV_SEQ_START_VALUE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(compareValues(start, minv) < 0 || compareValues(start, maxv) > 0) + throw Exception(ErrorCode::AsgInvalidSequenceStartValue,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error when the increment value is null (0) - else if(isNullValue(inc)) - throw Exception(ERR_ASG_INV_SEQ_INCR_VALUE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(isZeroValue(inc)) + throw Exception(ErrorCode::AsgInvalidSequenceIncrementValue,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error when the cache value is null (0) - else if(isNullValue(cache)) - throw Exception(ERR_ASG_INV_SEQ_CACHE_VALUE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(isZeroValue(cache)) + throw Exception(ErrorCode::AsgInvalidSequenceCacheValue,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->min_value=minv; this->max_value=maxv; @@ -270,24 +274,24 @@ void Sequence::setOwnerColumn(Table *table, const QString &col_name) { //Raises an error if the table schema differs from the sequence schema if(table->getSchema()!=this->schema) - throw Exception(Exception::getErrorMessage(ERR_ASG_TAB_DIF_SEQ_SCHEMA) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgSeqOwnerTableDifferentSchema) .arg(this->getName(true)), - ERR_ASG_TAB_DIF_SEQ_SCHEMA,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgSeqOwnerTableDifferentSchema,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error when the table owner role differs from the sequence owner if(table->getOwner()!=this->owner) - throw Exception(Exception::getErrorMessage(ERR_ASG_SEQ_OWNER_DIF_TABLE) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgSeqOwnerTableDifferentRole) .arg(this->getName(true)), - ERR_ASG_SEQ_OWNER_DIF_TABLE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgSeqOwnerTableDifferentRole,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Gets the column with the passed name this->owner_col=table->getColumn(col_name); //Raises an error if the column doesn't exists if(!this->owner_col) - throw Exception(Exception::getErrorMessage(ERR_ASG_INEXIST_OWNER_COL_SEQ) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInexistentSeqOwnerColumn) .arg(this->getName(true)), - ERR_ASG_INEXIST_OWNER_COL_SEQ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgInexistentSeqOwnerColumn,__PRETTY_FUNCTION__,__FILE__,__LINE__); /* If the onwer column was added by relationship and the column id is greater than sequence id, change the sequence id to be greater to avoid reference errors */ @@ -311,21 +315,21 @@ void Sequence::setOwnerColumn(Column *column) //Raises an error when the column doesn't has a parent table if(!table) - throw Exception(Exception::getErrorMessage(ERR_ASG_INV_OWNER_COL_SEQ) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidSeqOwnerColumn) .arg(this->getName(true)), - ERR_ASG_INV_OWNER_COL_SEQ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgInvalidSeqOwnerColumn,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the table schema differs from the sequence schema if(table->getSchema()!=this->schema) - throw Exception(Exception::getErrorMessage(ERR_ASG_TAB_DIF_SEQ_SCHEMA) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgSeqOwnerTableDifferentSchema) .arg(this->getName(true)), - ERR_ASG_TAB_DIF_SEQ_SCHEMA,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgSeqOwnerTableDifferentSchema,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error when the table owner role differs from the sequence owner if(table->getOwner()!=this->owner) - throw Exception(Exception::getErrorMessage(ERR_ASG_SEQ_OWNER_DIF_TABLE) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgSeqOwnerTableDifferentRole) .arg(this->getName(true)), - ERR_ASG_SEQ_OWNER_DIF_TABLE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgSeqOwnerTableDifferentRole,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->owner_col=column; @@ -388,22 +392,22 @@ QString Sequence::getCodeDefinition(unsigned def_type) if(owner_col) { - attributes[ParsersAttributes::OWNER_COLUMN]=owner_col->getSignature(); + attributes[Attributes::OwnerColumn]=owner_col->getSignature(); table=dynamic_cast
(owner_col->getParentTable()); } - attributes[ParsersAttributes::TABLE]=(table ? table->getName(true) : QString()); - attributes[ParsersAttributes::COLUMN]=(owner_col ? owner_col->getName(true) : QString()); + attributes[Attributes::Table]=(table ? table->getName(true) : QString()); + attributes[Attributes::Column]=(owner_col ? owner_col->getName(true) : QString()); - attributes[ParsersAttributes::COL_IS_IDENTITY]= - (owner_col && owner_col->getIdentityType() != BaseType::null ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::ColIsIdentity]= + (owner_col && owner_col->getIdentityType() != BaseType::Null ? Attributes::True : QString()); - attributes[ParsersAttributes::INCREMENT]=increment; - attributes[ParsersAttributes::MIN_VALUE]=min_value; - attributes[ParsersAttributes::MAX_VALUE]=max_value; - attributes[ParsersAttributes::START]=start; - attributes[ParsersAttributes::CACHE]=cache; - attributes[ParsersAttributes::CYCLE]=(cycle ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::Increment]=increment; + attributes[Attributes::MinValue]=min_value; + attributes[Attributes::MaxValue]=max_value; + attributes[Attributes::Start]=start; + attributes[Attributes::Cache]=cache; + attributes[Attributes::Cycle]=(cycle ? Attributes::True : QString()); return(BaseObject::__getCodeDefinition(def_type)); } @@ -413,14 +417,14 @@ QString Sequence::getAlterDefinition(BaseObject *object) Sequence *seq=dynamic_cast(object); if(!seq) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { Table *table=nullptr; attribs_map attribs; - attributes[ParsersAttributes::ALTER_CMDS]=BaseObject::getAlterDefinition(object); + attributes[Attributes::AlterCmds]=BaseObject::getAlterDefinition(object); if((this->owner_col && !seq->owner_col) || (!this->owner_col && seq->owner_col) || @@ -429,43 +433,43 @@ QString Sequence::getAlterDefinition(BaseObject *object) { if(seq->owner_col) { - attribs[ParsersAttributes::OWNER_COLUMN]=seq->owner_col->getSignature(); + attribs[Attributes::OwnerColumn]=seq->owner_col->getSignature(); table=dynamic_cast
(seq->owner_col->getParentTable()); if(table) { - attribs[ParsersAttributes::TABLE]=table->getName(true); - attribs[ParsersAttributes::COLUMN]=seq->owner_col->getName(true); + attribs[Attributes::Table]=table->getName(true); + attribs[Attributes::Column]=seq->owner_col->getName(true); } } else - attribs[ParsersAttributes::OWNER_COLUMN]=ParsersAttributes::UNSET; + attribs[Attributes::OwnerColumn]=Attributes::Unset; } - if(this->increment!=seq->increment) - attribs[ParsersAttributes::INCREMENT]=seq->increment; + if(!seq->increment.isEmpty() && this->increment!=seq->increment) + attribs[Attributes::Increment]=seq->increment; - if(this->min_value!=seq->min_value) - attribs[ParsersAttributes::MIN_VALUE]=seq->min_value; + if(!seq->min_value.isEmpty() && this->min_value!=seq->min_value) + attribs[Attributes::MinValue]=seq->min_value; - if(this->max_value!=seq->max_value) - attribs[ParsersAttributes::MAX_VALUE]=seq->max_value; + if(!seq->max_value.isEmpty() && this->max_value!=seq->max_value) + attribs[Attributes::MaxValue]=seq->max_value; - if(this->start!=seq->start) - attribs[ParsersAttributes::START]=seq->start; + if(!seq->start.isEmpty() && this->start!=seq->start) + attribs[Attributes::Start]=seq->start; - if(this->cache!=seq->cache) - attribs[ParsersAttributes::CACHE]=seq->cache; + if(!seq->cache.isEmpty() && this->cache!=seq->cache) + attribs[Attributes::Cache]=seq->cache; if(this->cycle!=seq->cycle) - attribs[ParsersAttributes::CYCLE]=(seq->cycle ? ParsersAttributes::_TRUE_ : ParsersAttributes::UNSET); + attribs[Attributes::Cycle]=(seq->cycle ? Attributes::True : Attributes::Unset); copyAttributes(attribs); return(BaseObject::getAlterDefinition(this->getSchemaName(), attributes, false, true)); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -483,6 +487,6 @@ void Sequence::operator = (Sequence &seq) this->cache=seq.cache; this->owner_col=seq.owner_col; - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } diff --git a/libpgmodeler/src/sequence.h b/libpgmodeler/src/sequence.h index 4f7bd2cf5e..f63700c80c 100644 --- a/libpgmodeler/src/sequence.h +++ b/libpgmodeler/src/sequence.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -53,7 +53,7 @@ class Sequence: public BaseObject { bool isValidValue(const QString &value); //! \brief Returns true when the passed value is null (zero) - bool isNullValue(const QString &value); + bool isZeroValue(const QString &value); //! \brief Returns the formated value excluding the aditional operators QString formatValue(const QString &value); @@ -67,14 +67,14 @@ class Sequence: public BaseObject { public: //! \brief Constants that indicates the maximum and minimum values accepted by sequence static const QString //For serial sequences - MAX_POSITIVE_VALUE, - MAX_NEGATIVE_VALUE, + MaxPositiveValue, + MaxNegativeValue, //For smallserial sequences - MAX_SMALL_POSITIVE_VALUE, - MAX_SMALL_NEGATIVE_VALUE, + MaxSmallPositiveValue, + MaxSmallNegativeValue, //For bigserial sequences - MAX_BIG_POSITIVE_VALUE, - MAX_BIG_NEGATIVE_VALUE; + MaxBigPositiveValue, + MaxBigNegativeValue; Sequence(void); @@ -86,7 +86,7 @@ class Sequence: public BaseObject { /*! \brief Sets all values at once based on the serial type specified (smallserial, serial or bigserial). If other type the three serial types are passed the method will consider as 'serial' */ - void setDefaultValues(PgSQLType serial_type); + void setDefaultValues(PgSqlType serial_type); //! \brief Defines the owner column using a table and a column name void setOwnerColumn(Table *tabela, const QString &col_name); diff --git a/libpgmodeler/src/table.cpp b/libpgmodeler/src/table.cpp index 3daa505f40..035d66c4fb 100644 --- a/libpgmodeler/src/table.cpp +++ b/libpgmodeler/src/table.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -19,30 +19,36 @@ #include "table.h" #include "pgmodelerns.h" -const QString Table::DATA_SEPARATOR = QString("•"); -const QString Table::DATA_LINE_BREAK = QString("%1%2").arg("⸣").arg('\n'); +const QString Table::DataSeparator = QString("•"); +const QString Table::DataLineBreak = QString("%1%2").arg("⸣").arg('\n'); Table::Table(void) : BaseTable() { - obj_type=OBJ_TABLE; + obj_type=ObjectType::Table; with_oid=gen_alter_cmds=unlogged=rls_enabled=rls_forced=false; - attributes[ParsersAttributes::COLUMNS]=QString(); - attributes[ParsersAttributes::INH_COLUMNS]=QString(); - attributes[ParsersAttributes::CONSTRAINTS]=QString(); - attributes[ParsersAttributes::OIDS]=QString(); - attributes[ParsersAttributes::COLS_COMMENT]=QString(); - attributes[ParsersAttributes::COPY_TABLE]=QString(); - attributes[ParsersAttributes::ANCESTOR_TABLE]=QString(); - attributes[ParsersAttributes::GEN_ALTER_CMDS]=QString(); - attributes[ParsersAttributes::CONSTR_SQL_DISABLED]=QString(); - attributes[ParsersAttributes::COL_INDEXES]=QString(); - attributes[ParsersAttributes::CONSTR_INDEXES]=QString(); - attributes[ParsersAttributes::UNLOGGED]=QString(); - attributes[ParsersAttributes::INITIAL_DATA]=QString(); - attributes[ParsersAttributes::RLS_ENABLED]=QString(); - attributes[ParsersAttributes::RLS_FORCED]=QString(); - - copy_table=nullptr; + attributes[Attributes::Columns]=QString(); + attributes[Attributes::InhColumns]=QString(); + attributes[Attributes::Constraints]=QString(); + attributes[Attributes::Oids]=QString(); + attributes[Attributes::ColsComment]=QString(); + attributes[Attributes::CopyTable]=QString(); + attributes[Attributes::AncestorTable]=QString(); + attributes[Attributes::GenAlterCmds]=QString(); + attributes[Attributes::ConstrSqlDisabled]=QString(); + attributes[Attributes::ColIndexes]=QString(); + attributes[Attributes::ConstrIndexes]=QString(); + attributes[Attributes::Unlogged]=QString(); + attributes[Attributes::InitialData]=QString(); + attributes[Attributes::RlsEnabled]=QString(); + attributes[Attributes::RlsForced]=QString(); + attributes[Attributes::Partitioning]=QString(); + attributes[Attributes::PartitionKey]=QString(); + attributes[Attributes::PartitionedTable]=QString(); + attributes[Attributes::PartitionBoundExpr]=QString(); + + copy_table=partitioned_table=nullptr; + partitioning_type=BaseType::Null; + this->setName(trUtf8("new_table").toUtf8()); } @@ -57,20 +63,21 @@ Table::~Table(void) } ancestor_tables.clear(); + partition_tables.clear(); } void Table::setName(const QString &name) { QString prev_name=this->getName(true); BaseObject::setName(name); - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } void Table::setSchema(BaseObject *schema) { QString prev_name=this->getName(true); BaseObject::setSchema(schema); - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } void Table::setWithOIDs(bool value) @@ -97,10 +104,26 @@ void Table::setRLSForced(bool value) rls_forced = value; } +void Table::setPartitioningType(PartitioningType part_type) +{ + setCodeInvalidated(partitioning_type != part_type); + partitioning_type = part_type; +} + +PartitioningType Table::getPartitioningType(void) +{ + return(partitioning_type); +} + +Table *Table::getPartitionedTable(void) +{ + return(partitioned_table); +} + void Table::setProtected(bool value) { - ObjectType obj_types[]={ OBJ_COLUMN, OBJ_CONSTRAINT, - OBJ_INDEX, OBJ_RULE, OBJ_TRIGGER }; + ObjectType obj_types[]={ ObjectType::Column, ObjectType::Constraint, + ObjectType::Index, ObjectType::Rule, ObjectType::Trigger }; unsigned i; vector::iterator itr, itr_end; vector *list=nullptr; @@ -132,23 +155,23 @@ void Table::setProtected(bool value) void Table::setCommentAttribute(TableObject *tab_obj) { - if(tab_obj && !tab_obj->getComment().isEmpty()) + if(tab_obj && !tab_obj->getComment().isEmpty() && tab_obj->isDeclaredInTable()) { attribs_map attribs; - attribs[ParsersAttributes::SIGNATURE]=tab_obj->getSignature(); - attribs[ParsersAttributes::SQL_OBJECT]=tab_obj->getSQLName(); - attribs[ParsersAttributes::COLUMN]=(tab_obj->getObjectType()==OBJ_COLUMN ? ParsersAttributes::_TRUE_ : QString()); - attribs[ParsersAttributes::CONSTRAINT]=(tab_obj->getObjectType()==OBJ_CONSTRAINT ? ParsersAttributes::_TRUE_ : QString()); - attribs[ParsersAttributes::TABLE]=this->getName(true); - attribs[ParsersAttributes::NAME]=tab_obj->getName(true); - attribs[ParsersAttributes::COMMENT]=QString(tab_obj->getComment()).replace(QString("'"), QString("''"));; + attribs[Attributes::Signature]=tab_obj->getSignature(); + attribs[Attributes::SqlObject]=tab_obj->getSQLName(); + attribs[Attributes::Column]=(tab_obj->getObjectType()==ObjectType::Column ? Attributes::True : QString()); + attribs[Attributes::Constraint]=(tab_obj->getObjectType()==ObjectType::Constraint ? Attributes::True : QString()); + attribs[Attributes::Table]=this->getName(true); + attribs[Attributes::Name]=tab_obj->getName(true); + attribs[Attributes::Comment]=QString(tab_obj->getComment()).replace(QString("'"), QString("''"));; schparser.ignoreUnkownAttributes(true); if(tab_obj->isSQLDisabled()) - attributes[ParsersAttributes::COLS_COMMENT]+=QString("-- "); + attributes[Attributes::ColsComment]+=QString("-- "); - attributes[ParsersAttributes::COLS_COMMENT]+=schparser.getCodeDefinition(ParsersAttributes::COMMENT, attribs, SchemaParser::SQL_DEFINITION); + attributes[Attributes::ColsComment]+=schparser.getCodeDefinition(Attributes::Comment, attribs, SchemaParser::SqlDefinition); schparser.ignoreUnkownAttributes(false); } } @@ -161,15 +184,15 @@ void Table::setAncestorTableAttribute(void) for(i=0; i < count; i++) list.push_back(ancestor_tables[i]->getName(true)); - attributes[ParsersAttributes::ANCESTOR_TABLE]=list.join(','); + attributes[Attributes::AncestorTable]=list.join(','); } void Table::setRelObjectsIndexesAttribute(void) { attribs_map aux_attribs; vector *> obj_indexes={ &col_indexes, &constr_indexes }; - QString attribs[]={ ParsersAttributes::COL_INDEXES, ParsersAttributes::CONSTR_INDEXES }; - ObjectType obj_types[]={ OBJ_COLUMN, OBJ_CONSTRAINT }; + QString attribs[]={ Attributes::ColIndexes, Attributes::ConstrIndexes }; + ObjectType obj_types[]={ ObjectType::Column, ObjectType::Constraint }; unsigned idx=0, size=obj_indexes.size(); for(idx=0; idx < size; idx++) @@ -180,19 +203,21 @@ void Table::setRelObjectsIndexesAttribute(void) { for(auto &obj_idx : (*obj_indexes[idx])) { - aux_attribs[ParsersAttributes::NAME]=obj_idx.first; - aux_attribs[ParsersAttributes::INDEX]=QString::number(obj_idx.second); - aux_attribs[ParsersAttributes::OBJECTS]+=schparser.getCodeDefinition(ParsersAttributes::OBJECT, aux_attribs, SchemaParser::XML_DEFINITION); + aux_attribs[Attributes::Name]=obj_idx.first; + aux_attribs[Attributes::Index]=QString::number(obj_idx.second); + + schparser.ignoreUnkownAttributes(true); + aux_attribs[Attributes::Objects]+=schparser.getCodeDefinition(Attributes::Object, aux_attribs, SchemaParser::XmlDefinition); } - aux_attribs[ParsersAttributes::OBJECT_TYPE]=BaseObject::getSchemaName(obj_types[idx]); - attributes[attribs[idx]]=schparser.getCodeDefinition(ParsersAttributes::CUSTOMIDXS, aux_attribs, SchemaParser::XML_DEFINITION); + aux_attribs[Attributes::ObjectType]=BaseObject::getSchemaName(obj_types[idx]); + attributes[attribs[idx]]=schparser.getCodeDefinition(Attributes::CustomIdxs, aux_attribs, SchemaParser::XmlDefinition); aux_attribs.clear(); } } } -void Table::setColumnsAttribute(unsigned def_type) +void Table::setColumnsAttribute(unsigned def_type, bool incl_rel_added_cols) { QString str_cols, inh_cols; unsigned i, count; @@ -202,33 +227,44 @@ void Table::setColumnsAttribute(unsigned def_type) { /* Do not generates the column code definition when it is not included by relatoinship, in case of XML definition. */ - if((def_type==SchemaParser::SQL_DEFINITION && !columns[i]->isAddedByCopy() && !columns[i]->isAddedByGeneralization())|| - (def_type==SchemaParser::XML_DEFINITION && !columns[i]->isAddedByRelationship())) + if((def_type==SchemaParser::SqlDefinition && !columns[i]->isAddedByCopy() && !columns[i]->isAddedByGeneralization()) || + (def_type==SchemaParser::SqlDefinition && columns[i]->isAddedByCopy() && this->isPartition()) || + (def_type==SchemaParser::XmlDefinition && (!columns[i]->isAddedByRelationship() || (incl_rel_added_cols && columns[i]->isAddedByRelationship())))) { str_cols+=columns[i]->getCodeDefinition(def_type); - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) setCommentAttribute(columns[i]); } - else if(def_type==SchemaParser::SQL_DEFINITION && columns[i]->isAddedByGeneralization() && !gen_alter_cmds) + else if(def_type==SchemaParser::SqlDefinition && columns[i]->isAddedByGeneralization() && !gen_alter_cmds) { inh_cols+=QString("-- ") + columns[i]->getCodeDefinition(def_type); } } - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) { if(!str_cols.isEmpty()) { - count=str_cols.size(); - if(str_cols[count-2]==',' || str_cols[count-2]=='\n') - str_cols.remove(count-2,2); + count = str_cols.size(); + + // Removing the last comma from the columns SQL + if(str_cols[count-2] == ',' || str_cols[count-2] == '\n') + str_cols.remove(count - 2, 2); + + /* Special case: if we have the last column's SQL disabled we need to remove + * the comma from the last line (the enabled one) in order to avoid syntax error */ + int disabled_col_idx = str_cols.lastIndexOf(QString("-- ")), + last_comma_idx = str_cols.lastIndexOf(',', disabled_col_idx); + + if(last_comma_idx >= 0 && last_comma_idx < disabled_col_idx) + str_cols.remove(last_comma_idx, 1); } - attributes[ParsersAttributes::INH_COLUMNS]=inh_cols; + attributes[Attributes::InhColumns]=inh_cols; } - attributes[ParsersAttributes::COLUMNS]=str_cols; + attributes[Attributes::Columns]=str_cols; } void Table::setConstraintsAttribute(unsigned def_type) @@ -244,31 +280,31 @@ void Table::setConstraintsAttribute(unsigned def_type) { constr=dynamic_cast(constraints[i]); - if(constr->getConstraintType()!=ConstraintType::foreign_key && + if(constr->getConstraintType()!=ConstraintType::ForeignKey && - ((def_type==SchemaParser::SQL_DEFINITION && - ((!constr->isReferRelationshipAddedColumn() && constr->getConstraintType()!=ConstraintType::check) || - (constr->getConstraintType()==ConstraintType::check && !constr->isAddedByGeneralization()) || - constr->getConstraintType()==ConstraintType::primary_key)) || + ((def_type==SchemaParser::SqlDefinition && + ((!constr->isReferRelationshipAddedColumn() && constr->getConstraintType()!=ConstraintType::Check) || + (constr->getConstraintType()==ConstraintType::Check && !constr->isAddedByGeneralization()) || + constr->getConstraintType()==ConstraintType::PrimaryKey)) || - (def_type==SchemaParser::XML_DEFINITION && !constr->isAddedByRelationship() && - ((constr->getConstraintType()!=ConstraintType::primary_key && !constr->isReferRelationshipAddedColumn()) || - (constr->getConstraintType()==ConstraintType::primary_key))))) + (def_type==SchemaParser::XmlDefinition && !constr->isAddedByRelationship() && + ((constr->getConstraintType()!=ConstraintType::PrimaryKey && !constr->isReferRelationshipAddedColumn()) || + (constr->getConstraintType()==ConstraintType::PrimaryKey))))) { - inc_added_by_rel=(def_type==SchemaParser::SQL_DEFINITION); + inc_added_by_rel=(def_type==SchemaParser::SqlDefinition); - if(def_type==SchemaParser::XML_DEFINITION) + if(def_type==SchemaParser::XmlDefinition) str_constr+=constr->getCodeDefinition(def_type,inc_added_by_rel); else //For sql definition the generated constraints are stored in a vector to be treated below lines.push_back(constr->getCodeDefinition(def_type,inc_added_by_rel)); - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) setCommentAttribute(constr); } } - if(def_type==SchemaParser::SQL_DEFINITION && !lines.empty()) + if(def_type==SchemaParser::SqlDefinition && !lines.empty()) { /* When the coistraints are being generated in form of ALTER commands simply concatenates all the lines */ @@ -298,29 +334,34 @@ void Table::setConstraintsAttribute(unsigned def_type) str_constr+=lines[i]; } - attributes[ParsersAttributes::CONSTR_SQL_DISABLED]=(dis_sql_cnt==lines.size() ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::ConstrSqlDisabled]=(dis_sql_cnt==lines.size() ? Attributes::True : QString()); } } - attributes[ParsersAttributes::CONSTRAINTS]=str_constr; + attributes[Attributes::Constraints]=str_constr; } vector *Table::getObjectList(ObjectType obj_type) { - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) return(&columns); - else if(obj_type==OBJ_CONSTRAINT) + + if(obj_type==ObjectType::Constraint) return(&constraints); - else if(obj_type==OBJ_RULE) + + if(obj_type==ObjectType::Rule) return(&rules); - else if(obj_type==OBJ_TRIGGER) + + if(obj_type==ObjectType::Trigger) return(&triggers); - else if(obj_type==OBJ_INDEX) + + if(obj_type==ObjectType::Index) return(&indexes); - else if(obj_type==OBJ_POLICY) + + if(obj_type==ObjectType::Policy) return(&policies); - else - throw Exception(ERR_OBT_OBJ_INVALID_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + throw Exception(ErrorCode::ObtObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); } void Table::addObject(BaseObject *obj, int obj_idx) @@ -328,7 +369,7 @@ void Table::addObject(BaseObject *obj, int obj_idx) ObjectType obj_type; if(!obj) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { int idx; @@ -336,14 +377,14 @@ void Table::addObject(BaseObject *obj, int obj_idx) #ifdef DEMO_VERSION #warning "DEMO VERSION: table children objects creation limit." - vector *obj_list=(obj_type!=OBJ_TABLE ? getObjectList(obj_type) : nullptr); + vector *obj_list=(obj_type!=ObjectType::Table ? getObjectList(obj_type) : nullptr); - if((obj_list && obj_list->size() >= GlobalAttributes::MAX_OBJECT_COUNT) || - (obj_type==OBJ_TABLE && ancestor_tables.size() >= GlobalAttributes::MAX_OBJECT_COUNT)) + if((obj_list && obj_list->size() >= GlobalAttributes::MaxObjectCount) || + (obj_type==ObjectType::Table && ancestor_tables.size() >= GlobalAttributes::MaxObjectCount)) throw Exception(trUtf8("In demonstration version tables can have only `%1' instances of each child object type or ancestor tables! You've reach this limit for the type: `%2'") - .arg(GlobalAttributes::MAX_OBJECT_COUNT) + .arg(GlobalAttributes::MaxObjectCount) .arg(BaseObject::getTypeName(obj_type)), - ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); #endif @@ -352,26 +393,26 @@ void Table::addObject(BaseObject *obj, int obj_idx) //Raises an error if already exists a object with the same name and type if(getObject(obj->getName(),obj_type,idx)) { - throw Exception(QString(Exception::getErrorMessage(ERR_ASG_DUPLIC_OBJECT)) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgDuplicatedObject) .arg(obj->getName(true)) .arg(obj->getTypeName()) .arg(this->getName(true)) .arg(this->getTypeName()), - ERR_ASG_DUPLIC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgDuplicatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); } //Raises an error if the user try to set the table as ancestor/copy of itself - else if((obj_type==OBJ_TABLE || obj_type==BASE_TABLE) && obj==this) - throw Exception(ERR_INV_INH_COPY_RELATIONSHIP,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if((obj_type==ObjectType::Table || obj_type==ObjectType::BaseTable) && obj==this) + throw Exception(ErrorCode::InvInheritCopyPartRelationship,__PRETTY_FUNCTION__,__FILE__,__LINE__); switch(obj_type) { - case OBJ_COLUMN: - case OBJ_CONSTRAINT: - case OBJ_TRIGGER: - case OBJ_INDEX: - case OBJ_RULE: - case OBJ_POLICY: + case ObjectType::Column: + case ObjectType::Constraint: + case ObjectType::Trigger: + case ObjectType::Index: + case ObjectType::Rule: + case ObjectType::Policy: TableObject *tab_obj; vector *obj_list; Column *col; @@ -384,26 +425,26 @@ void Table::addObject(BaseObject *obj, int obj_idx) tab_obj->setParentTable(this); //Raises an error if the parent table of the table object is different from table 'this' else if(tab_obj->getParentTable()!=this) - throw Exception(ERR_ASG_OBJ_BELONGS_OTHER_TABLE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgObjectBelongsAnotherTable,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Validates the object SQL code befor insert on table - obj->getCodeDefinition(SchemaParser::SQL_DEFINITION); + obj->getCodeDefinition(SchemaParser::SqlDefinition); if(col && col->getType()==this) { - throw Exception(Exception::getErrorMessage(ERR_INV_COLUMN_TABLE_TYPE) + throw Exception(Exception::getErrorMessage(ErrorCode::InvColumnTableType) .arg(col->getName()) .arg(this->getName()), - ERR_INV_COLUMN_TABLE_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::InvColumnTableType,__PRETTY_FUNCTION__,__FILE__,__LINE__); } - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) { //Raises a error if the user try to add a second primary key on the table - if(dynamic_cast(tab_obj)->getConstraintType()==ConstraintType::primary_key && + if(dynamic_cast(tab_obj)->getConstraintType()==ConstraintType::PrimaryKey && this->getPrimaryKey()) - throw Exception(ERR_ASG_EXISTING_PK_TABLE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgExistingPrimaryKeyTable,__PRETTY_FUNCTION__,__FILE__,__LINE__); } - else if(obj_type==OBJ_TRIGGER) + else if(obj_type==ObjectType::Trigger) dynamic_cast(tab_obj)->validateTrigger(); obj_list=getObjectList(obj_type); @@ -420,16 +461,16 @@ void Table::addObject(BaseObject *obj, int obj_idx) obj_list->push_back(tab_obj); } - if(obj_type==OBJ_COLUMN || obj_type==OBJ_CONSTRAINT) + if(obj_type==ObjectType::Column || obj_type==ObjectType::Constraint) { updateAlterCmdsStatus(); - if(obj_type==OBJ_CONSTRAINT) + if(obj_type==ObjectType::Constraint) dynamic_cast(tab_obj)->setColumnsNotNull(true); } break; - case OBJ_TABLE: + case ObjectType::Table: Table *tab; tab=dynamic_cast
(obj); if(obj_idx < 0 || obj_idx >= static_cast(ancestor_tables.size())) @@ -443,7 +484,7 @@ void Table::addObject(BaseObject *obj, int obj_idx) break; default: - throw Exception(ERR_ASG_OBJECT_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); break; } @@ -451,13 +492,13 @@ void Table::addObject(BaseObject *obj, int obj_idx) } catch(Exception &e) { - if(e.getErrorType()==ERR_UNDEF_ATTRIB_VALUE) - throw Exception(Exception::getErrorMessage(ERR_ASG_OBJ_INV_DEFINITION) + if(e.getErrorCode()==ErrorCode::UndefinedAttributeValue) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgObjectInvalidDefinition) .arg(obj->getName()) .arg(obj->getTypeName()), - ERR_ASG_OBJ_INV_DEFINITION,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + ErrorCode::AsgObjectInvalidDefinition,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } } @@ -470,7 +511,7 @@ void Table::addColumn(Column *col, int idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -482,7 +523,7 @@ void Table::addTrigger(Trigger *trig, int idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -494,7 +535,7 @@ void Table::addIndex(Index *ind, int idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -506,7 +547,7 @@ void Table::addRule(Rule *reg, int idx_reg) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -518,8 +559,42 @@ void Table::addPolicy(Policy *pol, int idx_pol) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); - } + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +void Table::setPartionedTable(Table *table) +{ + setCodeInvalidated(partitioned_table != table); + + if(table != partitioned_table && partitioned_table) + partitioned_table->removePartitionTable(this); + + partitioned_table = table; + + if(partitioned_table) + partitioned_table->addPartitionTable(this); +} + +void Table::setPartitionBoundingExpr(const QString part_bound_expr) +{ + setCodeInvalidated(part_bounding_expr != part_bound_expr); + part_bounding_expr = part_bound_expr; +} + +QString Table::getPartitionBoundingExpr(void) +{ + return(part_bounding_expr); +} + +vector
Table::getPartionTables(void) +{ + return(partition_tables); +} + +bool Table::isPartitionTableExists(Table *table, bool compare_names) +{ + return(getPartitionTableIndex(table, compare_names) >= 0); } void Table::addConstraint(Constraint *constr, int idx) @@ -530,7 +605,7 @@ void Table::addConstraint(Constraint *constr, int idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -542,10 +617,45 @@ void Table::addAncestorTable(Table *tab, int idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } +void Table::addPartitionTable(Table *tab) +{ + if(tab && std::find(partition_tables.begin(), partition_tables.end(), tab) == partition_tables.end()) + partition_tables.push_back(tab); +} + +void Table::removePartitionTable(Table *tab) +{ + int idx = getPartitionTableIndex(tab, false); + + if(idx >= 0) + partition_tables.erase(partition_tables.begin() + idx); +} + +int Table::getPartitionTableIndex(Table *tab, bool compare_names) +{ + if(!tab) + return(-1); + + vector
::iterator itr = partition_tables.begin(); + + while(itr != partition_tables.end()) + { + if(*itr == tab || (compare_names && tab->getName(true) == (*itr)->getName(true))) + break; + + itr++; + } + + if(itr == partition_tables.end()) + return(-1); + + return(itr - partition_tables.begin()); +} + void Table::setCopyTable(Table *tab) { setCodeInvalidated(copy_table != tab); @@ -564,6 +674,47 @@ void Table::setCopyTableOptions(CopyOptions like_op) } } +void Table::addPartitionKeys(vector &part_keys) +{ + vector part_keys_bkp = partition_keys; + + if(partitioning_type == BaseType::Null) + return; + + if(partitioning_type == PartitioningType::List && part_keys.size() > 1) + throw Exception(Exception::getErrorMessage(ErrorCode::InvPartitionKeyCount).arg(this->getSignature()), + ErrorCode::InvPartitionKeyCount,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + partition_keys.clear(); + + for(auto &part_key : part_keys) + { + if(std::find(partition_keys.begin(), partition_keys.end(), part_key) != partition_keys.end()) + { + partition_keys = part_keys_bkp; + throw Exception(ErrorCode::InsDuplicatedElement,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + + if(part_key.getColumn() && part_key.getColumn()->isAddedByRelationship()) + { + partition_keys = part_keys_bkp; + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidColumnPartitionKey) + .arg(part_key.getColumn()->getSignature(true)), + ErrorCode::AsgInvalidColumnPartitionKey,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + + partition_keys.push_back(part_key); + } + + setCodeInvalidated(true); +} + +void Table::removePartitionKeys(void) +{ + partition_keys.clear(); + setCodeInvalidated(true); +} + Table *Table::getCopyTable(void) { return(copy_table); @@ -585,12 +736,12 @@ void Table::removeObject(BaseObject *obj) if(tab_obj) removeObject(getObjectIndex(tab_obj), obj->getObjectType()); else - removeObject(obj->getName(true), OBJ_TABLE); + removeObject(obj->getName(true), ObjectType::Table); } } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -609,10 +760,10 @@ void Table::removeObject(const QString &name, ObjectType obj_type) void Table::removeObject(unsigned obj_idx, ObjectType obj_type) { //Raises an error if the user try to remove a object with invalid type - if(!TableObject::isTableObject(obj_type) && obj_type!=OBJ_TABLE) - throw Exception(ERR_REM_OBJ_INVALID_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(!TableObject::isTableObject(obj_type) && obj_type!=ObjectType::Table) + throw Exception(ErrorCode::RemObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); - else if(obj_type==OBJ_TABLE && obj_idx < ancestor_tables.size()) + else if(obj_type==ObjectType::Table && obj_idx < ancestor_tables.size()) { vector
::iterator itr; Table *tab=nullptr; @@ -632,7 +783,7 @@ void Table::removeObject(unsigned obj_idx, ObjectType obj_type) } } } - else if(obj_type!=OBJ_TABLE && obj_type!=BASE_TABLE) + else if(obj_type!=ObjectType::Table && obj_type!=ObjectType::BaseTable) { vector *obj_list=nullptr; vector::iterator itr; @@ -641,9 +792,9 @@ void Table::removeObject(unsigned obj_idx, ObjectType obj_type) //Raises an error if the object index is out of bound if(obj_idx >= obj_list->size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(obj_type!=OBJ_COLUMN) + if(obj_type!=ObjectType::Column) { itr=obj_list->begin() + obj_idx; TableObject *tab_obj=(*itr); @@ -652,7 +803,7 @@ void Table::removeObject(unsigned obj_idx, ObjectType obj_type) tab_obj->setParentTable(nullptr); obj_list->erase(itr); - if(constr && constr->getConstraintType()==ConstraintType::primary_key) + if(constr && constr->getConstraintType()==ConstraintType::PrimaryKey) dynamic_cast(tab_obj)->setColumnsNotNull(false); } else @@ -669,14 +820,22 @@ void Table::removeObject(unsigned obj_idx, ObjectType obj_type) //Case some trigger, constraint, index is referencing the column raises an error if(!refs.empty()) { - throw Exception(Exception::getErrorMessage(ERR_REM_INDIRECT_REFERENCE) + throw Exception(Exception::getErrorMessage(ErrorCode::RemInderectReference) .arg(column->getName()) .arg(column->getTypeName()) .arg(refs[0]->getName()) .arg(refs[0]->getTypeName()) .arg(this->getName(true)) .arg(this->getTypeName()), - ERR_REM_INDIRECT_REFERENCE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::RemInderectReference,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + + //Raises an error if the column is being referenced by any partition key + if(isPartitionKeyRefColumn(column)) + { + throw Exception(Exception::getErrorMessage(ErrorCode::RemColumnRefByPartitionKey) + .arg(column->getName()).arg(this->getName(true)), + ErrorCode::RemColumnRefByPartitionKey,__PRETTY_FUNCTION__,__FILE__,__LINE__); } column->setParentTable(nullptr); @@ -691,11 +850,11 @@ void Table::removeColumn(const QString &name) { try { - removeObject(name,OBJ_COLUMN); + removeObject(name,ObjectType::Column); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -703,11 +862,11 @@ void Table::removeColumn(unsigned idx) { try { - removeObject(idx,OBJ_COLUMN); + removeObject(idx,ObjectType::Column); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -715,11 +874,11 @@ void Table::removeTrigger(const QString &name) { try { - removeObject(name,OBJ_TRIGGER); + removeObject(name,ObjectType::Trigger); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -727,11 +886,11 @@ void Table::removeTrigger(unsigned idx) { try { - removeObject(idx,OBJ_TRIGGER); + removeObject(idx,ObjectType::Trigger); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -739,11 +898,11 @@ void Table::removeIndex(const QString &name) { try { - removeObject(name,OBJ_INDEX); + removeObject(name,ObjectType::Index); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -751,11 +910,11 @@ void Table::removeIndex(unsigned idx) { try { - removeObject(idx,OBJ_INDEX); + removeObject(idx,ObjectType::Index); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -763,11 +922,11 @@ void Table::removeRule(const QString &name) { try { - removeObject(name,OBJ_RULE); + removeObject(name,ObjectType::Rule); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -775,11 +934,11 @@ void Table::removeRule(unsigned idx) { try { - removeObject(idx,OBJ_RULE); + removeObject(idx,ObjectType::Rule); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -787,11 +946,11 @@ void Table::removePolicy(const QString &name) { try { - removeObject(name, OBJ_POLICY); + removeObject(name, ObjectType::Policy); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -799,11 +958,11 @@ void Table::removePolicy(unsigned idx) { try { - removeObject(idx, OBJ_POLICY); + removeObject(idx, ObjectType::Policy); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -811,11 +970,11 @@ void Table::removeConstraint(const QString &name) { try { - removeObject(name,OBJ_CONSTRAINT); + removeObject(name,ObjectType::Constraint); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -823,11 +982,11 @@ void Table::removeConstraint(unsigned idx) { try { - removeObject(idx,OBJ_CONSTRAINT); + removeObject(idx,ObjectType::Constraint); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -835,11 +994,11 @@ void Table::removeAncestorTable(const QString &name) { try { - removeObject(name,OBJ_TABLE); + removeObject(name,ObjectType::Table); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -847,11 +1006,11 @@ void Table::removeAncestorTable(unsigned idx) { try { - removeObject(idx,OBJ_TABLE); + removeObject(idx,ObjectType::Table); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -929,7 +1088,7 @@ BaseObject *Table::getObject(const QString &name, ObjectType obj_type, int &obj_ } else obj_idx=-1; } - else if(obj_type==OBJ_TABLE) + else if(obj_type==ObjectType::Table) { vector
::iterator itr_tab, itr_end_tab; QString tab_name, aux_name=name; @@ -957,7 +1116,7 @@ BaseObject *Table::getObject(const QString &name, ObjectType obj_type, int &obj_ else obj_idx=-1; } else - throw Exception(ERR_OBT_OBJ_INVALID_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::ObtObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(object); } @@ -966,11 +1125,11 @@ BaseObject *Table::getObject(unsigned obj_idx, ObjectType obj_type) { vector *obj_list=nullptr; - if(obj_type==OBJ_TABLE) + if(obj_type==ObjectType::Table) { //Raises an error if the object index is out of bound if(obj_idx >= ancestor_tables.size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(ancestor_tables[obj_idx]); } @@ -981,19 +1140,19 @@ BaseObject *Table::getObject(unsigned obj_idx, ObjectType obj_type) return(obj_list->at(obj_idx)); else //Raises an error if the object index is out of bound - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } Table *Table::getAncestorTable(const QString &name) { int idx; - return(dynamic_cast
(getObject(name,OBJ_TABLE,idx))); + return(dynamic_cast
(getObject(name,ObjectType::Table,idx))); } Table *Table::getAncestorTable(unsigned idx) { - return(dynamic_cast
(getObject(idx,OBJ_TABLE))); + return(dynamic_cast
(getObject(idx,ObjectType::Table))); } Column *Table::getColumn(const QString &name, bool ref_old_name) @@ -1001,7 +1160,7 @@ Column *Table::getColumn(const QString &name, bool ref_old_name) if(!ref_old_name) { int idx; - return(dynamic_cast(getObject(name,OBJ_COLUMN,idx))); + return(dynamic_cast(getObject(name,ObjectType::Column,idx))); } else { @@ -1028,62 +1187,62 @@ Column *Table::getColumn(const QString &name, bool ref_old_name) Column *Table::getColumn(unsigned idx) { - return(dynamic_cast(getObject(idx,OBJ_COLUMN))); + return(dynamic_cast(getObject(idx,ObjectType::Column))); } Trigger *Table::getTrigger(const QString &name) { int idx; - return(dynamic_cast(getObject(name,OBJ_TRIGGER,idx))); + return(dynamic_cast(getObject(name,ObjectType::Trigger,idx))); } Trigger *Table::getTrigger(unsigned idx) { - return(dynamic_cast(getObject(idx,OBJ_TRIGGER))); + return(dynamic_cast(getObject(idx,ObjectType::Trigger))); } Constraint *Table::getConstraint(const QString &name) { int idx; - return(dynamic_cast(getObject(name,OBJ_CONSTRAINT,idx))); + return(dynamic_cast(getObject(name,ObjectType::Constraint,idx))); } Constraint *Table::getConstraint(unsigned idx) { - return(dynamic_cast(getObject(idx,OBJ_CONSTRAINT))); + return(dynamic_cast(getObject(idx,ObjectType::Constraint))); } Index *Table::getIndex(const QString &name) { int idx; - return(dynamic_cast(getObject(name,OBJ_INDEX,idx))); + return(dynamic_cast(getObject(name,ObjectType::Index,idx))); } Index *Table::getIndex(unsigned idx) { - return(dynamic_cast(getObject(idx,OBJ_INDEX))); + return(dynamic_cast(getObject(idx,ObjectType::Index))); } Rule *Table::getRule(const QString &name) { int idx; - return(dynamic_cast(getObject(name,OBJ_RULE,idx))); + return(dynamic_cast(getObject(name,ObjectType::Rule,idx))); } Rule *Table::getRule(unsigned idx) { - return(dynamic_cast(getObject(idx,OBJ_RULE))); + return(dynamic_cast(getObject(idx,ObjectType::Rule))); } Policy *Table::getPolicy(const QString &name) { int idx; - return(dynamic_cast(getObject(name, OBJ_POLICY,idx))); + return(dynamic_cast(getObject(name, ObjectType::Policy,idx))); } Policy *Table::getPolicy(unsigned idx) { - return(dynamic_cast(getObject(idx, OBJ_POLICY))); + return(dynamic_cast(getObject(idx, ObjectType::Policy))); } unsigned Table::getColumnCount(void) @@ -1123,9 +1282,9 @@ unsigned Table::getAncestorTableCount(void) unsigned Table::getObjectCount(ObjectType obj_type, bool inc_added_by_rel) { - if(TableObject::isTableObject(obj_type) || obj_type==OBJ_TABLE) + if(TableObject::isTableObject(obj_type) || obj_type==ObjectType::Table) { - if(obj_type==OBJ_TABLE) + if(obj_type==ObjectType::Table) { return(ancestor_tables.size()); } @@ -1154,7 +1313,7 @@ unsigned Table::getObjectCount(ObjectType obj_type, bool inc_added_by_rel) } } else - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); } Constraint *Table::getPrimaryKey(void) @@ -1166,7 +1325,7 @@ Constraint *Table::getPrimaryKey(void) for(i=0; i < count && !pk; i++) { constr=dynamic_cast(constraints[i]); - pk=(constr->getConstraintType()==ConstraintType::primary_key ? constr : nullptr); + pk=(constr->getConstraintType()==ConstraintType::PrimaryKey ? constr : nullptr); } return(pk); @@ -1182,7 +1341,7 @@ void Table::getForeignKeys(vector &fks, bool inc_added_by_rel, Tab { constr=dynamic_cast(constraints[i]); - if(constr->getConstraintType()==ConstraintType::foreign_key && + if(constr->getConstraintType()==ConstraintType::ForeignKey && (!ref_table || (ref_table && constr->getReferencedTable()==ref_table)) && (!constr->isAddedByLinking() || (constr->isAddedByLinking() && inc_added_by_rel))) @@ -1220,7 +1379,7 @@ bool Table::isReferTableOnForeignKey(Table *ref_tab) for(i=0; i < count && !found; i++) { constr=dynamic_cast(constraints[i]); - found=(constr->getConstraintType()==ConstraintType::foreign_key && + found=(constr->getConstraintType()==ConstraintType::ForeignKey && !constr->isAddedByLinking() && constr->getReferencedTable() == ref_tab); } @@ -1235,12 +1394,12 @@ void Table::setRelObjectsIndexes(const vector &obj_names, const vector< map *obj_idxs_map=nullptr; unsigned idx=0, size=obj_names.size(); - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) obj_idxs_map=&col_indexes; - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) obj_idxs_map=&constr_indexes; else - throw Exception(ERR_OPR_OBJ_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); for(idx=0; idx < size; idx++) (*obj_idxs_map)[obj_names[idx]]=idxs[idx]; @@ -1252,12 +1411,12 @@ void Table::saveRelObjectsIndexes(ObjectType obj_type) map *obj_idxs_map=nullptr; vector *list=nullptr; - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) { obj_idxs_map=&col_indexes; list=&columns; } - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) { obj_idxs_map=&constr_indexes; list=&constraints; @@ -1282,14 +1441,14 @@ void Table::saveRelObjectsIndexes(ObjectType obj_type) void Table::saveRelObjectsIndexes(void) { - saveRelObjectsIndexes(OBJ_COLUMN); - saveRelObjectsIndexes(OBJ_CONSTRAINT); + saveRelObjectsIndexes(ObjectType::Column); + saveRelObjectsIndexes(ObjectType::Constraint); } void Table::restoreRelObjectsIndexes(void) { - restoreRelObjectsIndexes(OBJ_COLUMN); - restoreRelObjectsIndexes(OBJ_CONSTRAINT); + restoreRelObjectsIndexes(ObjectType::Column); + restoreRelObjectsIndexes(ObjectType::Constraint); if(!col_indexes.empty() || !constr_indexes.empty()) { @@ -1302,7 +1461,7 @@ void Table::restoreRelObjectsIndexes(ObjectType obj_type) { map *obj_idxs=nullptr; - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) obj_idxs=&col_indexes; else obj_idxs=&constr_indexes; @@ -1404,6 +1563,25 @@ bool Table::isConstraintRefColumn(Column *column, ConstraintType constr_type) return(found); } +bool Table::isPartitionKeyRefColumn(Column *column) +{ + bool found=false; + + if(column) + { + for(auto &part_key : partition_keys) + { + if(part_key.getColumn() == column) + { + found = true; + break; + } + } + } + + return(found); +} + void Table::setGenerateAlterCmds(bool value) { setCodeInvalidated(gen_alter_cmds != value); @@ -1426,69 +1604,97 @@ void Table::updateAlterCmdsStatus(void) //Foreign keys are aways created as ALTER form for(i=0; i < constraints.size(); i++) constraints[i]->setDeclaredInTable(!gen_alter_cmds && - dynamic_cast(constraints[i])->getConstraintType()!=ConstraintType::foreign_key); -} - -QString Table::getCodeDefinition(unsigned def_type) -{ - QString code_def=getCachedCode(def_type, false); - if(!code_def.isEmpty()) return(code_def); + dynamic_cast(constraints[i])->getConstraintType()!=ConstraintType::ForeignKey); +} + +QString Table::__getCodeDefinition(unsigned def_type, bool incl_rel_added_objs) +{ + QStringList part_keys_code; + attributes[Attributes::Oids]=(with_oid ? Attributes::True : QString()); + attributes[Attributes::GenAlterCmds]=(gen_alter_cmds ? Attributes::True : QString()); + attributes[Attributes::Unlogged]=(unlogged ? Attributes::True : QString()); + attributes[Attributes::RlsEnabled]=(rls_enabled ? Attributes::True : QString()); + attributes[Attributes::RlsForced]=(rls_forced ? Attributes::True : QString()); + attributes[Attributes::CopyTable]=QString(); + attributes[Attributes::AncestorTable]=QString(); + attributes[Attributes::Tag]=QString(); + attributes[Attributes::Partitioning]=~partitioning_type; + attributes[Attributes::PartitionKey]=QString(); + attributes[Attributes::PartitionBoundExpr]=part_bounding_expr; + attributes[Attributes::Layer]=QString::number(layer); + attributes[Attributes::Pagination]=(pagination_enabled ? Attributes::True : QString()); + attributes[Attributes::CollapseMode]=QString::number(enum_cast(collapse_mode)); + attributes[Attributes::AttribsPage]=(pagination_enabled ? QString::number(curr_page[AttribsSection]) : QString()); + attributes[Attributes::ExtAttribsPage]=(pagination_enabled ? QString::number(curr_page[ExtAttribsSection]) : QString()); + + for(auto part_key : partition_keys) + part_keys_code+=part_key.getCodeDefinition(def_type); + + if(def_type == SchemaParser::SqlDefinition) + attributes[Attributes::PartitionKey]=part_keys_code.join(','); + else + attributes[Attributes::PartitionKey]=part_keys_code.join(' '); - attributes[ParsersAttributes::OIDS]=(with_oid ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::GEN_ALTER_CMDS]=(gen_alter_cmds ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::UNLOGGED]=(unlogged ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::RLS_ENABLED]=(rls_enabled ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::RLS_FORCED]=(rls_forced ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::COPY_TABLE]=QString(); - attributes[ParsersAttributes::ANCESTOR_TABLE]=QString(); - attributes[ParsersAttributes::TAG]=QString(); - attributes[ParsersAttributes::HIDE_EXT_ATTRIBS]=(isExtAttribsHidden() ? ParsersAttributes::_TRUE_ : QString()); + if(def_type==SchemaParser::SqlDefinition && copy_table) + attributes[Attributes::CopyTable]=copy_table->getName(true) + copy_op.getSQLDefinition(); - if(def_type==SchemaParser::SQL_DEFINITION && copy_table) - attributes[ParsersAttributes::COPY_TABLE]=copy_table->getName(true) + copy_op.getSQLDefinition(); + if(def_type==SchemaParser::SqlDefinition && partitioned_table) + attributes[Attributes::PartitionedTable]=partitioned_table->getName(true); - if(tag && def_type==SchemaParser::XML_DEFINITION) - attributes[ParsersAttributes::TAG]=tag->getCodeDefinition(def_type, true); + if(tag && def_type==SchemaParser::XmlDefinition) + attributes[Attributes::Tag]=tag->getCodeDefinition(def_type, true); (copy_table ? copy_table->getName(true) : QString()); - setColumnsAttribute(def_type); + setColumnsAttribute(def_type, incl_rel_added_objs); setConstraintsAttribute(def_type); setAncestorTableAttribute(); - if(def_type==SchemaParser::XML_DEFINITION) + if(def_type==SchemaParser::XmlDefinition) { setRelObjectsIndexesAttribute(); setPositionAttribute(); setFadedOutAttribute(); - attributes[ParsersAttributes::INITIAL_DATA]=initial_data; + attributes[Attributes::InitialData]=initial_data; + attributes[Attributes::MaxObjCount]=QString::number(static_cast(getMaxObjectCount() * 1.20)); } else - attributes[ParsersAttributes::INITIAL_DATA]=getInitialDataCommands(); + attributes[Attributes::InitialData]=getInitialDataCommands(); return(BaseObject::__getCodeDefinition(def_type)); } +QString Table::getCodeDefinition(unsigned def_type) +{ + QString code_def=getCachedCode(def_type, false); + if(!code_def.isEmpty()) return(code_def); + + return(__getCodeDefinition(def_type, false)); +} + void Table::operator = (Table &tab) { QString prev_name = this->getName(true); (*dynamic_cast(this))=dynamic_cast(tab); + this->layer = tab.layer; this->with_oid=tab.with_oid; this->col_indexes=tab.col_indexes; this->constr_indexes=tab.constr_indexes; + this->partitioning_type=tab.partitioning_type; + this->initial_data=tab.initial_data; + this->partition_keys=tab.partition_keys; + this->copy_op=tab.copy_op; + this->unlogged=tab.unlogged; - setGenerateAlterCmds(tab.gen_alter_cmds); - setProtected(tab.is_protected); - - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } bool Table::isReferRelationshipAddedObject(void) { vector::iterator itr, itr_end; - ObjectType types[]={ OBJ_COLUMN, OBJ_CONSTRAINT }; + ObjectType types[]={ ObjectType::Column, ObjectType::Constraint }; bool found=false; for(unsigned i=0; i < 2 && !found; i++) @@ -1506,6 +1712,16 @@ bool Table::isReferRelationshipAddedObject(void) return(found); } +bool Table::isPartition(void) +{ + return(partitioned_table != nullptr); +} + +bool Table::isPartitioned(void) +{ + return(partitioning_type != BaseType::Null); +} + void Table::swapObjectsIndexes(ObjectType obj_type, unsigned idx1, unsigned idx2) { vector *obj_list=nullptr; @@ -1520,7 +1736,7 @@ void Table::swapObjectsIndexes(ObjectType obj_type, unsigned idx1, unsigned idx2 //Raises an error if both index is out of list bounds if(idx1 >= obj_list->size() && idx2 >= obj_list->size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); //If the idx1 is out of bound inserts the element idx2 at the list's begin else if(idx1 >= obj_list->size()) { @@ -1549,7 +1765,7 @@ void Table::swapObjectsIndexes(ObjectType obj_type, unsigned idx1, unsigned idx2 (*itr2)=aux_obj; } - if(obj_type!=OBJ_COLUMN && obj_type!=OBJ_CONSTRAINT) + if(obj_type!=ObjectType::Column && obj_type!=ObjectType::Constraint) BaseObject::swapObjectsIds(aux_obj, aux_obj1, false); setCodeInvalidated(true); @@ -1557,7 +1773,7 @@ void Table::swapObjectsIndexes(ObjectType obj_type, unsigned idx1, unsigned idx2 } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1634,15 +1850,17 @@ void Table::getColumnReferences(Column *column, vector &refs, boo } } -vector Table::getObjects(bool excl_cols_constr) + +vector Table::getObjects(const vector &excl_types) { vector list; - vector types={ OBJ_COLUMN, OBJ_CONSTRAINT, - OBJ_TRIGGER, OBJ_INDEX, OBJ_RULE, OBJ_POLICY }; + vector types={ ObjectType::Column, ObjectType::Constraint, + ObjectType::Trigger, ObjectType::Index, + ObjectType::Rule, ObjectType::Policy }; for(auto type : types) { - if(excl_cols_constr && (type == OBJ_COLUMN || type == OBJ_CONSTRAINT)) + if(std::find(excl_types.begin(), excl_types.end(), type) != excl_types.end()) continue; list.insert(list.end(), getObjectList(type)->begin(), getObjectList(type)->end()) ; @@ -1651,15 +1869,16 @@ vector Table::getObjects(bool excl_cols_constr) return(list); } -vector Table::getObjects(void) +vector Table::getPartitionKeys(void) { - return(getObjects(false)); + return(partition_keys); } void Table::setCodeInvalidated(bool value) { - vector types={ OBJ_COLUMN, OBJ_CONSTRAINT, - OBJ_TRIGGER, OBJ_INDEX, OBJ_RULE, OBJ_POLICY }; + vector types={ ObjectType::Column, ObjectType::Constraint, + ObjectType::Trigger, ObjectType::Index, + ObjectType::Rule, ObjectType::Policy }; for(auto type : types) { @@ -1675,31 +1894,31 @@ QString Table::getAlterDefinition(BaseObject *object) Table *tab=dynamic_cast
(object); if(!tab) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { QString alter_def; attribs_map attribs; - attribs[ParsersAttributes::OIDS]=QString(); - attribs[ParsersAttributes::ALTER_CMDS]=BaseObject::getAlterDefinition(object, true); + attribs[Attributes::Oids]=QString(); + attribs[Attributes::AlterCmds]=BaseObject::getAlterDefinition(object, true); if(this->getName()==tab->getName()) { - attribs[ParsersAttributes::HAS_CHANGES]=ParsersAttributes::_TRUE_; + attribs[Attributes::HasChanges]=Attributes::True; if(this->with_oid!=tab->with_oid) - attribs[ParsersAttributes::OIDS]=(tab->with_oid ? ParsersAttributes::_TRUE_ : ParsersAttributes::UNSET); + attribs[Attributes::Oids]=(tab->with_oid ? Attributes::True : Attributes::Unset); if(this->unlogged!=tab->unlogged) - attribs[ParsersAttributes::UNLOGGED]=(tab->unlogged ? ParsersAttributes::_TRUE_ : ParsersAttributes::UNSET); + attribs[Attributes::Unlogged]=(tab->unlogged ? Attributes::True : Attributes::Unset); if(this->rls_enabled!=tab->rls_enabled) - attribs[ParsersAttributes::RLS_ENABLED]=(tab->rls_enabled ? ParsersAttributes::_TRUE_ : ParsersAttributes::UNSET); + attribs[Attributes::RlsEnabled]=(tab->rls_enabled ? Attributes::True : Attributes::Unset); if(this->rls_forced!=tab->rls_forced) - attribs[ParsersAttributes::RLS_FORCED]=(tab->rls_forced ? ParsersAttributes::_TRUE_ : ParsersAttributes::UNSET); + attribs[Attributes::RlsForced]=(tab->rls_forced ? Attributes::True : Attributes::Unset); } copyAttributes(attribs); @@ -1709,7 +1928,7 @@ QString Table::getAlterDefinition(BaseObject *object) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1718,12 +1937,12 @@ QString Table::getTruncateDefinition(bool cascade) try { BaseObject::setBasicAttributes(true); - attributes[ParsersAttributes::CASCADE]=(cascade ? ParsersAttributes::_TRUE_ : QString()); - return(BaseObject::getAlterDefinition(ParsersAttributes::TRUNCATE_PRIV, attributes, false, false)); + attributes[Attributes::Cascade]=(cascade ? Attributes::True : QString()); + return(BaseObject::getAlterDefinition(Attributes::TruncatePriv, attributes, false, false)); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1740,7 +1959,7 @@ QString Table::getInitialData(void) QString Table::getInitialDataCommands(void) { - QStringList buffer=initial_data.split(DATA_LINE_BREAK); + QStringList buffer=initial_data.split(DataLineBreak); if(!buffer.isEmpty() && !buffer.at(0).isEmpty()) { @@ -1748,14 +1967,14 @@ QString Table::getInitialDataCommands(void) int curr_col=0; QList ignored_cols; - col_names=(buffer.at(0)).split(DATA_SEPARATOR); + col_names=(buffer.at(0)).split(DataSeparator); col_names.removeDuplicates(); buffer.removeFirst(); //Separating valid columns (selected) from the invalids (ignored) for(QString col_name : col_names) { - if(getObjectIndex(col_name, OBJ_COLUMN) >= 0) + if(getObjectIndex(col_name, ObjectType::Column) >= 0) selected_cols.append(col_name); else ignored_cols.append(curr_col); @@ -1768,7 +1987,7 @@ QString Table::getInitialDataCommands(void) curr_col=0; //Filtering the invalid columns' values - for(QString value : buf_row.split(DATA_SEPARATOR)) + for(QString value : buf_row.split(DataSeparator)) { if(ignored_cols.contains(curr_col)) continue; @@ -1803,7 +2022,7 @@ QString Table::createInsertCommand(const QStringList &col_names, const QStringLi value=QString("DEFAULT"); } //Unescaped values will not be enclosed in quotes - else if(value.startsWith(PgModelerNS::UNESC_VALUE_START) && value.endsWith(PgModelerNS::UNESC_VALUE_END)) + else if(value.startsWith(PgModelerNs::UnescValueStart) && value.endsWith(PgModelerNs::UnescValueEnd)) { value.remove(0,1); value.remove(value.length()-1, 1); @@ -1811,8 +2030,8 @@ QString Table::createInsertCommand(const QStringList &col_names, const QStringLi //Quoting value else { - value.replace(QString("\\") + PgModelerNS::UNESC_VALUE_START, PgModelerNS::UNESC_VALUE_START); - value.replace(QString("\\") + PgModelerNS::UNESC_VALUE_END, PgModelerNS::UNESC_VALUE_END); + value.replace(QString("\\") + PgModelerNs::UnescValueStart, PgModelerNs::UnescValueStart); + value.replace(QString("\\") + PgModelerNs::UnescValueEnd, PgModelerNs::UnescValueEnd); value.replace(QString("\'"), QString("''")); value.replace(QChar(QChar::LineFeed), QString("\\n")); value=QString("E'") + value + QString("'"); @@ -1834,8 +2053,36 @@ QString Table::createInsertCommand(const QStringList &col_names, const QStringLi } fmt_cmd=insert_cmd.arg(getSignature()).arg(col_list.join(", ")) - .arg(val_list.join(", ")).arg(ParsersAttributes::DDL_END_TOKEN); + .arg(val_list.join(", ")).arg(Attributes::DdlEndToken); } return(fmt_cmd); } + +void Table::setObjectListsCapacity(unsigned capacity) +{ + if(capacity < DefMaxObjectCount || capacity > DefMaxObjectCount * 10) + capacity = DefMaxObjectCount; + + columns.reserve(capacity); + constraints.reserve(capacity/2); + indexes.reserve(capacity/2); + rules.reserve(capacity/2); + triggers.reserve(capacity/2); + policies.reserve(capacity/2); +} + +unsigned Table::getMaxObjectCount(void) +{ + unsigned count = 0, max = 0; + vector types = { ObjectType::Column, ObjectType::Constraint, ObjectType::Index, + ObjectType::Rule, ObjectType::Trigger, ObjectType::Policy }; + + for(auto type : types) + { + count = getObjectList(type)->size(); + if(count > max) max = count; + } + + return(max); +} diff --git a/libpgmodeler/src/table.h b/libpgmodeler/src/table.h index f94db964e8..87ac2e2cab 100644 --- a/libpgmodeler/src/table.h +++ b/libpgmodeler/src/table.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -36,6 +36,7 @@ #include "role.h" #include "policy.h" #include "copyoptions.h" +#include "partitionkey.h" #include class Table: public BaseTable { @@ -44,6 +45,9 @@ class Table: public BaseTable { This will produce a set of INSERT commands that is appended to the table's SQL definition */ QString initial_data; + //! \brief The partition bounding expression + QString part_bounding_expr; + //! \brief Vectors that store basic table attributes vector columns; vector constraints; @@ -55,6 +59,15 @@ class Table: public BaseTable { //! \brief Stores the tables that 'this' object inherits attributes vector
ancestor_tables; + //! \brief Stores the tables that 'this' object has as its partitions + vector
partition_tables; + + //! \brief Stores the partition keys of the table partitioning being used + vector partition_keys; + + //! \brief Stores the table which this one is partition of + Table *partitioned_table; + //! \brief Specifies the table from which columns are copied Table *copy_table; @@ -80,24 +93,35 @@ class Table: public BaseTable { //! \brief Stores the relationship added column / constraints indexes map col_indexes, constr_indexes; - /*! \brief Gets one table ancestor (OBJ_TABLE) or copy (BASE_TABLE) using its name and stores + //! \brief The partitioning mode/type used by the table + PartitioningType partitioning_type; + + /*! \brief Gets one table ancestor (ObjectType::Table) or copy (ObjectType::ObjBaseTable) using its name and stores the index of the found object on parameter 'obj_idx' */ BaseObject *getObject(const QString &name, ObjectType obj_type, int &obj_idx); //! \brief The methods below generates the table attributes used by the SchemaParser - void setColumnsAttribute(unsigned def_type); + void setColumnsAttribute(unsigned def_type, bool incl_rel_added_cols); void setConstraintsAttribute(unsigned def_type); void setCommentAttribute(TableObject *tab_obj); void setAncestorTableAttribute(void); - void setRelObjectsIndexesAttribute(void); + void setRelObjectsIndexesAttribute(void); protected: //! \brief Adds an ancestor table void addAncestorTable(Table *tab, int idx=-1); - //! \brief Adds an copy table - void addCopyTable(Table *tab, int idx=-1); + //! \brief Adds a partition table + void addPartitionTable(Table *tab); + + //! \brief Removes a partition table + void removePartitionTable(Table *tab); + /*! \brief Returns the index of the partition table. If the + * compare_names is true then the search will compare the names if + * the object itself is not present in the list of partitions */ + int getPartitionTableIndex(Table *tab, bool compare_names); + //! \brief Removes an acestor table using its name void removeAncestorTable(const QString &name); @@ -116,10 +140,10 @@ class Table: public BaseTable { public: //! \brief Default char for data separator in initial-data tag - static const QString DATA_SEPARATOR, + static const QString DataSeparator, //! \brief Default char for data line break in initial-data tag - DATA_LINE_BREAK; + DataLineBreak; Table(void); ~Table(void); @@ -139,6 +163,15 @@ class Table: public BaseTable { //! \brief Defines if the row level security on table is forced for the table owner void setRLSForced(bool value); + //! \brief Defines if the partitioning type of the table + void setPartitioningType(PartitioningType part_type); + + //! \brief Returns the current partitioning type defined for the table + PartitioningType getPartitioningType(void); + + //! \brief Returns the partitioned table which this table is a partition of + Table *getPartitionedTable(void); + //! \brief Adds an object to the table. It can be inserted at a specified index 'obj_idx'. void addObject(BaseObject *obj, int obj_idx=-1); @@ -175,12 +208,33 @@ class Table: public BaseTable { //! \brief Adds a policy to table (optionally the user can add the object at the specified index 'idx') void addPolicy(Policy *pol, int idx_pol=-1); + //! \brief Adds a partition table + void setPartionedTable(Table *table); + + //! \brief Defines the partition bounding expression + void setPartitionBoundingExpr(const QString part_bound_expr); + + //! \brief Returns the partition bounding expression + QString getPartitionBoundingExpr(void); + + //! \brief Returns the partition tables + vector
getPartionTables(void); + + //! \brief Returs if the provided table is amongst the partitions + bool isPartitionTableExists(Table *table, bool compare_names); + //! \brief Configures the copy table void setCopyTable(Table *tab); //! \brief Configures the copy table options void setCopyTableOptions(CopyOptions copy_op); + //! \brief Adds partition keys to the table. This method overrides the currently configure partition keys. + void addPartitionKeys(vector &part_keys); + + //! \brief Remove all partition keys configured for the table + void removePartitionKeys(void); + //! \brief Returns the copy table Table *getCopyTable(void); @@ -305,12 +359,11 @@ class Table: public BaseTable { //! \brief Returns the primary key of the table. Returns nullptr when it doesn't exists Constraint *getPrimaryKey(void); - /*! \brief Returns all child objects of the table. If the excl_cols_contr is true - then the method will return all objects except columns and constraint */ - vector getObjects(bool excl_cols_constr); + //! \brief Returns the children objects of the table excluding the provided children types + vector getObjects(const vector &excl_types = {}); - //! \brief Returns all child objects of the table. This is the same as call getObjects(false) - vector getObjects(void); + //! \brief Returns all the partition keys used by the table + vector getPartitionKeys(void); /*! \brief Stores on the specified vector 'fks' the foreign key present on table. The boolean paramenter is used to include those foreign keys includes by relationship. The third parameter @@ -342,11 +395,21 @@ class Table: public BaseTable { The user must specify the constraint type */ bool isConstraintRefColumn(Column *column, ConstraintType constr_type); + /*! \brief Returns if the specified column is referenced by one of the constraints on table. + The user must specify the constraint type */ + bool isPartitionKeyRefColumn(Column *column); + //! \brief Swaps two objects position void swapObjectsIndexes(ObjectType obj_type, unsigned idx1, unsigned idx2); //! \brief Returns if the table references objects added by relationship bool isReferRelationshipAddedObject(void); + + //! \brief Returns if the table is a partition of another table + bool isPartition(void); + + //! \brief Returns if the table is a partitioned. This is the same as getPartitioningType() != BaseType::null + bool isPartitioned(void); //! \brief Copy the attributes between two tables void operator = (Table &tabela); @@ -393,6 +456,16 @@ class Table: public BaseTable { In invalid columns exist in the buffer they will be rejected when generating the commands */ QString getInitialDataCommands(void); + /*! \brief Generates the table's SQL code considering adding the relationship added object or not. + * Note if the method is called with incl_rel_added_objs = true it can produce an SQL/XML code + * that does not reflect the real semantics of the table. So take care to use this method and always + * invalidate the tables code (see setCodeInvalidated()) after retrieving the resulting code */ + QString __getCodeDefinition(unsigned def_type, bool incl_rel_added_objs); + + void setObjectListsCapacity(unsigned capacity); + + unsigned getMaxObjectCount(void); + friend class Relationship; friend class OperationList; }; diff --git a/libpgmodeler/src/tableobject.cpp b/libpgmodeler/src/tableobject.cpp index 0b4b6f500c..8d3514cd1b 100644 --- a/libpgmodeler/src/tableobject.cpp +++ b/libpgmodeler/src/tableobject.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -89,8 +89,8 @@ bool TableObject::isDeclaredInTable(void) bool TableObject::isTableObject(ObjectType type) { - return(type==OBJ_COLUMN || type==OBJ_CONSTRAINT || type==OBJ_TRIGGER || - type==OBJ_RULE || type==OBJ_INDEX || type==OBJ_POLICY); + return(type==ObjectType::Column || type==ObjectType::Constraint || type==ObjectType::Trigger || + type==ObjectType::Rule || type==ObjectType::Index || type==ObjectType::Policy); } void TableObject::operator = (TableObject &object) @@ -114,9 +114,9 @@ void TableObject::setCodeInvalidated(bool value) QString TableObject::getDropDefinition(bool cascade) { if(getParentTable()) - attributes[ParsersAttributes::TABLE]=getParentTable()->getName(true); + attributes[Attributes::Table]=getParentTable()->getName(true); - attributes[this->getSchemaName()]=ParsersAttributes::_TRUE_; + attributes[this->getSchemaName()]=Attributes::True; return(BaseObject::getDropDefinition(cascade)); } diff --git a/libpgmodeler/src/tableobject.h b/libpgmodeler/src/tableobject.h index 06e155d0f9..35058d82af 100644 --- a/libpgmodeler/src/tableobject.h +++ b/libpgmodeler/src/tableobject.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libpgmodeler/src/tablespace.cpp b/libpgmodeler/src/tablespace.cpp index 1531dd87d9..3973edde96 100644 --- a/libpgmodeler/src/tablespace.cpp +++ b/libpgmodeler/src/tablespace.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -22,8 +22,8 @@ unsigned Tablespace::tabspace_id=1000; Tablespace::Tablespace(void) { - obj_type=OBJ_TABLESPACE; - attributes[ParsersAttributes::DIRECTORY]=QString(); + obj_type=ObjectType::Tablespace; + attributes[Attributes::Directory]=QString(); object_id=Tablespace::tabspace_id++; } @@ -32,10 +32,10 @@ void Tablespace::setName(const QString &name) /* Tablespace names starting with pg_ is reserved to PostgreSQL if its the case raises an error */ if(name.mid(0,3)==QString("pg_")) - throw Exception(Exception::getErrorMessage(ERR_ASG_RESERVED_NAME) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgReservedName) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_TABLESPACE)), - ERR_ASG_RESERVED_NAME,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Tablespace)), + ErrorCode::AsgReservedName,__PRETTY_FUNCTION__,__FILE__,__LINE__); BaseObject::setName(name); } @@ -47,7 +47,7 @@ void Tablespace::setDirectory(const QString &dir) //Raises an error if the directory is an empty path if(dir_aux.isEmpty()) - throw Exception(ERR_ASG_EMPTY_DIR_NAME,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgEmptyDirectoryName,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->directory != dir_aux); this->directory=dir_aux; @@ -64,7 +64,7 @@ QString Tablespace::getCodeDefinition(unsigned def_type) if(!code_def.isEmpty()) return(code_def); if(!directory.isEmpty()) - attributes[ParsersAttributes::DIRECTORY]=QString("'") + directory + QString("'"); + attributes[Attributes::Directory]=QString("'") + directory + QString("'"); return(BaseObject::__getCodeDefinition(def_type)); } diff --git a/libpgmodeler/src/tablespace.h b/libpgmodeler/src/tablespace.h index 4ea0052549..03eff268e4 100644 --- a/libpgmodeler/src/tablespace.h +++ b/libpgmodeler/src/tablespace.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libpgmodeler/src/tag.cpp b/libpgmodeler/src/tag.cpp index 0a736bb857..38f7c546d5 100644 --- a/libpgmodeler/src/tag.cpp +++ b/libpgmodeler/src/tag.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -22,17 +22,17 @@ unsigned Tag::tag_id=3000; Tag::Tag(void) { - QStringList attribs={ ParsersAttributes::TABLE_NAME, ParsersAttributes::TABLE_SCHEMA_NAME, - ParsersAttributes::TABLE_TITLE, ParsersAttributes::TABLE_BODY, - ParsersAttributes::TABLE_EXT_BODY }; + QStringList attribs={ Attributes::TableName, Attributes::TableSchemaName, + Attributes::TableTitle, Attributes::TableBody, + Attributes::TableExtBody }; - obj_type=OBJ_TAG; + obj_type=ObjectType::Tag; object_id=Tag::tag_id++; - attributes[ParsersAttributes::STYLES]=QString(); + attributes[Attributes::Styles]=QString(); for(auto &attr : attribs) { - if(attr!=ParsersAttributes::TABLE_NAME && attr!=ParsersAttributes::TABLE_SCHEMA_NAME) + if(attr!=Attributes::TableName && attr!=Attributes::TableSchemaName) color_config[attr] = { QColor(0,0,0), QColor(0,0,0), QColor(0,0,0) }; else color_config[attr] = { QColor(0,0,0) }; @@ -42,9 +42,9 @@ Tag::Tag(void) void Tag::setName(const QString &name) { if(name.isEmpty()) - throw Exception(ERR_ASG_EMPTY_NAME_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); - else if(name.size() > BaseObject::OBJECT_NAME_MAX_LENGTH) - throw Exception(ERR_ASG_LONG_NAME_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgEmptyNameObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(name.size() > BaseObject::ObjectNameMaxLength) + throw Exception(ErrorCode::AsgLongNameObject ,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->obj_name=name; } @@ -64,7 +64,7 @@ void Tag::setElementColor(const QString &elem_id, const QColor &color, unsigned } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -73,7 +73,7 @@ void Tag::setElementColors(const QString &elem_id, const QString &colors) try { QStringList color_lst=colors.split(','); - unsigned color_id=FILL_COLOR1; + unsigned color_id=FillColor1; for(auto &color : color_lst) { @@ -86,7 +86,7 @@ void Tag::setElementColors(const QString &elem_id, const QString &colors) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -99,20 +99,20 @@ QColor Tag::getElementColor(const QString &elem_id, unsigned color_id) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void Tag::validateElementId(const QString &id, unsigned color_id) { if(color_config.count(id) == 0) - throw Exception(Exception::getErrorMessage(ERR_OPR_INV_ELEMENT_ID).arg(id), - ERR_OPR_INV_ELEMENT_ID ,__PRETTY_FUNCTION__,__FILE__,__LINE__); - else if((color_id > COLOR_COUNT) || + throw Exception(Exception::getErrorMessage(ErrorCode::OprInvalidElementId).arg(id), + ErrorCode::OprInvalidElementId ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if((color_id > ColorCount) || (color_id > 0 && - (id==ParsersAttributes::TABLE_NAME || id==ParsersAttributes::TABLE_SCHEMA_NAME))) - throw Exception(Exception::getErrorMessage(ERR_REF_ELEMENT_COLOR_ID).arg(id).arg(color_id), - ERR_REF_ELEMENT_COLOR_ID ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + (id==Attributes::TableName || id==Attributes::TableSchemaName))) + throw Exception(Exception::getErrorMessage(ErrorCode::RefInvalidElementColorId).arg(id).arg(color_id), + ErrorCode::RefInvalidElementColorId ,__PRETTY_FUNCTION__,__FILE__,__LINE__); } QLinearGradient Tag::getFillStyle(const QString &elem_id) @@ -123,14 +123,14 @@ QLinearGradient Tag::getFillStyle(const QString &elem_id) QLinearGradient grad(QPointF(0,0),QPointF(0,1)); grad.setCoordinateMode(QGradient::ObjectBoundingMode); - grad.setColorAt(0, color_config[elem_id][FILL_COLOR1]); - grad.setColorAt(1, color_config[elem_id][FILL_COLOR2]); + grad.setColorAt(0, color_config[elem_id][FillColor1]); + grad.setColorAt(1, color_config[elem_id][FillColor2]); return(grad); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -141,7 +141,7 @@ QString Tag::getCodeDefinition(unsigned def_type) QString Tag::getCodeDefinition(unsigned def_type, bool reduced_form) { - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) return(QString()); else { @@ -154,21 +154,21 @@ QString Tag::getCodeDefinition(unsigned def_type, bool reduced_form) for(auto &itr : color_config) { - attribs[ParsersAttributes::ID]=itr.first; - attribs[ParsersAttributes::COLORS]=QString(); + attribs[Attributes::Id]=itr.first; + attribs[Attributes::Colors]=QString(); - if(itr.first==ParsersAttributes::TABLE_NAME || itr.first==ParsersAttributes::TABLE_SCHEMA_NAME) - attribs[ParsersAttributes::COLORS]=itr.second[FILL_COLOR1].name(); + if(itr.first==Attributes::TableName || itr.first==Attributes::TableSchemaName) + attribs[Attributes::Colors]=itr.second[FillColor1].name(); else - attribs[ParsersAttributes::COLORS]=itr.second[FILL_COLOR1].name() + QString(",") + - itr.second[FILL_COLOR2].name() + QString(",") + itr.second[BORDER_COLOR].name(); + attribs[Attributes::Colors]=itr.second[FillColor1].name() + QString(",") + + itr.second[FillColor2].name() + QString(",") + itr.second[BorderColor].name(); - attributes[ParsersAttributes::STYLES]+=schparser.getCodeDefinition(ParsersAttributes::STYLE, attribs, SchemaParser::XML_DEFINITION); + attributes[Attributes::Styles]+=schparser.getCodeDefinition(Attributes::Style, attribs, SchemaParser::XmlDefinition); } } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } return(BaseObject::getCodeDefinition(def_type, reduced_form)); diff --git a/libpgmodeler/src/tag.h b/libpgmodeler/src/tag.h index e4ca3a6809..b31b407d89 100644 --- a/libpgmodeler/src/tag.h +++ b/libpgmodeler/src/tag.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -43,10 +43,10 @@ class Tag: public BaseObject { void validateElementId(const QString &elem_id, unsigned color_id); public: - static const unsigned FILL_COLOR1=0, - FILL_COLOR2=1, - BORDER_COLOR=2, - COLOR_COUNT=3; + static constexpr unsigned FillColor1=0, + FillColor2=1, + BorderColor=2, + ColorCount=3; Tag(void); diff --git a/libpgmodeler/src/textbox.cpp b/libpgmodeler/src/textbox.cpp index 53ab434176..6b46d8b8dc 100644 --- a/libpgmodeler/src/textbox.cpp +++ b/libpgmodeler/src/textbox.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,19 +20,19 @@ Textbox::Textbox(void) { - obj_type=OBJ_TEXTBOX; - font_size=9.0f; + obj_type=ObjectType::Textbox; + font_size=9.0; text_attributes[0]=text_attributes[1]=text_attributes[2]=false; - attributes[ParsersAttributes::ITALIC]=QString(); - attributes[ParsersAttributes::BOLD]=QString(); - attributes[ParsersAttributes::UNDERLINE]=QString(); - attributes[ParsersAttributes::COLOR]=QString(); - attributes[ParsersAttributes::FONT_SIZE]=QString(); + attributes[Attributes::Italic]=QString(); + attributes[Attributes::Bold]=QString(); + attributes[Attributes::Underline]=QString(); + attributes[Attributes::Color]=QString(); + attributes[Attributes::FontSize]=QString(); } QString Textbox::getCodeDefinition(unsigned def_type) { - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) return(QString()); else { @@ -42,21 +42,22 @@ QString Textbox::getCodeDefinition(unsigned def_type) setPositionAttribute(); setFadedOutAttribute(); - if(text_attributes[ITALIC_TXT]) - attributes[ParsersAttributes::ITALIC]=ParsersAttributes::_TRUE_; + if(text_attributes[ItalicText]) + attributes[Attributes::Italic]=Attributes::True; - if(text_attributes[BOLD_TXT]) - attributes[ParsersAttributes::BOLD]=ParsersAttributes::_TRUE_; + if(text_attributes[BoldText]) + attributes[Attributes::Bold]=Attributes::True; - if(text_attributes[UNDERLINE_TXT]) - attributes[ParsersAttributes::UNDERLINE]=ParsersAttributes::_TRUE_; + if(text_attributes[UnderlineText]) + attributes[Attributes::Underline]=Attributes::True; if(text_color.name()!=QString("#000000")) - attributes[ParsersAttributes::COLOR]=text_color.name(); + attributes[Attributes::Color]=text_color.name(); - attributes[ParsersAttributes::FONT_SIZE]=QString("%1").arg(font_size); + attributes[Attributes::FontSize]=QString("%1").arg(font_size); + attributes[Attributes::Layer]=QString::number(layer); - return(this->BaseObject::__getCodeDefinition(SchemaParser::XML_DEFINITION)); + return(this->BaseObject::__getCodeDefinition(SchemaParser::XmlDefinition)); } } @@ -69,12 +70,13 @@ void Textbox::operator = (Textbox &txtbox) this->text_attributes[2]=txtbox.text_attributes[2]; this->text_color=txtbox.text_color; this->font_size=txtbox.font_size; + this->layer = txtbox.layer; } void Textbox::setTextAttribute(unsigned attrib, bool value) { - if(attrib > UNDERLINE_TXT) - throw Exception(ERR_REF_ATTRIB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(attrib > UnderlineText) + throw Exception(ErrorCode::RefAttributeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); text_attributes[attrib]=value; } @@ -91,8 +93,8 @@ QColor Textbox::getTextColor(void) bool Textbox::getTextAttribute(unsigned attrib) { - if(attrib > UNDERLINE_TXT) - throw Exception(ERR_REF_ATTRIB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(attrib > UnderlineText) + throw Exception(ErrorCode::RefAttributeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(text_attributes[attrib]); } diff --git a/libpgmodeler/src/textbox.h b/libpgmodeler/src/textbox.h index 321e3f8c07..c6db6a8f1d 100644 --- a/libpgmodeler/src/textbox.h +++ b/libpgmodeler/src/textbox.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -42,9 +42,9 @@ class Textbox: public BaseGraphicObject{ public: //! \brief Constants used to configure the text attributes - static const unsigned ITALIC_TXT=0, - BOLD_TXT=1, - UNDERLINE_TXT=2; + static constexpr unsigned ItalicText=0, + BoldText=1, + UnderlineText=2; /*! \brief To define the content of the textboxes the method setComment() must be used and the getComment() diff --git a/libpgmodeler/src/trigger.cpp b/libpgmodeler/src/trigger.cpp index 0b26af80e2..0c75999bf8 100644 --- a/libpgmodeler/src/trigger.cpp +++ b/libpgmodeler/src/trigger.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -21,34 +21,36 @@ Trigger::Trigger(void) { unsigned i; - EventType tipos[4]={EventType::on_insert, EventType::on_delete, - EventType::on_update, EventType::on_truncate}; + EventType tipos[4]={EventType::OnInsert, EventType::OnDelete, + EventType::OnUpdate, EventType::OnTruncate}; function=nullptr; is_exec_per_row=is_constraint=is_deferrable=false; - obj_type=OBJ_TRIGGER; + obj_type=ObjectType::Trigger; referenced_table=nullptr; for(i=0; i < 4; i++) events[tipos[i]]=false; - attributes[ParsersAttributes::ARGUMENTS]=QString(); - attributes[ParsersAttributes::EVENTS]=QString(); - attributes[ParsersAttributes::TRIGGER_FUNC]=QString(); - attributes[ParsersAttributes::TABLE]=QString(); - attributes[ParsersAttributes::COLUMNS]=QString(); - attributes[ParsersAttributes::FIRING_TYPE]=QString(); - attributes[ParsersAttributes::PER_ROW]=QString(); - attributes[ParsersAttributes::INS_EVENT]=QString(); - attributes[ParsersAttributes::DEL_EVENT]=QString(); - attributes[ParsersAttributes::UPD_EVENT]=QString(); - attributes[ParsersAttributes::TRUNC_EVENT]=QString(); - attributes[ParsersAttributes::CONDITION]=QString(); - attributes[ParsersAttributes::REF_TABLE]=QString(); - attributes[ParsersAttributes::DEFER_TYPE]=QString(); - attributes[ParsersAttributes::DEFERRABLE]=QString(); - attributes[ParsersAttributes::DECL_IN_TABLE]=QString(); - attributes[ParsersAttributes::CONSTRAINT]=QString(); + attributes[Attributes::Arguments]=QString(); + attributes[Attributes::Events]=QString(); + attributes[Attributes::TriggerFunc]=QString(); + attributes[Attributes::Table]=QString(); + attributes[Attributes::Columns]=QString(); + attributes[Attributes::FiringType]=QString(); + attributes[Attributes::PerRow]=QString(); + attributes[Attributes::InsEvent]=QString(); + attributes[Attributes::DelEvent]=QString(); + attributes[Attributes::UpdEvent]=QString(); + attributes[Attributes::TruncEvent]=QString(); + attributes[Attributes::Condition]=QString(); + attributes[Attributes::RefTable]=QString(); + attributes[Attributes::DeferType]=QString(); + attributes[Attributes::Deferrable]=QString(); + attributes[Attributes::DeclInTable]=QString(); + attributes[Attributes::Constraint]=QString(); + attributes[Attributes::OldTableName]=QString(); + attributes[Attributes::NewTableName]=QString(); } void Trigger::addArgument(const QString &arg) @@ -64,7 +66,7 @@ void Trigger::setArgumentAttribute(unsigned def_type) count=arguments.size(); for(i=0; i < count; i++) { - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) str_args+=QString("'") + arguments[i] + QString("'"); else str_args+=arguments[i]; @@ -72,7 +74,7 @@ void Trigger::setArgumentAttribute(unsigned def_type) if(i < (count-1)) str_args+=QString(","); } - attributes[ParsersAttributes::ARGUMENTS]=str_args; + attributes[Attributes::Arguments]=str_args; } void Trigger::setFiringType(FiringType firing_type) @@ -83,8 +85,8 @@ void Trigger::setFiringType(FiringType firing_type) void Trigger::setEvent(EventType event, bool value) { - if(event==EventType::on_select) - throw Exception(ERR_REF_INV_TRIGGER_EVENT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(event==EventType::OnSelect) + throw Exception(ErrorCode::RefInvalidTriggerEvent,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(events[event] != value); events[event]=value; @@ -94,21 +96,21 @@ void Trigger::setFunction(Function *func) { //Case the function is null an error is raised if(!func) - throw Exception(Exception::getErrorMessage(ERR_ASG_NOT_ALOC_FUNCTION) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgNotAllocatedFunction) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_TRIGGER)), - ERR_ASG_NOT_ALOC_FUNCTION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Trigger)), + ErrorCode::AsgNotAllocatedFunction,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { //Case the function doesn't returns 'trigger' it cannot be used with the trigger thus raise an error if(func->getReturnType()!=QString("trigger")) - throw Exception(Exception::getErrorMessage(ERR_ASG_INV_TRIGGER_FUNCTION).arg(QString("trigger")),__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidTriggerFunction).arg(QString("trigger")),__PRETTY_FUNCTION__,__FILE__,__LINE__); //Case the function has some parameters raise an error else if(func->getParameterCount()!=0) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNC_INV_PARAM_COUNT) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidParamCount) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_TRIGGER)), - ERR_ASG_FUNC_INV_PARAM_COUNT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Trigger)), + ErrorCode::AsgFunctionInvalidParamCount,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(function != func); this->function=func; @@ -124,21 +126,21 @@ void Trigger::setCondition(const QString &cond) void Trigger::addColumn(Column *column) { if(!column) - throw Exception(QString(Exception::getErrorMessage(ERR_ASG_NOT_ALOC_COLUMN)) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgNotAllocatedColumn) .arg(this->getName(true)) .arg(this->getTypeName()), - ERR_ASG_NOT_ALOC_COLUMN,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgNotAllocatedColumn,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(!column->getParentTable()) - throw Exception(QString(Exception::getErrorMessage(ERR_ASG_COLUMN_NO_PARENT)) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgColumnNoParent) .arg(this->getName(true)) .arg(this->getTypeName()), - ERR_ASG_NOT_ALOC_COLUMN,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgNotAllocatedColumn,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(this->getParentTable() && column->getParentTable() != this->getParentTable()) - throw Exception(QString(Exception::getErrorMessage(ERR_ASG_INV_COLUMN_TRIGGER)) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidColumnTrigger) .arg(column->getName(true)) .arg(this->getName(true)), - ERR_ASG_INV_COLUMN_TRIGGER,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgInvalidColumnTrigger,__PRETTY_FUNCTION__,__FILE__,__LINE__); upd_columns.push_back(column); setCodeInvalidated(true); @@ -148,7 +150,7 @@ void Trigger::editArgument(unsigned arg_idx, const QString &new_arg) { //Raises an error if the argument index is invalid (out of bound) if(arg_idx>=arguments.size()) - throw Exception(ERR_REF_ARG_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefArgumentInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); vector::iterator itr; @@ -166,8 +168,8 @@ void Trigger::setExecutePerRow(bool value) bool Trigger::isExecuteOnEvent(EventType event) { - if(event==EventType::on_select) - throw Exception(ERR_REF_INV_TRIGGER_EVENT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(event==EventType::OnSelect) + throw Exception(ErrorCode::RefInvalidTriggerEvent,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(events.at(!event)); } @@ -181,7 +183,7 @@ QString Trigger::getArgument(unsigned arg_idx) { //Raises an error if the argument index is invalid (out of bound) if(arg_idx>=arguments.size()) - throw Exception(ERR_REF_ARG_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefArgumentInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(arguments[arg_idx]); } @@ -190,7 +192,7 @@ Column *Trigger::getColumn(unsigned col_idx) { //Raises an error if the column index is invalid (out of bound) if(col_idx>=upd_columns.size()) - throw Exception(ERR_REF_COLUMN_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefColumnInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(upd_columns[col_idx]); } @@ -224,7 +226,7 @@ void Trigger::removeArgument(unsigned arg_idx) { //Raises an error if the argument index is invalid (out of bound) if(arg_idx>=arguments.size()) - throw Exception(ERR_REF_ARG_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefArgumentInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); vector::iterator itr; itr=arguments.begin()+arg_idx; @@ -247,8 +249,8 @@ void Trigger::removeColumns(void) void Trigger::setReferecendTable(BaseTable *ref_table) { //If the referenced table isn't valid raises an error - if(ref_table && ref_table->getObjectType()!=OBJ_TABLE) - throw Exception(ERR_ASG_OBJECT_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(ref_table && ref_table->getObjectType()!=ObjectType::Table) + throw Exception(ErrorCode::AsgObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(referenced_table != ref_table); this->referenced_table=ref_table; @@ -287,6 +289,23 @@ void Trigger::setConstraint(bool value) is_constraint=value; } +void Trigger::setTransitionTableName(unsigned tab_idx, const QString &name) +{ + if(tab_idx > NewTableName) + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + setCodeInvalidated(transition_tabs_names[tab_idx] != name); + transition_tabs_names[tab_idx] = name; +} + +QString Trigger::getTransitionTableName(unsigned tab_idx) +{ + if(tab_idx > NewTableName) + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + return(transition_tabs_names[tab_idx]); +} + bool Trigger::isConstraint(void) { return(is_constraint); @@ -327,11 +346,11 @@ vector Trigger::getRelationshipAddedColumns(void) void Trigger::setBasicAttributes(unsigned def_type) { QString str_aux, - attribs[4]={ParsersAttributes::INS_EVENT, ParsersAttributes::DEL_EVENT, - ParsersAttributes::TRUNC_EVENT, ParsersAttributes::UPD_EVENT }, + attribs[4]={Attributes::InsEvent, Attributes::DelEvent, + Attributes::TruncEvent, Attributes::UpdEvent }, sql_event[4]={"INSERT OR ", "DELETE OR ", "TRUNCATE OR ", "UPDATE "}; - unsigned count, i, i1, event_types[4]={EventType::on_insert, EventType::on_delete, - EventType::on_truncate, EventType::on_update}; + unsigned count, i, i1, event_types[4]={EventType::OnInsert, EventType::OnDelete, + EventType::OnTruncate, EventType::OnUpdate}; setArgumentAttribute(def_type); @@ -341,18 +360,18 @@ void Trigger::setBasicAttributes(unsigned def_type) if(events.at(event_types[i])) { str_aux+=sql_event[i]; - attributes[attribs[i]]=ParsersAttributes::_TRUE_; + attributes[attribs[i]]=Attributes::True; - if(event_types[i]==EventType::on_update) + if(event_types[i]==EventType::OnUpdate) { count=upd_columns.size(); - attributes[ParsersAttributes::COLUMNS]=QString(); + attributes[Attributes::Columns]=QString(); for(i1=0; i1 < count; i1++) { - attributes[ParsersAttributes::COLUMNS]+=upd_columns.at(i1)->getName(true); + attributes[Attributes::Columns]+=upd_columns.at(i1)->getName(true); if(i1 < count-1) - attributes[ParsersAttributes::COLUMNS]+=QString(","); + attributes[Attributes::Columns]+=QString(","); } } } @@ -360,17 +379,17 @@ void Trigger::setBasicAttributes(unsigned def_type) if(!str_aux.isEmpty()) str_aux.remove(str_aux.size()-3,3); - if(def_type==SchemaParser::SQL_DEFINITION && !attributes[ParsersAttributes::COLUMNS].isEmpty()) - str_aux+=QString(" OF ") + attributes[ParsersAttributes::COLUMNS]; + if(def_type==SchemaParser::SqlDefinition && !attributes[Attributes::Columns].isEmpty()) + str_aux+=QString(" OF ") + attributes[Attributes::Columns]; - attributes[ParsersAttributes::EVENTS]=str_aux; + attributes[Attributes::Events]=str_aux; if(function) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::TRIGGER_FUNC]=function->getName(true); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::TriggerFunc]=function->getName(true); else - attributes[ParsersAttributes::TRIGGER_FUNC]=function->getCodeDefinition(def_type, true); + attributes[Attributes::TriggerFunc]=function->getCodeDefinition(def_type, true); } } @@ -384,24 +403,35 @@ QString Trigger::getCodeDefinition(unsigned def_type) /* Case the trigger doesn't referece some column added by relationship it will be declared inside the parent table construction by the use of 'decl-in-table' schema attribute */ if(!isReferRelationshipAddedColumn()) - attributes[ParsersAttributes::DECL_IN_TABLE]=ParsersAttributes::_TRUE_; + attributes[Attributes::DeclInTable]=Attributes::True; if(getParentTable()) - attributes[ParsersAttributes::TABLE]=getParentTable()->getName(true); + attributes[Attributes::Table]=getParentTable()->getName(true); - attributes[ParsersAttributes::CONSTRAINT]=(is_constraint ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::FIRING_TYPE]=(~firing_type); + attributes[Attributes::Constraint]=(is_constraint ? Attributes::True : QString()); + attributes[Attributes::FiringType]=(~firing_type); //** Constraint trigger MUST execute per row ** - attributes[ParsersAttributes::PER_ROW]=((is_exec_per_row && !is_constraint) || is_constraint ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::PerRow]=((is_exec_per_row && !is_constraint) || is_constraint ? Attributes::True : QString()); - attributes[ParsersAttributes::CONDITION]=condition; + attributes[Attributes::Condition]=condition; if(referenced_table) - attributes[ParsersAttributes::REF_TABLE]=referenced_table->getName(true); + attributes[Attributes::RefTable]=referenced_table->getName(true); + + attributes[Attributes::Deferrable]=(is_deferrable ? Attributes::True : QString()); + attributes[Attributes::DeferType]=(~deferral_type); - attributes[ParsersAttributes::DEFERRABLE]=(is_deferrable ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::DEFER_TYPE]=(~deferral_type); + if(def_type == SchemaParser::XmlDefinition) + { + attributes[Attributes::OldTableName]=transition_tabs_names[OldTableName]; + attributes[Attributes::NewTableName]=transition_tabs_names[NewTableName]; + } + else + { + attributes[Attributes::OldTableName]=BaseObject::formatName(transition_tabs_names[OldTableName]); + attributes[Attributes::NewTableName]=BaseObject::formatName(transition_tabs_names[NewTableName]); + } return(BaseObject::__getCodeDefinition(def_type)); } @@ -415,34 +445,34 @@ void Trigger::validateTrigger(void) if(!is_constraint) { //The INSTEAD OF mode cannot be used on triggers that belongs to tables! This is available only for view triggers - if(firing_type==FiringType::instead_of && parent_type==OBJ_TABLE) - throw Exception(ERR_TABLE_TRIG_INSTEADOF_FIRING,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(firing_type==FiringType::InsteadOf && parent_type==ObjectType::Table) + throw Exception(ErrorCode::InvTableTriggerInsteadOfFiring,__PRETTY_FUNCTION__,__FILE__,__LINE__); //The INSTEAD OF mode cannot be used on view triggers that executes for each statement - else if(firing_type==FiringType::instead_of && parent_type==OBJ_VIEW && !is_exec_per_row) - throw Exception(ERR_TRIGGER_INV_INSTEADOF_USAGE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(firing_type==FiringType::InsteadOf && parent_type==ObjectType::View && !is_exec_per_row) + throw Exception(ErrorCode::InvUsageInsteadOfOnTrigger,__PRETTY_FUNCTION__,__FILE__,__LINE__); //A trigger cannot make reference to columns when using INSTEAD OF mode and UPDATE event - else if(firing_type==FiringType::instead_of && events[EventType::on_update] && !upd_columns.empty()) - throw Exception(ERR_TRIGGER_INV_INSTEADOF_UPDATE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(firing_type==FiringType::InsteadOf && events[EventType::OnUpdate] && !upd_columns.empty()) + throw Exception(ErrorCode::InvUsageInsteadOfUpdateTrigger,__PRETTY_FUNCTION__,__FILE__,__LINE__); //The TRUNCATE event can only be used when the trigger executes for each statement and belongs to a table - else if(events[EventType::on_truncate] && (is_exec_per_row || parent_type==OBJ_VIEW)) - throw Exception(ERR_TRIGGER_INV_TRUNCATE_USAGE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(events[EventType::OnTruncate] && (is_exec_per_row || parent_type==ObjectType::View)) + throw Exception(ErrorCode::InvUsageTruncateOnTrigger,__PRETTY_FUNCTION__,__FILE__,__LINE__); //A view trigger cannot be AFTER/BEFORE when it executes for each row - else if(parent_type==OBJ_VIEW && is_exec_per_row && (firing_type==FiringType::after || firing_type==FiringType::before)) - throw Exception(ERR_VIEW_TRIG_INV_AFTBFR_USAGE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(parent_type==ObjectType::View && is_exec_per_row && (firing_type==FiringType::After || firing_type==FiringType::Before)) + throw Exception(ErrorCode::InvUsageAfterBeforeViewTrigger,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Only constraint triggers can be deferrable or reference another table else if(referenced_table || is_deferrable) - throw Exception(ERR_TRIG_USING_CONSTRIG_ATRIBS,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InvUseConstraintTriggerAttribs,__PRETTY_FUNCTION__,__FILE__,__LINE__); } //Constraint triggers can only be executed on AFTER events and for each row else { - if(firing_type!=FiringType::after && !is_exec_per_row) - throw Exception(ERR_CONST_TRIG_NOT_AFTER_ROW,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(firing_type!=FiringType::After && !is_exec_per_row) + throw Exception(ErrorCode::InvConstrTriggerNotAfterRow,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } } diff --git a/libpgmodeler/src/trigger.h b/libpgmodeler/src/trigger.h index bc2d86dca2..1951823f11 100644 --- a/libpgmodeler/src/trigger.h +++ b/libpgmodeler/src/trigger.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -31,6 +31,9 @@ class Trigger: public TableObject{ private: + //! \brief Stores the transtion tables names (OLD and NEW) [REFERENCING { OLD | NEW } TABLE name] + QString transition_tabs_names[2]; + //! \brief Arguments passed to the function that trigger executes vector arguments; @@ -73,6 +76,8 @@ class Trigger: public TableObject{ void setArgumentAttribute(unsigned tipo_def); public: + static constexpr unsigned OldTableName=0, NewTableName=1; + Trigger(void); /*! \brief Adds a column as a firing condition (only when the event UPDATE is used). @@ -112,6 +117,12 @@ class Trigger: public TableObject{ //! \brief Defines if the trigger is constraint void setConstraint(bool value); + //! \brief Defines the transition table name (OLD|NEW) referenced by the trigger + void setTransitionTableName(unsigned tab_idx, const QString &name); + + //! \brief Returns the transition table name (OLD|NEW) referenced by the trigger + QString getTransitionTableName(unsigned tab_idx); + //! \brief Returns true if the trigger executes on the passed event bool isExecuteOnEvent(EventType event); diff --git a/libpgmodeler/src/type.cpp b/libpgmodeler/src/type.cpp index cc3c5d5c87..12fb203989 100644 --- a/libpgmodeler/src/type.cpp +++ b/libpgmodeler/src/type.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,38 +20,38 @@ Type::Type(void) { - obj_type=OBJ_TYPE; - setConfiguration(ENUMERATION_TYPE); - - attributes[ParsersAttributes::BASE_TYPE]=QString(); - attributes[ParsersAttributes::COMPOSITE_TYPE]=QString(); - attributes[ParsersAttributes::RANGE_TYPE]=QString(); - attributes[ParsersAttributes::TYPE_ATTRIBUTE]=QString(); - attributes[ParsersAttributes::ENUM_TYPE]=QString(); - attributes[ParsersAttributes::ENUMERATIONS]=QString(); - attributes[ParsersAttributes::INPUT_FUNC]=QString(); - attributes[ParsersAttributes::OUTPUT_FUNC]=QString(); - attributes[ParsersAttributes::RECV_FUNC]=QString(); - attributes[ParsersAttributes::SEND_FUNC]=QString(); - attributes[ParsersAttributes::TPMOD_IN_FUNC]=QString(); - attributes[ParsersAttributes::TPMOD_OUT_FUNC]=QString(); - attributes[ParsersAttributes::ANALYZE_FUNC]=QString(); - attributes[ParsersAttributes::INTERNAL_LENGTH]=QString(); - attributes[ParsersAttributes::BY_VALUE]=QString(); - attributes[ParsersAttributes::ALIGNMENT]=QString(); - attributes[ParsersAttributes::STORAGE]=QString(); - attributes[ParsersAttributes::DEFAULT_VALUE]=QString(); - attributes[ParsersAttributes::ELEMENT]=QString(); - attributes[ParsersAttributes::DELIMITER]=QString(); - attributes[ParsersAttributes::REDUCED_FORM]=QString(); - attributes[ParsersAttributes::CATEGORY]=QString(); - attributes[ParsersAttributes::PREFERRED]=QString(); - attributes[ParsersAttributes::LIKE_TYPE]=QString(); - attributes[ParsersAttributes::COLLATABLE]=QString(); - attributes[ParsersAttributes::SUBTYPE]=QString(); - attributes[ParsersAttributes::SUBTYPE_DIFF_FUNC]=QString(); - attributes[ParsersAttributes::CANONICAL_FUNC]=QString(); - attributes[ParsersAttributes::OP_CLASS]=QString(); + obj_type=ObjectType::Type; + setConfiguration(EnumerationType); + + attributes[Attributes::BaseType]=QString(); + attributes[Attributes::CompositeType]=QString(); + attributes[Attributes::RangeType]=QString(); + attributes[Attributes::TypeAttribute]=QString(); + attributes[Attributes::EnumType]=QString(); + attributes[Attributes::Enumerations]=QString(); + attributes[Attributes::InputFunc]=QString(); + attributes[Attributes::OutputFunc]=QString(); + attributes[Attributes::RecvFunc]=QString(); + attributes[Attributes::SendFunc]=QString(); + attributes[Attributes::TpmodInFunc]=QString(); + attributes[Attributes::TpmodOutFunc]=QString(); + attributes[Attributes::AnalyzeFunc]=QString(); + attributes[Attributes::InternalLength]=QString(); + attributes[Attributes::ByValue]=QString(); + attributes[Attributes::Alignment]=QString(); + attributes[Attributes::Storage]=QString(); + attributes[Attributes::DefaultValue]=QString(); + attributes[Attributes::Element]=QString(); + attributes[Attributes::Delimiter]=QString(); + attributes[Attributes::ReducedForm]=QString(); + attributes[Attributes::Category]=QString(); + attributes[Attributes::Preferred]=QString(); + attributes[Attributes::LikeType]=QString(); + attributes[Attributes::Collatable]=QString(); + attributes[Attributes::Subtype]=QString(); + attributes[Attributes::SubtypeDiffFunc]=QString(); + attributes[Attributes::CanonicalFunc]=QString(); + attributes[Attributes::OpClass]=QString(); } void Type::setName(const QString &name) @@ -60,7 +60,7 @@ void Type::setName(const QString &name) prev_name=this->getName(true);//this->nome; BaseObject::setName(name); - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } void Type::setSchema(BaseObject *schema) @@ -69,7 +69,7 @@ void Type::setSchema(BaseObject *schema) prev_name=this->getName(true); BaseObject::setSchema(schema); - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } int Type::getAttributeIndex(const QString &attrib_name) @@ -97,15 +97,15 @@ int Type::getAttributeIndex(const QString &attrib_name) void Type::addAttribute(TypeAttribute attrib) { //Raises an error if the attribute has an empty name or null type - if(attrib.getName().isEmpty() || attrib.getType()==PgSQLType::null) - throw Exception(ERR_INS_INV_TYPE_ATTRIB,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(attrib.getName().isEmpty() || attrib.getType()==PgSqlType::Null) + throw Exception(ErrorCode::InsInvalidTypeAttribute,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the passed attribute has the same type as the defining type (this) - else if(PgSQLType::getUserTypeIndex(this->getName(true), this) == !attrib.getType()) - throw Exception(Exception::getErrorMessage(ERR_USER_TYPE_SELF_REFERENCE).arg(this->getName(true)), - ERR_USER_TYPE_SELF_REFERENCE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(PgSqlType::getUserTypeIndex(this->getName(true), this) == !attrib.getType()) + throw Exception(Exception::getErrorMessage(ErrorCode::InvUserTypeSelfReference).arg(this->getName(true)), + ErrorCode::InvUserTypeSelfReference,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error when the attribute already exists else if(getAttributeIndex(attrib.getName()) >= 0) - throw Exception(ERR_INS_DUPLIC_ITEMS,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InsDuplicatedItems,__PRETTY_FUNCTION__,__FILE__,__LINE__); type_attribs.push_back(attrib); setCodeInvalidated(true); @@ -115,7 +115,7 @@ void Type::removeAttribute(unsigned attrib_idx) { //Raises an error if the attribute index is out of bound if(attrib_idx >= type_attribs.size()) - throw Exception(ERR_REF_ATTRIB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefAttributeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); type_attribs.erase(type_attribs.begin() + attrib_idx); setCodeInvalidated(true); @@ -148,17 +148,17 @@ void Type::addEnumeration(const QString &enum_name) { //Raises an error if the enumaration name is empty if(enum_name.isEmpty()) - throw Exception(ERR_INS_INV_TYPE_ENUM_ITEM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InsInvalidEnumerationItem,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the enumeration name is invalid (exceeds the maximum length) - else if(enum_name.size() > BaseObject::OBJECT_NAME_MAX_LENGTH) - throw Exception(Exception::getErrorMessage(ERR_ASG_ENUM_LONG_NAME).arg(enum_name).arg(this->getName(true)), - ERR_ASG_ENUM_LONG_NAME,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(enum_name.size() > BaseObject::ObjectNameMaxLength) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgEnumLongName).arg(enum_name).arg(this->getName(true)), + ErrorCode::AsgEnumLongName,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(enum_name.contains(QChar(','))) - throw Exception(Exception::getErrorMessage(ERR_ASG_ENUM_INV_CHARS).arg(enum_name).arg(this->getName(true)), - ERR_ASG_ENUM_INV_CHARS,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::AsgEnumInvalidChars).arg(enum_name).arg(this->getName(true)), + ErrorCode::AsgEnumInvalidChars,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the enumeration already exists else if(isEnumerationExists(enum_name)) - throw Exception(ERR_INS_DUPLIC_ENUM_ITEM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InsDuplicatedEnumerationItem,__PRETTY_FUNCTION__,__FILE__,__LINE__); enumerations.push_back(enum_name); setCodeInvalidated(true); @@ -167,7 +167,7 @@ void Type::addEnumeration(const QString &enum_name) void Type::removeEnumeration(unsigned enum_idx) { if(enum_idx >= enumerations.size()) - throw Exception(ERR_REF_ENUM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefEnumerationInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); enumerations.erase(enumerations.begin() + enum_idx); setCodeInvalidated(true); @@ -182,8 +182,8 @@ void Type::removeEnumerations(void) void Type::setConfiguration(unsigned conf) { //Raises an error if the configuration type is invalid - if(conf < BASE_TYPE || conf > RANGE_TYPE) - throw Exception(ERR_ASG_INV_TYPE_CONFIG,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(conf < BaseType || conf > RangeType) + throw Exception(ErrorCode::AsgInvalidTypeConfiguration,__PRETTY_FUNCTION__,__FILE__,__LINE__); type_attribs.clear(); enumerations.clear(); @@ -196,10 +196,10 @@ void Type::setConfiguration(unsigned conf) alignment=QString("integer"); delimiter='\0'; - storage=StorageType::plain; + storage=StorageType::Plain; element=QString("\"any\""); internal_len=0; - category=CategoryType::userdefined; + category=CategoryType::UserDefined; preferred=collatable=by_value=false; like_type=QString("\"any\""); @@ -211,51 +211,51 @@ void Type::setFunction(unsigned func_id, Function *func) { unsigned param_count=0; LanguageType lang; - lang=LanguageType::c; + lang=LanguageType::C; unsigned funcs_len=sizeof(functions)/sizeof(Function *); //Raises an error if the function id is invalid if(func_id >= funcs_len) - throw Exception(ERR_REF_FUNCTION_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefFunctionInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); if(func) param_count=func->getParameterCount(); /* Raises an error if the user try to reference a function id which is incompatible according to the type's configuraiton */ - if((config==BASE_TYPE && func_id >= CANONICAL_FUNC) || - (config==RANGE_TYPE && func_id <= ANALYZE_FUNC)) - throw Exception(ERR_REF_FUNCTION_INV_TYPE_CONF,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if((config==BaseType && func_id >= CanonicalFunc) || + (config==RangeType && func_id <= AnalyzeFunc)) + throw Exception(ErrorCode::RefInvalidFunctionIdTypeConfig,__PRETTY_FUNCTION__,__FILE__,__LINE__); /* Raises an error if the function isn't defined and the function id is INPUT or OUTPUT, because this function is mandatory for base types */ - else if(!func && (func_id==INPUT_FUNC || func_id==OUTPUT_FUNC)) - throw Exception(Exception::getErrorMessage(ERR_ASG_NOT_ALOC_FUNCTION) + else if(!func && (func_id==InputFunc || func_id==OutputFunc)) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgNotAllocatedFunction) .arg(this->getName(true)) - .arg(BaseObject::getTypeName(OBJ_TYPE)), - ERR_ASG_NOT_ALOC_FUNCTION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Type)), + ErrorCode::AsgNotAllocatedFunction,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(func) { /* Raises an error if the function language is not C. Functions assigned to base type must be written in C */ - if((func_id!=CANONICAL_FUNC && func_id!=SUBTYPE_DIFF_FUNC) && - func->getLanguage()->getName()!=~LanguageType(LanguageType::c) && - func->getLanguage()->getName()!=~LanguageType(LanguageType::internal)) - throw Exception(ERR_ASG_FUNC_INV_LANGUAGE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if((func_id!=CanonicalFunc && func_id!=SubtypeDiffFunc) && + func->getLanguage()->getName()!=~LanguageType(LanguageType::C) && + func->getLanguage()->getName()!=~LanguageType(LanguageType::Internal)) + throw Exception(ErrorCode::AsgFunctionInvalidLanguage,__PRETTY_FUNCTION__,__FILE__,__LINE__); /* Raises an error if the parameter count for INPUT and RECV functions is different from 1 or 3. */ else if((param_count!=1 && param_count!=3 && - (func_id==INPUT_FUNC || func_id==RECV_FUNC)) || - (param_count!=2 && func_id==SUBTYPE_DIFF_FUNC) || + (func_id==InputFunc || func_id==RecvFunc)) || + (param_count!=2 && func_id==SubtypeDiffFunc) || (param_count!=1 && - (func_id==OUTPUT_FUNC || func_id==SEND_FUNC || - func_id==TPMOD_IN_FUNC || func_id==TPMOD_OUT_FUNC || - func_id==ANALYZE_FUNC || func_id==CANONICAL_FUNC))) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNC_INV_PARAM_COUNT) + (func_id==OutputFunc || func_id==SendFunc || + func_id==TpmodInFunc || func_id==TpmodOutFunc || + func_id==AnalyzeFunc || func_id==CanonicalFunc))) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidParamCount) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_TYPE)), - ERR_ASG_FUNC_INV_PARAM_COUNT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Type)), + ErrorCode::AsgFunctionInvalidParamCount,__PRETTY_FUNCTION__,__FILE__,__LINE__); /* Checking the return types of function in relation to type. INPUT, RECV and CANONICAL functions must return the data type that is being defined according to the documentation, but to facilitate the implementation the function must return data type @@ -263,19 +263,19 @@ void Type::setFunction(unsigned func_id, Function *func) OUTPUT and TPMOD_OUT should return cstring. The other functions SEND, TPMOD_IN and ANALYZE should return bytea, integer and boolean, respectively. Raises an error if some of conditions above is not satisfied. */ - else if((func_id==INPUT_FUNC && func->getReturnType()!=QString("\"any\"")) || - (func_id==OUTPUT_FUNC && func->getReturnType()!=QString("cstring")) || - (func_id==RECV_FUNC && func->getReturnType()!=QString("\"any\"")) || - (func_id==SEND_FUNC && func->getReturnType()!=QString("bytea")) || - (func_id==TPMOD_IN_FUNC && func->getReturnType()!=QString("integer")) || - (func_id==TPMOD_OUT_FUNC && func->getReturnType()!=QString("cstring")) || - (func_id==ANALYZE_FUNC && func->getReturnType()!=QString("boolean")) || - (func_id==CANONICAL_FUNC && func->getReturnType()!=QString("\"any\"")) || - (func_id==SUBTYPE_DIFF_FUNC && func->getReturnType()!=QString("double precision"))) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNCTION_INV_RET_TYPE) + else if((func_id==InputFunc && func->getReturnType()!=QString("\"any\"")) || + (func_id==OutputFunc && func->getReturnType()!=QString("cstring")) || + (func_id==RecvFunc && func->getReturnType()!=QString("\"any\"")) || + (func_id==SendFunc && func->getReturnType()!=QString("bytea")) || + (func_id==TpmodInFunc && func->getReturnType()!=QString("integer")) || + (func_id==TpmodOutFunc && func->getReturnType()!=QString("cstring")) || + (func_id==AnalyzeFunc && func->getReturnType()!=QString("boolean")) || + (func_id==CanonicalFunc && func->getReturnType()!=QString("\"any\"")) || + (func_id==SubtypeDiffFunc && func->getReturnType()!=QString("double precision"))) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidReturnType) .arg(this->getName()) - .arg(BaseObject::getTypeName(OBJ_TYPE)), - ERR_ASG_FUNCTION_INV_RET_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + .arg(BaseObject::getTypeName(ObjectType::Type)), + ErrorCode::AsgFunctionInvalidReturnType,__PRETTY_FUNCTION__,__FILE__,__LINE__); /* Validating the parameter types of function in relation to the type configuration. The INPUT function must have parameters with type (cstring, oid, integer). @@ -286,27 +286,27 @@ void Type::setFunction(unsigned func_id, Function *func) TPMOD_OUT function must have a parameter of type (integer). The ANALYZE function must have a parameter of type (internal). Raises an error if some of above conditions is not satisfied.*/ - else if((func_id==INPUT_FUNC && + else if((func_id==InputFunc && (func->getParameter(0).getType()!=QString("cstring") || (param_count==3 && (func->getParameter(1).getType()!=QString("oid") || func->getParameter(2).getType()!=QString("integer"))))) || - (func_id==RECV_FUNC && + (func_id==RecvFunc && (func->getParameter(0).getType()!=QString("internal") || (param_count==3 && (func->getParameter(1).getType()!=QString("oid") || func->getParameter(2).getType()!=QString("integer"))))) || - ((func_id==SEND_FUNC || func_id==CANONICAL_FUNC || func_id==OUTPUT_FUNC) && func->getParameter(0).getType()!=QString("\"any\"")) || - (func_id==TPMOD_IN_FUNC && *(func->getParameter(0).getType())!=QString("cstring[]")) || - (func_id==TPMOD_OUT_FUNC && func->getParameter(0).getType()!=QString("integer")) || - (func_id==ANALYZE_FUNC && func->getParameter(0).getType()!=QString("internal")) || - (func_id==SUBTYPE_DIFF_FUNC && + ((func_id==SendFunc || func_id==CanonicalFunc || func_id==OutputFunc) && func->getParameter(0).getType()!=QString("\"any\"")) || + (func_id==TpmodInFunc && *(func->getParameter(0).getType())!=QString("cstring[]")) || + (func_id==TpmodOutFunc && func->getParameter(0).getType()!=QString("integer")) || + (func_id==AnalyzeFunc && func->getParameter(0).getType()!=QString("internal")) || + (func_id==SubtypeDiffFunc && (func->getParameter(0).getType()!=this->subtype || func->getParameter(1).getType()!=this->subtype))) - throw Exception(Exception::getErrorMessage(ERR_ASG_FUNCTION_INV_PARAMS) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgFunctionInvalidParameters) .arg(this->getName()) .arg(this->getTypeName()), - ERR_ASG_FUNCTION_INV_PARAMS,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgFunctionInvalidParameters,__PRETTY_FUNCTION__,__FILE__,__LINE__); func->setProtected(false); } @@ -317,8 +317,8 @@ void Type::setFunction(unsigned func_id, Function *func) void Type::convertFunctionParameters(bool inverse_conv) { - unsigned i, conf_funcs[]={ INPUT_FUNC, RECV_FUNC, - OUTPUT_FUNC, SEND_FUNC }; + unsigned i, conf_funcs[]={ InputFunc, RecvFunc, + OutputFunc, SendFunc }; Parameter param; Function *func=nullptr; @@ -328,28 +328,28 @@ void Type::convertFunctionParameters(bool inverse_conv) if(func) { - if(conf_funcs[i]==OUTPUT_FUNC || conf_funcs[i]==SEND_FUNC) + if(conf_funcs[i]==OutputFunc || conf_funcs[i]==SendFunc) { param=func->getParameter(0); func->removeParameter(0); if(!inverse_conv) { - param.setType(PgSQLType(this)); + param.setType(PgSqlType(this)); func->addParameter(param); } else { - param.setType(PgSQLType(QString("\"any\""))); + param.setType(PgSqlType(QString("\"any\""))); func->addParameter(param); } } - else if(conf_funcs[i]==INPUT_FUNC || conf_funcs[i]==RECV_FUNC) + else if(conf_funcs[i]==InputFunc || conf_funcs[i]==RecvFunc) { if(!inverse_conv) - func->setReturnType(PgSQLType(this)); + func->setReturnType(PgSqlType(this)); else - func->setReturnType(PgSQLType(QString("\"any\""))); + func->setReturnType(PgSqlType(QString("\"any\""))); } } } @@ -369,14 +369,14 @@ void Type::setByValue(bool value) by_value=value; } -void Type::setAlignment(PgSQLType type) +void Type::setAlignment(PgSqlType type) { QString tp=(*type); //Raises an error if the type assigned to the alignment is invalid according to the rule if(tp!=QString("char") && tp!=QString("smallint") && tp!=QString("integer") && tp!=QString("double precision")) - throw Exception(Exception::getErrorMessage(ERR_ASG_INV_ALIGNMENT_TYPE).arg(this->getName(true)), - ERR_ASG_INV_ALIGNMENT_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidAlignmentType).arg(this->getName(true)), + ErrorCode::AsgInvalidAlignmentType,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(alignment != type); alignment=tp; @@ -396,16 +396,16 @@ void Type::setDefaultValue(const QString &value) this->default_value=def; } -void Type::setElement(PgSQLType elem) +void Type::setElement(PgSqlType elem) { - if(PgSQLType::getUserTypeIndex(this->getName(true), this) == !elem) - throw Exception(Exception::getErrorMessage(ERR_USER_TYPE_SELF_REFERENCE).arg(this->getName(true)), - ERR_USER_TYPE_SELF_REFERENCE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(PgSqlType::getUserTypeIndex(this->getName(true), this) == !elem) + throw Exception(Exception::getErrorMessage(ErrorCode::InvUserTypeSelfReference).arg(this->getName(true)), + ErrorCode::InvUserTypeSelfReference,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(elem!=QString("\"any\"") && (elem.isOIDType() || elem.isPseudoType() || elem.isUserType() || elem.isArrayType())) - throw Exception(Exception::getErrorMessage(ERR_ASG_INV_ELEMENT_TYPE).arg(this->getName(true)), - ERR_ASG_INV_ELEMENT_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidElementType).arg(this->getName(true)), + ErrorCode::AsgInvalidElementType,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(element != elem); this->element=elem; @@ -426,10 +426,10 @@ void Type::setElementsAttribute(unsigned def_type) for(i=0; i < count; i++) str_elem+=type_attribs[i].getCodeDefinition(def_type); - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) str_elem.remove(str_elem.lastIndexOf(','), str_elem.size()); - attributes[ParsersAttributes::TYPE_ATTRIBUTE]=str_elem; + attributes[Attributes::TypeAttribute]=str_elem; } void Type::setEnumerationsAttribute(unsigned def_type) @@ -440,7 +440,7 @@ void Type::setEnumerationsAttribute(unsigned def_type) count=enumerations.size(); for(i=0; i < count; i++) { - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) str_enum+=QString("'") + enumerations[i] + QString("'"); else str_enum+=enumerations[i]; @@ -448,7 +448,7 @@ void Type::setEnumerationsAttribute(unsigned def_type) if(i < (count-1)) str_enum+=QString(","); } - attributes[ParsersAttributes::ENUMERATIONS]=str_enum; + attributes[Attributes::Enumerations]=str_enum; } void Type::setCategory(CategoryType categ) @@ -469,21 +469,21 @@ void Type::setCollatable(bool value) this->collatable=value; } -void Type::setLikeType(PgSQLType like_type) +void Type::setLikeType(PgSqlType like_type) { - if(PgSQLType::getUserTypeIndex(this->getName(true), this) == !like_type) - throw Exception(Exception::getErrorMessage(ERR_USER_TYPE_SELF_REFERENCE).arg(this->getName(true)), - ERR_USER_TYPE_SELF_REFERENCE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(PgSqlType::getUserTypeIndex(this->getName(true), this) == !like_type) + throw Exception(Exception::getErrorMessage(ErrorCode::InvUserTypeSelfReference).arg(this->getName(true)), + ErrorCode::InvUserTypeSelfReference,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->like_type != like_type); this->like_type=like_type; } -void Type::setSubtype(PgSQLType subtype) +void Type::setSubtype(PgSqlType subtype) { - if(PgSQLType::getUserTypeIndex(this->getName(true), this) == !subtype) - throw Exception(Exception::getErrorMessage(ERR_USER_TYPE_SELF_REFERENCE).arg(this->getName(true)), - ERR_USER_TYPE_SELF_REFERENCE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(PgSqlType::getUserTypeIndex(this->getName(true), this) == !subtype) + throw Exception(Exception::getErrorMessage(ErrorCode::InvUserTypeSelfReference).arg(this->getName(true)), + ErrorCode::InvUserTypeSelfReference,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(this->subtype != subtype); this->subtype=subtype; @@ -491,11 +491,11 @@ void Type::setSubtype(PgSQLType subtype) void Type::setSubtypeOpClass(OperatorClass *opclass) { - if(opclass && opclass->getIndexingType()!=IndexingType::btree) - throw Exception(Exception::getErrorMessage(ERR_ASG_INV_OPCLASS_OBJ) + if(opclass && opclass->getIndexingType()!=IndexingType::Btree) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgInvalidOpClassObject) .arg(this->getName(true)) .arg(this->getTypeName()), - ERR_ASG_INV_OPCLASS_OBJ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgInvalidOpClassObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); setCodeInvalidated(subtype_opclass != opclass); subtype_opclass=opclass; @@ -504,7 +504,7 @@ void Type::setSubtypeOpClass(OperatorClass *opclass) TypeAttribute Type::getAttribute(unsigned attrib_idx) { if(attrib_idx >= type_attribs.size()) - throw Exception(ERR_REF_ATTRIB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefAttributeInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(type_attribs[attrib_idx]); } @@ -517,7 +517,7 @@ unsigned Type::getAttributeCount(void) QString Type::getEnumeration(unsigned idx_enum) { if(idx_enum >= enumerations.size()) - throw Exception(ERR_REF_ENUM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefEnumerationInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(enumerations[idx_enum]); } @@ -530,7 +530,7 @@ unsigned Type::getEnumerationCount(void) Function *Type::getFunction(unsigned func_id) { if(func_id >= sizeof(functions)/sizeof(Function *)) - throw Exception(ERR_REF_FUNCTION_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefFunctionInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(functions[func_id]); } @@ -545,7 +545,7 @@ bool Type::isByValue(void) return(by_value); } -PgSQLType Type::getAlignment(void) +PgSqlType Type::getAlignment(void) { return(alignment); } @@ -560,7 +560,7 @@ QString Type::getDefaultValue(void) return(default_value); } -PgSQLType Type::getElement(void) +PgSqlType Type::getElement(void) { return(element); } @@ -590,12 +590,12 @@ bool Type::isCollatable(void) return(collatable); } -PgSQLType Type::getLikeType(void) +PgSqlType Type::getLikeType(void) { return(like_type); } -PgSQLType Type::getSubtype(void) +PgSqlType Type::getSubtype(void) { return(subtype); } @@ -615,89 +615,89 @@ QString Type::getCodeDefinition(unsigned def_type, bool reduced_form) QString code_def=getCachedCode(def_type, reduced_form); if(!code_def.isEmpty()) return(code_def); - if(config==ENUMERATION_TYPE) + if(config==EnumerationType) { - attributes[ParsersAttributes::ENUM_TYPE]=ParsersAttributes::_TRUE_; + attributes[Attributes::EnumType]=Attributes::True; setEnumerationsAttribute(def_type); } - else if(config==COMPOSITE_TYPE) + else if(config==CompositeType) { - attributes[ParsersAttributes::COMPOSITE_TYPE]=ParsersAttributes::_TRUE_; + attributes[Attributes::CompositeType]=Attributes::True; setElementsAttribute(def_type); } - else if(config==RANGE_TYPE) + else if(config==RangeType) { - attributes[ParsersAttributes::RANGE_TYPE]=ParsersAttributes::_TRUE_; + attributes[Attributes::RangeType]=Attributes::True; - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::SUBTYPE]=(*subtype); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Subtype]=(*subtype); else - attributes[ParsersAttributes::SUBTYPE]=subtype.getCodeDefinition(SchemaParser::XML_DEFINITION); + attributes[Attributes::Subtype]=subtype.getCodeDefinition(SchemaParser::XmlDefinition); if(subtype_opclass) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::OP_CLASS]=subtype_opclass->getName(true); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::OpClass]=subtype_opclass->getName(true); else - attributes[ParsersAttributes::OP_CLASS]=subtype_opclass->getCodeDefinition(def_type, true); + attributes[Attributes::OpClass]=subtype_opclass->getCodeDefinition(def_type, true); } } else { - attributes[ParsersAttributes::BASE_TYPE]=ParsersAttributes::_TRUE_; + attributes[Attributes::BaseType]=Attributes::True; - if(internal_len==0 && def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::INTERNAL_LENGTH]=QString("VARIABLE"); + if(internal_len==0 && def_type==SchemaParser::SqlDefinition) + attributes[Attributes::InternalLength]=QString("VARIABLE"); else - attributes[ParsersAttributes::INTERNAL_LENGTH]=QString("%1").arg(internal_len); + attributes[Attributes::InternalLength]=QString("%1").arg(internal_len); - attributes[ParsersAttributes::BY_VALUE]=(by_value ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::ALIGNMENT]=(*alignment); - attributes[ParsersAttributes::STORAGE]=(~storage); - attributes[ParsersAttributes::DEFAULT_VALUE]=default_value; + attributes[Attributes::ByValue]=(by_value ? Attributes::True : QString()); + attributes[Attributes::Alignment]=(*alignment); + attributes[Attributes::Storage]=(~storage); + attributes[Attributes::DefaultValue]=default_value; if(element!=QString("\"any\"")) - attributes[ParsersAttributes::ELEMENT]=(*element); + attributes[Attributes::Element]=(*element); if(delimiter!='\0') - attributes[ParsersAttributes::DELIMITER]=delimiter; + attributes[Attributes::Delimiter]=delimiter; - attributes[ParsersAttributes::CATEGORY]=~(category); + attributes[Attributes::Category]=~(category); - attributes[ParsersAttributes::PREFERRED]=(preferred ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::COLLATABLE]=(collatable ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::Preferred]=(preferred ? Attributes::True : QString()); + attributes[Attributes::Collatable]=(collatable ? Attributes::True : QString()); if(like_type!=QString("\"any\"")) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::LIKE_TYPE]=(*like_type); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::LikeType]=(*like_type); else - attributes[ParsersAttributes::LIKE_TYPE]=like_type.getCodeDefinition(SchemaParser::XML_DEFINITION); + attributes[Attributes::LikeType]=like_type.getCodeDefinition(SchemaParser::XmlDefinition); } } - if(config==BASE_TYPE || config==RANGE_TYPE) + if(config==BaseType || config==RangeType) { unsigned i; - QString func_attrib[]={ParsersAttributes::INPUT_FUNC, - ParsersAttributes::OUTPUT_FUNC, - ParsersAttributes::RECV_FUNC, - ParsersAttributes::SEND_FUNC, - ParsersAttributes::TPMOD_IN_FUNC, - ParsersAttributes::TPMOD_OUT_FUNC, - ParsersAttributes::ANALYZE_FUNC, - ParsersAttributes::CANONICAL_FUNC, - ParsersAttributes::SUBTYPE_DIFF_FUNC}; + QString func_attrib[]={Attributes::InputFunc, + Attributes::OutputFunc, + Attributes::RecvFunc, + Attributes::SendFunc, + Attributes::TpmodInFunc, + Attributes::TpmodOutFunc, + Attributes::AnalyzeFunc, + Attributes::CanonicalFunc, + Attributes::SubtypeDiffFunc}; for(i=0; i < sizeof(functions)/sizeof(Function *); i++) { if(functions[i]) { - if(def_type==SchemaParser::SQL_DEFINITION) + if(def_type==SchemaParser::SqlDefinition) attributes[func_attrib[i]]=functions[i]->getName(); else { - functions[i]->setAttribute(ParsersAttributes::REF_TYPE, func_attrib[i]); + functions[i]->setAttribute(Attributes::RefType, func_attrib[i]); attributes[func_attrib[i]]=functions[i]->getCodeDefinition(def_type, true); } } @@ -712,7 +712,7 @@ QString Type::getAlterDefinition(BaseObject *object) Type *type=dynamic_cast(object); if(!type) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { @@ -724,21 +724,21 @@ QString Type::getAlterDefinition(BaseObject *object) if(this->config==type->config) { - if(config==ENUMERATION_TYPE) + if(config==EnumerationType) { for(QString enum_val : type->enumerations) { if(std::find(this->enumerations.begin(), this->enumerations.end(), enum_val)==this->enumerations.end()) { - attribs[ParsersAttributes::BEFORE]=QString(); + attribs[Attributes::Before]=QString(); if(prev_val.isEmpty()) { - attribs[ParsersAttributes::BEFORE]=ParsersAttributes::_TRUE_; + attribs[Attributes::Before]=Attributes::True; prev_val=this->enumerations[0]; } - attribs[ParsersAttributes::VALUE]=enum_val; - attribs[ParsersAttributes::EXISTING_VALUE]=prev_val; + attribs[Attributes::Value]=enum_val; + attribs[Attributes::ExistingValue]=prev_val; copyAttributes(attribs); alter_def+=BaseObject::getAlterDefinition(this->getSchemaName(), attributes, true, true); attribs.clear(); @@ -747,19 +747,19 @@ QString Type::getAlterDefinition(BaseObject *object) prev_val=enum_val; } } - else if(config==COMPOSITE_TYPE) + else if(config==CompositeType) { //Removing type attributes for(TypeAttribute attrib : this->type_attribs) { if(type->getAttributeIndex(attrib.getName()) < 0) { - attribs[ParsersAttributes::DROP]=ParsersAttributes::_TRUE_; - attribs[ParsersAttributes::ATTRIBUTE]=attrib.getName(true); + attribs[Attributes::Drop]=Attributes::True; + attribs[Attributes::Attribute]=attrib.getName(true); copyAttributes(attribs); alter_def+=BaseObject::getAlterDefinition(this->getSchemaName(), attributes, true, true); attribs.clear(); - attributes[ParsersAttributes::DROP]=QString(); + attributes[Attributes::Drop]=QString(); } } @@ -770,12 +770,12 @@ QString Type::getAlterDefinition(BaseObject *object) //Creating type attributes if(attrib_idx < 0) { - attribs[ParsersAttributes::ATTRIBUTE]=attrib.getName(true); - attribs[ParsersAttributes::TYPE]=attrib.getType().getCodeDefinition(SchemaParser::SQL_DEFINITION); - attribs[ParsersAttributes::COLLATION]=QString(); + attribs[Attributes::Attribute]=attrib.getName(true); + attribs[Attributes::Type]=attrib.getType().getCodeDefinition(SchemaParser::SqlDefinition); + attribs[Attributes::Collation]=QString(); if(attrib.getCollation()) - attribs[ParsersAttributes::COLLATION]=attrib.getCollation()->getName(true); + attribs[Attributes::Collation]=attrib.getCollation()->getName(true); copyAttributes(attribs); alter_def+=BaseObject::getAlterDefinition(this->getSchemaName(), attributes, true, true); @@ -783,17 +783,17 @@ QString Type::getAlterDefinition(BaseObject *object) //Changing type attributes else { - attribs[ParsersAttributes::CHANGE]=ParsersAttributes::_TRUE_; + attribs[Attributes::Change]=Attributes::True; if(!type_attribs[attrib_idx].getType().isEquivalentTo(attrib.getType())) { - attribs[ParsersAttributes::ATTRIBUTE]=attrib.getName(true); - attribs[ParsersAttributes::TYPE]=attrib.getType().getCodeDefinition(SchemaParser::SQL_DEFINITION); + attribs[Attributes::Attribute]=attrib.getName(true); + attribs[Attributes::Type]=attrib.getType().getCodeDefinition(SchemaParser::SqlDefinition); } copyAttributes(attribs); alter_def+=BaseObject::getAlterDefinition(this->getSchemaName(), attributes, true, true); - attributes[ParsersAttributes::CHANGE]=QString(); + attributes[Attributes::Change]=QString(); } attribs.clear(); @@ -805,7 +805,7 @@ QString Type::getAlterDefinition(BaseObject *object) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -840,6 +840,6 @@ void Type::operator = (Type &type) i++; } - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } diff --git a/libpgmodeler/src/type.h b/libpgmodeler/src/type.h index 1d4eb4e371..aed37a7b44 100644 --- a/libpgmodeler/src/type.h +++ b/libpgmodeler/src/type.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -60,7 +60,7 @@ class Type: public BaseObject { preferred; //PREFERRED //! \brief Storage alignmnet (char, smallint (int2), integer (int4) ou double precision) - PgSQLType alignment, //ALIGNMENT + PgSqlType alignment, //ALIGNMENT element; //ELEMENT //! \brief Type's storage @@ -75,7 +75,7 @@ class Type: public BaseObject { /*! \brief Type which will have some of its attributes copied to the current type (only for base type). If like_type is 'any' means that the current type does not copy attributes of any type */ - PgSQLType like_type, //LIKE + PgSqlType like_type, //LIKE //! \brief Subtype used by a range type subtype; //SUBTYPE @@ -106,20 +106,20 @@ class Type: public BaseObject { void convertFunctionParameters(bool inverse_conv=false); public: - static const unsigned BASE_TYPE=10, - ENUMERATION_TYPE=11, - COMPOSITE_TYPE=12, - RANGE_TYPE=13; - - static const unsigned INPUT_FUNC=0, - OUTPUT_FUNC=1, - RECV_FUNC=2, - SEND_FUNC=3, - TPMOD_IN_FUNC=4, - TPMOD_OUT_FUNC=5, - ANALYZE_FUNC=6, - CANONICAL_FUNC=7, - SUBTYPE_DIFF_FUNC=8; + static constexpr unsigned BaseType=10, + EnumerationType=11, + CompositeType=12, + RangeType=13; + + static constexpr unsigned InputFunc=0, + OutputFunc=1, + RecvFunc=2, + SendFunc=3, + TpmodInFunc=4, + TpmodOutFunc=5, + AnalyzeFunc=6, + CanonicalFunc=7, + SubtypeDiffFunc=8; Type(void); @@ -165,7 +165,7 @@ class Type: public BaseObject { void setCollatable(bool value); //! \brief Sets the alignment for the type (only for base type) - void setAlignment(PgSQLType type); + void setAlignment(PgSqlType type); //! \brief Sets the storage type (only for base type) void setStorage(StorageType strg); @@ -174,7 +174,7 @@ class Type: public BaseObject { void setDefaultValue(const QString &value); //! \brief Sets the element for the type (only for base type) - void setElement(PgSQLType elem); + void setElement(PgSqlType elem); //! \brief Sets the delimiter for the type (only for base type) void setDelimiter(char delim); @@ -186,15 +186,15 @@ class Type: public BaseObject { void setPreferred(bool value); //! \brief Sets the type that will be used as template (only for base type) - void setLikeType(PgSQLType like_type); + void setLikeType(PgSqlType like_type); //! \brief Sets the subtype that will be used by the range (only for range type) - void setSubtype(PgSQLType subtype); + void setSubtype(PgSqlType subtype); //! \brief Sets the subtype operator class (only for range type) void setSubtypeOpClass(OperatorClass *opclass); - PgSQLType getSubtype(void); + PgSqlType getSubtype(void); OperatorClass *getSubtypeOpClass(void); TypeAttribute getAttribute(unsigned attrib_idx); unsigned getAttributeCount(void); @@ -203,15 +203,15 @@ class Type: public BaseObject { unsigned getConfiguration(void); CategoryType getCategory(void); bool isPreferred(void); - PgSQLType getLikeType(void); + PgSqlType getLikeType(void); Function *getFunction(unsigned func_id); unsigned getInternalLength(void); bool isByValue(void); bool isCollatable(void); - PgSQLType getAlignment(void); + PgSqlType getAlignment(void); StorageType getStorage(void); QString getDefaultValue(void); - PgSQLType getElement(void); + PgSqlType getElement(void); char getDelimiter(void); /*! \brief Returns the SQL / XML definition for the type. If the boolean diff --git a/libpgmodeler/src/typeattribute.cpp b/libpgmodeler/src/typeattribute.cpp index d5add59c47..cc1ac3aa35 100644 --- a/libpgmodeler/src/typeattribute.cpp +++ b/libpgmodeler/src/typeattribute.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,16 +20,16 @@ TypeAttribute::TypeAttribute(void) { - obj_type=OBJ_TYPE_ATTRIBUTE; + obj_type=ObjectType::TypeAttribute; } -void TypeAttribute::setType(PgSQLType type) +void TypeAttribute::setType(PgSqlType type) { setCodeInvalidated(this->type != type); this->type=type; } -PgSQLType TypeAttribute::getType(void) +PgSqlType TypeAttribute::getType(void) { return(type); } @@ -39,19 +39,19 @@ QString TypeAttribute::getCodeDefinition(unsigned def_type) QString code_def=getCachedCode(def_type, false); if(!code_def.isEmpty()) return(code_def); - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::NAME]=BaseObject::formatName(obj_name); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Name]=BaseObject::formatName(obj_name); else - attributes[ParsersAttributes::NAME]=obj_name; + attributes[Attributes::Name]=obj_name; - attributes[ParsersAttributes::TYPE]=type.getCodeDefinition(def_type); + attributes[Attributes::Type]=type.getCodeDefinition(def_type); if(collation) { - if(def_type==SchemaParser::SQL_DEFINITION) - attributes[ParsersAttributes::COLLATION]=collation->getName(true); + if(def_type==SchemaParser::SqlDefinition) + attributes[Attributes::Collation]=collation->getName(true); else - attributes[ParsersAttributes::COLLATION]=collation->getCodeDefinition(def_type, true); + attributes[Attributes::Collation]=collation->getCodeDefinition(def_type, true); } return(BaseObject::__getCodeDefinition(def_type)); diff --git a/libpgmodeler/src/typeattribute.h b/libpgmodeler/src/typeattribute.h index a8385a3c19..6417c7321e 100644 --- a/libpgmodeler/src/typeattribute.h +++ b/libpgmodeler/src/typeattribute.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -29,15 +29,15 @@ class TypeAttribute: public BaseObject { private: - PgSQLType type; + PgSqlType type; QString getCodeDefinition(unsigned, bool){ return(""); } public: TypeAttribute(void); - void setType(PgSQLType type); - PgSQLType getType(void); + void setType(PgSqlType type); + PgSqlType getType(void); //! \brief Returns the SQL / XML code definition for the parameter virtual QString getCodeDefinition(unsigned def_type) final; diff --git a/libpgmodeler/src/usermapping.cpp b/libpgmodeler/src/usermapping.cpp new file mode 100644 index 0000000000..e77f4e4cce --- /dev/null +++ b/libpgmodeler/src/usermapping.cpp @@ -0,0 +1,101 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "usermapping.h" + +UserMapping::UserMapping(void) : ForeignObject() +{ + obj_type = ObjectType::UserMapping; + foreign_server = nullptr; + setName(""); + attributes[Attributes::Server] = QString(); +} + +void UserMapping::setForeignServer(ForeignServer *server) +{ + setCodeInvalidated(foreign_server != server); + foreign_server = server; + setName(""); +} + +ForeignServer *UserMapping::getForeignServer(void) +{ + return(foreign_server); +} + +void UserMapping::setOwner(BaseObject *role) +{ + BaseObject::setOwner(role); + setName(""); +} + +void UserMapping::setName(const QString &) +{ + //Configures a fixed name for the user mapping (in form: role@server) + this->obj_name=QString("%1@%2").arg(owner ? owner->getName() : QString("public")) + .arg(foreign_server ? foreign_server->getName() : QString()); +} + +QString UserMapping::getName(bool, bool) +{ + return(this->obj_name); +} + +QString UserMapping::getSignature(bool) +{ + return(QString("FOR %1 SERVER %2").arg(owner ? owner->getName() : QString("public")) + .arg(foreign_server ? foreign_server->getName() : QString())); +} + +QString UserMapping::getCodeDefinition(unsigned def_type) +{ + QString code_def=getCachedCode(def_type, false); + if(!code_def.isEmpty()) return(code_def); + + attributes[Attributes::Role] = QString(); + attributes[Attributes::Server] = QString(); + + if(foreign_server) + { + if(def_type == SchemaParser::SqlDefinition) + attributes[Attributes::Server] = foreign_server->getName(true); + else + attributes[Attributes::Server] = foreign_server->getCodeDefinition(def_type, true); + } + + setOptionsAttribute(def_type); + return(this->BaseObject::__getCodeDefinition(def_type)); +} + +QString UserMapping::getAlterDefinition(BaseObject *object) +{ + try + { + attributes[Attributes::AlterCmds] = ForeignObject::getAlterDefinition(object); + return(BaseObject::getAlterDefinition(this->getSchemaName(), attributes, false, true)); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + } +} + +QString UserMapping::getDropDefinition(bool) +{ + return(BaseObject::getDropDefinition(false)); +} diff --git a/libpgmodeler/src/usermapping.h b/libpgmodeler/src/usermapping.h new file mode 100644 index 0000000000..0d9eb7117b --- /dev/null +++ b/libpgmodeler/src/usermapping.h @@ -0,0 +1,51 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +/** +\ingroup libpgmodeler +\class Server +\brief Implements the operations to manipulate user mappings on the database. +*/ + +#ifndef USER_MAPPING_H +#define USER_MAPPING_H + +#include "baseobject.h" +#include "foreignserver.h" + +class UserMapping: public ForeignObject { + private: + //! \brief The foreign server which is managed by this user mapping the server + ForeignServer *foreign_server; + + public: + UserMapping(void); + + void setForeignServer(ForeignServer *server); + ForeignServer *getForeignServer(void); + + virtual void setName(const QString &); + virtual void setOwner(BaseObject *role); + virtual QString getName(bool = false, bool = false); + virtual QString getSignature(bool = false); + virtual QString getCodeDefinition(unsigned def_type); + virtual QString getAlterDefinition(BaseObject *object); + virtual QString getDropDefinition(bool); +}; + +#endif diff --git a/libpgmodeler/src/view.cpp b/libpgmodeler/src/view.cpp index 864a50fb41..2ecf38a042 100644 --- a/libpgmodeler/src/view.cpp +++ b/libpgmodeler/src/view.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,27 +20,27 @@ View::View(void) : BaseTable() { - obj_type=OBJ_VIEW; + obj_type=ObjectType::View; materialized=recursive=with_no_data=false; - attributes[ParsersAttributes::DEFINITION]=QString(); - attributes[ParsersAttributes::REFERENCES]=QString(); - attributes[ParsersAttributes::SELECT_EXP]=QString(); - attributes[ParsersAttributes::FROM_EXP]=QString(); - attributes[ParsersAttributes::SIMPLE_EXP]=QString(); - attributes[ParsersAttributes::END_EXP]=QString(); - attributes[ParsersAttributes::CTE_EXPRESSION]=QString(); - attributes[ParsersAttributes::MATERIALIZED]=QString(); - attributes[ParsersAttributes::RECURSIVE]=QString(); - attributes[ParsersAttributes::WITH_NO_DATA]=QString(); - attributes[ParsersAttributes::COLUMNS]=QString(); + attributes[Attributes::Definition]=QString(); + attributes[Attributes::References]=QString(); + attributes[Attributes::SelectExp]=QString(); + attributes[Attributes::FromExp]=QString(); + attributes[Attributes::SimpleExp]=QString(); + attributes[Attributes::EndExp]=QString(); + attributes[Attributes::CteExpression]=QString(); + attributes[Attributes::Materialized]=QString(); + attributes[Attributes::Recursive]=QString(); + attributes[Attributes::WithNoData]=QString(); + attributes[Attributes::Columns]=QString(); } View::~View(void) { - ObjectType types[]={ OBJ_TRIGGER, OBJ_RULE }; + ObjectType types[]={ ObjectType::Trigger, ObjectType::Rule, ObjectType::Index }; vector *list=nullptr; - for(unsigned i=0; i < 2; i++) + for(unsigned i=0; i < 3; i++) { list=getObjectList(types[i]); while(!list->empty()) @@ -55,19 +55,19 @@ void View::setName(const QString &name) { QString prev_name=this->getName(true); BaseObject::setName(name); - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } void View::setSchema(BaseObject *schema) { QString prev_name=this->getName(true); BaseObject::setSchema(schema); - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } void View::setProtected(bool value) { - ObjectType obj_types[]={ OBJ_RULE, OBJ_TRIGGER }; + ObjectType obj_types[]={ ObjectType::Rule, ObjectType::Trigger }; unsigned i; vector::iterator itr, itr_end; vector *list=nullptr; @@ -173,46 +173,92 @@ int View::getReferenceIndex(Reference &refer) vector *View::getExpressionList(unsigned sql_type) { - if(sql_type==Reference::SQL_REFER_SELECT) + if(sql_type==Reference::SqlReferSelect) return(&exp_select); - else if(sql_type==Reference::SQL_REFER_FROM) + else if(sql_type==Reference::SqlReferFrom) return(&exp_from); - else if(sql_type==Reference::SQL_REFER_WHERE) + else if(sql_type==Reference::SqlReferWhere) return(&exp_where); - else if(sql_type==Reference::SQL_REFER_END_EXPR) + else if(sql_type==Reference::SqlReferEndExpr) return(&exp_end); else return(nullptr); } -QStringList View::getColumnsList(void) +void View::generateColumns(void) { - QStringList col_list; - unsigned i=0, count=exp_select.size(), col_id=0, col_count=0; - Table *tab=nullptr; + unsigned col_id = 0, col_count = 0, expr_idx = 0; + Table *tab = nullptr; + Reference ref; + Column *col = nullptr; + QString name, alias; - for(i=0; i < count; i++) - { - if(!references[i].getColumn()) - { - tab=references[i].getTable(); + columns.clear(); - if(!tab) continue; - col_count=tab->getColumnCount(); + if(hasDefinitionExpression()) + { + vector ref_cols = references[0].getColumns(); - for(col_id=0; col_id < col_count; col_id++) - col_list.push_back(tab->getColumn(col_id)->getName(true)); - } + if(ref_cols.empty()) + columns.push_back(SimpleColumn(QString("%1...").arg(references[0].getExpression().simplified().mid(0, 20)), + Attributes::Expression, + !references[0].getReferenceAlias().isEmpty() ? references[0].getReferenceAlias() : QString())); else + columns = ref_cols; + } + else + { + for(auto ref_id : exp_select) { - if(!references[i].getColumnAlias().isEmpty()) - col_list.push_back(references[i].getColumnAlias()); + ref = references[ref_id]; + + if(!ref.getExpression().isEmpty()) + { + if(!ref.getAlias().isEmpty()) + name = ref.getAlias(); + else + name = QString("_expr%1_").arg(expr_idx++); + + name = getUniqueColumnName(name); + columns.push_back(SimpleColumn(name, Attributes::Expression, + !ref.getReferenceAlias().isEmpty() ? ref.getReferenceAlias() : name)); + } + else if(!ref.getColumn()) + { + tab=ref.getTable(); + col_count=tab->getColumnCount(); + + for(col_id=0; col_id < col_count; col_id++) + { + col = tab->getColumn(col_id); + name = getUniqueColumnName(col->getName()); + columns.push_back(SimpleColumn(name, *col->getType(), + !col->getAlias().isEmpty() ? col->getAlias() : col->getName())); + } + } else - col_list.push_back(references[i].getColumn()->getName(true)); + { + col = ref.getColumn(); + + if(!ref.getColumnAlias().isEmpty()) + name = getUniqueColumnName(ref.getColumnAlias()); + else + name = getUniqueColumnName(col->getName()); + + if(!ref.getReferenceAlias().isEmpty()) + alias = ref.getReferenceAlias(); + else + alias = !col->getAlias().isEmpty() ? col->getAlias() : col->getName(); + + columns.push_back(SimpleColumn(name, *col->getType(), alias)); + } } } +} - return(col_list); +vector View::getColumns(void) +{ + return(columns); } void View::addReference(Reference &refer, unsigned sql_type, int expr_id) @@ -222,21 +268,21 @@ void View::addReference(Reference &refer, unsigned sql_type, int expr_id) Column *col=nullptr; //Specific tests for expressions used as view definition - if(sql_type==Reference::SQL_VIEW_DEFINITION) + if(sql_type==Reference::SqlViewDefinition) { //Raises an error if the expression is empty if(refer.getExpression().isEmpty()) - throw Exception(ERR_INV_VIEW_DEF_EXPRESSION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgInvalidViewDefExpression,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if already exists a definition expression else if(hasDefinitionExpression()) - throw Exception(ERR_ASG_SEC_VIEW_DEF_EXPRESSION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgSecondViewDefExpression,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the user try to add a definition expression when already exists another references else if(!references.empty()) - throw Exception(ERR_MIX_VIEW_DEF_EXPR_REFS,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::MixingViewDefExprsReferences,__PRETTY_FUNCTION__,__FILE__,__LINE__); } //Raises an error if the user try to add a ordinary reference when there is a reference used as definition expression else if(hasDefinitionExpression()) - throw Exception(ERR_MIX_VIEW_DEF_EXPR_REFS,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::MixingViewDefExprsReferences,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Checks if the reference already exists idx=getReferenceIndex(refer); @@ -245,22 +291,26 @@ void View::addReference(Reference &refer, unsigned sql_type, int expr_id) if(idx < 0) { //Inserts the reference on the view - refer.setDefinitionExpression(sql_type==Reference::SQL_VIEW_DEFINITION); + refer.setDefinitionExpression(sql_type==Reference::SqlViewDefinition); references.push_back(refer); idx=references.size()-1; } - if(sql_type!=Reference::SQL_VIEW_DEFINITION) + if(sql_type!=Reference::SqlViewDefinition) { //Gets the expression list expr_list=getExpressionList(sql_type); + //Avoiding the insertion of a duplicated reference in the expression list + if(std::find(expr_list->begin(), expr_list->end(), idx) != expr_list->end()) + return; + //Inserts the reference id on the expression list if(expr_id >= 0 && expr_id < static_cast(expr_list->size())) expr_list->insert(expr_list->begin() + expr_id, static_cast(idx)); //Raises an error if the expression id is invalid else if(expr_id >= 0 && expr_id >= static_cast(expr_list->size())) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); else expr_list->push_back(static_cast(idx)); @@ -270,6 +320,7 @@ void View::addReference(Reference &refer, unsigned sql_type, int expr_id) this->object_id=BaseObject::getGlobalId(); } + generateColumns(); setCodeInvalidated(true); } @@ -284,7 +335,7 @@ unsigned View::getReferenceCount(unsigned sql_type, int ref_type) if(!vect_idref) { - if(sql_type==Reference::SQL_VIEW_DEFINITION) + if(sql_type==Reference::SqlViewDefinition) return(references.size()); else return(0); @@ -316,7 +367,7 @@ Reference View::getReference(unsigned ref_id) { //Raises an error if the reference id is out of bound if(ref_id >= references.size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(references[ref_id]); } @@ -327,9 +378,9 @@ Reference View::getReference(unsigned ref_id, unsigned sql_type) //Raises an error if the reference id is out of bound if(ref_id >= references.size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(sql_type==Reference::SQL_VIEW_DEFINITION || vect_idref) + if(sql_type==Reference::SqlViewDefinition || vect_idref) return(references[ref_id]); else return(references[vect_idref->at(ref_id)]); @@ -343,7 +394,7 @@ void View::removeReference(unsigned ref_id) //Raises an error if the reference id is out of bound if(ref_id >= references.size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); for(i=0; i < 3; i++) { @@ -354,14 +405,15 @@ void View::removeReference(unsigned ref_id) { //Removes the reference id from the expression list if(references[*itr]==references[ref_id]) - vect_idref[i]->erase(itr); - - itr++; + itr = vect_idref[i]->erase(itr); + else + itr++; } } //Removes the reference from the view references.erase(references.begin() + ref_id); + generateColumns(); setCodeInvalidated(true); } @@ -372,6 +424,7 @@ void View::removeReferences(void) exp_from.clear(); exp_where.clear(); exp_end.clear(); + columns.clear(); setCodeInvalidated(true); } @@ -380,7 +433,7 @@ void View::removeReference(unsigned expr_id, unsigned sql_type) vector *vect_idref=getExpressionList(sql_type); if(expr_id >= vect_idref->size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); vect_idref->erase(vect_idref->begin() + expr_id); setCodeInvalidated(true); @@ -395,10 +448,10 @@ int View::getReferenceIndex(Reference &ref, unsigned sql_type) idx_ref=getReferenceIndex(ref); - if(sql_type==Reference::SQL_VIEW_DEFINITION && + if(sql_type==Reference::SqlViewDefinition && idx_ref >=0 && ref.isDefinitionExpression()) return(idx_ref); - else if(sql_type!=Reference::SQL_VIEW_DEFINITION) + else if(sql_type!=Reference::SqlViewDefinition) { itr=vet_idref->begin(); itr_end=vet_idref->end(); @@ -433,10 +486,10 @@ void View::setDefinitionAttribute(void) vector *refs_vect[4]={&exp_select, &exp_from, &exp_where, &exp_end}; vector::iterator itr, itr_end; QString keywords[4]={"SELECT\n", "\nFROM\n", "\nWHERE\n", "\n"}; - unsigned i, cnt, idx, sql_type[4]={ Reference::SQL_REFER_SELECT, - Reference::SQL_REFER_FROM, - Reference::SQL_REFER_WHERE, - Reference::SQL_REFER_END_EXPR }; + unsigned i, cnt, idx, sql_type[4]={ Reference::SqlReferSelect, + Reference::SqlReferFrom, + Reference::SqlReferWhere, + Reference::SqlReferEndExpr }; for(i=0; i < 4; i++) { @@ -453,8 +506,8 @@ void View::setDefinitionAttribute(void) itr++; } - if(sql_type[i]==Reference::SQL_REFER_SELECT || - sql_type[i]==Reference::SQL_REFER_FROM) + if(sql_type[i]==Reference::SqlReferSelect || + sql_type[i]==Reference::SqlReferFrom) { //Removing the final comma from SELECT / FROM declarations cnt=decl.size(); @@ -467,26 +520,26 @@ void View::setDefinitionAttribute(void) } decl=decl.trimmed(); - if(!decl.endsWith(QChar(';'))) + if(!decl.isEmpty() && !decl.endsWith(QChar(';'))) decl.append(QChar(';')); - attributes[ParsersAttributes::DEFINITION]=decl; + attributes[Attributes::Definition]=decl; } void View::setReferencesAttribute(void) { QString str_aux; - QString attribs[]={ ParsersAttributes::SELECT_EXP, - ParsersAttributes::FROM_EXP, - ParsersAttributes::SIMPLE_EXP, - ParsersAttributes::END_EXP}; + QString attribs[]={ Attributes::SelectExp, + Attributes::FromExp, + Attributes::SimpleExp, + Attributes::EndExp}; vector *vect_exp[]={&exp_select, &exp_from, &exp_where, &exp_end}; int cnt, i, i1; cnt=references.size(); for(i=0; i < cnt; i++) str_aux+=references[i].getXMLDefinition(); - attributes[ParsersAttributes::REFERENCES]=str_aux; + attributes[Attributes::References]=str_aux; for(i=0; i < 4; i++) { @@ -543,8 +596,13 @@ bool View::isReferencingTable(Table *tab) for(i=0; i < count && !found; i++) { - aux_tab=references[i].getTable(); - found=(aux_tab && (aux_tab == tab)); + if(references[i].isDefinitionExpression()) + found = references[i].getReferencedTableIndex(tab) >= 0; + else + { + aux_tab = references[i].getTable(); + found = (aux_tab && (aux_tab == tab)); + } } return(found); @@ -569,29 +627,45 @@ QString View::getCodeDefinition(unsigned def_type) QString code_def=getCachedCode(def_type, false); if(!code_def.isEmpty()) return(code_def); - attributes[ParsersAttributes::CTE_EXPRESSION]=cte_expression; - attributes[ParsersAttributes::MATERIALIZED]=(materialized ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::RECURSIVE]=(recursive ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::WITH_NO_DATA]=(with_no_data ? ParsersAttributes::_TRUE_ : QString()); - attributes[ParsersAttributes::COLUMNS]=QString(); - attributes[ParsersAttributes::TAG]=QString(); - attributes[ParsersAttributes::HIDE_EXT_ATTRIBS]=(isExtAttribsHidden() ? ParsersAttributes::_TRUE_ : QString()); + attributes[Attributes::CteExpression]=cte_expression; + attributes[Attributes::Materialized]=(materialized ? Attributes::True : QString()); + attributes[Attributes::Recursive]=(recursive ? Attributes::True : QString()); + attributes[Attributes::WithNoData]=(with_no_data ? Attributes::True : QString()); + attributes[Attributes::Columns]=QString(); + attributes[Attributes::Tag]=QString(); + attributes[Attributes::Layer]=QString::number(layer); + attributes[Attributes::Pagination]=(pagination_enabled ? Attributes::True : QString()); + attributes[Attributes::CollapseMode]=QString::number(enum_cast(collapse_mode)); + attributes[Attributes::AttribsPage]=(pagination_enabled ? QString::number(curr_page[AttribsSection]) : QString()); + attributes[Attributes::ExtAttribsPage]=(pagination_enabled ? QString::number(curr_page[ExtAttribsSection]) : QString()); setSQLObjectAttribute(); - if(recursive) - attributes[ParsersAttributes::COLUMNS]=getColumnsList().join(','); + // We use column names only if the view has references that aren't its whole definition (Reference::SqlViewDefinition) + if(recursive && !hasDefinitionExpression()) + { + QStringList fmt_names; + + //for(auto &name : col_names) + // fmt_names.push_back(formatName(name)); - if(tag && def_type==SchemaParser::XML_DEFINITION) - attributes[ParsersAttributes::TAG]=tag->getCodeDefinition(def_type, true); + for(auto &col : columns) + fmt_names.push_back(formatName(col.name)); - if(def_type==SchemaParser::SQL_DEFINITION) + attributes[Attributes::Columns]=fmt_names.join(','); + } + + if(tag && def_type==SchemaParser::XmlDefinition) + attributes[Attributes::Tag]=tag->getCodeDefinition(def_type, true); + + if(def_type==SchemaParser::SqlDefinition) setDefinitionAttribute(); else { setPositionAttribute(); setFadedOutAttribute(); setReferencesAttribute(); + attributes[Attributes::MaxObjCount]=QString::number(static_cast(getMaxObjectCount() * 1.20)); } return(BaseObject::__getCodeDefinition(def_type)); @@ -600,7 +674,56 @@ QString View::getCodeDefinition(unsigned def_type) void View::setSQLObjectAttribute(void) { if(materialized) - attributes[ParsersAttributes::SQL_OBJECT]=QString("MATERIALIZED ") + BaseObject::getSQLName(OBJ_VIEW); + attributes[Attributes::SqlObject]=QString("MATERIALIZED ") + BaseObject::getSQLName(ObjectType::View); +} + +QString View::getUniqueColumnName(const QString &name) +{ + unsigned idx = 1; + QString fmt_name = name; + vector::iterator itr, itr_end; + + itr = columns.begin(); + itr_end = columns.end(); + + while(itr != itr_end) + { + if(itr->name == fmt_name) + { + fmt_name = name + QString::number(idx); + idx++; + itr = columns.begin(); + } + else + itr++; + } + + return(fmt_name); +} + +void View::setObjectListsCapacity(unsigned capacity) +{ + if(capacity < DefMaxObjectCount || capacity > DefMaxObjectCount * 10) + capacity = DefMaxObjectCount; + + references.reserve(capacity); + indexes.reserve(capacity/2); + rules.reserve(capacity/2); + triggers.reserve(capacity/2); +} + +unsigned View::getMaxObjectCount(void) +{ + unsigned count = 0, max = references.size(); + vector types = { ObjectType::Index, ObjectType::Rule, ObjectType::Trigger }; + + for(auto type : types) + { + count = getObjectList(type)->size(); + if(count > max) max = count; + } + + return(max); } QString View::getDropDefinition(bool cascade) @@ -667,7 +790,7 @@ int View::getObjectIndex(const QString &name, ObjectType obj_type) void View::addObject(BaseObject *obj, int obj_idx) { if(!obj) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { try @@ -678,20 +801,20 @@ void View::addObject(BaseObject *obj, int obj_idx) //Raises an error if already exists a object with the same name and type if(getObjectIndex(obj->getName(), tab_obj->getObjectType()) >= 0) { - throw Exception(QString(Exception::getErrorMessage(ERR_ASG_DUPLIC_OBJECT)) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgDuplicatedObject) .arg(obj->getName(true)) .arg(obj->getTypeName()) .arg(this->getName(true)) .arg(this->getTypeName()), - ERR_ASG_DUPLIC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgDuplicatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); } //Validates the object definition tab_obj->setParentTable(this); - tab_obj->getCodeDefinition(SchemaParser::SQL_DEFINITION); + tab_obj->getCodeDefinition(SchemaParser::SqlDefinition); //Make a additional validation if the object is a trigger - if(tab_obj->getObjectType()==OBJ_TRIGGER) + if(tab_obj->getObjectType()==ObjectType::Trigger) dynamic_cast(tab_obj)->validateTrigger(); //Inserts the object at specified position @@ -704,13 +827,13 @@ void View::addObject(BaseObject *obj, int obj_idx) } catch(Exception &e) { - if(e.getErrorType()==ERR_UNDEF_ATTRIB_VALUE) - throw Exception(Exception::getErrorMessage(ERR_ASG_OBJ_INV_DEFINITION) + if(e.getErrorCode()==ErrorCode::UndefinedAttributeValue) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgObjectInvalidDefinition) .arg(obj->getName()) .arg(obj->getTypeName()), - ERR_ASG_OBJ_INV_DEFINITION,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + ErrorCode::AsgObjectInvalidDefinition,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } } @@ -723,7 +846,7 @@ void View::addTrigger(Trigger *trig, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -735,7 +858,7 @@ void View::addRule(Rule *rule, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -747,7 +870,7 @@ void View::addIndex(Index *index, int obj_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -758,7 +881,7 @@ void View::removeObject(unsigned obj_idx, ObjectType obj_type) //Raises an error if the object index is out of bound if(obj_idx >= obj_list->size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); itr=obj_list->begin() + obj_idx; (*itr)->setParentTable(nullptr); @@ -774,7 +897,7 @@ void View::removeObject(BaseObject *obj) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -786,7 +909,7 @@ void View::removeObject(const QString &name, ObjectType obj_type) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -794,11 +917,11 @@ void View::removeTrigger(unsigned idx) { try { - removeObject(idx, OBJ_TRIGGER); + removeObject(idx, ObjectType::Trigger); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -806,11 +929,11 @@ void View::removeRule(unsigned idx) { try { - removeObject(idx, OBJ_RULE); + removeObject(idx, ObjectType::Rule); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -818,11 +941,11 @@ void View::removeIndex(unsigned idx) { try { - removeObject(idx, OBJ_INDEX); + removeObject(idx, ObjectType::Index); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -832,7 +955,7 @@ TableObject *View::getObject(unsigned obj_idx, ObjectType obj_type) //Raises an error if the object index is out of bound if(obj_idx >= obj_list->size()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(obj_list->at(obj_idx)); } @@ -851,7 +974,7 @@ TableObject *View::getObject(const QString &name, ObjectType obj_type) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -859,11 +982,11 @@ Trigger *View::getTrigger(unsigned obj_idx) { try { - return(dynamic_cast(getObject(obj_idx, OBJ_TRIGGER))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Trigger))); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -871,11 +994,11 @@ Rule *View::getRule(unsigned obj_idx) { try { - return(dynamic_cast(getObject(obj_idx, OBJ_RULE))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Rule))); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -883,11 +1006,11 @@ Index *View::getIndex(unsigned obj_idx) { try { - return(dynamic_cast(getObject(obj_idx, OBJ_INDEX))); + return(dynamic_cast(getObject(obj_idx, ObjectType::Index))); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -899,7 +1022,7 @@ unsigned View::getObjectCount(ObjectType obj_type, bool) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -920,14 +1043,16 @@ unsigned View::getIndexCount() vector *View::getObjectList(ObjectType obj_type) { - if(obj_type==OBJ_TRIGGER) + if(obj_type==ObjectType::Trigger) return(&triggers); - else if(obj_type==OBJ_RULE) + + if(obj_type==ObjectType::Rule) return(&rules); - else if(obj_type==OBJ_INDEX) + + if(obj_type==ObjectType::Index) return(&indexes); - else - throw Exception(ERR_OBT_OBJ_INVALID_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + throw Exception(ErrorCode::ObtObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); } void View::removeObjects(void) @@ -957,6 +1082,8 @@ void View::operator = (View &view) (*dynamic_cast(this))=reinterpret_cast(view); + this->pagination_enabled = view.pagination_enabled; + this->layer = view.layer; this->references=view.references; this->exp_select=view.exp_select; this->exp_from=view.exp_from; @@ -966,16 +1093,21 @@ void View::operator = (View &view) this->recursive=view.recursive; this->with_no_data=view.with_no_data; - PgSQLType::renameUserType(prev_name, this, this->getName(true)); + PgSqlType::renameUserType(prev_name, this, this->getName(true)); } -vector View::getObjects(void) +vector View::getObjects(const vector &excl_types) { vector list; + vector types={ ObjectType::Trigger, ObjectType::Index, ObjectType::Rule }; - list.assign(triggers.begin(), triggers.end()); - list.insert(list.end(), rules.begin(), rules.end()); - list.insert(list.end(), indexes.begin(), indexes.end()); + for(auto type : types) + { + if(std::find(excl_types.begin(), excl_types.end(), type) != excl_types.end()) + continue; + + list.insert(list.end(), getObjectList(type)->begin(), getObjectList(type)->end()) ; + } return(list); } diff --git a/libpgmodeler/src/view.h b/libpgmodeler/src/view.h index 8c0547a5e8..14178de510 100644 --- a/libpgmodeler/src/view.h +++ b/libpgmodeler/src/view.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -44,6 +44,8 @@ class View: public BaseTable { vector rules; vector indexes; + vector columns; + /*! \brief Commom table expression. This is prepend on the views definition. CTE's are available since PostgreSQL 8.4: > http://www.postgresql.org/docs/8.4/interactive/queries-with.html */ @@ -71,13 +73,11 @@ class View: public BaseTable { //! \brief Returns the reference to internal expression list according to the SQL expression type vector *getExpressionList(unsigned sql_type); - /*! \brief Returns a list of deduced names for view's colums for recursive views. - The names are retrieved, first, from columns aliases and lastly from table's columns - when TABLE.* syntax is used */ - QStringList getColumnsList(void); - void setSQLObjectAttribute(void); + //! \brief Returns a unique name for a columns comparing it to the existent columns. In case of duplication the name receives a suffix + QString getUniqueColumnName(const QString &name); + public: View(void); ~View(void); @@ -137,8 +137,8 @@ class View: public BaseTable { //! \brief Returns the object index searching by its index and type int getObjectIndex(const QString &name, ObjectType obj_type); - //! \brief Returns all child objects of the view (does not include references) - vector getObjects(void); + //! \brief Returns the children objects of the view excluding the provided children types (does not include references) + vector getObjects(const vector &excl_types = {}); //! \brief Returns the view's child object using its index and type TableObject *getObject(unsigned obj_idx, ObjectType obj_type); @@ -234,6 +234,19 @@ class View: public BaseTable { //! \brief Returns if the view has an reference expression that is used as view definition bool hasDefinitionExpression(void); + void setObjectListsCapacity(unsigned capacity); + + unsigned getMaxObjectCount(void); + + /*! \brief Returns a list of deduced names for view's colums (useful for recursive views). + * The names are retrieved, first, from columns aliases and lastly from table's columns + * when TABLE.* syntax is used. For expressions, if aliases aren't defined, a column name in the + * for _expr#_ is used. */ + void generateColumns(void); + + //! \brief Returns the deduced columns of the view + vector getColumns(void); + //! \brief Copy the attributes between two views void operator = (View &visao); }; diff --git a/libpgmodeler_ui/libpgmodeler_ui.pro b/libpgmodeler_ui/libpgmodeler_ui.pro index e0eacb7103..97bb31e847 100644 --- a/libpgmodeler_ui/libpgmodeler_ui.pro +++ b/libpgmodeler_ui/libpgmodeler_ui.pro @@ -66,7 +66,6 @@ SOURCES += src/mainwindow.cpp \ src/pgmodelerplugin.cpp \ src/pluginsconfigwidget.cpp \ src/collationwidget.cpp \ - src/elementswidget.cpp \ src/modelexporthelper.cpp \ src/modelvalidationwidget.cpp \ src/modelvalidationhelper.cpp \ @@ -112,7 +111,16 @@ SOURCES += src/mainwindow.cpp \ src/sceneinfowidget.cpp \ src/bulkdataeditwidget.cpp \ src/policywidget.cpp \ - src/objectstablewidget.cpp + src/objectstablewidget.cpp \ + src/resultsetmodel.cpp \ + src/referencewidget.cpp \ + src/sqlexecutionhelper.cpp \ + src/elementstablewidget.cpp \ + src/elementwidget.cpp \ + src/layerswidget.cpp \ + src/foreigndatawrapperwidget.cpp \ + src/foreignserverwidget.cpp \ + src/usermappingwidget.cpp HEADERS += src/mainwindow.h \ @@ -166,7 +174,6 @@ HEADERS += src/mainwindow.h \ src/objectrenamewidget.h \ src/pluginsconfigwidget.h \ src/collationwidget.h \ - src/elementswidget.h \ src/modelexporthelper.h \ src/modelvalidationwidget.h \ src/modelvalidationhelper.h \ @@ -212,7 +219,16 @@ HEADERS += src/mainwindow.h \ src/sceneinfowidget.h \ src/bulkdataeditwidget.h \ src/policywidget.h \ - src/objectstablewidget.h + src/objectstablewidget.h \ + src/resultsetmodel.h \ + src/referencewidget.h \ + src/sqlexecutionhelper.h \ + src/elementstablewidget.h \ + src/elementwidget.h \ + src/layerswidget.h \ + src/foreigndatawrapperwidget.h \ + src/foreignserverwidget.h \ + src/usermappingwidget.h FORMS += ui/mainwindow.ui \ ui/textboxwidget.ui \ @@ -261,7 +277,6 @@ FORMS += ui/mainwindow.ui \ ui/pluginsconfigwidget.ui \ ui/schemawidget.ui \ ui/collationwidget.ui \ - ui/elementswidget.ui \ ui/modelvalidationwidget.ui \ ui/extensionwidget.ui \ ui/objectfinderwidget.ui \ @@ -295,7 +310,13 @@ FORMS += ui/mainwindow.ui \ ui/sceneinfowidget.ui \ ui/bulkdataeditwidget.ui \ ui/policywidget.ui \ - ui/objectstablewidget.ui + ui/objectstablewidget.ui \ + ui/referencewidget.ui \ + ui/elementwidget.ui \ + ui/layerswidget.ui \ + ui/foreigndatawrapperwidget.ui \ + ui/foreignserverwidget.ui \ + ui/usermappingwidget.ui unix|windows: LIBS += -L$$OUT_PWD/../libobjrenderer/ -lobjrenderer \ -L$$OUT_PWD/../libpgconnector/ -lpgconnector \ diff --git a/libpgmodeler_ui/res/icones/addlayer.png b/libpgmodeler_ui/res/icones/addlayer.png new file mode 100644 index 0000000000..b516c27070 Binary files /dev/null and b/libpgmodeler_ui/res/icones/addlayer.png differ diff --git a/libpgmodeler_ui/res/icones/clearlayers.png b/libpgmodeler_ui/res/icones/clearlayers.png new file mode 100644 index 0000000000..01f76cea54 Binary files /dev/null and b/libpgmodeler_ui/res/icones/clearlayers.png differ diff --git a/libpgmodeler_ui/res/icones/collapse.png b/libpgmodeler_ui/res/icones/collapse.png new file mode 100644 index 0000000000..cb094f2c9b Binary files /dev/null and b/libpgmodeler_ui/res/icones/collapse.png differ diff --git a/libpgmodeler_ui/res/icones/compactview.png b/libpgmodeler_ui/res/icones/compactview.png new file mode 100644 index 0000000000..671d3fdcba Binary files /dev/null and b/libpgmodeler_ui/res/icones/compactview.png differ diff --git a/libpgmodeler_ui/res/icones/dellayer.png b/libpgmodeler_ui/res/icones/dellayer.png new file mode 100644 index 0000000000..fc45ce4811 Binary files /dev/null and b/libpgmodeler_ui/res/icones/dellayer.png differ diff --git a/libpgmodeler_ui/res/icones/delrow.png b/libpgmodeler_ui/res/icones/delrow.png index 2556e26a44..33ab7be33e 100644 Binary files a/libpgmodeler_ui/res/icones/delrow.png and b/libpgmodeler_ui/res/icones/delrow.png differ diff --git a/libpgmodeler_ui/res/icones/delrows.png b/libpgmodeler_ui/res/icones/delrows.png index d24247f319..19c9614bb8 100644 Binary files a/libpgmodeler_ui/res/icones/delrows.png and b/libpgmodeler_ui/res/icones/delrows.png differ diff --git a/libpgmodeler_ui/res/icones/foreigndatawrapper.png b/libpgmodeler_ui/res/icones/foreigndatawrapper.png new file mode 100644 index 0000000000..691461de89 Binary files /dev/null and b/libpgmodeler_ui/res/icones/foreigndatawrapper.png differ diff --git a/libpgmodeler_ui/res/icones/foreigndatawrapper_grp.png b/libpgmodeler_ui/res/icones/foreigndatawrapper_grp.png new file mode 100644 index 0000000000..9eb0d5a595 Binary files /dev/null and b/libpgmodeler_ui/res/icones/foreigndatawrapper_grp.png differ diff --git a/libpgmodeler_ui/res/icones/foreignserver.png b/libpgmodeler_ui/res/icones/foreignserver.png new file mode 100644 index 0000000000..6c9321da5e Binary files /dev/null and b/libpgmodeler_ui/res/icones/foreignserver.png differ diff --git a/libpgmodeler_ui/res/icones/foreignserver_grp.png b/libpgmodeler_ui/res/icones/foreignserver_grp.png new file mode 100644 index 0000000000..81daa0bc56 Binary files /dev/null and b/libpgmodeler_ui/res/icones/foreignserver_grp.png differ diff --git a/libpgmodeler_ui/res/icones/help_big.png b/libpgmodeler_ui/res/icones/help_big.png new file mode 100644 index 0000000000..34d769e6b1 Binary files /dev/null and b/libpgmodeler_ui/res/icones/help_big.png differ diff --git a/libpgmodeler_ui/res/icones/layers.png b/libpgmodeler_ui/res/icones/layers.png new file mode 100644 index 0000000000..1028e204fe Binary files /dev/null and b/libpgmodeler_ui/res/icones/layers.png differ diff --git a/libpgmodeler_ui/res/icones/moreactions.png b/libpgmodeler_ui/res/icones/moreactions.png new file mode 100644 index 0000000000..2ffd625838 Binary files /dev/null and b/libpgmodeler_ui/res/icones/moreactions.png differ diff --git a/libpgmodeler_ui/res/icones/movetolayer.png b/libpgmodeler_ui/res/icones/movetolayer.png new file mode 100644 index 0000000000..f1ed6cc39b Binary files /dev/null and b/libpgmodeler_ui/res/icones/movetolayer.png differ diff --git a/libpgmodeler_ui/res/icones/newtab.png b/libpgmodeler_ui/res/icones/newtab.png new file mode 100644 index 0000000000..294d150697 Binary files /dev/null and b/libpgmodeler_ui/res/icones/newtab.png differ diff --git a/libpgmodeler_ui/res/icones/pagination.png b/libpgmodeler_ui/res/icones/pagination.png new file mode 100644 index 0000000000..eabba28bd9 Binary files /dev/null and b/libpgmodeler_ui/res/icones/pagination.png differ diff --git a/libpgmodeler_ui/res/icones/relationshippart.png b/libpgmodeler_ui/res/icones/relationshippart.png new file mode 100644 index 0000000000..ae77edd457 Binary files /dev/null and b/libpgmodeler_ui/res/icones/relationshippart.png differ diff --git a/libpgmodeler_ui/res/icones/resizecols.png b/libpgmodeler_ui/res/icones/resizecols.png new file mode 100644 index 0000000000..e71e89b51c Binary files /dev/null and b/libpgmodeler_ui/res/icones/resizecols.png differ diff --git a/libpgmodeler_ui/res/icones/stop.png b/libpgmodeler_ui/res/icones/stop.png new file mode 100644 index 0000000000..2fa991e063 Binary files /dev/null and b/libpgmodeler_ui/res/icones/stop.png differ diff --git a/libpgmodeler_ui/res/icones/usermapping.png b/libpgmodeler_ui/res/icones/usermapping.png new file mode 100644 index 0000000000..05f14c5808 Binary files /dev/null and b/libpgmodeler_ui/res/icones/usermapping.png differ diff --git a/libpgmodeler_ui/res/icones/usermapping_grp.png b/libpgmodeler_ui/res/icones/usermapping_grp.png new file mode 100644 index 0000000000..289d9b0ffc Binary files /dev/null and b/libpgmodeler_ui/res/icones/usermapping_grp.png differ diff --git a/libpgmodeler_ui/res/resources.qrc b/libpgmodeler_ui/res/resources.qrc index c4688eecf5..ee50fda2fa 100644 --- a/libpgmodeler_ui/res/resources.qrc +++ b/libpgmodeler_ui/res/resources.qrc @@ -239,6 +239,26 @@ icones/bulkedit.png icones/policy_grp.png icones/policy.png + icones/compactview.png + icones/help_big.png + icones/moreactions.png + icones/stop.png + icones/newtab.png + icones/relationshippart.png + icones/resizecols.png + icones/collapse.png + icones/pagination.png + icones/layers.png + icones/addlayer.png + icones/dellayer.png + icones/clearlayers.png + icones/movetolayer.png + icones/foreigndatawrapper_grp.png + icones/foreigndatawrapper.png + icones/foreignserver.png + icones/foreignserver_grp.png + icones/usermapping.png + icones/usermapping_grp.png imagens/model2sql.png diff --git a/libpgmodeler_ui/src/aboutwidget.cpp b/libpgmodeler_ui/src/aboutwidget.cpp index 5c36d6391d..6fcf4ce570 100644 --- a/libpgmodeler_ui/src/aboutwidget.cpp +++ b/libpgmodeler_ui/src/aboutwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -31,14 +31,13 @@ AboutWidget::AboutWidget(QWidget *parent) : QWidget(parent) drop_shadow->setBlurRadius(30); this->setGraphicsEffect(drop_shadow); - pgmodeler_ver_lbl->setText(QString("v%1").arg(GlobalAttributes::PGMODELER_VERSION)); - build_num_lbl->setText(GlobalAttributes::PGMODELER_BUILD_NUMBER); + PgModelerUiNs::configureWidgetFont(title_lbl, PgModelerUiNs::HugeFontFactor); + PgModelerUiNs::configureWidgetFont(pgmodeler_ver_lbl, PgModelerUiNs::HugeFontFactor); + PgModelerUiNs::configureWidgetFont(build_lbl, PgModelerUiNs::BigFontFactor); + PgModelerUiNs::configureWidgetFont(build_num_lbl, PgModelerUiNs::BigFontFactor); - for(int row=0; row < contributors_tab->rowCount(); row++) - contributors_tab->item(row, 2)->setToolTip(contributors_tab->item(row, 2)->text().replace(QString("; "), QString(";\n"))); - - contributors_tab->sortByColumn(0, Qt::AscendingOrder); - contributors_tab->resizeColumnsToContents(); + pgmodeler_ver_lbl->setText(QString("v%1 ").arg(GlobalAttributes::PgModelerVersion)); + build_num_lbl->setText(QString("%1 Qt %2").arg(GlobalAttributes::PgModelerBuildNumber).arg(QT_VERSION_STR)); connect(hide_tb, &QToolButton::clicked, this, [&](){ @@ -46,13 +45,7 @@ AboutWidget::AboutWidget(QWidget *parent) : QWidget(parent) emit s_visibilityChanged(false); }); - PgModelerUiNS::configureWidgetFont(title_lbl, PgModelerUiNS::HUGE_FONT_FACTOR); - PgModelerUiNS::configureWidgetFont(slogan_lbl, PgModelerUiNS::BIG_FONT_FACTOR); - PgModelerUiNS::configureWidgetFont(pgmodeler_ver_lbl, PgModelerUiNS::HUGE_FONT_FACTOR); - PgModelerUiNS::configureWidgetFont(build_lbl, PgModelerUiNS::MEDIUM_FONT_FACTOR); - PgModelerUiNS::configureWidgetFont(build_num_lbl, PgModelerUiNS::MEDIUM_FONT_FACTOR); - - float factor = BaseObjectView::getScreenDpiFactor(); + double factor = BaseObjectView::getScreenDpiFactor(); this->adjustSize(); this->resize(this->minimumWidth() * factor, this->minimumHeight() * factor); } diff --git a/libpgmodeler_ui/src/aboutwidget.h b/libpgmodeler_ui/src/aboutwidget.h index 046441549d..0cf8317e85 100644 --- a/libpgmodeler_ui/src/aboutwidget.h +++ b/libpgmodeler_ui/src/aboutwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -35,7 +35,7 @@ class AboutWidget: public QWidget, public Ui::AboutWidget { Q_OBJECT public: - AboutWidget(QWidget *parent = 0); + AboutWidget(QWidget *parent = nullptr); signals: void s_visibilityChanged(bool value); diff --git a/libpgmodeler_ui/src/aggregatewidget.cpp b/libpgmodeler_ui/src/aggregatewidget.cpp index 38b6169c21..c90d971f88 100644 --- a/libpgmodeler_ui/src/aggregatewidget.cpp +++ b/libpgmodeler_ui/src/aggregatewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "aggregatewidget.h" -AggregateWidget::AggregateWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_AGGREGATE) +AggregateWidget::AggregateWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Aggregate) { try { @@ -28,17 +28,17 @@ AggregateWidget::AggregateWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_ QFrame *frame=nullptr; initial_cond_hl=new SyntaxHighlighter(initial_cond_txt); - initial_cond_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + initial_cond_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); - final_func_sel=new ObjectSelectorWidget(OBJ_FUNCTION, true, this); - transition_func_sel=new ObjectSelectorWidget(OBJ_FUNCTION, true, this); - sort_op_sel=new ObjectSelectorWidget(OBJ_OPERATOR, true, this); + final_func_sel=new ObjectSelectorWidget(ObjectType::Function, true, this); + transition_func_sel=new ObjectSelectorWidget(ObjectType::Function, true, this); + sort_op_sel=new ObjectSelectorWidget(ObjectType::Operator, true, this); input_type=new PgSQLTypeWidget(this, trUtf8("Input Data Type")); state_type=new PgSQLTypeWidget(this, trUtf8("State Data Type")); - input_types_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ - ObjectsTableWidget::EDIT_BUTTON, true, this); + input_types_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + ObjectsTableWidget::EditButton, true, this); input_types_tab->setColumnCount(1); funcaoagregacao_grid->addWidget(final_func_sel,0,1,1,1); @@ -66,7 +66,7 @@ AggregateWidget::AggregateWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_ funcaoagregacao_grid->addWidget(frame, funcaoagregacao_grid->count()+1, 0, 1, 2); frame->setParent(this); - configureFormLayout(funcaoagregacao_grid, OBJ_AGGREGATE); + configureFormLayout(funcaoagregacao_grid, ObjectType::Aggregate); setRequiredField(state_type); setRequiredField(input_type); @@ -79,14 +79,14 @@ AggregateWidget::AggregateWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_ } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void AggregateWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, Aggregate *aggregate) { unsigned count, i; - PgSQLType type; + PgSqlType type; BaseObjectWidget::setAttributes(model,op_list, aggregate, schema); @@ -98,8 +98,8 @@ void AggregateWidget::setAttributes(DatabaseModel *model, OperationList *op_list if(aggregate) { - final_func_sel->setSelectedObject(aggregate->getFunction(Aggregate::FINAL_FUNC)); - transition_func_sel->setSelectedObject(aggregate->getFunction(Aggregate::TRANSITION_FUNC)); + final_func_sel->setSelectedObject(aggregate->getFunction(Aggregate::FinalFunc)); + transition_func_sel->setSelectedObject(aggregate->getFunction(Aggregate::TransitionFunc)); sort_op_sel->setSelectedObject(aggregate->getSortOperator()); initial_cond_txt->setPlainText(aggregate->getInitialCondition()); @@ -110,7 +110,7 @@ void AggregateWidget::setAttributes(DatabaseModel *model, OperationList *op_list { input_types_tab->addRow(); type=aggregate->getDataType(i); - input_types_tab->setRowData(QVariant::fromValue(type), i); + input_types_tab->setRowData(QVariant::fromValue(type), i); input_types_tab->setCellText(*type,i,0); } input_types_tab->blockSignals(false); @@ -124,10 +124,10 @@ void AggregateWidget::handleDataType(int row) { try { - PgSQLType type; + PgSqlType type; type=input_type->getPgSQLType(); - input_types_tab->setRowData(QVariant::fromValue(type), row); + input_types_tab->setRowData(QVariant::fromValue(type), row); input_types_tab->setCellText(*type,row,0); } catch(Exception &e) @@ -135,7 +135,7 @@ void AggregateWidget::handleDataType(int row) if(input_types_tab->getCellText(row, 0).isEmpty()) input_types_tab->removeRow(row); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -156,10 +156,10 @@ void AggregateWidget::applyConfiguration(void) count=input_types_tab->getRowCount(); for(i=0; i < count; i++) - aggregate->addDataType(input_types_tab->getRowData(i).value()); + aggregate->addDataType(input_types_tab->getRowData(i).value()); - aggregate->setFunction(Aggregate::TRANSITION_FUNC, dynamic_cast(transition_func_sel->getSelectedObject())); - aggregate->setFunction(Aggregate::FINAL_FUNC, dynamic_cast(final_func_sel->getSelectedObject())); + aggregate->setFunction(Aggregate::TransitionFunc, dynamic_cast(transition_func_sel->getSelectedObject())); + aggregate->setFunction(Aggregate::FinalFunc, dynamic_cast(final_func_sel->getSelectedObject())); aggregate->setSortOperator(dynamic_cast(sort_op_sel->getSelectedObject())); BaseObjectWidget::applyConfiguration(); @@ -168,7 +168,7 @@ void AggregateWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/aggregatewidget.h b/libpgmodeler_ui/src/aggregatewidget.h index 32b8936d3d..1c8d45cbe7 100644 --- a/libpgmodeler_ui/src/aggregatewidget.h +++ b/libpgmodeler_ui/src/aggregatewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -55,7 +55,7 @@ class AggregateWidget: public BaseObjectWidget, public Ui::AggregateWidget { *transition_func_sel; public: - AggregateWidget(QWidget * parent = 0); + AggregateWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, Aggregate *aggregate); private slots: diff --git a/libpgmodeler_ui/src/appearanceconfigwidget.cpp b/libpgmodeler_ui/src/appearanceconfigwidget.cpp index 15104d7136..81cbb6c323 100644 --- a/libpgmodeler_ui/src/appearanceconfigwidget.cpp +++ b/libpgmodeler_ui/src/appearanceconfigwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -25,36 +25,70 @@ AppearanceConfigWidget::AppearanceConfigWidget(QWidget * parent) : BaseConfigWid setupUi(this); QString conf_ids[]={ - ParsersAttributes::GLOBAL,ParsersAttributes::CONSTRAINTS, ParsersAttributes::OBJ_SELECTION, - ParsersAttributes::POSITION_INFO, ParsersAttributes::POSITION_INFO, - ParsersAttributes::OBJECT_TYPE, ParsersAttributes::LOCKER_ARC, ParsersAttributes::LOCKER_BODY, - ParsersAttributes::TABLE_SCHEMA_NAME, ParsersAttributes::TABLE_NAME, ParsersAttributes::TABLE_BODY, - ParsersAttributes::TABLE_EXT_BODY, ParsersAttributes::TABLE_TITLE, - BaseObject::getSchemaName(OBJ_RULE), BaseObject::getSchemaName(OBJ_RULE), - BaseObject::getSchemaName(OBJ_INDEX), BaseObject::getSchemaName(OBJ_INDEX), - BaseObject::getSchemaName(OBJ_TRIGGER), BaseObject::getSchemaName(OBJ_TRIGGER), - BaseObject::getSchemaName(OBJ_CONSTRAINT), BaseObject::getSchemaName(OBJ_CONSTRAINT), - ParsersAttributes::VIEW_SCHEMA_NAME, ParsersAttributes::VIEW_NAME, - ParsersAttributes::VIEW_BODY /*23*/, ParsersAttributes::VIEW_EXT_BODY /*24*/, ParsersAttributes::VIEW_TITLE /*25*/, ParsersAttributes::ALIAS, - ParsersAttributes::REF_COLUMN, ParsersAttributes::REF_TABLE, ParsersAttributes::REFERENCE, - BaseObject::getSchemaName(OBJ_TEXTBOX), ParsersAttributes::COLUMN, ParsersAttributes::COLUMN, - ParsersAttributes::INH_COLUMN, ParsersAttributes::PROT_COLUMN, ParsersAttributes::PK_COLUMN, - ParsersAttributes::PK_COLUMN, ParsersAttributes::FK_COLUMN, ParsersAttributes::FK_COLUMN, - ParsersAttributes::UQ_COLUMN, ParsersAttributes::UQ_COLUMN, ParsersAttributes::NN_COLUMN, - ParsersAttributes::NN_COLUMN, ParsersAttributes::RELATIONSHIP, ParsersAttributes::LABEL, - ParsersAttributes::LABEL, ParsersAttributes::ATTRIBUTE, ParsersAttributes::ATTRIBUTE, - ParsersAttributes::TAG, ParsersAttributes::TAG, ParsersAttributes::PLACEHOLDER}; + Attributes::Global, //0 + Attributes::Constraints, //1 + Attributes::ObjSelection, //2 + Attributes::PositionInfo, //3 + Attributes::PositionInfo, //4 + Attributes::ObjectType, //5 + Attributes::LockerArc, //6 + Attributes::LockerBody, //7 + Attributes::TableSchemaName, //8 + Attributes::TableName, //9 + Attributes::TableBody, //10 + Attributes::TableExtBody, //11 + Attributes::TableTitle, //12 + BaseObject::getSchemaName(ObjectType::Rule), //13 + BaseObject::getSchemaName(ObjectType::Rule), //14 + BaseObject::getSchemaName(ObjectType::Index), //15 + BaseObject::getSchemaName(ObjectType::Index), //16 + BaseObject::getSchemaName(ObjectType::Trigger), //17 + BaseObject::getSchemaName(ObjectType::Trigger), //18 + BaseObject::getSchemaName(ObjectType::Constraint), //19 + BaseObject::getSchemaName(ObjectType::Constraint), //20 + BaseObject::getSchemaName(ObjectType::Policy), //21 + BaseObject::getSchemaName(ObjectType::Policy), //22 + Attributes::ViewSchemaName, //21 -> 23 + Attributes::ViewName, //22 + Attributes::ViewBody, //23 + Attributes::ViewExtBody, //24 + Attributes::ViewTitle, //25 + Attributes::Alias, //26 + Attributes::RefColumn, //27 + Attributes::RefTable, //28 + Attributes::Reference, //29 + BaseObject::getSchemaName(ObjectType::Textbox), //30 + Attributes::Column, //31 + Attributes::Column, //32 + Attributes::InhColumn, //33 + Attributes::ProtColumn, //34 + Attributes::PkColumn, //35 + Attributes::PkColumn, //36 + Attributes::FkColumn, //37 + Attributes::FkColumn, //38 + Attributes::UqColumn, //39 + Attributes::UqColumn, //40 + Attributes::NnColumn, //41 + Attributes::NnColumn, //42 + Attributes::Relationship, //43 + Attributes::Label, //44 + Attributes::Label, //45 + Attributes::Attribute, //46 + Attributes::Attribute, //47 + Attributes::Tag, //48 + Attributes::Tag, //49 + Attributes::Placeholder /*50*/}; int i, count=element_cmb->count(), //This auxiliary vector stores the id of elements that represents color/font conf. of objects - obj_conf_ids_vect[]={ 2, 4, 6, 7, 10, 11, 12, 14, 16, 18, 20, 23, 24, 25, - 29, 30, 32, 36, 38, 40, 42, 43, 45, 47, 49, 50 }; + obj_conf_ids_vect[]={ 2, 4, 6, 7, 10, 11, 12, 14, 16, 18, 20, 22, 25, 26, 27, + 31, 32, 34, 38, 40, 42, 44, 45, 47, 49, 51, 52 }; vector conf_obj_ids(obj_conf_ids_vect, obj_conf_ids_vect + sizeof(obj_conf_ids_vect) / sizeof(int)); conf_items.resize(count); for(i=0; i < count; i++) { conf_items[i].conf_id=conf_ids[i]; - conf_items[i].obj_conf=(std::find(conf_obj_ids.begin(), conf_obj_ids.end(), i)!=conf_obj_ids.end()); + conf_items[i].obj_conf=(std::find(conf_obj_ids.begin(), conf_obj_ids.end(), i) != conf_obj_ids.end()); } color_picker=new ColorPickerWidget(3, this); @@ -123,11 +157,11 @@ void AppearanceConfigWidget::loadExampleModel(void) if(model->getObjectCount()==0) { - model->loadModel(GlobalAttributes::TMPL_CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::EXAMPLE_MODEL); + model->loadModel(GlobalAttributes::TmplConfigurationDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::ExampleModel); - count=model->getObjectCount(OBJ_TABLE); + count=model->getObjectCount(ObjectType::Table); for(i=0; i < count; i++) { tab=new TableView(model->getTable(i)); @@ -135,28 +169,28 @@ void AppearanceConfigWidget::loadExampleModel(void) scene->addItem(tab); } - count=model->getObjectCount(OBJ_VIEW); + count=model->getObjectCount(ObjectType::View); for(i=0; i < count; i++) { view=new GraphicalView(model->getView(i)); scene->addItem(view); } - count=model->getObjectCount(OBJ_RELATIONSHIP); + count=model->getObjectCount(ObjectType::Relationship); for(i=0; i < count; i++) { - rel=new RelationshipView(model->getRelationship(i, OBJ_RELATIONSHIP)); + rel=new RelationshipView(model->getRelationship(i, ObjectType::Relationship)); scene->addItem(rel); } - count=model->getObjectCount(BASE_RELATIONSHIP); + count=model->getObjectCount(ObjectType::BaseRelationship); for(i=0; i < count; i++) { - rel=new RelationshipView(model->getRelationship(i, BASE_RELATIONSHIP)); + rel=new RelationshipView(model->getRelationship(i, ObjectType::BaseRelationship)); scene->addItem(rel); } - count=model->getObjectCount(OBJ_TEXTBOX); + count=model->getObjectCount(ObjectType::Textbox); for(i=0; i < count; i++) { txtbox=new StyledTextboxView(model->getTextbox(i)); @@ -171,14 +205,14 @@ void AppearanceConfigWidget::loadExampleModel(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void AppearanceConfigWidget::updatePlaceholderItem(void) { - placeholder->setBrush(BaseObjectView::getFillStyle(ParsersAttributes::PLACEHOLDER)); - QPen pen=BaseObjectView::getBorderStyle(ParsersAttributes::PLACEHOLDER); + placeholder->setBrush(BaseObjectView::getFillStyle(Attributes::Placeholder)); + QPen pen=BaseObjectView::getBorderStyle(Attributes::Placeholder); pen.setStyle(Qt::DashLine); placeholder->setPen(pen); } @@ -204,14 +238,14 @@ void AppearanceConfigWidget::loadConfiguration(void) } this->enableConfigElement(); - font_cmb->setCurrentFont(BaseObjectView::getFontStyle(ParsersAttributes::GLOBAL).font()); + font_cmb->setCurrentFont(BaseObjectView::getFontStyle(Attributes::Global).font()); model->setObjectsModified(); updatePlaceholderItem(); scene->update(); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo()); } } @@ -248,7 +282,7 @@ void AppearanceConfigWidget::saveConfiguration(void) attribs[attrib_id]=item.colors[2].name(); } //If the item is a font config - else if(item.conf_id!=ParsersAttributes::GLOBAL && !item.obj_conf) + else if(item.conf_id!=Attributes::Global && !item.obj_conf) { font=item.font_fmt.font(); @@ -256,14 +290,14 @@ void AppearanceConfigWidget::saveConfiguration(void) attrib_id=item.conf_id + QString("-fcolor"); attribs[attrib_id]=item.font_fmt.foreground().color().name(); - attrib_id=item.conf_id + QString("-") + ParsersAttributes::ITALIC; - attribs[attrib_id]=(font.italic() ? ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_); + attrib_id=item.conf_id + QString("-") + Attributes::Italic; + attribs[attrib_id]=(font.italic() ? Attributes::True : Attributes::False); - attrib_id=item.conf_id + QString("-") + ParsersAttributes::BOLD; - attribs[attrib_id]=(font.bold() ? ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_); + attrib_id=item.conf_id + QString("-") + Attributes::Bold; + attribs[attrib_id]=(font.bold() ? Attributes::True : Attributes::False); - attrib_id=item.conf_id + QString("-") + ParsersAttributes::UNDERLINE; - attribs[attrib_id]=(font.underline() ? ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_); + attrib_id=item.conf_id + QString("-") + Attributes::Underline; + attribs[attrib_id]=(font.underline() ? Attributes::True : Attributes::False); } //Special case: treating the global font element else @@ -273,12 +307,12 @@ void AppearanceConfigWidget::saveConfiguration(void) } } - config_params[GlobalAttributes::OBJECTS_STYLE_CONF]=attribs; - BaseConfigWidget::saveConfiguration(GlobalAttributes::OBJECTS_STYLE_CONF, config_params); + config_params[GlobalAttributes::ObjectsStyleConf]=attribs; + BaseConfigWidget::saveConfiguration(GlobalAttributes::ObjectsStyleConf, config_params); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -302,8 +336,8 @@ void AppearanceConfigWidget::enableConfigElement(void) color_picker->setVisible(colors_lbl->isVisible()); //Buttons visible when a object configuration element is selected - //color_picker->setButtonVisible(1, conf_items[idx].obj_conf); - //color_picker->setButtonVisible(2, conf_items[idx].obj_conf); + color_picker->setButtonVisible(1, conf_items[idx].obj_conf); + color_picker->setButtonVisible(2, conf_items[idx].obj_conf); underline_chk->blockSignals(true); italic_chk->blockSignals(true); @@ -384,13 +418,13 @@ void AppearanceConfigWidget::restoreDefaults(void) { try { - BaseConfigWidget::restoreDefaults(GlobalAttributes::OBJECTS_STYLE_CONF); + BaseConfigWidget::restoreDefaults(GlobalAttributes::ObjectsStyleConf, false); this->loadConfiguration(); setConfigurationChanged(true); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/appearanceconfigwidget.h b/libpgmodeler_ui/src/appearanceconfigwidget.h index 40e64f84cf..d5c58d30fd 100644 --- a/libpgmodeler_ui/src/appearanceconfigwidget.h +++ b/libpgmodeler_ui/src/appearanceconfigwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -73,7 +73,7 @@ class AppearanceConfigWidget: public BaseConfigWidget, public Ui::AppearanceConf void updatePlaceholderItem(void); public: - AppearanceConfigWidget(QWidget * parent=0); + AppearanceConfigWidget(QWidget * parent = nullptr); ~AppearanceConfigWidget(void); void saveConfiguration(void); diff --git a/libpgmodeler_ui/src/baseconfigwidget.cpp b/libpgmodeler_ui/src/baseconfigwidget.cpp index 8a94221c0b..49c4b250b7 100644 --- a/libpgmodeler_ui/src/baseconfigwidget.cpp +++ b/libpgmodeler_ui/src/baseconfigwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -50,18 +50,18 @@ void BaseConfigWidget::saveConfiguration(const QString &conf_id, map::iterator itr, itr_end; @@ -83,8 +83,8 @@ void BaseConfigWidget::saveConfiguration(const QString &conf_id, map%1!").arg(bkp_filename), Messagebox::INFO_ICON); + msg_box.show(trUtf8("A backup of the previous settings was saved into %1!").arg(bkp_filename), Messagebox::InfoIcon); } } } @@ -148,24 +148,24 @@ void BaseConfigWidget::loadConfiguration(const QString &conf_id, mapgetConfigurationParams(config_params, key_attribs); - if(xmlparser.hasElement(XMLParser::CHILD_ELEMENT, XML_ELEMENT_NODE)) + if(xmlparser.hasElement(XmlParser::ChildElement, XML_ELEMENT_NODE)) { xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); if(xmlparser.getElementType()!=XML_TEXT_NODE) { @@ -184,19 +184,19 @@ void BaseConfigWidget::loadConfiguration(const QString &conf_id, mapgetConfigurationParams(config_params, key_attribs); } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } xmlparser.restorePosition(); } } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, filename); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, filename); } } @@ -223,11 +223,11 @@ void BaseConfigWidget::getConfigurationParams(map &config_ key=xmlparser.getElementName(); //Extract the contents of the child element and create a special element on map called "_contents_" - if(xmlparser.hasElement(XMLParser::CHILD_ELEMENT, XML_TEXT_NODE)) + if(xmlparser.hasElement(XmlParser::ChildElement, XML_TEXT_NODE)) { xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); - aux_attribs[ParsersAttributes::CONTENTS]=xmlparser.getElementContent(); + xmlparser.accessElement(XmlParser::ChildElement); + aux_attribs[Attributes::Contents]=xmlparser.getElementContent(); xmlparser.restorePosition(); } diff --git a/libpgmodeler_ui/src/baseconfigwidget.h b/libpgmodeler_ui/src/baseconfigwidget.h index 572f584f5f..ddd742d448 100644 --- a/libpgmodeler_ui/src/baseconfigwidget.h +++ b/libpgmodeler_ui/src/baseconfigwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -29,7 +29,7 @@ #include "exception.h" #include "xmlparser.h" -#include "parsersattributes.h" +#include "attributes.h" #include #include @@ -40,7 +40,7 @@ class BaseConfigWidget: public QWidget { bool config_changed; protected: - XMLParser xmlparser; + XmlParser xmlparser; SchemaParser schparser; /*! \brief Saves the configuration params on file. The conf_id param indicates the type of @@ -55,8 +55,9 @@ class BaseConfigWidget: public QWidget { //! \brief Get a configuratoin key from the xml parser void getConfigurationParams(map &config_params, const vector &key_attribs); - //! \brief Restore the configuration specified by conf_in loading them from the original file (conf/defaults) - void restoreDefaults(const QString &conf_id); + /*! \brief Restore the configuration specified by conf_in loading them from the original file (conf/defaults) + * The silent parameter indicates that the restoration should not emit a message box informing the restoration sucess */ + void restoreDefaults(const QString &conf_id, bool silent); //! \brief Adds a parameter to the specified configuration parameters set static void addConfigurationParam(map &config_params, const QString ¶m, const attribs_map &attribs); @@ -64,7 +65,7 @@ class BaseConfigWidget: public QWidget { void showEvent(QShowEvent *); public: - BaseConfigWidget(QWidget *parent = 0); + BaseConfigWidget(QWidget *parent = nullptr); ~BaseConfigWidget(void){} bool isConfigurationChanged(void); diff --git a/libpgmodeler_ui/src/baseform.cpp b/libpgmodeler_ui/src/baseform.cpp index 309c2b35b7..e45ef52a41 100644 --- a/libpgmodeler_ui/src/baseform.cpp +++ b/libpgmodeler_ui/src/baseform.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -26,7 +26,7 @@ BaseForm::BaseForm(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f) void BaseForm::setButtonConfiguration(unsigned button_conf) { - if(button_conf==Messagebox::OK_CANCEL_BUTTONS) + if(button_conf==Messagebox::OkCancelButtons) { apply_ok_btn->setText(trUtf8("&Apply")); cancel_btn->setVisible(true); @@ -45,14 +45,16 @@ void BaseForm::resizeForm(QWidget *widget) int max_h = 0, max_w = 0, curr_w =0, curr_h = 0, screen_id = qApp->desktop()->screenNumber(qApp->activeWindow()); QScreen *screen=qApp->screens().at(screen_id); - float dpi_factor = 0; + double dpi_factor = 0; + double pixel_ratio = 0; max_w = screen->size().width() * 0.70; max_h = screen->size().height() * 0.70; - dpi_factor = screen->logicalDotsPerInch() / 96.0f; + dpi_factor = screen->logicalDotsPerInch() / 96.0; + pixel_ratio = screen->devicePixelRatio(); - if(dpi_factor <= 1.01f) - dpi_factor = 1.0f; + if(dpi_factor <= 1.01) + dpi_factor = 1.0; vbox->setContentsMargins(2,2,2,2); @@ -85,7 +87,7 @@ void BaseForm::resizeForm(QWidget *widget) main_frm->setLayout(vbox); this->adjustSize(); - curr_h=this->height(), + curr_h=this->height(); curr_w=min_size.width(); // If the current height is greater than the widget's minimum height we will use a medium value @@ -102,8 +104,8 @@ void BaseForm::resizeForm(QWidget *widget) ((buttons_lt->contentsMargins().top() + buttons_lt->contentsMargins().bottom()) * 6); - curr_w *= dpi_factor; - curr_h *= dpi_factor; + curr_w *= dpi_factor * pixel_ratio; + curr_h *= dpi_factor * pixel_ratio; if(curr_w > screen->size().width()) curr_w = screen->size().width() * 0.80; @@ -113,6 +115,7 @@ void BaseForm::resizeForm(QWidget *widget) this->setMinimumSize(min_size); this->resize(curr_w, curr_h); + this->adjustSize(); } void BaseForm::closeEvent(QCloseEvent *) @@ -124,17 +127,17 @@ void BaseForm::setMainWidget(BaseObjectWidget *widget) { if(!widget) return; - if(widget->getHandledObjectType()!=BASE_OBJECT && widget->windowTitle().isEmpty()) + if(widget->getHandledObjectType()!=ObjectType::BaseObject && widget->windowTitle().isEmpty()) setWindowTitle(trUtf8("%1 properties").arg(BaseObject::getTypeName(widget->getHandledObjectType()))); else setWindowTitle(widget->windowTitle()); apply_ok_btn->setDisabled(widget->isHandledObjectProtected()); resizeForm(widget); - setButtonConfiguration(Messagebox::OK_CANCEL_BUTTONS); + setButtonConfiguration(Messagebox::OkCancelButtons); + connect(cancel_btn, SIGNAL(clicked(bool)), widget, SLOT(cancelConfiguration())); connect(cancel_btn, SIGNAL(clicked(bool)), this, SLOT(reject())); - //connect(this, SIGNAL(rejected()), widget, SLOT(cancelConfiguration())); connect(apply_ok_btn, SIGNAL(clicked(bool)), widget, SLOT(applyConfiguration())); connect(widget, SIGNAL(s_closeRequested()), this, SLOT(accept())); } @@ -145,7 +148,7 @@ void BaseForm::setMainWidget(QWidget *widget) setWindowTitle(widget->windowTitle()); resizeForm(widget); - setButtonConfiguration(Messagebox::OK_BUTTON); + setButtonConfiguration(Messagebox::OkButton); connect(cancel_btn, SIGNAL(clicked(bool)), this, SLOT(reject())); connect(apply_ok_btn, SIGNAL(clicked(bool)), this, SLOT(accept())); diff --git a/libpgmodeler_ui/src/baseform.h b/libpgmodeler_ui/src/baseform.h index 488fc17071..d209bd19b3 100644 --- a/libpgmodeler_ui/src/baseform.h +++ b/libpgmodeler_ui/src/baseform.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -45,9 +45,9 @@ class BaseForm: public QDialog, public Ui::BaseForm { void closeEvent(QCloseEvent *); public: - BaseForm(QWidget * parent = 0, Qt::WindowFlags f = 0); + BaseForm(QWidget * parent = nullptr, Qt::WindowFlags f = Qt::Widget); - void setButtonConfiguration(unsigned button_conf=Messagebox::OK_CANCEL_BUTTONS); + void setButtonConfiguration(unsigned button_conf=Messagebox::OkCancelButtons); /*! \brief Injects the specified object into the form and turns it the main widget. The widget is reparented to the stack widget within the form */ diff --git a/libpgmodeler_ui/src/baseobjectwidget.cpp b/libpgmodeler_ui/src/baseobjectwidget.cpp index a1f300b212..bd3706fc93 100644 --- a/libpgmodeler_ui/src/baseobjectwidget.cpp +++ b/libpgmodeler_ui/src/baseobjectwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,11 +20,12 @@ #include "permissionwidget.h" #include "customsqlwidget.h" #include "baseform.h" +#include "generalconfigwidget.h" -const QColor BaseObjectWidget::PROT_LINE_BGCOLOR=QColor(255,180,180); -const QColor BaseObjectWidget::PROT_LINE_FGCOLOR=QColor(80,80,80); -const QColor BaseObjectWidget::RELINC_LINE_BGCOLOR=QColor(164,249,176); -const QColor BaseObjectWidget::RELINC_LINE_FGCOLOR=QColor(80,80,80); +const QColor BaseObjectWidget::ProtRowBgColor=QColor(255,180,180); +const QColor BaseObjectWidget::ProtRowFgColor=QColor(80,80,80); +const QColor BaseObjectWidget::RelAddedRowBgColor=QColor(164,249,176); +const QColor BaseObjectWidget::RelAddedRowFgColor=QColor(80,80,80); BaseObjectWidget::BaseObjectWidget(QWidget *parent, ObjectType obj_type): QWidget(parent) { @@ -44,22 +45,25 @@ BaseObjectWidget::BaseObjectWidget(QWidget *parent, ObjectType obj_type): QWidge prev_schema=nullptr; op_list=nullptr; object=nullptr; - object_px=NAN; - object_py=NAN; + object_px=DNaN; + object_py=DNaN; schema_sel=nullptr; owner_sel=nullptr; tablespace_sel=nullptr; object_protected = false; - PgModelerUiNS::configureWidgetFont(protected_obj_lbl, PgModelerUiNS::MEDIUM_FONT_FACTOR); + PgModelerUiNs::configureWidgetFont(protected_obj_lbl, PgModelerUiNs::MediumFontFactor); connect(edt_perms_tb, SIGNAL(clicked(bool)),this, SLOT(editPermissions(void))); connect(append_sql_tb, SIGNAL(clicked(bool)),this, SLOT(editCustomSQL(void))); - schema_sel=new ObjectSelectorWidget(OBJ_SCHEMA, true, this); - collation_sel=new ObjectSelectorWidget(OBJ_COLLATION, true, this); - tablespace_sel=new ObjectSelectorWidget(OBJ_TABLESPACE, true, this); - owner_sel=new ObjectSelectorWidget(OBJ_ROLE, true, this); + schema_sel=new ObjectSelectorWidget(ObjectType::Schema, true, this); + collation_sel=new ObjectSelectorWidget(ObjectType::Collation, true, this); + tablespace_sel=new ObjectSelectorWidget(ObjectType::Tablespace, true, this); + owner_sel=new ObjectSelectorWidget(ObjectType::Role, true, this); + + alias_ht=new HintTextWidget(alias_hint, this); + alias_ht->setText(alias_edt->statusTip()); baseobject_grid = new QGridLayout; baseobject_grid->setObjectName("objetobase_grid"); @@ -67,6 +71,9 @@ BaseObjectWidget::BaseObjectWidget(QWidget *parent, ObjectType obj_type): QWidge baseobject_grid->addWidget(name_lbl, 1, 0, 1, 1); baseobject_grid->addWidget(name_edt, 1, 1, 1, 1); baseobject_grid->addWidget(id_ico_wgt, 1, 2, 1, 3); + baseobject_grid->addWidget(logical_name_lbl, 2, 0, 1, 1); + baseobject_grid->addWidget(alias_edt, 2, 1, 1, 1); + baseobject_grid->addWidget(alias_hint_wgt, 2, 2, 1, 3); baseobject_grid->addWidget(schema_lbl, 4, 0, 1, 1); baseobject_grid->addWidget(schema_sel, 4, 1, 1, 4); baseobject_grid->addWidget(collation_lbl, 5, 0, 1, 1); @@ -90,7 +97,7 @@ BaseObjectWidget::BaseObjectWidget(QWidget *parent, ObjectType obj_type): QWidge } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -156,14 +163,18 @@ void BaseObjectWidget::setRequiredField(QWidget *widget) } else if(edt || txt || sel) { - QPalette pal; - pal.setColor(QPalette::Base, bgcolor); - pal.setColor(QPalette::Text, QColor(0,0,0)); - if(sel) + { widget=sel->obj_name_txt; - - widget->setPalette(pal); + widget->setStyleSheet(QString("ObjectSelectorWidget > QPlainTextEdit { background-color: %1; }").arg(bgcolor.name())); + } + else + { + QPalette pal; + pal.setColor(QPalette::Base, bgcolor); + pal.setColor(QPalette::Text, QColor(0,0,0)); + widget->setPalette(pal); + } } str_aux=(!widget->toolTip().isEmpty() ? QString("\n") : QString()); @@ -173,7 +184,7 @@ void BaseObjectWidget::setRequiredField(QWidget *widget) void BaseObjectWidget::setAttributes(DatabaseModel *model, BaseObject *object, BaseObject *parent_obj) { - setAttributes(model, nullptr, object, parent_obj, NAN, NAN, false); + setAttributes(model, nullptr, object, parent_obj, DNaN, DNaN, false); } void BaseObjectWidget::disableReferencesSQL(BaseObject *object) @@ -212,7 +223,7 @@ void BaseObjectWidget::configureTabOrder(vector widgets) int idx=0, cnt=0; widgets.insert(widgets.begin(), - { name_edt, schema_sel , collation_sel, owner_sel, tablespace_sel, + { name_edt, alias_edt, alias_ht, schema_sel , collation_sel, owner_sel, tablespace_sel, comment_edt, append_sql_tb, edt_perms_tb, disable_sql_chk }); for(auto &wgt : widgets) @@ -247,6 +258,11 @@ void BaseObjectWidget::configureTabOrder(vector widgets) QWidget::setTabOrder(tab_order[idx], tab_order[idx+1]); } +BaseObject *BaseObjectWidget::getHandledObject(void) +{ + return(object); +} + void BaseObjectWidget::cancelChainedOperation(void) { bool op_list_changed=false; @@ -271,7 +287,7 @@ void BaseObjectWidget::cancelChainedOperation(void) void BaseObjectWidget::setAttributes(DatabaseModel *model, OperationList *op_list, BaseObject *object, BaseObject *parent_obj, double obj_px, double obj_py, bool uses_op_list) { - ObjectType obj_type, parent_type=BASE_OBJECT; + ObjectType obj_type, parent_type=ObjectType::BaseObject; /* Reseting the objects attributes in order to force them to be redefined every time this method is called */ @@ -282,7 +298,10 @@ void BaseObjectWidget::setAttributes(DatabaseModel *model, OperationList *op_lis this->table=nullptr; if(!model || (uses_op_list && !op_list)) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + if(op_list) + operation_count = op_list->getCurrentSize(); this->model=model; @@ -290,12 +309,12 @@ void BaseObjectWidget::setAttributes(DatabaseModel *model, OperationList *op_lis { parent_type=parent_obj->getObjectType(); - if(parent_type==OBJ_TABLE || parent_type==OBJ_VIEW) + if(parent_type==ObjectType::Table || parent_type==ObjectType::View) this->table=dynamic_cast(parent_obj); - else if(parent_type==OBJ_RELATIONSHIP) + else if(parent_type==ObjectType::Relationship) this->relationship=dynamic_cast(parent_obj); - else if(parent_type!=OBJ_DATABASE && parent_type!=OBJ_SCHEMA) - throw Exception(ERR_ASG_OBJECT_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if(parent_type!=ObjectType::Database && parent_type!=ObjectType::Schema) + throw Exception(ErrorCode::AsgObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); } else { @@ -331,30 +350,29 @@ void BaseObjectWidget::setAttributes(DatabaseModel *model, OperationList *op_lis append_sql_tb->setEnabled(object!=nullptr && !new_object); owner_sel->setModel(model); - owner_sel->setSelectedObject(model->getDefaultObject(OBJ_ROLE)); + owner_sel->setSelectedObject(model->getDefaultObject(ObjectType::Role)); schema_sel->setModel(model); - schema_sel->setSelectedObject(model->getDefaultObject(OBJ_SCHEMA)); + schema_sel->setSelectedObject(model->getDefaultObject(ObjectType::Schema)); tablespace_sel->setModel(model); - tablespace_sel->setSelectedObject(model->getDefaultObject(OBJ_TABLESPACE)); + tablespace_sel->setSelectedObject(model->getDefaultObject(ObjectType::Tablespace)); collation_sel->setModel(model); - collation_sel->setSelectedObject(model->getDefaultObject(OBJ_COLLATION)); + collation_sel->setSelectedObject(model->getDefaultObject(ObjectType::Collation)); if(object) { - //bool prot = false; - obj_id_lbl->setVisible(true); obj_id_lbl->setText(QString("ID: %1").arg(object->getObjectId())); - if(handled_obj_type!=BASE_OBJECT) + if(handled_obj_type != ObjectType::BaseObject) name_edt->setText(object->getName()); else name_edt->setText(object->getSignature()); comment_edt->setPlainText(object->getComment()); + alias_edt->setText(object->getAlias()); /* When creating a new table or relationship the object is pre allocated and the flag new_object is set. In order to avoid the selectors to have empty values, we check if the flag is false which means @@ -372,9 +390,9 @@ void BaseObjectWidget::setAttributes(DatabaseModel *model, OperationList *op_lis schema_sel->setSelectedObject(object->getSchema()); obj_type=object->getObjectType(); - object_protected=(parent_type!=OBJ_RELATIONSHIP && + object_protected=(parent_type!=ObjectType::Relationship && (object->isProtected() || - ((obj_type==OBJ_COLUMN || obj_type==OBJ_CONSTRAINT) && + ((obj_type==ObjectType::Column || obj_type==ObjectType::Constraint) && dynamic_cast(object)->isAddedByRelationship()))); protected_obj_frm->setVisible(object_protected); disable_sql_chk->setChecked(object->isSQLDisabled()); @@ -385,7 +403,7 @@ void BaseObjectWidget::setAttributes(DatabaseModel *model, OperationList *op_lis obj_id_lbl->setVisible(false); protected_obj_frm->setVisible(false); - if(parent_obj && parent_obj->getObjectType()==OBJ_SCHEMA) + if(parent_obj && parent_obj->getObjectType()==ObjectType::Schema) schema_sel->setSelectedObject(parent_obj); } } @@ -428,11 +446,15 @@ void BaseObjectWidget::configureFormLayout(QGridLayout *grid, ObjectType obj_typ this->setLayout(baseobject_grid); baseobject_grid->setContentsMargins(4, 4, 4, 4); - disable_sql_chk->setVisible(obj_type!=BASE_OBJECT && obj_type!=OBJ_PERMISSION && - obj_type!=OBJ_TEXTBOX && obj_type!=OBJ_TAG && - obj_type!=OBJ_PARAMETER); + disable_sql_chk->setVisible(obj_type!=ObjectType::BaseObject && obj_type!=ObjectType::Permission && + obj_type!=ObjectType::Textbox && obj_type!=ObjectType::Tag && + obj_type!=ObjectType::Parameter); - edt_perms_tb->setVisible(Permission::objectAcceptsPermission(obj_type)); + alias_edt->setVisible(BaseObject::acceptsAlias(obj_type)); + alias_hint_wgt->setVisible(BaseObject::acceptsAlias(obj_type)); + logical_name_lbl->setVisible(BaseObject::acceptsAlias(obj_type)); + + edt_perms_tb->setVisible(Permission::acceptsPermission(obj_type)); append_sql_tb->setVisible(BaseObject::acceptsCustomSQL(obj_type)); schema_lbl->setVisible(BaseObject::acceptsSchema(obj_type)); @@ -447,22 +469,31 @@ void BaseObjectWidget::configureFormLayout(QGridLayout *grid, ObjectType obj_typ collation_lbl->setVisible(BaseObject::acceptsCollation(obj_type)); collation_sel->setVisible(BaseObject::acceptsCollation(obj_type)); - show_comment=obj_type!=OBJ_RELATIONSHIP && obj_type!=OBJ_TEXTBOX && obj_type!=OBJ_PARAMETER; + show_comment=obj_type!=ObjectType::Relationship && obj_type!=ObjectType::Textbox && + obj_type!=ObjectType::Parameter && obj_type!=ObjectType::UserMapping && + obj_type!=ObjectType::Permission; comment_lbl->setVisible(show_comment); comment_edt->setVisible(show_comment); - if(obj_type!=BASE_OBJECT) + if(obj_type!=ObjectType::BaseObject) { - obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath(obj_type))); + obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath(obj_type))); obj_icon_lbl->setToolTip(BaseObject::getTypeName(obj_type)); - if(obj_type!=OBJ_PERMISSION && obj_type!=OBJ_CAST) + if(obj_type!=ObjectType::Permission && obj_type!=ObjectType::Cast && obj_type!=ObjectType::UserMapping) { setRequiredField(name_lbl); setRequiredField(name_edt); } + else + { + QFont font=name_edt->font(); + name_edt->setReadOnly(true); + font.setItalic(true); + name_edt->setFont(font); + } - if(obj_type!=OBJ_EXTENSION) + if(obj_type!=ObjectType::Extension) { setRequiredField(schema_lbl); setRequiredField(schema_sel); @@ -473,7 +504,7 @@ void BaseObjectWidget::configureFormLayout(QGridLayout *grid, ObjectType obj_typ { QFrame *frame=nullptr; map > fields_map; - fields_map[generateVersionsInterval(AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_91)].push_back(collation_lbl); + fields_map[generateVersionsInterval(AfterVersion, PgSqlVersions::PgSqlVersion91)].push_back(collation_lbl); frame=generateVersionWarningFrame(fields_map); baseobject_grid->addWidget(frame, baseobject_grid->count()+1, 0, 1, 0); frame->setParent(this); @@ -497,12 +528,12 @@ void BaseObjectWidget::configureFormLayout(QGridLayout *grid, ObjectType obj_typ QString BaseObjectWidget::generateVersionsInterval(unsigned ver_interv_id, const QString &ini_ver, const QString &end_ver) { - if(ver_interv_id==UNTIL_VERSION && !ini_ver.isEmpty()) - return(XMLParser::CHAR_LT + QString("= ") + ini_ver); - else if(ver_interv_id==VERSIONS_INTERVAL && !ini_ver.isEmpty() && !end_ver.isEmpty()) - return(XMLParser::CHAR_GT + QString("= ") + ini_ver + XMLParser::CHAR_AMP + XMLParser::CHAR_LT + QString("= ") + end_ver); - else if(ver_interv_id==AFTER_VERSION && !ini_ver.isEmpty()) - return(XMLParser::CHAR_GT + QString("= ") + ini_ver); + if(ver_interv_id==UntilVersion && !ini_ver.isEmpty()) + return(XmlParser::CharLt + QString("= ") + ini_ver); + else if(ver_interv_id==VersionsInterval && !ini_ver.isEmpty() && !end_ver.isEmpty()) + return(XmlParser::CharGt + QString("= ") + ini_ver + XmlParser::CharAmp + XmlParser::CharLt + QString("= ") + end_ver); + else if(ver_interv_id==AfterVersion && !ini_ver.isEmpty()) + return(XmlParser::CharGt + QString("= ") + ini_ver); else return(QString()); } @@ -520,7 +551,7 @@ QFrame *BaseObjectWidget::generateInformationFrame(const QString &msg) font.setBold(false); info_frm->setFont(font); - PgModelerUiNS::configureWidgetFont(info_frm, PgModelerUiNS::MEDIUM_FONT_FACTOR); + PgModelerUiNs::configureWidgetFont(info_frm, PgModelerUiNs::MediumFontFactor); info_frm->setObjectName("info_frm"); info_frm->setFrameShape(QFrame::StyledPanel); @@ -536,7 +567,7 @@ QFrame *BaseObjectWidget::generateInformationFrame(const QString &msg) ico_lbl->setMinimumSize(QSize(24, 24)); ico_lbl->setMaximumSize(QSize(24, 24)); ico_lbl->setScaledContents(true); - ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("msgbox_info"))); + ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("msgbox_info"))); ico_lbl->setAlignment(Qt::AlignLeft|Qt::AlignTop); grid->addWidget(ico_lbl, 0, 0, 1, 1); @@ -579,8 +610,8 @@ void BaseObjectWidget::highlightVersionSpecificFields(mapsetStyleSheet(QString("QWidget { font-weight: bold; font-style: italic; color: %1}").arg(color.name())); - wgt->setToolTip(QString("") + - trUtf8("Version") + + wgt->setToolTip(QString("") + + trUtf8("Version ") + itr.first + QString(" %1").arg(field_name)); } } @@ -601,7 +632,7 @@ QFrame *BaseObjectWidget::generateVersionWarningFrame(mapsetObjectName("alerta_frm"); alert_frm->setFrameShape(QFrame::StyledPanel); @@ -616,7 +647,7 @@ QFrame *BaseObjectWidget::generateVersionWarningFrame(mapsetMinimumSize(QSize(24, 24)); ico_lbl->setMaximumSize(QSize(24, 24)); ico_lbl->setScaledContents(true); - ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta"))); + ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta"))); ico_lbl->setAlignment(Qt::AlignLeft|Qt::AlignTop); grid->addWidget(ico_lbl, 0, 0, 1, 1); @@ -648,18 +679,24 @@ void BaseObjectWidget::editPermissions(void) permission_wgt->setAttributes(this->model, parent_obj, this->object); parent_form.setMainWidget(permission_wgt); - parent_form.setButtonConfiguration(Messagebox::OK_BUTTON); + parent_form.setButtonConfiguration(Messagebox::OkButton); + + GeneralConfigWidget::restoreWidgetGeometry(&parent_form, permission_wgt->metaObject()->className()); parent_form.exec(); + GeneralConfigWidget::saveWidgetGeometry(&parent_form, permission_wgt->metaObject()->className()); } void BaseObjectWidget::editCustomSQL(void) { BaseForm parent_form(this); - CustomSQLWidget *customsql_wgt=new CustomSQLWidget; + CustomSQLWidget *customsql_wgt=new CustomSQLWidget; - customsql_wgt->setAttributes(this->model, this->object); - parent_form.setMainWidget(customsql_wgt); + customsql_wgt->setAttributes(this->model, this->object); + parent_form.setMainWidget(customsql_wgt); + + GeneralConfigWidget::restoreWidgetGeometry(&parent_form, customsql_wgt->metaObject()->className()); parent_form.exec(); + GeneralConfigWidget::saveWidgetGeometry(&parent_form, customsql_wgt->metaObject()->className()); } void BaseObjectWidget::applyConfiguration(void) @@ -674,13 +711,13 @@ void BaseObjectWidget::applyConfiguration(void) QString obj_name; QApplication::setOverrideCursor(Qt::WaitCursor); - obj_name=BaseObject::formatName(name_edt->text().toUtf8(), obj_type==OBJ_OPERATOR); + obj_name=BaseObject::formatName(name_edt->text().toUtf8(), obj_type==ObjectType::Operator); if(this->object->acceptsSchema() && schema_sel->getSelectedObject()) obj_name=schema_sel->getSelectedObject()->getName(true) + "." + obj_name; //Checking the object duplicity - if(obj_type!=OBJ_DATABASE && obj_type!=OBJ_PERMISSION && obj_type!=OBJ_PARAMETER) + if(obj_type!=ObjectType::Database && obj_type!=ObjectType::Permission && obj_type!=ObjectType::Parameter) { if(table) { @@ -708,10 +745,10 @@ void BaseObjectWidget::applyConfiguration(void) checking on table list when the configured object is a view or a checking on view list when the configured object is a table, this because PostgreSQL does not accepts tables and views have the same name on the same schema */ - if(!aux_obj && obj_type==OBJ_TABLE) - aux_obj=model->getObject(obj_name, OBJ_VIEW); - else if(!aux_obj && obj_type==OBJ_VIEW) - aux_obj=model->getObject(obj_name, OBJ_TABLE); + if(!aux_obj && obj_type==ObjectType::Table) + aux_obj=model->getObject(obj_name, ObjectType::View); + else if(!aux_obj && obj_type==ObjectType::View) + aux_obj=model->getObject(obj_name, ObjectType::Table); aux_obj1=model->getObject(object->getSignature(), obj_type); new_obj=(!aux_obj && !aux_obj1); @@ -720,22 +757,25 @@ void BaseObjectWidget::applyConfiguration(void) //Raises an error if another object is found with the same name as the editing object if(!new_obj && aux_obj && aux_obj!=object) { - throw Exception(QString(Exception::getErrorMessage(ERR_ASG_DUPLIC_OBJECT)) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgDuplicatedObject) .arg(obj_name) .arg(BaseObject::getTypeName(obj_type)) .arg(parent_obj->getName(true)) .arg(parent_obj->getTypeName()), - ERR_ASG_DUPLIC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgDuplicatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } //Renames the object (only cast object aren't renamed) - if(obj_type!=OBJ_CAST) + if(obj_type!=ObjectType::Cast) { prev_name=object->getName(); object->setName(name_edt->text().trimmed().toUtf8()); } + if(alias_edt->isVisible()) + object->setAlias(alias_edt->text().trimmed()); + //Sets the object's comment if(comment_edt->isVisible()) object->setComment(comment_edt->toPlainText().toUtf8()); @@ -761,12 +801,12 @@ void BaseObjectWidget::applyConfiguration(void) } if(!object->isProtected() && !object->isSystemObject()) - PgModelerUiNS::disableObjectSQL(object, disable_sql_chk->isChecked()); + PgModelerUiNs::disableObjectSQL(object, disable_sql_chk->isChecked()); } catch(Exception &e) { QApplication::restoreOverrideCursor(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } } @@ -788,10 +828,10 @@ void BaseObjectWidget::finishConfiguration(void) if(table && TableObject::isTableObject(obj_type)) table->addObject(this->object); //Adding the object on the relationship, if specified - else if(relationship && (obj_type==OBJ_COLUMN || obj_type==OBJ_CONSTRAINT)) + else if(relationship && (obj_type==ObjectType::Column || obj_type==ObjectType::Constraint)) relationship->addObject(dynamic_cast(this->object)); //Adding the object on the model - else if(obj_type!=OBJ_PARAMETER) + else if(obj_type!=ObjectType::Parameter) model->addObject(this->object); registerNewObject(); @@ -800,10 +840,10 @@ void BaseObjectWidget::finishConfiguration(void) else { //If the object is being updated, validates its SQL definition - if(obj_type==BASE_RELATIONSHIP || obj_type==OBJ_TEXTBOX || obj_type==OBJ_TAG) - this->object->getCodeDefinition(SchemaParser::XML_DEFINITION); + if(obj_type==ObjectType::BaseRelationship || obj_type==ObjectType::Textbox || obj_type==ObjectType::Tag) + this->object->getCodeDefinition(SchemaParser::XmlDefinition); else - this->object->getCodeDefinition(SchemaParser::SQL_DEFINITION); + this->object->getCodeDefinition(SchemaParser::SqlDefinition); } model->getObjectReferences(object, ref_objs); @@ -811,7 +851,7 @@ void BaseObjectWidget::finishConfiguration(void) { obj->setCodeInvalidated(true); - if(obj->getObjectType()==OBJ_COLUMN) + if(obj->getObjectType()==ObjectType::Column) dynamic_cast(obj)->getParentTable()->setModified(true); } @@ -820,7 +860,7 @@ void BaseObjectWidget::finishConfiguration(void) //If the object is graphical (or a table object), updates it (or its parent) on the scene if(graph_obj || tab_obj) { - if(!graph_obj && tab_obj && tab_obj->getObjectType()!=OBJ_PARAMETER) + if(!graph_obj && tab_obj && tab_obj->getObjectType()!=ObjectType::Parameter) { if(this->table) graph_obj=dynamic_cast(this->table); @@ -860,12 +900,12 @@ void BaseObjectWidget::finishConfiguration(void) { QApplication::restoreOverrideCursor(); - if(e.getErrorType()==ERR_ASG_OBJ_INV_DEFINITION) - throw Exception(Exception::getErrorMessage(ERR_REQ_FIELDS_NOT_FILLED) + if(e.getErrorCode()==ErrorCode::AsgObjectInvalidDefinition) + throw Exception(Exception::getErrorMessage(ErrorCode::RequiredFieldsNotFilled) .arg(this->object->getName()).arg(this->object->getTypeName()), - ERR_REQ_FIELDS_NOT_FILLED,__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + ErrorCode::RequiredFieldsNotFilled,__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -889,11 +929,11 @@ void BaseObjectWidget::cancelConfiguration(void) else if(relationship && relationship->getObjectIndex(tab_obj) >= 0) relationship->removeObject(tab_obj); - if(obj_type!=OBJ_TABLE && - obj_type!=OBJ_VIEW && - obj_type!=OBJ_RELATIONSHIP) + if(obj_type!=ObjectType::Table && + obj_type!=ObjectType::View && + obj_type!=ObjectType::Relationship) { - if(!op_list->isObjectRegistered(this->object, Operation::OBJECT_CREATED)) + if(!op_list->isObjectRegistered(this->object, Operation::ObjectCreated)) delete(this->object); this->object=nullptr; @@ -902,8 +942,8 @@ void BaseObjectWidget::cancelConfiguration(void) //If the object is not a new one, restore its previous state if(op_list && - ((!new_object && obj_type!=OBJ_DATABASE && obj_type!=OBJ_PERMISSION) || - (new_object && (obj_type==OBJ_TABLE || obj_type==OBJ_VIEW || obj_type==OBJ_RELATIONSHIP)))) + ((!new_object && obj_type!=ObjectType::Database && obj_type!=ObjectType::Permission && operation_count != op_list->getCurrentSize()) || + (new_object && (obj_type==ObjectType::Table || obj_type==ObjectType::View || obj_type==ObjectType::Relationship)))) { try { @@ -921,19 +961,19 @@ void BaseObjectWidget::registerNewObject(void) { try { - if(this->new_object && op_list && !op_list->isObjectRegistered(this->object, Operation::OBJECT_CREATED)) + if(this->new_object && op_list && !op_list->isObjectRegistered(this->object, Operation::ObjectCreated)) { //If the object is a new one is necessary register it on the operation list if(this->table) - op_list->registerObject(this->object, Operation::OBJECT_CREATED, -1, this->table); + op_list->registerObject(this->object, Operation::ObjectCreated, -1, this->table); else if(this->relationship) - op_list->registerObject(this->object, Operation::OBJECT_CREATED, -1, this->relationship); + op_list->registerObject(this->object, Operation::ObjectCreated, -1, this->relationship); else - op_list->registerObject(this->object, Operation::OBJECT_CREATED); + op_list->registerObject(this->object, Operation::ObjectCreated); } } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } diff --git a/libpgmodeler_ui/src/baseobjectwidget.h b/libpgmodeler_ui/src/baseobjectwidget.h index 4f31363919..5c8ec5247a 100644 --- a/libpgmodeler_ui/src/baseobjectwidget.h +++ b/libpgmodeler_ui/src/baseobjectwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -33,27 +33,31 @@ #include "ui_baseobjectwidget.h" #include "pgsqltypewidget.h" #include "pgmodeleruins.h" +#include "hinttextwidget.h" /* Declaring the PgSQLType class as a Qt metatype in order to permit that instances of the class be used as data of QVariant and QMetaType */ #include -Q_DECLARE_METATYPE(PgSQLType) +Q_DECLARE_METATYPE(PgSqlType) class BaseObjectWidget: public QWidget, public Ui::BaseObjectWidget { private: Q_OBJECT protected: - static const int MAX_OBJECT_SIZE=16777215; - static const QColor PROT_LINE_BGCOLOR, - PROT_LINE_FGCOLOR, - RELINC_LINE_BGCOLOR, - RELINC_LINE_FGCOLOR; + static constexpr int MaxObjectSize=16777215; + + static const QColor ProtRowBgColor, + ProtRowFgColor, + RelAddedRowBgColor, + RelAddedRowFgColor; bool object_protected; QHBoxLayout *misc_btns_lt; + HintTextWidget *alias_ht; + //! \brief Store the kind of object being handled by the widget (configured in the constructor) ObjectType handled_obj_type; @@ -102,7 +106,7 @@ class BaseObjectWidget: public QWidget, public Ui::BaseObjectWidget { /*! \brief Merges the specified grid layout with the 'baseobject_grid' creating a single form. The obj_type parameter must be specified to show the object type icon */ - void configureFormLayout(QGridLayout *grid=nullptr, ObjectType obj_type=BASE_OBJECT); + void configureFormLayout(QGridLayout *grid=nullptr, ObjectType obj_type=ObjectType::BaseObject); /*! \brief Starts a object configuration, alocating a new one if necessary, registering the object on the operation list. This method doens't applies to database model edition */ @@ -120,25 +124,27 @@ class BaseObjectWidget: public QWidget, public Ui::BaseObjectWidget { void setAttributes(DatabaseModel *model, OperationList *op_list, BaseObject *object, BaseObject *parent_obj=nullptr, - double obj_px=NAN, double obj_py=NAN, bool uses_op_list=true); + double obj_px=DNaN, double obj_py=DNaN, bool uses_op_list=true); /*! \brief This method is a simplification of the original setAttributes. This method must be used only on forms that does not make use of operaton list and not treat graphical objects, since it calls - this original one whit the op_list=nullptr and obj_px=NAN, obj_py=NAN */ + this original one whit the op_list=nullptr and obj_px=DoubleNaN, obj_py=DoubleNaN */ void setAttributes(DatabaseModel *model, BaseObject *object, BaseObject *parent_obj); //! \brief Disable the object's refereces SQL code void disableReferencesSQL(BaseObject *object); void configureTabOrder(vector widgets={}); + + BaseObject *getHandledObject(void); public: //! \brief Constants used to generate version intervals for version alert frame - static const unsigned UNTIL_VERSION=0, - VERSIONS_INTERVAL=1, - AFTER_VERSION=2; + static constexpr unsigned UntilVersion=0, + VersionsInterval=1, + AfterVersion=2; - BaseObjectWidget(QWidget * parent = 0, ObjectType obj_type=BASE_OBJECT); + BaseObjectWidget(QWidget * parent = nullptr, ObjectType obj_type=ObjectType::BaseObject); virtual ~BaseObjectWidget(void); @@ -189,6 +195,7 @@ class BaseObjectWidget: public QWidget, public Ui::BaseObjectWidget { void s_closeRequested(void); friend class BaseForm; + friend class ModelWidget; }; template @@ -200,12 +207,12 @@ void BaseObjectWidget::startConfiguration(void) //! \brief If the object is already allocated if(this->object && op_list && - this->object->getObjectType()!=OBJ_DATABASE) + this->object->getObjectType()!=ObjectType::Database) { if(this->table) - op_list->registerObject(this->object, Operation::OBJECT_MODIFIED, -1, this->table); + op_list->registerObject(this->object, Operation::ObjectModified, -1, this->table); else - op_list->registerObject(this->object, Operation::OBJECT_MODIFIED, -1, this->relationship); + op_list->registerObject(this->object, Operation::ObjectModified, -1, this->relationship); new_object=false; } //! \brief If there is need to allocate the object @@ -218,7 +225,7 @@ void BaseObjectWidget::startConfiguration(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/bugreportform.cpp b/libpgmodeler_ui/src/bugreportform.cpp index 2e9262cf49..f7d775a104 100644 --- a/libpgmodeler_ui/src/bugreportform.cpp +++ b/libpgmodeler_ui/src/bugreportform.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -22,8 +22,6 @@ #include "messagebox.h" #include "pgmodeleruins.h" -const char BugReportForm::CHR_DELIMITER=static_cast(3); - BugReportForm::BugReportForm(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f) { setupUi(this); @@ -32,7 +30,7 @@ BugReportForm::BugReportForm(QWidget *parent, Qt::WindowFlags f) : QDialog(paren Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint); - PgModelerUiNS::configureWidgetFont(hint_lbl, PgModelerUiNS::MEDIUM_FONT_FACTOR); + PgModelerUiNs::configureWidgetFont(hint_lbl, PgModelerUiNs::MediumFontFactor); connect(cancel_btn, SIGNAL(clicked(void)), this, SLOT(close(void))); connect(create_btn, SIGNAL(clicked(void)), this, SLOT(generateReport(void))); @@ -42,13 +40,13 @@ BugReportForm::BugReportForm(QWidget *parent, Qt::WindowFlags f) : QDialog(paren connect(actions_txt, SIGNAL(textChanged()), this, SLOT(enableGeneration())); connect(output_edt, SIGNAL(textChanged(QString)), this, SLOT(enableGeneration())); - output_edt->setText(QFileInfo(GlobalAttributes::TEMPORARY_DIR).absoluteFilePath()); + output_edt->setText(QFileInfo(GlobalAttributes::TemporaryDir).absoluteFilePath()); //Installs a syntax highlighter on model_txt widget hl_model_txt=new SyntaxHighlighter(model_txt); - hl_model_txt->loadConfiguration(GlobalAttributes::XML_HIGHLIGHT_CONF_PATH); + hl_model_txt->loadConfiguration(GlobalAttributes::XMLHighlightConfPath); - QDir tmp_dir=QDir(GlobalAttributes::TEMPORARY_DIR, QString("*.dbm"), QDir::Name, QDir::Files | QDir::NoDotAndDotDot); + QDir tmp_dir=QDir(GlobalAttributes::TemporaryDir, QString("*.dbm"), QDir::Name, QDir::Files | QDir::NoDotAndDotDot); tmp_dir.setSorting(QDir::Time); QStringList list=tmp_dir.entryList(); @@ -57,8 +55,8 @@ BugReportForm::BugReportForm(QWidget *parent, Qt::WindowFlags f) : QDialog(paren QFile input; //Opens the last modified model file showing it on the proper widget - input.setFileName(GlobalAttributes::TEMPORARY_DIR + - GlobalAttributes::DIR_SEPARATOR + list[0]); + input.setFileName(GlobalAttributes::TemporaryDir + + GlobalAttributes::DirSeparator + list[0]); input.open(QFile::ReadOnly); model_txt->setPlainText(QString(input.readAll())); @@ -71,11 +69,11 @@ QByteArray BugReportForm::generateReportBuffer(void) QByteArray buf; buf.append(actions_txt->toPlainText().toUtf8()); - buf.append(CHR_DELIMITER); + buf.append(CharDelimiter); if(attach_mod_chk->isChecked()) buf.append(model_txt->toPlainText().toUtf8()); - buf.append(CHR_DELIMITER); + buf.append(CharDelimiter); return(buf); } @@ -96,8 +94,8 @@ void BugReportForm::generateReport(const QByteArray &buf) Messagebox msgbox; QFile output; QString filename=QFileInfo(QString(output_edt->text() + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::BUG_REPORT_FILE) + GlobalAttributes::DirSeparator + + GlobalAttributes::BugReportFile) .arg(QDateTime::currentDateTime().toString(QString("_yyyyMMdd_hhmm")))).absoluteFilePath(); //Opens the file for writting @@ -105,7 +103,7 @@ void BugReportForm::generateReport(const QByteArray &buf) output.open(QFile::WriteOnly); if(!output.isOpen()) - msgbox.show(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(filename), Messagebox::ERROR_ICON); + msgbox.show(Exception::getErrorMessage(ErrorCode::FileDirectoryNotWritten).arg(filename), Messagebox::ErrorIcon); else { QByteArray comp_buf; @@ -117,8 +115,9 @@ void BugReportForm::generateReport(const QByteArray &buf) output.write(comp_buf.data(), comp_buf.size()); output.close(); - msgbox.show(trUtf8("Bug report successfuly generated! Please, send the file %1 to %2 in order be analyzed. Thank you for the collaboration!").arg(filename).arg(GlobalAttributes::BUG_REPORT_EMAIL), - Messagebox::INFO_ICON); + msgbox.show(trUtf8("Bug report successfuly generated! Please, send the file %1 to %2 in order be analyzed. Thank you for the collaboration!") + .arg(QDir::toNativeSeparators(filename)).arg(GlobalAttributes::BugReportEmail), + Messagebox::InfoIcon); } } @@ -142,8 +141,8 @@ void BugReportForm::attachModel(void) input.open(QFile::ReadOnly); if(!input.isOpen()) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED).arg(file_dlg.selectedFiles().at(0)), - ERR_FILE_DIR_NOT_ACCESSED,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed).arg(file_dlg.selectedFiles().at(0)), + ErrorCode::FileDirectoryNotAccessed,__PRETTY_FUNCTION__,__FILE__,__LINE__); buf=input.readAll(); model_txt->setPlainText(QString(buf)); diff --git a/libpgmodeler_ui/src/bugreportform.h b/libpgmodeler_ui/src/bugreportform.h index 58ce26c9cc..01a3fe1798 100644 --- a/libpgmodeler_ui/src/bugreportform.h +++ b/libpgmodeler_ui/src/bugreportform.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -38,7 +38,7 @@ class BugReportForm : public QDialog, public Ui::BugReportForm { protected: //! \brief Delimiter character which separates the sections of the compressed file - const static char CHR_DELIMITER; + static constexpr char CharDelimiter = static_cast(3); //! \brief Generates an uncompressed buffer based upon the data in fields virtual QByteArray generateReportBuffer(void); @@ -47,7 +47,7 @@ class BugReportForm : public QDialog, public Ui::BugReportForm { void generateReport(const QByteArray &buf); public: - BugReportForm(QWidget * parent = 0, Qt::WindowFlags f = 0); + BugReportForm(QWidget * parent = nullptr, Qt::WindowFlags f = Qt::Widget); public slots: void generateReport(void); diff --git a/libpgmodeler_ui/src/bulkdataeditwidget.cpp b/libpgmodeler_ui/src/bulkdataeditwidget.cpp index a94af2ac89..f868755fa6 100644 --- a/libpgmodeler_ui/src/bulkdataeditwidget.cpp +++ b/libpgmodeler_ui/src/bulkdataeditwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libpgmodeler_ui/src/bulkdataeditwidget.h b/libpgmodeler_ui/src/bulkdataeditwidget.h index bad6b36ff4..33f894d627 100644 --- a/libpgmodeler_ui/src/bulkdataeditwidget.h +++ b/libpgmodeler_ui/src/bulkdataeditwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -29,7 +29,7 @@ class BulkDataEditWidget: public QWidget, public Ui::BulkDataEditWidget { void showEvent(QShowEvent *); public: - BulkDataEditWidget(QWidget *parent = 0); + BulkDataEditWidget(QWidget *parent = nullptr); }; #endif diff --git a/libpgmodeler_ui/src/castwidget.cpp b/libpgmodeler_ui/src/castwidget.cpp index 4e383e5f18..91fcbc5fa4 100644 --- a/libpgmodeler_ui/src/castwidget.cpp +++ b/libpgmodeler_ui/src/castwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,11 +18,10 @@ #include "castwidget.h" -CastWidget::CastWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_CAST) +CastWidget::CastWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Cast) { try { - QFont font; QFrame *frame=nullptr; QSpacerItem *spacer=new QSpacerItem(10,1,QSizePolicy::Fixed,QSizePolicy::Expanding); @@ -30,18 +29,13 @@ CastWidget::CastWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_CAST) src_datatype=new PgSQLTypeWidget(this, trUtf8("Source data type")); trg_datatype=new PgSQLTypeWidget(this, trUtf8("Target data type")); - conv_func_sel=new ObjectSelectorWidget(OBJ_FUNCTION, true, this); + conv_func_sel=new ObjectSelectorWidget(ObjectType::Function, true, this); cast_grid->addWidget(conv_func_sel,1,1,1,4); cast_grid->addWidget(src_datatype,2,0,1,5); cast_grid->addWidget(trg_datatype,3,0,1,5); - configureFormLayout(cast_grid, OBJ_CAST); - - name_edt->setReadOnly(true); - font=name_edt->font(); - font.setItalic(true); - name_edt->setFont(font); + configureFormLayout(cast_grid, ObjectType::Cast); frame=generateInformationFrame(trUtf8("The function to be assigned to a cast from typeA to typeB must have the following signature: typeB function(typeA, integer, boolean).")); cast_grid->addItem(spacer, cast_grid->count()+1, 0, 1, 0); @@ -58,27 +52,27 @@ CastWidget::CastWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_CAST) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void CastWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Cast *cast) { - PgSQLType src_type, trg_type; + PgSqlType src_type, trg_type; BaseObjectWidget::setAttributes(model, op_list, cast); conv_func_sel->setModel(model); if(cast) { - src_type=cast->getDataType(Cast::SRC_TYPE); - trg_type=cast->getDataType(Cast::DST_TYPE); + src_type=cast->getDataType(Cast::SrcType); + trg_type=cast->getDataType(Cast::DstType); conv_func_sel->setSelectedObject(cast->getCastFunction()); input_output_chk->setChecked(cast->isInOut()); - explicit_rb->setChecked(cast->getCastType()==Cast::EXPLICIT); - implicit_rb->setChecked(cast->getCastType()==Cast::IMPLICIT); - assignment_rb->setChecked(cast->getCastType()==Cast::ASSIGNMENT); + explicit_rb->setChecked(cast->getCastType()==Cast::Explicit); + implicit_rb->setChecked(cast->getCastType()==Cast::Implicit); + assignment_rb->setChecked(cast->getCastType()==Cast::Assignment); } src_datatype->setAttributes(src_type,model); @@ -94,16 +88,16 @@ void CastWidget::applyConfiguration(void) startConfiguration(); cast=dynamic_cast(this->object); - cast->setDataType(Cast::SRC_TYPE, src_datatype->getPgSQLType()); - cast->setDataType(Cast::DST_TYPE, trg_datatype->getPgSQLType()); + cast->setDataType(Cast::SrcType, src_datatype->getPgSQLType()); + cast->setDataType(Cast::DstType, trg_datatype->getPgSQLType()); cast->setInOut(input_output_chk->isChecked()); if(implicit_rb->isChecked()) - cast->setCastType(Cast::IMPLICIT); + cast->setCastType(Cast::Implicit); else if(assignment_rb->isChecked()) - cast->setCastType(Cast::ASSIGNMENT); + cast->setCastType(Cast::Assignment); else - cast->setCastType(Cast::EXPLICIT); + cast->setCastType(Cast::Explicit); cast->setCastFunction(dynamic_cast(conv_func_sel->getSelectedObject())); @@ -113,7 +107,7 @@ void CastWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/castwidget.h b/libpgmodeler_ui/src/castwidget.h index 157a779e74..3511d18124 100644 --- a/libpgmodeler_ui/src/castwidget.h +++ b/libpgmodeler_ui/src/castwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -40,7 +40,7 @@ class CastWidget: public BaseObjectWidget, public Ui::CastWidget { ObjectSelectorWidget *conv_func_sel; public: - CastWidget(QWidget * parent = 0); + CastWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Cast *cast); public slots: diff --git a/libpgmodeler_ui/src/codecompletionwidget.cpp b/libpgmodeler_ui/src/codecompletionwidget.cpp index 5324a4f59e..b3fca997e6 100644 --- a/libpgmodeler_ui/src/codecompletionwidget.cpp +++ b/libpgmodeler_ui/src/codecompletionwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -24,7 +24,7 @@ CodeCompletionWidget::CodeCompletionWidget(QPlainTextEdit *code_field_txt, bool enable_snippets) : QWidget(dynamic_cast(code_field_txt)) { if(!code_field_txt) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->enable_snippets = enable_snippets; popup_timer.setInterval(300); @@ -35,7 +35,7 @@ CodeCompletionWidget::CodeCompletionWidget(QPlainTextEdit *code_field_txt, bool name_list=new QListWidget(completion_wgt); name_list->setSpacing(2); name_list->setIconSize(QSize(16,16)); - name_list->setSortingEnabled(true); + name_list->setSortingEnabled(false); persistent_chk=new QCheckBox(completion_wgt); persistent_chk->setText(trUtf8("Make &persistent")); @@ -49,9 +49,7 @@ CodeCompletionWidget::CodeCompletionWidget(QPlainTextEdit *code_field_txt, bool vbox->setSpacing(6); completion_wgt->setLayout(vbox); - QFont font=name_list->font(); - font.setPointSizeF(8); - name_list->setFont(font); + PgModelerUiNs::configureWidgetFont(name_list, PgModelerUiNs::MediumFontFactor); this->code_field_txt=code_field_txt; auto_triggered=false; @@ -204,7 +202,7 @@ void CodeCompletionWidget::configureCompletion(DatabaseModel *db_model, SyntaxHi auto_triggered=false; this->db_model=db_model; - if(confs[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_COMPLETION]==ParsersAttributes::_TRUE_) + if(confs[Attributes::Configuration][Attributes::CodeCompletion]==Attributes::True) { code_field_txt->installEventFilter(this); name_list->installEventFilter(this); @@ -228,9 +226,9 @@ void CodeCompletionWidget::configureCompletion(DatabaseModel *db_model, SyntaxHi if(enable_snippets) { clearCustomItems(); - insertCustomItems(SnippetsConfigWidget::getAllSnippetsAttribute(ParsersAttributes::ID), - SnippetsConfigWidget::getAllSnippetsAttribute(ParsersAttributes::LABEL), - QPixmap(PgModelerUiNS::getIconPath("codesnippet"))); + insertCustomItems(SnippetsConfigWidget::getAllSnippetsAttribute(Attributes::Id), + SnippetsConfigWidget::getAllSnippetsAttribute(Attributes::Label), + QPixmap(PgModelerUiNs::getIconPath("codesnippet"))); } } else @@ -258,6 +256,12 @@ void CodeCompletionWidget::insertCustomItems(const QStringList &names, const QSt } } +void CodeCompletionWidget::insertCustomItems(const QStringList &names, const QString &tooltip, ObjectType obj_type) +{ + for(auto &name : names) + insertCustomItem(name, tooltip, QPixmap(PgModelerUiNs::getIconPath(obj_type))); +} + void CodeCompletionWidget::clearCustomItems(void) { custom_items.clear(); @@ -278,12 +282,12 @@ void CodeCompletionWidget::populateNameList(vector &objects, QStri obj_name.clear(); //Formatting the object name according to the object type - if(obj_type==OBJ_FUNCTION) + if(obj_type==ObjectType::Function) { dynamic_cast(objects[i])->createSignature(false); obj_name=dynamic_cast(objects[i])->getSignature(); } - else if(obj_type==OBJ_OPERATOR) + else if(obj_type==ObjectType::Operator) obj_name=dynamic_cast(objects[i])->getSignature(false); else obj_name+=objects[i]->getName(false, false); @@ -291,7 +295,7 @@ void CodeCompletionWidget::populateNameList(vector &objects, QStri //The object will be inserted if its name matches the filter or there is no filter set if(filter.isEmpty() || regexp.exactMatch(obj_name)) { - item=new QListWidgetItem(QPixmap(PgModelerUiNS::getIconPath(objects[i]->getSchemaName())), obj_name); + item=new QListWidgetItem(QPixmap(PgModelerUiNs::getIconPath(objects[i]->getSchemaName())), obj_name); item->setToolTip(QString("%1 (%2)").arg(objects[i]->getName(true)).arg(objects[i]->getTypeName())); item->setData(Qt::UserRole, QVariant::fromValue(objects[i])); item->setToolTip(BaseObject::getTypeName(obj_type)); @@ -315,10 +319,10 @@ void CodeCompletionWidget::setQualifyingLevel(BaseObject *obj) { if(!obj) qualifying_level=-1; - else if(obj->getObjectType()==OBJ_SCHEMA) + else if(obj->getObjectType()==ObjectType::Schema) qualifying_level=0; - else if(obj->getObjectType()==OBJ_TABLE || - obj->getObjectType()==OBJ_VIEW) + else if(obj->getObjectType()==ObjectType::Table || + obj->getObjectType()==ObjectType::View) qualifying_level=1; else qualifying_level=2; @@ -340,7 +344,7 @@ void CodeCompletionWidget::updateList(void) QString pattern; QStringList list; vector objects; - vector types=BaseObject::getObjectTypes(false, { OBJ_TEXTBOX, OBJ_RELATIONSHIP, BASE_RELATIONSHIP }); + vector types=BaseObject::getObjectTypes(false, { ObjectType::Textbox, ObjectType::Relationship, ObjectType::BaseRelationship }); QTextCursor tc; name_list->clear(); @@ -369,7 +373,7 @@ void CodeCompletionWidget::updateList(void) word.remove(completion_trigger); word.remove('"'); - objects=db_model->findObjects(word, { OBJ_SCHEMA, OBJ_TABLE, OBJ_VIEW }, false, false, false, true); + objects=db_model->findObjects(word, { ObjectType::Schema, ObjectType::Table, ObjectType::View }, false, false, true); if(objects.size()==1) setQualifyingLevel(objects[0]); @@ -388,7 +392,7 @@ void CodeCompletionWidget::updateList(void) //Negative qualifying level means that user called the completion before a space (empty word) if(qualifying_level < 0) //The default behavior for this is to search all the objects on the model - objects=db_model->findObjects(pattern, types, false, false, !auto_triggered, auto_triggered); + objects=db_model->findObjects(pattern, types, false, !auto_triggered, auto_triggered); else { QString left_word; @@ -421,7 +425,7 @@ void CodeCompletionWidget::updateList(void) we try to find any object in the model and reset the qualifying level */ else { - objects=db_model->findObjects(pattern, types, false, false, !auto_triggered, auto_triggered); + objects=db_model->findObjects(pattern, types, false, !auto_triggered, auto_triggered); setQualifyingLevel(nullptr); } @@ -443,7 +447,7 @@ void CodeCompletionWidget::updateList(void) list=keywords.filter(regexp); for(int i=0; i < list.size(); i++) { - item=new QListWidgetItem(QPixmap(PgModelerUiNS::getIconPath("keyword")), list[i]); + item=new QListWidgetItem(QPixmap(PgModelerUiNs::getIconPath("keyword")), list[i]); item->setToolTip(trUtf8("SQL Keyword")); name_list->addItem(item); } @@ -583,9 +587,9 @@ void CodeCompletionWidget::insertObjectName(BaseObject *obj) if(modify_name && - (obj_type==OBJ_TABLE || TableObject::isTableObject(obj_type))) + (obj_type==ObjectType::Table || TableObject::isTableObject(obj_type))) { - if(obj_type==OBJ_TABLE) + if(obj_type==ObjectType::Table) { Table *tab=dynamic_cast
(obj); @@ -607,17 +611,17 @@ void CodeCompletionWidget::insertObjectName(BaseObject *obj) code_field_txt->setTextCursor(lvl_cur); } } - else if(obj_type==OBJ_FUNCTION) + else if(obj_type==ObjectType::Function) { Function *func=dynamic_cast(obj); func->createSignature(true, sch_qualified); name=func->getSignature(); } - else if(obj_type==OBJ_CAST) + else if(obj_type==ObjectType::Cast) { name.replace(',', QLatin1String(" AS ")); } - else if(obj_type==OBJ_AGGREGATE) + else if(obj_type==ObjectType::Aggregate) { Aggregate *agg; agg=dynamic_cast(obj); diff --git a/libpgmodeler_ui/src/codecompletionwidget.h b/libpgmodeler_ui/src/codecompletionwidget.h index 347104e912..a38d2e1e05 100644 --- a/libpgmodeler_ui/src/codecompletionwidget.h +++ b/libpgmodeler_ui/src/codecompletionwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -112,11 +112,14 @@ class CodeCompletionWidget: public QWidget highlighter uses an different configuration */ void configureCompletion(DatabaseModel *db_model, SyntaxHighlighter *syntax_hl=nullptr, const QString &keywords_grp=QString("keywords")); - //! \brief Inserts a custom named item on the list with a custom icon. Custom item will be always appear at the beggining of the list + //! \brief Inserts a custom named item on the list with a custom icon. Custom item will always appear at the beggining of the list void insertCustomItem(const QString &name, const QString &tooltip, const QPixmap &icon); - //! \brief Inserts several custom named item on the list with a custom icon. Custom item will be always appear at the beggining of the list + //! \brief Inserts several custom named item on the list with a custom icon. Custom item will always appear at the beggining of the list void insertCustomItems(const QStringList &names, const QStringList &tooltips, const QPixmap &icon); + +//! \brief Inserts several custom named items on the list with an icon related to the obj_type. Custom item will always appear at the beggining of the list + void insertCustomItems(const QStringList &names, const QString &tooltip, ObjectType obj_type); //! \brief Clear the custom added items void clearCustomItems(void); diff --git a/libpgmodeler_ui/src/collationwidget.cpp b/libpgmodeler_ui/src/collationwidget.cpp index ceec9a4bb9..1b1f22227f 100644 --- a/libpgmodeler_ui/src/collationwidget.cpp +++ b/libpgmodeler_ui/src/collationwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "collationwidget.h" -CollationWidget::CollationWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_COLLATION) +CollationWidget::CollationWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Collation) { try { @@ -32,7 +32,7 @@ CollationWidget::CollationWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_ collation_grid->addItem(new QSpacerItem(10,10, QSizePolicy::Minimum,QSizePolicy::Expanding), collation_grid->count()+1, 0, 1, 0); collation_grid->addWidget(frame, collation_grid->count()+1, 0, 1, 0); frame->setParent(this); - configureFormLayout(collation_grid, OBJ_COLLATION); + configureFormLayout(collation_grid, ObjectType::Collation); //Configures the encoding combobox EncodingType::getTypes(encodings); @@ -66,7 +66,7 @@ CollationWidget::CollationWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_ } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -88,10 +88,10 @@ void CollationWidget::setAttributes(DatabaseModel *model, OperationList *op_list if(locale_cmb->currentIndex()==0) { - idx=lcctype_cmb->findText(collation->getLocalization(Collation::_LC_CTYPE)); + idx=lcctype_cmb->findText(collation->getLocalization(Collation::LcCtype)); lcctype_cmb->setCurrentIndex(idx < 0 ? 0 : idx); - idx=lccollate_cmb->findText(collation->getLocalization(Collation::_LC_COLLATE)); + idx=lccollate_cmb->findText(collation->getLocalization(Collation::LcCollate)); lccollate_cmb->setCurrentIndex(idx < 0 ? 0 : idx); } } @@ -160,16 +160,16 @@ void CollationWidget::applyConfiguration(void) collation->setLocale(locale_cmb->currentText()); if(lccollate_cmb->currentIndex() > 0) - collation->setLocalization(Collation::_LC_COLLATE, lccollate_cmb->currentText()); + collation->setLocalization(Collation::LcCollate, lccollate_cmb->currentText()); if(lcctype_cmb->currentIndex() > 0) - collation->setLocalization(Collation::_LC_CTYPE, lcctype_cmb->currentText()); + collation->setLocalization(Collation::LcCtype, lcctype_cmb->currentText()); finishConfiguration(); } catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/collationwidget.h b/libpgmodeler_ui/src/collationwidget.h index 8a287e5f50..442e2d0842 100644 --- a/libpgmodeler_ui/src/collationwidget.h +++ b/libpgmodeler_ui/src/collationwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -33,7 +33,7 @@ class CollationWidget: public BaseObjectWidget, public Ui::CollationWidget { Q_OBJECT public: - CollationWidget(QWidget * parent = 0); + CollationWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, Collation *collation); public slots: diff --git a/libpgmodeler_ui/src/colorpickerwidget.cpp b/libpgmodeler_ui/src/colorpickerwidget.cpp index 857c59d715..84a6fcd3af 100644 --- a/libpgmodeler_ui/src/colorpickerwidget.cpp +++ b/libpgmodeler_ui/src/colorpickerwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -32,8 +32,8 @@ ColorPickerWidget::ColorPickerWidget(int color_count, QWidget * parent) : QWidge if(color_count==0) color_count=1; - else if(color_count > MAX_COLOR_BUTTONS) - color_count=MAX_COLOR_BUTTONS; + else if(color_count > MaxColorButtons) + color_count=MaxColorButtons; hbox=new QHBoxLayout(this); hbox->setContentsMargins(0,0,0,0); @@ -80,7 +80,7 @@ void ColorPickerWidget::setColor(int color_idx, const QColor &color) QString cl_name; if(color_idx < 0 || color_idx >= colors.size()) - throw Exception(ERR_REF_ELEM_INV_INDEX ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefElementInvalidIndex ,__PRETTY_FUNCTION__,__FILE__,__LINE__); if(this->isEnabled()) cl_name=color.name(); @@ -94,7 +94,7 @@ void ColorPickerWidget::setColor(int color_idx, const QColor &color) QColor ColorPickerWidget::getColor(int color_idx) { if(color_idx < 0 || color_idx >= colors.size()) - throw Exception(ERR_REF_ELEM_INV_INDEX ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefElementInvalidIndex ,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(colors[color_idx]); } @@ -107,7 +107,7 @@ unsigned ColorPickerWidget::getColorCount(void) bool ColorPickerWidget::isButtonVisible(unsigned idx) { if(idx >= static_cast(buttons.size())) - throw Exception(ERR_REF_ELEM_INV_INDEX ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefElementInvalidIndex ,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(buttons[idx]->isVisible()); } @@ -115,7 +115,7 @@ bool ColorPickerWidget::isButtonVisible(unsigned idx) void ColorPickerWidget::setButtonToolTip(unsigned button_idx, const QString &tooltip) { if(button_idx >= static_cast(buttons.size())) - throw Exception(ERR_REF_ELEM_INV_INDEX ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefElementInvalidIndex ,__PRETTY_FUNCTION__,__FILE__,__LINE__); buttons[button_idx]->setToolTip(tooltip); } @@ -134,7 +134,7 @@ void ColorPickerWidget::setEnabled(bool value) void ColorPickerWidget::setButtonVisible(unsigned idx, bool value) { if(idx >= static_cast(buttons.size())) - throw Exception(ERR_REF_ELEM_INV_INDEX ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefElementInvalidIndex ,__PRETTY_FUNCTION__,__FILE__,__LINE__); buttons[idx]->setVisible(value); } diff --git a/libpgmodeler_ui/src/colorpickerwidget.h b/libpgmodeler_ui/src/colorpickerwidget.h index 95e30b3611..25be79bac8 100644 --- a/libpgmodeler_ui/src/colorpickerwidget.h +++ b/libpgmodeler_ui/src/colorpickerwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -53,9 +53,9 @@ class ColorPickerWidget: public QWidget, public Ui::ColorPickerWidget { bool eventFilter(QObject *object, QEvent *event); public: - static const int MAX_COLOR_BUTTONS=20; + static constexpr int MaxColorButtons=20; - explicit ColorPickerWidget(int color_count, QWidget * parent = 0); + explicit ColorPickerWidget(int color_count, QWidget * parent = nullptr); void setColor(int color_idx, const QColor &color); QColor getColor(int color_idx); diff --git a/libpgmodeler_ui/src/columnwidget.cpp b/libpgmodeler_ui/src/columnwidget.cpp index 6eb8f8467e..af0ffe3412 100644 --- a/libpgmodeler_ui/src/columnwidget.cpp +++ b/libpgmodeler_ui/src/columnwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -17,8 +17,11 @@ */ #include "columnwidget.h" +#include "sequencewidget.h" +#include "baseform.h" +#include "generalconfigwidget.h" -ColumnWidget::ColumnWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_COLUMN) +ColumnWidget::ColumnWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Column) { try { @@ -26,6 +29,7 @@ ColumnWidget::ColumnWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_COLUMN QStringList list; Ui_ColumnWidget::setupUi(this); + edit_seq_btn->setVisible(false); IdentityType::getTypes(list); identity_type_cmb->addItems(list); @@ -35,22 +39,22 @@ ColumnWidget::ColumnWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_COLUMN hl_default_value=nullptr; hl_default_value=new SyntaxHighlighter(def_value_txt, true); - hl_default_value->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + hl_default_value->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); - sequence_sel=new ObjectSelectorWidget(OBJ_SEQUENCE, true, this); + sequence_sel=new ObjectSelectorWidget(ObjectType::Sequence, true, this); sequence_sel->setEnabled(false); column_grid->addWidget(data_type,0,0,1,0); column_grid->addWidget(default_value_grp,1,0,1,1); column_grid->addItem(spacer,column_grid->count(),0); - dynamic_cast(default_value_grp->layout())->addWidget(sequence_sel, 1, 1, 1, 2); + dynamic_cast(default_value_grp->layout())->addWidget(sequence_sel, 1, 1, 1, 6); - configureFormLayout(column_grid, OBJ_COLUMN); + configureFormLayout(column_grid, ObjectType::Column); configureTabOrder({ data_type }); map > fields_map; - fields_map[generateVersionsInterval(AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_100)].push_back(identity_rb); + fields_map[generateVersionsInterval(AfterVersion, PgSqlVersions::PgSqlVersion100)].push_back(identity_rb); highlightVersionSpecificFields(fields_map); connect(sequence_rb, &QRadioButton::clicked, @@ -59,6 +63,7 @@ ColumnWidget::ColumnWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_COLUMN def_value_txt->setEnabled(false); identity_type_cmb->setEnabled(false); notnull_chk->setEnabled(true); + edit_seq_btn->setVisible(false); }); connect(expression_rb, &QRadioButton::clicked, @@ -67,6 +72,7 @@ ColumnWidget::ColumnWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_COLUMN def_value_txt->setEnabled(true); identity_type_cmb->setEnabled(false); notnull_chk->setEnabled(true); + edit_seq_btn->setVisible(false); }); connect(identity_rb, &QRadioButton::clicked, @@ -76,26 +82,32 @@ ColumnWidget::ColumnWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_COLUMN identity_type_cmb->setEnabled(true); notnull_chk->setChecked(true); notnull_chk->setEnabled(false); + edit_seq_btn->setVisible(true); }); + connect(edit_seq_btn, SIGNAL(clicked(bool)), this, SLOT(editSequenceAttributes())); + setMinimumSize(540, 480); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void ColumnWidget::setAttributes(DatabaseModel *model, OperationList *op_list, BaseObject *parent_obj, Column *column) { - PgSQLType type; + PgSqlType type; if(!parent_obj) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); BaseObjectWidget::setAttributes(model, op_list, column, parent_obj); sequence_sel->setModel(model); + ident_col_seq.setValues(QString(), QString(), QString(), QString(), QString()); + ident_col_seq.setCycle(false); + if(column) { type=column->getType(); @@ -104,13 +116,13 @@ void ColumnWidget::setAttributes(DatabaseModel *model, OperationList *op_list, B if(column->getSequence()) { - sequence_rb->setChecked(true); + sequence_rb->click(); sequence_sel->setEnabled(true); sequence_sel->setSelectedObject(column->getSequence()); } - else if(column->getIdentityType() != BaseType::null) + else if(column->getIdentityType() != BaseType::Null) { - identity_rb->setChecked(true); + identity_rb->click(); identity_type_cmb->setEnabled(true); identity_type_cmb->setCurrentText(~column->getIdentityType()); notnull_chk->setEnabled(false); @@ -118,8 +130,39 @@ void ColumnWidget::setAttributes(DatabaseModel *model, OperationList *op_list, B } data_type->setAttributes(type, model, - UserTypeConfig::BASE_TYPE | UserTypeConfig::TABLE_TYPE | UserTypeConfig::VIEW_TYPE | - UserTypeConfig::DOMAIN_TYPE | UserTypeConfig::EXTENSION_TYPE, true,false); + UserTypeConfig::BaseType | UserTypeConfig::TableType | UserTypeConfig::ViewType | + UserTypeConfig::DomainType | UserTypeConfig::ExtensionType, true,false); +} + +void ColumnWidget::editSequenceAttributes(void) +{ + Column *col = dynamic_cast(this->object); + Schema *schema = nullptr; + BaseForm editing_form(this); + SequenceWidget *seq_wgt=new SequenceWidget; + BaseTable *table = col ? col->getParentTable() : nullptr; + + if(table) + schema = dynamic_cast(table->getSchema()); + else + schema = this->model->getSchema("public"); + + ident_col_seq.setName(QString("%1_%2_seq").arg(table ? table->getName() : QString()).arg(col ? col->getName() : QString("new_column"))); + ident_col_seq.setName(PgModelerNs::generateUniqueName(&ident_col_seq, *model->getObjectList(ObjectType::Sequence), false)); + ident_col_seq.setSchema(schema); + + if(col) + { + ident_col_seq.setDefaultValues(col->getType()); + ident_col_seq.setValues(col->getIdSeqMinValue(), col->getIdSeqMaxValue(), col->getIdSeqIncrement(), col->getIdSeqStart(), col->getIdSeqCache()); + ident_col_seq.setCycle(col->isIdSeqCycle()); + } + + seq_wgt->setAttributesReadonly(this->model, nullptr, nullptr, &ident_col_seq, col); + editing_form.setMainWidget(seq_wgt); + GeneralConfigWidget::restoreWidgetGeometry(&editing_form, seq_wgt->metaObject()->className()); + editing_form.exec(); + GeneralConfigWidget::saveWidgetGeometry(&editing_form, seq_wgt->metaObject()->className()); } void ColumnWidget::applyConfiguration(void) @@ -141,23 +184,28 @@ void ColumnWidget::applyConfiguration(void) else column->setIdentityType(IdentityType(identity_type_cmb->currentText())); + column->setIdSeqAttributes(ident_col_seq.getMinValue(), ident_col_seq.getMaxValue(), ident_col_seq.getIncrement(), + ident_col_seq.getStart(), ident_col_seq.getCache(), ident_col_seq.isCycle()); + if(table) { pk = dynamic_cast
(table)->getPrimaryKey(); if(pk && pk->isColumnReferenced(column) && !notnull_chk->isChecked()) - throw Exception(Exception::getErrorMessage(ERR_NULL_PK_COLUMN) + throw Exception(Exception::getErrorMessage(ErrorCode::NullPrimaryKeyColumn) .arg(column->getName()) .arg(pk->getParentTable()->getSignature(true)), - ERR_NULL_PK_COLUMN,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::NullPrimaryKeyColumn,__PRETTY_FUNCTION__,__FILE__,__LINE__); } BaseObjectWidget::applyConfiguration(); + model->updateViewsReferencingTable(dynamic_cast
(table)); + finishConfiguration(); } catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/columnwidget.h b/libpgmodeler_ui/src/columnwidget.h index 42bf2dfa5c..84c9515e3a 100644 --- a/libpgmodeler_ui/src/columnwidget.h +++ b/libpgmodeler_ui/src/columnwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -36,12 +36,14 @@ class ColumnWidget: public BaseObjectWidget, public Ui::ColumnWidget { SyntaxHighlighter *hl_default_value; PgSQLTypeWidget *data_type; ObjectSelectorWidget *sequence_sel; + Sequence ident_col_seq; public: - ColumnWidget(QWidget * parent = 0); + ColumnWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, BaseObject *parent_obj, Column *column); private slots: + void editSequenceAttributes(void); public slots: void applyConfiguration(void); diff --git a/libpgmodeler_ui/src/configurationform.cpp b/libpgmodeler_ui/src/configurationform.cpp index b832b17f4d..e7a9f9d9b1 100644 --- a/libpgmodeler_ui/src/configurationform.cpp +++ b/libpgmodeler_ui/src/configurationform.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -30,10 +30,10 @@ ConfigurationForm::ConfigurationForm(QWidget *parent, Qt::WindowFlags f) : QDial plugins_conf=new PluginsConfigWidget(this); QWidgetList wgt_list={ general_conf, relationships_conf, - appearance_conf, connections_conf, - snippets_conf, plugins_conf}; + appearance_conf, connections_conf, + snippets_conf, plugins_conf}; - for(int i=GENERAL_CONF_WGT; i <= PLUGINS_CONF_WGT; i++) + for(int i=GeneralConfWgt; i <= PluginsConfWgt; i++) confs_stw->addWidget(wgt_list[i]); connect(icons_lst, SIGNAL(currentRowChanged(int)), confs_stw, SLOT(setCurrentIndex(int))); @@ -41,7 +41,8 @@ ConfigurationForm::ConfigurationForm(QWidget *parent, Qt::WindowFlags f) : QDial connect(apply_btn, SIGNAL(clicked(void)), this, SLOT(applyConfiguration(void))); connect(defaults_btn, SIGNAL(clicked(void)), this, SLOT(restoreDefaults(void))); - icons_lst->setCurrentRow(GENERAL_CONF_WGT); + icons_lst->setCurrentRow(GeneralConfWgt); + setMinimumSize(890, 740); } ConfigurationForm::~ConfigurationForm(void) @@ -51,7 +52,7 @@ ConfigurationForm::~ConfigurationForm(void) void ConfigurationForm::hideEvent(QHideEvent *) { - icons_lst->setCurrentRow(GENERAL_CONF_WGT); + icons_lst->setCurrentRow(GeneralConfWgt); } void ConfigurationForm::showEvent(QShowEvent *) @@ -87,7 +88,7 @@ void ConfigurationForm::applyConfiguration(void) { BaseConfigWidget *conf_wgt=nullptr; - for(int i=GENERAL_CONF_WGT; i <= SNIPPETS_CONF_WGT; i++) + for(int i=GeneralConfWgt; i <= SnippetsConfWgt; i++) { conf_wgt=qobject_cast(confs_stw->widget(i)); @@ -97,7 +98,6 @@ void ConfigurationForm::applyConfiguration(void) general_conf->applyConfiguration(); relationships_conf->applyConfiguration(); - QDialog::accept(); } @@ -105,7 +105,7 @@ void ConfigurationForm::loadConfiguration(void) { BaseConfigWidget *config_wgt = nullptr; - for(int i=GENERAL_CONF_WGT; i <= PLUGINS_CONF_WGT; i++) + for(int i=GeneralConfWgt; i <= PluginsConfWgt; i++) { try { @@ -116,15 +116,15 @@ void ConfigurationForm::loadConfiguration(void) { Messagebox msg_box; - if(e.getErrorType()==ERR_PLUGINS_NOT_LOADED) + if(e.getErrorCode()==ErrorCode::PluginsNotLoaded) { msg_box.show(e); } else { - Exception ex = Exception(Exception::getErrorMessage(ERR_CONFIG_NOT_LOADED).arg(e.getExtraInfo()),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + Exception ex = Exception(Exception::getErrorMessage(ErrorCode::ConfigurationNotLoaded).arg(e.getExtraInfo()),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); msg_box.show(ex, QString("%1 %2").arg(ex.getErrorMessage()).arg(trUtf8("In some cases restore the default settings related to it may solve the problem. Would like to do that?")), - Messagebox::ALERT_ICON, Messagebox::YES_NO_BUTTONS, trUtf8("Restore"), QString(), QString(), PgModelerUiNS::getIconPath("atualizar")); + Messagebox::AlertIcon, Messagebox::YesNoButtons, trUtf8("Restore"), QString(), QString(), PgModelerUiNs::getIconPath("atualizar")); if(msg_box.result() == QDialog::Accepted) config_wgt->restoreDefaults(); @@ -137,8 +137,8 @@ void ConfigurationForm::restoreDefaults(void) { Messagebox msg_box; msg_box.show(trUtf8("Any modification made until now in the current section will be lost! Do you really want to restore default settings?"), - Messagebox::CONFIRM_ICON, - Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon, + Messagebox::YesNoButtons); if(msg_box.result()==QDialog::Accepted) qobject_cast(confs_stw->currentWidget())->restoreDefaults(); diff --git a/libpgmodeler_ui/src/configurationform.h b/libpgmodeler_ui/src/configurationform.h index ab33447504..4d9bef2eb6 100644 --- a/libpgmodeler_ui/src/configurationform.h +++ b/libpgmodeler_ui/src/configurationform.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -48,14 +48,14 @@ class ConfigurationForm: public QDialog, public Ui::ConfigurationForm { void showEvent(QShowEvent *); public: - static const int GENERAL_CONF_WGT=0, - RELATIONSHIPS_CONF_WGT=1, - APPEARANCE_CONF_WGT=2, - CONNECTIONS_CONF_WGT=3, - SNIPPETS_CONF_WGT=4, - PLUGINS_CONF_WGT=5; + static constexpr int GeneralConfWgt=0, + RelationshipsConfWgt=1, + AppearanceConfWgt=2, + ConnectionsConfWgt=3, + SnippetsConfWgt=4, + PluginsConfWgt=5; - ConfigurationForm(QWidget * parent = 0, Qt::WindowFlags f = 0); + ConfigurationForm(QWidget * parent = nullptr, Qt::WindowFlags f = Qt::Widget); ~ConfigurationForm(void); BaseConfigWidget *getConfigurationWidget(unsigned idx); diff --git a/libpgmodeler_ui/src/connectionsconfigwidget.cpp b/libpgmodeler_ui/src/connectionsconfigwidget.cpp index 6af970c210..162a925d5c 100644 --- a/libpgmodeler_ui/src/connectionsconfigwidget.cpp +++ b/libpgmodeler_ui/src/connectionsconfigwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -22,7 +22,7 @@ vector ConnectionsConfigWidget::connections; map ConnectionsConfigWidget::config_params; -const QString ConnectionsConfigWidget::DEFAULT_FOR=QString("default-for-%1"); +const QString ConnectionsConfigWidget::DefaultFor=QString("default-for-%1"); ConnectionsConfigWidget::ConnectionsConfigWidget(QWidget * parent) : BaseConfigWidget(parent) { @@ -81,7 +81,7 @@ void ConnectionsConfigWidget::updateConnectionsCombo(void) connections_cmb->clear(); for(auto &conn : connections) - connections_cmb->addItem(QIcon(QString(":icones/icones/server.png")), conn->getConnectionId()); + connections_cmb->addItem(QIcon(PgModelerUiNs::getIconPath("server")), conn->getConnectionId()); } void ConnectionsConfigWidget::destroyConnections(void) @@ -111,8 +111,8 @@ void ConnectionsConfigWidget::loadConfiguration(void) Connection *conn=nullptr; destroyConnections(); - key_attribs.push_back(ParsersAttributes::ALIAS); - BaseConfigWidget::loadConfiguration(GlobalAttributes::CONNECTIONS_CONF, config_params, key_attribs); + key_attribs.push_back(Attributes::Alias); + BaseConfigWidget::loadConfiguration(GlobalAttributes::ConnectionsConf, config_params, key_attribs); /*try { @@ -134,27 +134,27 @@ void ConnectionsConfigWidget::loadConfiguration(void) { conn=new Connection; - conn->setConnectionParam(Connection::PARAM_ALIAS, itr->second[ParsersAttributes::ALIAS]); - conn->setConnectionParam(Connection::PARAM_SERVER_FQDN, itr->second[Connection::PARAM_SERVER_FQDN]); - conn->setConnectionParam(Connection::PARAM_PORT, itr->second[Connection::PARAM_PORT]); - conn->setConnectionParam(Connection::PARAM_USER, itr->second[Connection::PARAM_USER]); - conn->setConnectionParam(Connection::PARAM_PASSWORD,itr->second[Connection::PARAM_PASSWORD]); - conn->setConnectionParam(Connection::PARAM_DB_NAME, itr->second[Connection::PARAM_DB_NAME]); - conn->setConnectionParam(Connection::PARAM_CONN_TIMEOUT, itr->second[ParsersAttributes::CONNECTION_TIMEOUT]); - conn->setConnectionParam(Connection::PARAM_SSL_MODE, itr->second[Connection::PARAM_SSL_MODE]); - conn->setConnectionParam(Connection::PARAM_SSL_ROOT_CERT, itr->second[Connection::PARAM_SSL_ROOT_CERT]); - conn->setConnectionParam(Connection::PARAM_SSL_CERT, itr->second[Connection::PARAM_SSL_CERT]); - conn->setConnectionParam(Connection::PARAM_SSL_KEY, itr->second[Connection::PARAM_SSL_KEY]); - conn->setConnectionParam(Connection::PARAM_SSL_CRL, itr->second[Connection::PARAM_SSL_CRL]); - conn->setConnectionParam(Connection::PARAM_LIB_GSSAPI, itr->second[Connection::PARAM_LIB_GSSAPI]); - conn->setConnectionParam(Connection::PARAM_KERBEROS_SERVER, itr->second[Connection::PARAM_KERBEROS_SERVER]); - conn->setConnectionParam(Connection::PARAM_OTHERS, itr->second[Connection::PARAM_OTHERS]); - - conn->setAutoBrowseDB(itr->second[ParsersAttributes::AUTO_BROWSE_DB]==ParsersAttributes::_TRUE_); - conn->setDefaultForOperation(Connection::OP_DIFF, itr->second[DEFAULT_FOR.arg(ParsersAttributes::DIFF)]==ParsersAttributes::_TRUE_); - conn->setDefaultForOperation(Connection::OP_EXPORT, itr->second[DEFAULT_FOR.arg(ParsersAttributes::EXPORT)]==ParsersAttributes::_TRUE_); - conn->setDefaultForOperation(Connection::OP_IMPORT, itr->second[DEFAULT_FOR.arg(ParsersAttributes::IMPORT)]==ParsersAttributes::_TRUE_); - conn->setDefaultForOperation(Connection::OP_VALIDATION, itr->second[DEFAULT_FOR.arg(ParsersAttributes::VALIDATION)]==ParsersAttributes::_TRUE_); + conn->setConnectionParam(Connection::ParamAlias, itr->second[Attributes::Alias]); + conn->setConnectionParam(Connection::ParamServerFqdn, itr->second[Connection::ParamServerFqdn]); + conn->setConnectionParam(Connection::ParamPort, itr->second[Connection::ParamPort]); + conn->setConnectionParam(Connection::ParamUser, itr->second[Connection::ParamUser]); + conn->setConnectionParam(Connection::ParamPassword,itr->second[Connection::ParamPassword]); + conn->setConnectionParam(Connection::ParamDbName, itr->second[Connection::ParamDbName]); + conn->setConnectionParam(Connection::ParamConnTimeout, itr->second[Attributes::ConnectionTimeout]); + conn->setConnectionParam(Connection::ParamSslMode, itr->second[Connection::ParamSslMode]); + conn->setConnectionParam(Connection::ParamSslRootCert, itr->second[Connection::ParamSslRootCert]); + conn->setConnectionParam(Connection::ParamSslCert, itr->second[Connection::ParamSslCert]); + conn->setConnectionParam(Connection::ParamSslKey, itr->second[Connection::ParamSslKey]); + conn->setConnectionParam(Connection::ParamSslCrl, itr->second[Connection::ParamSslCrl]); + conn->setConnectionParam(Connection::ParamLibGssapi, itr->second[Connection::ParamLibGssapi]); + conn->setConnectionParam(Connection::ParamKerberosServer, itr->second[Connection::ParamKerberosServer]); + conn->setConnectionParam(Connection::ParamOthers, itr->second[Connection::ParamOthers]); + + conn->setAutoBrowseDB(itr->second[Attributes::AutoBrowseDb]==Attributes::True); + conn->setDefaultForOperation(Connection::OpDiff, itr->second[DefaultFor.arg(Attributes::Diff)]==Attributes::True); + conn->setDefaultForOperation(Connection::OpExport, itr->second[DefaultFor.arg(Attributes::Export)]==Attributes::True); + conn->setDefaultForOperation(Connection::OpImport, itr->second[DefaultFor.arg(Attributes::Import)]==Attributes::True); + conn->setDefaultForOperation(Connection::OpValidation, itr->second[DefaultFor.arg(Attributes::Validation)]==Attributes::True); connections.push_back(conn); itr++; @@ -165,7 +165,7 @@ void ConnectionsConfigWidget::loadConfiguration(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo()); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo()); } } @@ -243,7 +243,7 @@ void ConnectionsConfigWidget::duplicateConnection(void) (*new_conn)=(*conn); connections.push_back(new_conn); - new_conn->setConnectionParam(Connection::PARAM_ALIAS, QString("cp_%1").arg(conn->getConnectionParam(Connection::PARAM_ALIAS))); + new_conn->setConnectionParam(Connection::ParamAlias, QString("cp_%1").arg(conn->getConnectionParam(Connection::ParamAlias))); connections_cmb->addItem(QIcon(QString(":icones/icones/server.png")), new_conn->getConnectionId()); connections_cmb->setCurrentIndex(connections_cmb->count()-1); setConfigurationChanged(true); @@ -253,7 +253,7 @@ void ConnectionsConfigWidget::duplicateConnection(void) if(new_conn) delete(new_conn); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -287,7 +287,7 @@ void ConnectionsConfigWidget::handleConnection(void) if(add_tb->isVisible()) delete(conn); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -312,46 +312,46 @@ void ConnectionsConfigWidget::editConnection(void) Connection *conn=nullptr; conn=connections.at(connections_cmb->currentIndex()); - alias_edt->setText(conn->getConnectionParam(Connection::PARAM_ALIAS)); + alias_edt->setText(conn->getConnectionParam(Connection::ParamAlias)); auto_browse_chk->setChecked(conn->isAutoBrowseDB()); - diff_chk->setChecked(conn->isDefaultForOperation(Connection::OP_DIFF)); - export_chk->setChecked(conn->isDefaultForOperation(Connection::OP_EXPORT)); - import_chk->setChecked(conn->isDefaultForOperation(Connection::OP_IMPORT)); - validation_chk->setChecked(conn->isDefaultForOperation(Connection::OP_VALIDATION)); + diff_chk->setChecked(conn->isDefaultForOperation(Connection::OpDiff)); + export_chk->setChecked(conn->isDefaultForOperation(Connection::OpExport)); + import_chk->setChecked(conn->isDefaultForOperation(Connection::OpImport)); + validation_chk->setChecked(conn->isDefaultForOperation(Connection::OpValidation)); - if(!conn->getConnectionParam(Connection::PARAM_SERVER_FQDN).isEmpty()) - host_edt->setText(conn->getConnectionParam(Connection::PARAM_SERVER_FQDN)); + if(!conn->getConnectionParam(Connection::ParamServerFqdn).isEmpty()) + host_edt->setText(conn->getConnectionParam(Connection::ParamServerFqdn)); else - host_edt->setText(conn->getConnectionParam(Connection::PARAM_SERVER_IP)); + host_edt->setText(conn->getConnectionParam(Connection::ParamServerIp)); - conn_db_edt->setText(conn->getConnectionParam(Connection::PARAM_DB_NAME)); - user_edt->setText(conn->getConnectionParam(Connection::PARAM_USER)); - passwd_edt->setText(conn->getConnectionParam(Connection::PARAM_PASSWORD)); - port_sbp->setValue(conn->getConnectionParam(Connection::PARAM_PORT).toInt()); - timeout_sbp->setValue(conn->getConnectionParam(Connection::PARAM_CONN_TIMEOUT).toInt()); + conn_db_edt->setText(conn->getConnectionParam(Connection::ParamDbName)); + user_edt->setText(conn->getConnectionParam(Connection::ParamUser)); + passwd_edt->setText(conn->getConnectionParam(Connection::ParamPassword)); + port_sbp->setValue(conn->getConnectionParam(Connection::ParamPort).toInt()); + timeout_sbp->setValue(conn->getConnectionParam(Connection::ParamConnTimeout).toInt()); - krb_server_edt->setText(conn->getConnectionParam(Connection::PARAM_KERBEROS_SERVER)); - gssapi_auth_chk->setChecked(conn->getConnectionParam(Connection::PARAM_LIB_GSSAPI)==QString("gssapi")); - other_params_edt->setText(conn->getConnectionParam(Connection::PARAM_OTHERS)); + krb_server_edt->setText(conn->getConnectionParam(Connection::ParamKerberosServer)); + gssapi_auth_chk->setChecked(conn->getConnectionParam(Connection::ParamLibGssapi)==QString("gssapi")); + other_params_edt->setText(conn->getConnectionParam(Connection::ParamOthers)); - if(conn->getConnectionParam(Connection::PARAM_SSL_MODE)==Connection::SSL_DESABLE) + if(conn->getConnectionParam(Connection::ParamSslMode)==Connection::SslDisable) ssl_mode_cmb->setCurrentIndex(0); - else if(conn->getConnectionParam(Connection::PARAM_SSL_MODE)==Connection::SSL_ALLOW) + else if(conn->getConnectionParam(Connection::ParamSslMode)==Connection::SslAllow) ssl_mode_cmb->setCurrentIndex(1); - else if(conn->getConnectionParam(Connection::PARAM_SSL_MODE)==Connection::SSL_REQUIRE) + else if(conn->getConnectionParam(Connection::ParamSslMode)==Connection::SslRequire) ssl_mode_cmb->setCurrentIndex(2); - else if(conn->getConnectionParam(Connection::PARAM_SSL_MODE)==Connection::SSL_CA_VERIF) + else if(conn->getConnectionParam(Connection::ParamSslMode)==Connection::SslCaVerify) ssl_mode_cmb->setCurrentIndex(3); else ssl_mode_cmb->setCurrentIndex(4); if(ssl_mode_cmb->currentIndex() > 0) { - client_cert_edt->setText(conn->getConnectionParam(Connection::PARAM_SSL_CERT)); - root_cert_edt->setText(conn->getConnectionParam(Connection::PARAM_SSL_ROOT_CERT)); - client_key_edt->setText(conn->getConnectionParam(Connection::PARAM_SSL_KEY)); - crl_edt->setText(conn->getConnectionParam(Connection::PARAM_SSL_CRL)); + client_cert_edt->setText(conn->getConnectionParam(Connection::ParamSslCert)); + root_cert_edt->setText(conn->getConnectionParam(Connection::ParamSslRootCert)); + client_key_edt->setText(conn->getConnectionParam(Connection::ParamSslKey)); + crl_edt->setText(conn->getConnectionParam(Connection::ParamSslCrl)); } update_tb->setVisible(true); @@ -370,56 +370,56 @@ void ConnectionsConfigWidget::configureConnection(Connection *conn) if(conn) { conn->setAutoBrowseDB(auto_browse_chk->isChecked()); - conn->setConnectionParam(Connection::PARAM_ALIAS, alias_edt->text()); - conn->setConnectionParam(Connection::PARAM_SERVER_IP, QString()); - conn->setConnectionParam(Connection::PARAM_SERVER_FQDN, host_edt->text()); - conn->setConnectionParam(Connection::PARAM_PORT, QString("%1").arg(port_sbp->value())); - conn->setConnectionParam(Connection::PARAM_USER, user_edt->text()); - conn->setConnectionParam(Connection::PARAM_PASSWORD, passwd_edt->text()); - conn->setConnectionParam(Connection::PARAM_DB_NAME, conn_db_edt->text()); - conn->setConnectionParam(Connection::PARAM_CONN_TIMEOUT, QString("%1").arg(timeout_sbp->value())); - - conn->setDefaultForOperation(Connection::OP_DIFF, diff_chk->isChecked()); - conn->setDefaultForOperation(Connection::OP_EXPORT, export_chk->isChecked()); - conn->setDefaultForOperation(Connection::OP_IMPORT, import_chk->isChecked()); - conn->setDefaultForOperation(Connection::OP_VALIDATION, validation_chk->isChecked()); + conn->setConnectionParam(Connection::ParamAlias, alias_edt->text()); + conn->setConnectionParam(Connection::ParamServerIp, QString()); + conn->setConnectionParam(Connection::ParamServerFqdn, host_edt->text()); + conn->setConnectionParam(Connection::ParamPort, QString("%1").arg(port_sbp->value())); + conn->setConnectionParam(Connection::ParamUser, user_edt->text()); + conn->setConnectionParam(Connection::ParamPassword, passwd_edt->text()); + conn->setConnectionParam(Connection::ParamDbName, conn_db_edt->text()); + conn->setConnectionParam(Connection::ParamConnTimeout, QString("%1").arg(timeout_sbp->value())); + + conn->setDefaultForOperation(Connection::OpDiff, diff_chk->isChecked()); + conn->setDefaultForOperation(Connection::OpExport, export_chk->isChecked()); + conn->setDefaultForOperation(Connection::OpImport, import_chk->isChecked()); + conn->setDefaultForOperation(Connection::OpValidation, validation_chk->isChecked()); switch(ssl_mode_cmb->currentIndex()) { case 1: - conn->setConnectionParam(Connection::PARAM_SSL_MODE, Connection::SSL_ALLOW); + conn->setConnectionParam(Connection::ParamSslMode, Connection::SslAllow); break; case 2: - conn->setConnectionParam(Connection::PARAM_SSL_MODE, Connection::SSL_REQUIRE); + conn->setConnectionParam(Connection::ParamSslMode, Connection::SslRequire); break; case 3: - conn->setConnectionParam(Connection::PARAM_SSL_MODE, Connection::SSL_CA_VERIF); + conn->setConnectionParam(Connection::ParamSslMode, Connection::SslCaVerify); break; case 4: - conn->setConnectionParam(Connection::PARAM_SSL_MODE, Connection::SSL_FULL_VERIF); + conn->setConnectionParam(Connection::ParamSslMode, Connection::SslFullVerify); break; default: case 0: - conn->setConnectionParam(Connection::PARAM_SSL_MODE, Connection::SSL_DESABLE); + conn->setConnectionParam(Connection::ParamSslMode, Connection::SslDisable); break; } if(ssl_mode_cmb->currentIndex()!=0) { - conn->setConnectionParam(Connection::PARAM_SSL_ROOT_CERT, root_cert_edt->text()); - conn->setConnectionParam(Connection::PARAM_SSL_CERT, client_cert_edt->text()); - conn->setConnectionParam(Connection::PARAM_SSL_KEY, client_key_edt->text()); - conn->setConnectionParam(Connection::PARAM_SSL_CRL, crl_edt->text()); + conn->setConnectionParam(Connection::ParamSslRootCert, root_cert_edt->text()); + conn->setConnectionParam(Connection::ParamSslCert, client_cert_edt->text()); + conn->setConnectionParam(Connection::ParamSslKey, client_key_edt->text()); + conn->setConnectionParam(Connection::ParamSslCrl, crl_edt->text()); } if(gssapi_auth_chk->isChecked()) - conn->setConnectionParam(Connection::PARAM_LIB_GSSAPI, QString("gssapi")); + conn->setConnectionParam(Connection::ParamLibGssapi, QString("gssapi")); if(!krb_server_edt->text().isEmpty()) - conn->setConnectionParam(Connection::PARAM_KERBEROS_SERVER, krb_server_edt->text()); + conn->setConnectionParam(Connection::ParamKerberosServer, krb_server_edt->text()); if(!other_params_edt->text().isEmpty()) - conn->setConnectionParam(Connection::PARAM_OTHERS, other_params_edt->text()); + conn->setConnectionParam(Connection::ParamOthers, other_params_edt->text()); } } @@ -435,14 +435,14 @@ void ConnectionsConfigWidget::testConnection(void) conn.connect(); srv_info=conn.getServerInfo(); msg_box.show(trUtf8("Success"), - PgModelerUiNS::formatMessage(trUtf8("Connection successfully established!\n\nServer details:\n\nPID: `%1'\nProtocol: `%2'\nVersion: `%3'")) - .arg(srv_info[Connection::SERVER_PID]) - .arg(srv_info[Connection::SERVER_PROTOCOL]) - .arg(srv_info[Connection::SERVER_VERSION]), Messagebox::INFO_ICON); + PgModelerUiNs::formatMessage(trUtf8("Connection successfully established!\n\nServer details:\n\nPID: `%1'\nProtocol: `%2'\nVersion: `%3'")) + .arg(srv_info[Connection::ServerPid]) + .arg(srv_info[Connection::ServerProtocol]) + .arg(srv_info[Connection::ServerVersion]), Messagebox::InfoIcon); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -451,7 +451,7 @@ void ConnectionsConfigWidget::restoreDefaults(void) try { //Restore the default connection config file - BaseConfigWidget::restoreDefaults(GlobalAttributes::CONNECTIONS_CONF); + BaseConfigWidget::restoreDefaults(GlobalAttributes::ConnectionsConf, false); //Remove all connections while(connections_cmb->count() > 0) @@ -465,7 +465,7 @@ void ConnectionsConfigWidget::restoreDefaults(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -483,44 +483,44 @@ void ConnectionsConfigWidget::saveConfiguration(void) Messagebox msg_box; msg_box.show(trUtf8("There is a connection being created or edited! Do you want to save it?"), - Messagebox::ALERT_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::AlertIcon, Messagebox::YesNoButtons); if(msg_box.result()==QDialog::Accepted) handleConnection(); } - config_params[GlobalAttributes::CONNECTIONS_CONF].clear(); + config_params[GlobalAttributes::ConnectionsConf].clear(); /* Workaround: When there is no connection, to prevent saving an empty file, is necessary to fill the attribute CONNECTIONS with white spaces */ if(connections.empty()) - config_params[GlobalAttributes::CONNECTIONS_CONF][ParsersAttributes::CONNECTIONS]=QString(" "); + config_params[GlobalAttributes::ConnectionsConf][Attributes::Connections]=QString(" "); else { for(Connection *conn : connections) { attribs=conn->getConnectionParams(); - if(attribs[Connection::PARAM_SERVER_FQDN].isEmpty()) - attribs[Connection::PARAM_SERVER_FQDN]=attribs[Connection::PARAM_SERVER_IP]; + if(attribs[Connection::ParamServerFqdn].isEmpty()) + attribs[Connection::ParamServerFqdn]=attribs[Connection::ParamServerIp]; - attribs[ParsersAttributes::ALIAS]=attribs[Connection::PARAM_ALIAS]; - attribs[ParsersAttributes::AUTO_BROWSE_DB]=(conn->isAutoBrowseDB() ? ParsersAttributes::_TRUE_ : QString()); - attribs[ParsersAttributes::CONNECTION_TIMEOUT]=attribs[Connection::PARAM_CONN_TIMEOUT]; + attribs[Attributes::Alias]=attribs[Connection::ParamAlias]; + attribs[Attributes::AutoBrowseDb]=(conn->isAutoBrowseDB() ? Attributes::True : QString()); + attribs[Attributes::ConnectionTimeout]=attribs[Connection::ParamConnTimeout]; - attribs[DEFAULT_FOR.arg(ParsersAttributes::EXPORT)]=(conn->isDefaultForOperation(Connection::OP_EXPORT) ? ParsersAttributes::_TRUE_ : QString()); - attribs[DEFAULT_FOR.arg(ParsersAttributes::IMPORT)]=(conn->isDefaultForOperation(Connection::OP_IMPORT) ? ParsersAttributes::_TRUE_ : QString()); - attribs[DEFAULT_FOR.arg(ParsersAttributes::DIFF)]=(conn->isDefaultForOperation(Connection::OP_DIFF) ? ParsersAttributes::_TRUE_ : QString()); - attribs[DEFAULT_FOR.arg(ParsersAttributes::VALIDATION)]=(conn->isDefaultForOperation(Connection::OP_VALIDATION) ? ParsersAttributes::_TRUE_ : QString()); + attribs[DefaultFor.arg(Attributes::Export)]=(conn->isDefaultForOperation(Connection::OpExport) ? Attributes::True : QString()); + attribs[DefaultFor.arg(Attributes::Import)]=(conn->isDefaultForOperation(Connection::OpImport) ? Attributes::True : QString()); + attribs[DefaultFor.arg(Attributes::Diff)]=(conn->isDefaultForOperation(Connection::OpDiff) ? Attributes::True : QString()); + attribs[DefaultFor.arg(Attributes::Validation)]=(conn->isDefaultForOperation(Connection::OpValidation) ? Attributes::True : QString()); schparser.ignoreUnkownAttributes(true); - config_params[GlobalAttributes::CONNECTIONS_CONF][ParsersAttributes::CONNECTIONS]+= - schparser.getCodeDefinition(GlobalAttributes::TMPL_CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::SCHEMAS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::CONNECTIONS_CONF + - GlobalAttributes::SCHEMA_EXT, + config_params[GlobalAttributes::ConnectionsConf][Attributes::Connections]+= + schparser.getCodeDefinition(GlobalAttributes::TmplConfigurationDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::SchemasDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::ConnectionsConf + + GlobalAttributes::SchemaExt, attribs); schparser.ignoreUnkownAttributes(false); @@ -528,12 +528,12 @@ void ConnectionsConfigWidget::saveConfiguration(void) } schparser.ignoreUnkownAttributes(true); - BaseConfigWidget::saveConfiguration(GlobalAttributes::CONNECTIONS_CONF, config_params); + BaseConfigWidget::saveConfiguration(GlobalAttributes::ConnectionsConf, config_params); schparser.ignoreUnkownAttributes(false); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -553,13 +553,24 @@ void ConnectionsConfigWidget::getConnections(map &conns, } } +Connection *ConnectionsConfigWidget::getConnection(const QString &conn_id) +{ + for(Connection *conn : connections) + { + if(conn->getConnectionId() == conn_id) + return(conn); + } + + return(nullptr); +} + void ConnectionsConfigWidget::fillConnectionsComboBox(QComboBox *combo, bool incl_placeholder, unsigned check_def_for) { map connections; Connection *def_conn=nullptr; if(!combo) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject ,__PRETTY_FUNCTION__,__FILE__,__LINE__); getConnections(connections); @@ -576,7 +587,7 @@ void ConnectionsConfigWidget::fillConnectionsComboBox(QComboBox *combo, bool inc for(auto &itr : connections) { - combo->addItem(QIcon(QString(":icones/icones/server.png")), itr.first, QVariant::fromValue(itr.second)); + combo->addItem(QIcon(PgModelerUiNs::getIconPath("server")), itr.first, QVariant::fromValue(itr.second)); if(!def_conn && itr.second->isDefaultForOperation(check_def_for)) def_conn=itr.second; @@ -612,7 +623,7 @@ bool ConnectionsConfigWidget::openConnectionsConfiguration(QComboBox *combo, boo conn_cfg_wgt.frame->layout()->setContentsMargins(2,2,2,2); parent_form.setMainWidget(&conn_cfg_wgt); - parent_form.setButtonConfiguration(Messagebox::OK_CANCEL_BUTTONS); + parent_form.setButtonConfiguration(Messagebox::OkCancelButtons); parent_form.exec(); if(parent_form.result()==QDialog::Accepted) @@ -626,7 +637,7 @@ bool ConnectionsConfigWidget::openConnectionsConfiguration(QComboBox *combo, boo catch(Exception &e) { combo->setCurrentIndex(0); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } return(conn_saved); diff --git a/libpgmodeler_ui/src/connectionsconfigwidget.h b/libpgmodeler_ui/src/connectionsconfigwidget.h index 4b82293019..ccd7731790 100644 --- a/libpgmodeler_ui/src/connectionsconfigwidget.h +++ b/libpgmodeler_ui/src/connectionsconfigwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -37,7 +37,7 @@ class ConnectionsConfigWidget: public BaseConfigWidget, public Ui::ConnectionsCo HintTextWidget *auto_browse_ht, *default_for_ops_ht, *other_params_ht; - static const QString DEFAULT_FOR; + static const QString DefaultFor; //! \brief Stores the connections created by the user static vector connections; @@ -54,7 +54,7 @@ class ConnectionsConfigWidget: public BaseConfigWidget, public Ui::ConnectionsCo void updateConnectionsCombo(void); public: - ConnectionsConfigWidget(QWidget * parent=0); + ConnectionsConfigWidget(QWidget * parent = nullptr); ~ConnectionsConfigWidget(void); void saveConfiguration(void); @@ -64,9 +64,12 @@ class ConnectionsConfigWidget: public BaseConfigWidget, public Ui::ConnectionsCo //! \brief Fills the passed map with all the loaded connections. static void getConnections(map &conns, bool inc_hosts=true); + + //! \brief Return a connection with the provided ID. If no connection is found the method returns nullptr + static Connection *getConnection(const QString &conn_id); //! \brief Fills the passed combobox with all the loaded connections - static void fillConnectionsComboBox(QComboBox *combo, bool incl_placeholder, unsigned check_def_for=Connection::OP_NONE); + static void fillConnectionsComboBox(QComboBox *combo, bool incl_placeholder, unsigned check_def_for=Connection::OpNone); //! \brief Opens a local instance of connection config dialog to permit user configures connections on-the-fly static bool openConnectionsConfiguration(QComboBox *combo, bool incl_placeholder); diff --git a/libpgmodeler_ui/src/constraintwidget.cpp b/libpgmodeler_ui/src/constraintwidget.cpp index 4bb4eca7c1..16eb907ec0 100644 --- a/libpgmodeler_ui/src/constraintwidget.cpp +++ b/libpgmodeler_ui/src/constraintwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "constraintwidget.h" -ConstraintWidget::ConstraintWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_CONSTRAINT) +ConstraintWidget::ConstraintWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Constraint) { try { @@ -29,45 +29,45 @@ ConstraintWidget::ConstraintWidget(QWidget *parent): BaseObjectWidget(parent, OB Ui_ConstraintWidget::setupUi(this); - excl_elems_wgt=new ElementsWidget(this); + excl_elems_tab=new ElementsTableWidget(this); grid=new QGridLayout; grid->setContentsMargins(4,4,4,4); - grid->addWidget(excl_elems_wgt,0,0); + grid->addWidget(excl_elems_tab,0,0); excl_elems_grp->setLayout(grid); expression_hl=new SyntaxHighlighter(expression_txt, false, true); - expression_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + expression_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); - columns_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ - (ObjectsTableWidget::EDIT_BUTTON | - ObjectsTableWidget::UPDATE_BUTTON | - ObjectsTableWidget::DUPLICATE_BUTTON), true, this); + columns_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + (ObjectsTableWidget::EditButton | + ObjectsTableWidget::UpdateButton | + ObjectsTableWidget::DuplicateButton), true, this); - ref_columns_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ - (ObjectsTableWidget::EDIT_BUTTON | - ObjectsTableWidget::UPDATE_BUTTON | - ObjectsTableWidget::DUPLICATE_BUTTON), true, this); + ref_columns_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + (ObjectsTableWidget::EditButton | + ObjectsTableWidget::UpdateButton | + ObjectsTableWidget::DuplicateButton), true, this); - ref_table_sel=new ObjectSelectorWidget(OBJ_TABLE, true, this); + ref_table_sel=new ObjectSelectorWidget(ObjectType::Table, true, this); columns_tab->setColumnCount(2); columns_tab->setHeaderLabel(trUtf8("Column"), 0); - columns_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("column")),0); + columns_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("column")),0); columns_tab->setHeaderLabel(trUtf8("Type"), 1); - columns_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("usertype")),1); + columns_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("usertype")),1); ref_columns_tab->setEnabled(false); ref_columns_tab->setColumnCount(2); ref_columns_tab->setHeaderLabel(trUtf8("Column"), 0); - ref_columns_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("column")),0); + ref_columns_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("column")),0); ref_columns_tab->setHeaderLabel(trUtf8("Type"), 1); - ref_columns_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("usertype")),1); + ref_columns_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("usertype")),1); dynamic_cast(columns_tbw->widget(0)->layout())->addWidget(columns_tab, 1,0,1,3); dynamic_cast(columns_tbw->widget(1)->layout())->addWidget(ref_table_sel, 0,1,1,2); dynamic_cast(columns_tbw->widget(1)->layout())->addWidget(ref_columns_tab, 3,0,1,3); - configureFormLayout(constraint_grid, OBJ_CONSTRAINT); + configureFormLayout(constraint_grid, ObjectType::Constraint); ConstraintType::getTypes(list); constr_type_cmb->addItems(list); @@ -89,9 +89,9 @@ ConstraintWidget::ConstraintWidget(QWidget *parent): BaseObjectWidget(parent, OB constraint_grid->addWidget(info_frm, constraint_grid->count()+1, 0, 1, 0); info_frm->setParent(this); - fields_map[generateVersionsInterval(AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_92)].push_back(no_inherit_lbl); - fields_map[generateVersionsInterval(AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_95)].push_back(indexing_chk); - values_map[indexing_chk].push_back(~IndexingType(IndexingType::brin)); + fields_map[generateVersionsInterval(AfterVersion, PgSqlVersions::PgSqlVersion92)].push_back(no_inherit_lbl); + fields_map[generateVersionsInterval(AfterVersion, PgSqlVersions::PgSqlVersion95)].push_back(indexing_chk); + values_map[indexing_chk].push_back(~IndexingType(IndexingType::Brin)); warn_frm=generateVersionWarningFrame(fields_map, &values_map); constraint_grid->addWidget(warn_frm, constraint_grid->count()+1, 0, 1, 0); @@ -119,7 +119,7 @@ ConstraintWidget::ConstraintWidget(QWidget *parent): BaseObjectWidget(parent, OB } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -137,13 +137,13 @@ void ConstraintWidget::addColumn(int row) { aux_col_tab=columns_tab; combo=column_cmb; - col_id=Constraint::SOURCE_COLS; + col_id=Constraint::SourceCols; } else { aux_col_tab=ref_columns_tab; combo=ref_column_cmb; - col_id=Constraint::REFERENCED_COLS; + col_id=Constraint::ReferencedCols; } //Gets the reference to the selected column @@ -156,29 +156,29 @@ void ConstraintWidget::addColumn(int row) addColumn(column, col_id, row); //When there is no items con the combo the insert button of the table is disabled - aux_col_tab->setButtonsEnabled(ObjectsTableWidget::ADD_BUTTON, (combo->count()!=0)); + aux_col_tab->setButtonsEnabled(ObjectsTableWidget::AddButton, (combo->count()!=0)); } catch(Exception &e) { aux_col_tab->removeRow(row); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void ConstraintWidget::removeColumn(int) { if(sender()==columns_tab) - updateColumnsCombo(Constraint::SOURCE_COLS); + updateColumnsCombo(Constraint::SourceCols); else - updateColumnsCombo(Constraint::REFERENCED_COLS); + updateColumnsCombo(Constraint::ReferencedCols); } void ConstraintWidget::removeColumns(void) { if(sender()==columns_tab) - updateColumnsCombo(Constraint::SOURCE_COLS); + updateColumnsCombo(Constraint::SourceCols); else - updateColumnsCombo(Constraint::REFERENCED_COLS); + updateColumnsCombo(Constraint::ReferencedCols); } void ConstraintWidget::addColumn(Column *column, unsigned col_id, int row) @@ -187,7 +187,7 @@ void ConstraintWidget::addColumn(Column *column, unsigned col_id, int row) if(column && row >= 0) { - if(col_id==Constraint::SOURCE_COLS) + if(col_id==Constraint::SourceCols) table_wgt=columns_tab; else table_wgt=ref_columns_tab; @@ -204,9 +204,9 @@ void ConstraintWidget::addColumn(Column *column, unsigned col_id, int row) fonte.setItalic(true); if(column->isProtected()) - table_wgt->setRowFont(row, fonte, PROT_LINE_FGCOLOR, PROT_LINE_BGCOLOR); + table_wgt->setRowFont(row, fonte, ProtRowFgColor, ProtRowBgColor); else - table_wgt->setRowFont(row, fonte, RELINC_LINE_FGCOLOR, RELINC_LINE_BGCOLOR); + table_wgt->setRowFont(row, fonte, RelAddedRowFgColor, RelAddedRowBgColor); } } } @@ -222,7 +222,7 @@ void ConstraintWidget::updateColumnsCombo(unsigned col_id) try { - if(col_id==Constraint::SOURCE_COLS) + if(col_id==Constraint::SourceCols) { combo=column_cmb; aux_col_tab=columns_tab; @@ -267,11 +267,11 @@ void ConstraintWidget::updateColumnsCombo(unsigned col_id) QString(")"), QVariant::fromValue(column)); } - aux_col_tab->setButtonsEnabled(ObjectsTableWidget::ADD_BUTTON, (combo->count()!=0)); + aux_col_tab->setButtonsEnabled(ObjectsTableWidget::AddButton, (combo->count()!=0)); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -279,18 +279,20 @@ void ConstraintWidget::selectReferencedTable(void) { Table *table=dynamic_cast
(ref_table_sel->getSelectedObject()); - if(!table) + if(!table || (this->object && dynamic_cast(this->object)->getReferencedTable() != table)) { - ref_column_cmb->clear(); ref_columns_tab->blockSignals(true); ref_columns_tab->removeRows(); ref_columns_tab->setEnabled(false); ref_columns_tab->blockSignals(false); } + + if(!table) + ref_column_cmb->clear(); else { ref_columns_tab->setEnabled(true); - updateColumnsCombo(Constraint::REFERENCED_COLS); + updateColumnsCombo(Constraint::ReferencedCols); } } @@ -298,48 +300,45 @@ void ConstraintWidget::selectConstraintType(void) { ConstraintType constr_type=ConstraintType(constr_type_cmb->currentText()); - tablespace_lbl->setVisible(constr_type==ConstraintType::primary_key || constr_type==ConstraintType::unique); - tablespace_sel->setVisible(constr_type==ConstraintType::primary_key || constr_type==ConstraintType::unique); + tablespace_lbl->setVisible(constr_type==ConstraintType::PrimaryKey || constr_type==ConstraintType::Unique); + tablespace_sel->setVisible(constr_type==ConstraintType::PrimaryKey || constr_type==ConstraintType::Unique); if(!tablespace_sel->isVisible()) tablespace_sel->clearSelector(); - expression_lbl->setVisible(constr_type==ConstraintType::check || constr_type==ConstraintType::exclude); - expression_txt->setVisible(constr_type==ConstraintType::check || constr_type==ConstraintType::exclude); - no_inherit_chk->setVisible(constr_type==ConstraintType::check); - no_inherit_lbl->setVisible(constr_type==ConstraintType::check); - warn_frm->setVisible(constr_type==ConstraintType::check); - - /*fill_factor_lbl->setVisible(constr_type==ConstraintType::unique || - constr_type==ConstraintType::primary_key || - constr_type==ConstraintType::exclude); */ - fill_factor_chk->setVisible(constr_type==ConstraintType::unique || - constr_type==ConstraintType::primary_key || - constr_type==ConstraintType::exclude); - fill_factor_sb->setVisible(constr_type==ConstraintType::unique || - constr_type==ConstraintType::primary_key || - constr_type==ConstraintType::exclude); - - info_frm->setVisible(constr_type==ConstraintType::primary_key); - - deferrable_lbl->setVisible(constr_type!=ConstraintType::check); - deferrable_chk->setVisible(constr_type!=ConstraintType::check); - deferral_cmb->setVisible(constr_type!=ConstraintType::check); - deferral_lbl->setVisible(constr_type!=ConstraintType::check); - - match_lbl->setVisible(constr_type==ConstraintType::foreign_key); - match_cmb->setVisible(constr_type==ConstraintType::foreign_key); - on_delete_cmb->setVisible(constr_type==ConstraintType::foreign_key); - on_delete_lbl->setVisible(constr_type==ConstraintType::foreign_key); - on_update_cmb->setVisible(constr_type==ConstraintType::foreign_key); - on_update_lbl->setVisible(constr_type==ConstraintType::foreign_key); - - columns_tbw->setVisible(constr_type!=ConstraintType::check && - constr_type!=ConstraintType::exclude); - - indexing_chk->setVisible(constr_type==ConstraintType::exclude); - indexing_cmb->setVisible(constr_type==ConstraintType::exclude); - - if(constr_type!=ConstraintType::foreign_key) + expression_lbl->setVisible(constr_type==ConstraintType::Check || constr_type==ConstraintType::Exclude); + expression_txt->setVisible(constr_type==ConstraintType::Check || constr_type==ConstraintType::Exclude); + no_inherit_chk->setVisible(constr_type==ConstraintType::Check); + no_inherit_lbl->setVisible(constr_type==ConstraintType::Check); + warn_frm->setVisible(constr_type==ConstraintType::Check); + + fill_factor_chk->setVisible(constr_type==ConstraintType::Unique || + constr_type==ConstraintType::PrimaryKey || + constr_type==ConstraintType::Exclude); + fill_factor_sb->setVisible(constr_type==ConstraintType::Unique || + constr_type==ConstraintType::PrimaryKey || + constr_type==ConstraintType::Exclude); + + info_frm->setVisible(constr_type==ConstraintType::PrimaryKey); + + deferrable_lbl->setVisible(constr_type!=ConstraintType::Check); + deferrable_chk->setVisible(constr_type!=ConstraintType::Check); + deferral_cmb->setVisible(constr_type!=ConstraintType::Check); + deferral_lbl->setVisible(constr_type!=ConstraintType::Check); + + match_lbl->setVisible(constr_type==ConstraintType::ForeignKey); + match_cmb->setVisible(constr_type==ConstraintType::ForeignKey); + on_delete_cmb->setVisible(constr_type==ConstraintType::ForeignKey); + on_delete_lbl->setVisible(constr_type==ConstraintType::ForeignKey); + on_update_cmb->setVisible(constr_type==ConstraintType::ForeignKey); + on_update_lbl->setVisible(constr_type==ConstraintType::ForeignKey); + + columns_tbw->setVisible(constr_type!=ConstraintType::Check && + constr_type!=ConstraintType::Exclude); + + indexing_chk->setVisible(constr_type==ConstraintType::Exclude); + indexing_cmb->setVisible(constr_type==ConstraintType::Exclude); + + if(constr_type!=ConstraintType::ForeignKey) { columns_tbw->setTabEnabled(1, false); columns_tbw->setCurrentIndex(0); @@ -348,59 +347,50 @@ void ConstraintWidget::selectConstraintType(void) else columns_tbw->setTabEnabled(1, true); - excl_elems_grp->setVisible(constr_type==ConstraintType::exclude); + excl_elems_grp->setVisible(constr_type==ConstraintType::Exclude); } void ConstraintWidget::setAttributes(DatabaseModel *model, OperationList *op_list, BaseObject *parent_obj, Constraint *constr) { ObjectType obj_type; - unsigned count, i, row; - Column *column=nullptr; + unsigned row = 0; Table *ref_table=nullptr; vector excl_elems; if(!parent_obj) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); obj_type=parent_obj->getObjectType(); - if(obj_type!=OBJ_TABLE && obj_type!=OBJ_RELATIONSHIP) - throw Exception(ERR_OPR_OBJ_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(obj_type!=ObjectType::Table && obj_type!=ObjectType::Relationship) + throw Exception(ErrorCode::OprObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); BaseObjectWidget::setAttributes(model, op_list, constr, parent_obj); info_frm->setVisible(this->table!=nullptr); ref_table_sel->setModel(model); - if(this->table) - count=table->getObjectCount(OBJ_COLUMN); - else - count=relationship->getAttributeCount(); - columns_tab->blockSignals(true); - for(i=0, row=0; i < count; i++) - { - if(this->table) - column=dynamic_cast(table->getObject(i, OBJ_COLUMN)); - else - column=relationship->getAttribute(i); - if(constr && constr->isColumnExists(column, Constraint::SOURCE_COLS)) - { - columns_tab->addRow(); - addColumn(column, Constraint::SOURCE_COLS, row); - row++; - } + if(constr) + { + row = 0; + for(auto column : constr->getColumns(Constraint::SourceCols)) + { + columns_tab->addRow(); + addColumn(column, Constraint::SourceCols, row); + row++; + } } - updateColumnsCombo(Constraint::SOURCE_COLS); - columns_tab->setButtonsEnabled(ObjectsTableWidget::ADD_BUTTON, (column_cmb->count()!=0)); + updateColumnsCombo(Constraint::SourceCols); + columns_tab->setButtonsEnabled(ObjectsTableWidget::AddButton, (column_cmb->count()!=0)); columns_tab->blockSignals(false); if(constr) { excl_elems = constr->getExcludeElements(); - indexing_chk->setChecked(constr->getIndexType()!=BaseType::null); + indexing_chk->setChecked(constr->getIndexType()!=BaseType::Null); indexing_cmb->setCurrentIndex(indexing_cmb->findText(~constr->getIndexType())); constr_type_cmb->setCurrentIndex(constr_type_cmb->findText(~constr->getConstraintType())); @@ -412,8 +402,8 @@ void ConstraintWidget::setAttributes(DatabaseModel *model, OperationList *op_lis deferrable_chk->setChecked(constr->isDeferrable()); deferral_cmb->setCurrentIndex(deferral_cmb->findText(~constr->getDeferralType())); match_cmb->setCurrentIndex(match_cmb->findText(~constr->getMatchType())); - on_delete_cmb->setCurrentIndex(on_delete_cmb->findText(~constr->getActionType(Constraint::DELETE_ACTION))); - on_update_cmb->setCurrentIndex(on_update_cmb->findText(~constr->getActionType(Constraint::UPDATE_ACTION))); + on_delete_cmb->setCurrentIndex(on_delete_cmb->findText(~constr->getActionType(Constraint::DeleteAction))); + on_update_cmb->setCurrentIndex(on_update_cmb->findText(~constr->getActionType(Constraint::UpdateAction))); fill_factor_chk->setChecked(constr->getFillFactor()!=0); if(fill_factor_chk->isChecked()) @@ -425,25 +415,22 @@ void ConstraintWidget::setAttributes(DatabaseModel *model, OperationList *op_lis ref_columns_tab->blockSignals(true); ref_table_sel->setSelectedObject(ref_table); - count=ref_table->getColumnCount(); - for(i=0, row=0; i < count; i++) + row = 0; + for(auto column : constr->getColumns(Constraint::ReferencedCols)) { - column=ref_table->getColumn(i); - if(constr->isColumnExists(column, Constraint::REFERENCED_COLS)) - { - ref_columns_tab->addRow(); - addColumn(column, Constraint::REFERENCED_COLS, row); - row++; - } + ref_columns_tab->addRow(); + addColumn(column, Constraint::ReferencedCols, row); + row++; } - updateColumnsCombo(Constraint::REFERENCED_COLS); - ref_columns_tab->setButtonsEnabled(ObjectsTableWidget::ADD_BUTTON, (column_cmb->count()!=0)); + updateColumnsCombo(Constraint::ReferencedCols); + ref_columns_tab->setButtonsEnabled(ObjectsTableWidget::AddButton, (column_cmb->count()!=0)); ref_columns_tab->blockSignals(false); } } - excl_elems_wgt->setAttributes(model, parent_obj, excl_elems); + excl_elems_tab->setAttributes(model, parent_obj); + excl_elems_tab->setElements(excl_elems); } void ConstraintWidget::applyConfiguration(void) @@ -470,22 +457,22 @@ void ConstraintWidget::applyConfiguration(void) constr->setMatchType(MatchType(match_cmb->currentText())); constr->setDeferrable(deferrable_chk->isChecked()); constr->setDeferralType(DeferralType(deferral_cmb->currentText())); - constr->setActionType(ActionType(on_delete_cmb->currentText()),Constraint::DELETE_ACTION); - constr->setActionType(ActionType(on_update_cmb->currentText()),Constraint::UPDATE_ACTION); + constr->setActionType(ActionType(on_delete_cmb->currentText()),Constraint::DeleteAction); + constr->setActionType(ActionType(on_update_cmb->currentText()),Constraint::UpdateAction); constr->setNoInherit(no_inherit_chk->isChecked()); if(indexing_chk->isChecked()) constr->setIndexType(IndexingType(indexing_cmb->currentText())); else - constr->setIndexType(BaseType::null); + constr->setIndexType(BaseType::Null); - if(constr->getConstraintType()==ConstraintType::foreign_key) + if(constr->getConstraintType()==ConstraintType::ForeignKey) constr->setReferencedTable(dynamic_cast(ref_table_sel->getSelectedObject())); constr->removeColumns(); - for(col_id=Constraint::SOURCE_COLS; col_id <= Constraint::REFERENCED_COLS; col_id++) + for(col_id=Constraint::SourceCols; col_id <= Constraint::ReferencedCols; col_id++) { - aux_col_tab=(col_id==Constraint::SOURCE_COLS ? columns_tab : ref_columns_tab); + aux_col_tab=(col_id==Constraint::SourceCols ? columns_tab : ref_columns_tab); count=aux_col_tab->getRowCount(); for(i=0; i < count; i++) @@ -495,29 +482,29 @@ void ConstraintWidget::applyConfiguration(void) } } - excl_elems_wgt->getElements(excl_elems); + excl_elems_tab->getElements(excl_elems); constr->addExcludeElements(excl_elems); //Raises an error if the user try to create a primary key that has columns added by relationship (not supported) - if(constr->getConstraintType()==ConstraintType::primary_key && + if(constr->getConstraintType()==ConstraintType::PrimaryKey && constr->isReferRelationshipAddedColumn()) - throw Exception(ERR_PK_USING_COLS_ADDED_BY_REL,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::UnsupportedPKColsAddedByRel,__PRETTY_FUNCTION__,__FILE__,__LINE__); BaseObjectWidget::applyConfiguration(); /* Raises an error if the constraint type requires at least one column to be assinged and there is no columns configured on the form */ - if(((constr->getConstraintType()==ConstraintType::foreign_key || - constr->getConstraintType()==ConstraintType::primary_key) && - constr->getColumnCount(Constraint::SOURCE_COLS)==0) || - (constr->getConstraintType()==ConstraintType::foreign_key && - constr->getColumnCount(Constraint::REFERENCED_COLS)==0)) - throw Exception(ERR_CONSTR_NO_COLUMNS,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(((constr->getConstraintType()==ConstraintType::ForeignKey || + constr->getConstraintType()==ConstraintType::PrimaryKey) && + constr->getColumnCount(Constraint::SourceCols)==0) || + (constr->getConstraintType()==ConstraintType::ForeignKey && + constr->getColumnCount(Constraint::ReferencedCols)==0)) + throw Exception(ErrorCode::InvConstratintNoColumns,__PRETTY_FUNCTION__,__FILE__,__LINE__); finishConfiguration(); //For the foreign keys, updates the fk relationships on the model - if(constr->getConstraintType()==ConstraintType::foreign_key) + if(constr->getConstraintType()==ConstraintType::ForeignKey) this->model->updateTableFKRelationships(dynamic_cast
(this->table)); } catch(Exception &e) diff --git a/libpgmodeler_ui/src/constraintwidget.h b/libpgmodeler_ui/src/constraintwidget.h index 531f64cb82..bd0994f879 100644 --- a/libpgmodeler_ui/src/constraintwidget.h +++ b/libpgmodeler_ui/src/constraintwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -29,7 +29,7 @@ #include "ui_constraintwidget.h" #include "objectstablewidget.h" #include "messagebox.h" -#include "elementswidget.h" +#include "elementstablewidget.h" class ConstraintWidget: public BaseObjectWidget, public Ui::ConstraintWidget { private: @@ -39,7 +39,7 @@ class ConstraintWidget: public BaseObjectWidget, public Ui::ConstraintWidget { SyntaxHighlighter *expression_hl; - ElementsWidget *excl_elems_wgt; + ElementsTableWidget *excl_elems_tab; /*! \brief Table widgets used to store the columns that forms the constraint as well the referenced columns (only for foreign keys) */ @@ -56,7 +56,7 @@ class ConstraintWidget: public BaseObjectWidget, public Ui::ConstraintWidget { void addColumn(Column *column, unsigned col_id, int row); public: - ConstraintWidget(QWidget * parent = 0); + ConstraintWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, BaseObject *parent_obj, Constraint *constr); private slots: diff --git a/libpgmodeler_ui/src/conversionwidget.cpp b/libpgmodeler_ui/src/conversionwidget.cpp index cefaa18f0f..e7d3db6d06 100644 --- a/libpgmodeler_ui/src/conversionwidget.cpp +++ b/libpgmodeler_ui/src/conversionwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "conversionwidget.h" -ConversionWidget::ConversionWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_CONVERSION) +ConversionWidget::ConversionWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Conversion) { try { @@ -28,7 +28,7 @@ ConversionWidget::ConversionWidget(QWidget *parent): BaseObjectWidget(parent, OB Ui_ConversionWidget::setupUi(this); conv_func_sel=nullptr; - conv_func_sel=new ObjectSelectorWidget(OBJ_FUNCTION, true, this); + conv_func_sel=new ObjectSelectorWidget(ObjectType::Function, true, this); convcod_grid->addWidget(conv_func_sel,1,1,1,3); setRequiredField(src_encoding_lbl); @@ -36,7 +36,7 @@ ConversionWidget::ConversionWidget(QWidget *parent): BaseObjectWidget(parent, OB setRequiredField(conv_func_lbl); setRequiredField(conv_func_sel); - configureFormLayout(convcod_grid, OBJ_CONVERSION); + configureFormLayout(convcod_grid, ObjectType::Conversion); frame=generateInformationFrame(trUtf8("The function to be assigned to an encoding conversion must have the following signature: void function(integer, integer, cstring, internal, integer).")); convcod_grid->addItem(new QSpacerItem(10,10,QSizePolicy::Minimum,QSizePolicy::Expanding), convcod_grid->count()+1, 0, 1, 0); convcod_grid->addWidget(frame, convcod_grid->count()+1, 0, 1, 0); @@ -52,7 +52,7 @@ ConversionWidget::ConversionWidget(QWidget *parent): BaseObjectWidget(parent, OB } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -65,8 +65,8 @@ void ConversionWidget::setAttributes(DatabaseModel *model, OperationList *op_lis { conv_func_sel->setSelectedObject(conv->getConversionFunction()); default_conv_chk->setChecked(conv->isDefault()); - src_encoding_cmb->setCurrentIndex(trg_encoding_cmb->findText(~(conv->getEncoding(Conversion::SRC_ENCODING)))); - trg_encoding_cmb->setCurrentIndex(trg_encoding_cmb->findText(~(conv->getEncoding(Conversion::DST_ENCODING)))); + src_encoding_cmb->setCurrentIndex(trg_encoding_cmb->findText(~(conv->getEncoding(Conversion::SrcEncoding)))); + trg_encoding_cmb->setCurrentIndex(trg_encoding_cmb->findText(~(conv->getEncoding(Conversion::DstEncoding)))); } } @@ -81,8 +81,8 @@ void ConversionWidget::applyConfiguration(void) BaseObjectWidget::applyConfiguration(); - conv->setEncoding(Conversion::SRC_ENCODING, src_encoding_cmb->currentText()); - conv->setEncoding(Conversion::DST_ENCODING, trg_encoding_cmb->currentText()); + conv->setEncoding(Conversion::SrcEncoding, src_encoding_cmb->currentText()); + conv->setEncoding(Conversion::DstEncoding, trg_encoding_cmb->currentText()); conv->setDefault(default_conv_chk->isChecked()); conv->setConversionFunction(dynamic_cast(conv_func_sel->getSelectedObject())); @@ -91,7 +91,7 @@ void ConversionWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/conversionwidget.h b/libpgmodeler_ui/src/conversionwidget.h index 1bf00490c6..1366b479be 100644 --- a/libpgmodeler_ui/src/conversionwidget.h +++ b/libpgmodeler_ui/src/conversionwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -34,7 +34,7 @@ class ConversionWidget: public BaseObjectWidget, public Ui::ConversionWidget { ObjectSelectorWidget *conv_func_sel; public: - ConversionWidget(QWidget * parent = 0); + ConversionWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, Conversion *conv); private slots: diff --git a/libpgmodeler_ui/src/csvloadwidget.cpp b/libpgmodeler_ui/src/csvloadwidget.cpp index 28f794e1a8..88cf760c51 100644 --- a/libpgmodeler_ui/src/csvloadwidget.cpp +++ b/libpgmodeler_ui/src/csvloadwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -87,22 +87,33 @@ QList CsvLoadWidget::loadCsvFromBuffer(const QString &csv_buffer, c if(!csv_buffer.isEmpty()) { QString double_quote=QString("%1%1").arg(text_delim), - placeholder = QString("⁋"), aux_buffer = csv_buffer; + placeholder = QString(QChar::ReplacementCharacter), + aux_buffer = csv_buffer, + win_line_break = QString("%1%2").arg(QChar(QChar::CarriageReturn)).arg(QChar(QChar::LineFeed)), + mac_line_break = QString("%1").arg(QChar(QChar::CarriageReturn)); QStringList values, rows; QRegExp empty_val; - //If no custom separator is specified we use the default ';' - aux_buffer.replace(QString("\r\n"), placeholder); - rows=aux_buffer.split(QChar::LineFeed, QString::SkipEmptyParts); - rows.replaceInStrings(placeholder, QString("\r\n")); + if(aux_buffer.contains(win_line_break)) + aux_buffer.replace(win_line_break, QString(QChar::LineFeed)); + else if(aux_buffer.contains(mac_line_break)) + aux_buffer.replace(mac_line_break, QString(QChar::LineFeed)); if(cols_in_first_row) { - csv_cols=rows[0].split(separator); + int lf_idx = aux_buffer.indexOf(QChar::LineFeed); + + if(lf_idx < 0) + lf_idx = aux_buffer.size(); + + csv_cols=aux_buffer.mid(0, lf_idx).split(separator); csv_cols.replaceInStrings(text_delim, QString()); - rows.removeAt(0); + aux_buffer.replace(0, lf_idx + 1, QString()); } + aux_buffer.replace(QString("%1%2").arg(QChar(QChar::LineFeed)).arg(text_delim), placeholder); + rows = aux_buffer.split(placeholder, QString::SkipEmptyParts); + //Configuring an regexp to remove empty quoted values, e.g, "", if(!text_delim.isEmpty()) empty_val = QRegExp(QString("(\\%1\\%1)(\\%2)").arg(text_delim).arg(separator)); @@ -113,12 +124,13 @@ QList CsvLoadWidget::loadCsvFromBuffer(const QString &csv_buffer, c row.replace(empty_val, separator); /* In order to preserve double quotes (double delimiters) inside the values, - we first replace them by a placeholder, erase the delimiters and restore the previous value */ + * we first replace them by a placeholder, erase the delimiters and restore the previous value */ row.replace(double_quote, placeholder); row.replace(text_delim, QString()); row.replace(placeholder, double_quote); values = row.split(separator); + for(int i =0; i < values.count(); i++) values[i] = values[i].trimmed(); @@ -137,8 +149,8 @@ void CsvLoadWidget::loadCsvFile(void) file.setFileName(file_edt->text()); if(!file.open(QFile::ReadOnly)) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED).arg(file_edt->text()), - ERR_FILE_DIR_NOT_ACCESSED,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed).arg(file_edt->text()), + ErrorCode::FileDirectoryNotAccessed,__PRETTY_FUNCTION__,__FILE__,__LINE__); csv_columns.clear(); csv_rows.clear(); @@ -147,11 +159,7 @@ void CsvLoadWidget::loadCsvFile(void) if(!csv_buffer.isEmpty()) { - QString separator; - QStringList separators={ QString(";"), QString(","), QString(" "), QString("\t") }; - separators += (separator_edt->text().isEmpty() ? QString(";") : separator_edt->text()); - separator = separators[separator_cmb->currentIndex()]; - csv_rows = loadCsvFromBuffer(csv_buffer, separator, + csv_rows = loadCsvFromBuffer(csv_buffer, getSeparator(), txt_delim_chk->isChecked() ? txt_delim_edt->text() : QString(), col_names_chk->isChecked(), csv_columns); } @@ -160,6 +168,13 @@ void CsvLoadWidget::loadCsvFile(void) emit s_csvFileLoaded(); } +QString CsvLoadWidget::getSeparator(void) +{ + QStringList separators={ QString(";"), QString(","), QString(" "), QString("\t") }; + separators += (separator_edt->text().isEmpty() ? QString(";") : separator_edt->text()); + return(separators[separator_cmb->currentIndex()]); +} + QString CsvLoadWidget::getCsvBuffer(QString separator, QString line_break) { QString buffer; @@ -185,3 +200,17 @@ bool CsvLoadWidget::isColumnsInFirstRow(void) { return(col_names_chk->isChecked()); } + +void CsvLoadWidget::loadCsvBuffer(const QString csv_buffer, const QString &separator, const QString &text_delim, bool cols_in_first_row) +{ + csv_columns.clear(); + csv_rows.clear(); + csv_rows = loadCsvFromBuffer(csv_buffer, separator, text_delim, cols_in_first_row, csv_columns); +} + +void CsvLoadWidget::loadCsvBuffer(const QString csv_buffer) +{ + loadCsvBuffer(csv_buffer, getSeparator(), + txt_delim_chk->isChecked() ? txt_delim_edt->text() : QString(), + col_names_chk->isChecked()); +} diff --git a/libpgmodeler_ui/src/csvloadwidget.h b/libpgmodeler_ui/src/csvloadwidget.h index be030eb609..bdc4b85eb9 100644 --- a/libpgmodeler_ui/src/csvloadwidget.h +++ b/libpgmodeler_ui/src/csvloadwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -42,7 +42,7 @@ class CsvLoadWidget : public QWidget, Ui::CsvLoadWidget { QList csv_rows; public: - CsvLoadWidget(QWidget * parent = 0, bool cols_in_first_row = true); + CsvLoadWidget(QWidget * parent = nullptr, bool cols_in_first_row = true); //! \brief Returns the extracted columns QStringList getCsvColumns(void); @@ -55,6 +55,15 @@ class CsvLoadWidget : public QWidget, Ui::CsvLoadWidget { bool isColumnsInFirstRow(void); + /*! \brief Loads a csv document from a buffer and stores the result in the internal csv_columns and csv_rows attributes for later usage. + * The separator and text delimiter chars can be specified overriding the ones configured in the widget */ + void loadCsvBuffer(const QString csv_buffer, const QString &separator, const QString &text_delim, bool cols_in_first_row); + + //! \brief Loads a csv document from a buffer and stores the result in the internal csv_columns and csv_rows attributes for later usage. + void loadCsvBuffer(const QString csv_buffer); + + QString getSeparator(void); + /*! \brief Loads a csv document from a buffer. The user can specify the value separator, text delimiter and an object which will store the column names. * In that case, the column names are only extracted from the first row if the cols_in_first_row is true */ static QList loadCsvFromBuffer(const QString &csv_buffer, const QString &separator, const QString &text_delim, bool cols_in_first_row, QStringList &csv_cols); diff --git a/libpgmodeler_ui/src/customsqlwidget.cpp b/libpgmodeler_ui/src/customsqlwidget.cpp index f0c5884812..3f8913596f 100644 --- a/libpgmodeler_ui/src/customsqlwidget.cpp +++ b/libpgmodeler_ui/src/customsqlwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -26,24 +26,24 @@ CustomSQLWidget::CustomSQLWidget(QWidget *parent) : BaseObjectWidget(parent) QFont font; Ui_CustomSQLWidget::setupUi(this); - configureFormLayout(sqlappend_grid, BASE_OBJECT); + configureFormLayout(sqlappend_grid, ObjectType::BaseObject); - append_sql_txt=PgModelerUiNS::createNumberedTextEditor(append_sql_wgt, true); - prepend_sql_txt=PgModelerUiNS::createNumberedTextEditor(prepend_sql_wgt, true); + append_sql_txt=PgModelerUiNs::createNumberedTextEditor(append_sql_wgt, true); + prepend_sql_txt=PgModelerUiNs::createNumberedTextEditor(prepend_sql_wgt, true); append_sql_hl=new SyntaxHighlighter(append_sql_txt); - append_sql_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + append_sql_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); append_sql_cp=new CodeCompletionWidget(append_sql_txt, true); prepend_sql_hl=new SyntaxHighlighter(prepend_sql_txt); - prepend_sql_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + prepend_sql_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); prepend_sql_cp=new CodeCompletionWidget(prepend_sql_txt, true); name_edt->setReadOnly(true); comment_edt->setVisible(false); comment_lbl->setVisible(false); - PgModelerUiNS::configureWidgetFont(message_lbl, PgModelerUiNS::MEDIUM_FONT_FACTOR); + PgModelerUiNs::configureWidgetFont(message_lbl, PgModelerUiNs::MediumFontFactor); action_gen_insert=new QAction(trUtf8("Generic INSERT"), this); action_gen_insert->setObjectName(QString("action_gen_insert")); @@ -93,7 +93,7 @@ CustomSQLWidget::CustomSQLWidget(QWidget *parent) : BaseObjectWidget(parent) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -106,9 +106,9 @@ void CustomSQLWidget::configureMenus(void) for(int i=0; i < count; i++) btns[i]->setMenu(nullptr); - if(obj_type==OBJ_TABLE || obj_type==OBJ_VIEW) + if(obj_type==ObjectType::Table || obj_type==ObjectType::View) { - if(obj_type==OBJ_TABLE) + if(obj_type==ObjectType::Table) { insert_tb->setMenu(&insert_menu); delete_tb->setMenu(&delete_menu); @@ -122,9 +122,9 @@ void CustomSQLWidget::configureMenus(void) void CustomSQLWidget::setAttributes(DatabaseModel *model, BaseObject *object) { if(!object) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(!BaseObject::acceptsCustomSQL(object->getObjectType())) - throw Exception(ERR_OPR_OBJ_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { @@ -132,7 +132,7 @@ void CustomSQLWidget::setAttributes(DatabaseModel *model, BaseObject *object) name_edt->setText(QString("%1 (%2)").arg(object->getSignature()).arg(object->getTypeName())); - if(object->getObjectType()==OBJ_DATABASE) + if(object->getObjectType()==ObjectType::Database) end_of_model_chk->setChecked(dynamic_cast(object)->isAppendAtEOD()); append_sql_txt->setFocus(); @@ -145,26 +145,26 @@ void CustomSQLWidget::setAttributes(DatabaseModel *model, BaseObject *object) prepend_sql_cp->configureCompletion(model, prepend_sql_hl); prepend_sql_txt->moveCursor(QTextCursor::End); - end_of_model_chk->setVisible(object->getObjectType()==OBJ_DATABASE); - begin_of_model_chk->setVisible(object->getObjectType()==OBJ_DATABASE); + end_of_model_chk->setVisible(object->getObjectType()==ObjectType::Database); + begin_of_model_chk->setVisible(object->getObjectType()==ObjectType::Database); protected_obj_frm->setVisible(false); obj_id_lbl->setVisible(false); - obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath(object->getObjectType()))); + obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath(object->getObjectType()))); configureMenus(); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void CustomSQLWidget::applyConfiguration(void) { - if(this->object->getObjectType()==OBJ_DATABASE) + if(this->object->getObjectType()==ObjectType::Database) { dynamic_cast(this->object)->setAppendAtEOD(end_of_model_chk->isChecked()); dynamic_cast(this->object)->setPrependAtBOD(begin_of_model_chk->isChecked()); diff --git a/libpgmodeler_ui/src/customsqlwidget.h b/libpgmodeler_ui/src/customsqlwidget.h index 0cc69627b7..05b0e38a7f 100644 --- a/libpgmodeler_ui/src/customsqlwidget.h +++ b/libpgmodeler_ui/src/customsqlwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -58,7 +58,7 @@ class CustomSQLWidget: public BaseObjectWidget, public Ui::CustomSQLWidget { void configureMenus(void); public: - CustomSQLWidget(QWidget *parent=0); + CustomSQLWidget(QWidget *parent = nullptr); void setAttributes(DatabaseModel *model, BaseObject *object); diff --git a/libpgmodeler_ui/src/databaseexplorerwidget.cpp b/libpgmodeler_ui/src/databaseexplorerwidget.cpp index 1f47174fe2..d581f13e7d 100644 --- a/libpgmodeler_ui/src/databaseexplorerwidget.cpp +++ b/libpgmodeler_ui/src/databaseexplorerwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -23,77 +23,115 @@ #include "snippetsconfigwidget.h" #include "plaintextitemdelegate.h" #include "pgmodeleruins.h" +#include "generalconfigwidget.h" -using namespace ParsersAttributes; - -const QString DatabaseExplorerWidget::DEP_NOT_DEFINED=QString(); -const QString DatabaseExplorerWidget::DEP_NOT_FOUND=QT_TR_NOOP("(not found, OID: %1)"); -const QString DatabaseExplorerWidget::ELEM_SEPARATOR=QString("•"); -const QString DatabaseExplorerWidget::DEFAULT_SOURCE_CODE=QT_TR_NOOP("-- Source code not generated! Hit F7 or middle-click the item to load it. --"); +const QString DatabaseExplorerWidget::DepNotDefined=QString(); +const QString DatabaseExplorerWidget::DepNotFound=QT_TR_NOOP("(not found, OID: %1)"); +const QString DatabaseExplorerWidget::ElemSeparator=QString("•"); +const QString DatabaseExplorerWidget::DefaultSourceCode=QString("-- %1 --").arg(QT_TR_NOOP("Source code not generated! Hit F7 or middle-click the item to load it.")); const attribs_map DatabaseExplorerWidget::attribs_i18n { - {ADMIN_ROLES, QT_TR_NOOP("Admin. roles")}, {ALIGNMENT, QT_TR_NOOP("Alignment")}, {ANALYZE_FUNC, QT_TR_NOOP("Analyze func.")}, - {ARG_COUNT, QT_TR_NOOP("Arg. count")}, {ARG_DEF_COUNT, QT_TR_NOOP("Arg. default count")}, {ARG_DEFAULTS, QT_TR_NOOP("Arg. defaults")}, - {ARG_MODES, QT_TR_NOOP("Arg. modes")}, {ARG_NAMES, QT_TR_NOOP("Arg. names")}, {ARG_TYPES, QT_TR_NOOP("Arg. types")}, - {ATTRIBUTE, QT_TR_NOOP("Attribute")}, {BEHAVIOR_TYPE, QT_TR_NOOP("Behavior type")}, {BY_VALUE, QT_TR_NOOP("By value")}, - {CAST_TYPE, QT_TR_NOOP("Cast type")}, {CATEGORY, QT_TR_NOOP("Category")}, {COLLATABLE, QT_TR_NOOP("Collatable")}, - {COLLATION, QT_TR_NOOP("Collation")}, {COMMENT, QT_TR_NOOP("Comment")}, {COMMUTATOR_OP, QT_TR_NOOP("Commutator Op.")}, - {CONFIGURATION, QT_TR_NOOP("Configuration")}, {CONN_LIMIT, QT_TR_NOOP("Conn. limit")}, {CONSTRAINT, QT_TR_NOOP("Constraint")}, - {CREATEDB, QT_TR_NOOP("Create DB")}, {CREATEROLE, QT_TR_NOOP("Create role")}, {CUR_VERSION, QT_TR_NOOP("Curr. version")}, - {DEFAULT, QT_TR_NOOP("Default")}, {DEFAULT_VALUE, QT_TR_NOOP("Default value")}, {DEFINITION, QT_TR_NOOP("Definition")}, - {DELIMITER, QT_TR_NOOP("Delimiter")}, {DEST_TYPE, QT_TR_NOOP("Dest. type")}, {DIMENSION, QT_TR_NOOP("Dimension")}, - {DIRECTORY, QT_TR_NOOP("Directory")}, {DST_ENCODING, QT_TR_NOOP("Dest. encoding")}, {ELEMENT, QT_TR_NOOP("Element")}, - {ENCODING, QT_TR_NOOP("Encoding")}, {ENCRYPTED, QT_TR_NOOP("Encrypted")}, {ENUMERATIONS, QT_TR_NOOP("Enumerations")}, - {EXECUTION_COST, QT_TR_NOOP("Exec. cost")}, {EXPRESSION, QT_TR_NOOP("Expression")}, {FAMILY, QT_TR_NOOP("Op. family")}, - {FINAL_FUNC, QT_TR_NOOP("Final func.")}, {FUNCTION, QT_TR_NOOP("Function")}, {FUNCTION_TYPE, QT_TR_NOOP("Func. type")}, - {HANDLER_FUNC, QT_TR_NOOP("Handler func.")}, {HANDLES_TYPE, QT_TR_NOOP("Handles type")}, {HASHES, QT_TR_NOOP("Hashes")}, - {INDEX_TYPE, QT_TR_NOOP("Index type")}, {INHERIT, QT_TR_NOOP("Inherit")}, {INITIAL_COND, QT_TR_NOOP("Ini. condition")}, - {INLINE_FUNC, QT_TR_NOOP("Inline func.")}, {INPUT_FUNC, QT_TR_NOOP("Input func.")}, {INTERNAL_LENGTH, QT_TR_NOOP("Internal length")}, - {INTERVAL_TYPE, QT_TR_NOOP("Interval type")}, {IO_CAST, QT_TR_NOOP("I/O cast")}, {JOIN_FUNC, QT_TR_NOOP("Join func.")}, - {LANGUAGE, QT_TR_NOOP("Language")}, {_LC_COLLATE_, QT_TR_NOOP("LC COLLATE")}, {_LC_CTYPE_, QT_TR_NOOP("LC CTYPE")}, - {LEAKPROOF, QT_TR_NOOP("Leak proof")}, {LEFT_TYPE, QT_TR_NOOP("Left type")}, {LENGTH, QT_TR_NOOP("Length")}, - {LIBRARY, QT_TR_NOOP("Library")}, {LOGIN, QT_TR_NOOP("Can login")}, {MATERIALIZED, QT_TR_NOOP("Materialized")}, - {MEMBER_ROLES, QT_TR_NOOP("Member roles")}, {MERGES, QT_TR_NOOP("Merges")}, {NAME, QT_TR_NOOP("Name")}, - {NEGATOR_OP, QT_TR_NOOP("Negator op.")}, {NOT_NULL, QT_TR_NOOP("Not null")}, {OBJECT_TYPE, QT_TR_NOOP("Object type")}, - {OID, QT_TR_NOOP("OID")}, {OIDS, QT_TR_NOOP("With OIDs")}, {OLD_VERSION, QT_TR_NOOP("Old version")}, - {OPERATOR, QT_TR_NOOP("Operator")}, {OPERATOR_FUNC, QT_TR_NOOP("Operator func.")}, {OUTPUT_FUNC, QT_TR_NOOP("Output func.")}, - {OWNER, QT_TR_NOOP("Owner")}, {OWNER_COLUMN, QT_TR_NOOP("Owner column")}, {PARENTS, QT_TR_NOOP("Parents")}, - {PASSWORD, QT_TR_NOOP("Password")}, {PERMISSION, QT_TR_NOOP("Permissions")}, {PRECISION, QT_TR_NOOP("Precision")}, - {PREFERRED, QT_TR_NOOP("Preferred")}, {RANGE_ATTRIBS, QT_TR_NOOP("Range attributes")}, {RECV_FUNC, QT_TR_NOOP("Receive func.")}, - {REF_ROLES, QT_TR_NOOP("Ref. roles")}, {REPLICATION, QT_TR_NOOP("Replication")}, {RESTRICTION_FUNC, QT_TR_NOOP("Restriction func.")}, - {RETURN_TYPE, QT_TR_NOOP("Return type")}, {RETURNS_SETOF, QT_TR_NOOP("Returns SETOF")}, {RIGHT_TYPE, QT_TR_NOOP("Right type")}, - {ROW_AMOUNT, QT_TR_NOOP("Rows amount")}, {SCHEMA, QT_TR_NOOP("Schema")}, {SECURITY_TYPE, QT_TR_NOOP("Security type")}, - {SEND_FUNC, QT_TR_NOOP("Send func.")}, {SORT_OP, QT_TR_NOOP("Sort op.")}, {SOURCE_TYPE, QT_TR_NOOP("Source type")}, - {SRC_ENCODING, QT_TR_NOOP("Src. encoding")}, {STATE_TYPE, QT_TR_NOOP("State type")}, {STORAGE, QT_TR_NOOP("Storage")}, - {SUPERUSER, QT_TR_NOOP("Superuser")}, {TABLESPACE, QT_TR_NOOP("Tablespace")}, {TPMOD_IN_FUNC, QT_TR_NOOP("Type mod. in func.")}, - {TPMOD_OUT_FUNC, QT_TR_NOOP("Type mod. out func.")}, {TRANSITION_FUNC, QT_TR_NOOP("Transition func.")}, {TRUSTED, QT_TR_NOOP("Trusted")}, - {TYPE, QT_TR_NOOP("Type")}, {TYPE_ATTRIBUTE, QT_TR_NOOP("Type attribute")}, {TYPES, QT_TR_NOOP("Types")}, - {UNLOGGED, QT_TR_NOOP("Unlogged")}, {VALIDATOR, QT_TR_NOOP("Validator func.")}, {VALIDITY, QT_TR_NOOP("Validity")}, - {WINDOW_FUNC, QT_TR_NOOP("Windows func.")}, {_FALSE_, QT_TR_NOOP("false")}, {_TRUE_, QT_TR_NOOP("true")}, - {CACHE, QT_TR_NOOP("Cache value")}, {CYCLE, QT_TR_NOOP("Cycle")}, {INCREMENT, QT_TR_NOOP("Increment")}, - {MAX_VALUE, QT_TR_NOOP("Max. value")}, {MIN_VALUE, QT_TR_NOOP("Min. value")}, {START, QT_TR_NOOP("Start value")}, - {LAST_VALUE, QT_TR_NOOP("Last value")}, {SUBTYPE, QT_TR_NOOP("Subtype")}, {OP_CLASS, QT_TR_NOOP("Op. class")}, - {CANONICAL_FUNC, QT_TR_NOOP("Canonical func.")}, {SUBTYPE_DIFF_FUNC, QT_TR_NOOP("Subtype diff func.")}, {CONSTRAINT, QT_TR_NOOP("Constraint")}, - {DEFERRABLE, QT_TR_NOOP("Deferrable")}, {PER_ROW, QT_TR_NOOP("For each row")}, {FIRING_TYPE, QT_TR_NOOP("Firing")}, - {INS_EVENT, QT_TR_NOOP("On insert")}, {DEL_EVENT, QT_TR_NOOP("On delete")}, {UPD_EVENT, QT_TR_NOOP("On update")}, - {TRUNC_EVENT, QT_TR_NOOP("On truncate")}, {ARGUMENTS, QT_TR_NOOP("Arguments")}, {TABLE, QT_TR_NOOP("Table")}, - {TRIGGER_FUNC, QT_TR_NOOP("Trigger func.")}, {COLUMNS, QT_TR_NOOP("Columns")}, {CONDITION, QT_TR_NOOP("Condition")}, - {DEFER_TYPE, QT_TR_NOOP("Deferment")}, {EVENT_TYPE, QT_TR_NOOP("Event")}, {EXEC_TYPE, QT_TR_NOOP("Execution mode")}, - {COMMANDS, QT_TR_NOOP("Commands")}, {POSITION, QT_TR_NOOP("Position")}, {COMPARISON_TYPE, QT_TR_NOOP("Comparison type")}, - {DEL_ACTION, QT_TR_NOOP("On delete")}, {DST_COLUMNS, QT_TR_NOOP("Ref. columns")}, {EXPRESSIONS, QT_TR_NOOP("Expressions")}, - {FACTOR, QT_TR_NOOP("Fill factor")}, {NO_INHERIT, QT_TR_NOOP("No inherit")}, {OP_CLASSES, QT_TR_NOOP("Op. classes")}, - {OPERATORS, QT_TR_NOOP("Operators")}, {REF_TABLE, QT_TR_NOOP("Ref. table")}, {COLUMNS, QT_TR_NOOP("Columns")}, - {UPD_ACTION, QT_TR_NOOP("On update")}, {SRC_COLUMNS, QT_TR_NOOP("Columns")}, {UNIQUE, QT_TR_NOOP("Unique")}, - {PREDICATE, QT_TR_NOOP("Predicate")}, {COLLATIONS, QT_TR_NOOP("Collations")}, {INHERITED, QT_TR_NOOP("Inherited")}, - {CLIENT_ENCODING, QT_TR_NOOP("Client encoding")}, {CONFIG_FILE, QT_TR_NOOP("Configuration file")}, {DATA_DIRECTORY, QT_TR_NOOP("Data directory")}, - {DYNAMIC_LIBRARY_PATH, QT_TR_NOOP("Dynamic library path")}, {DYNAMIC_SHARED_MEMORY, QT_TR_NOOP("Dynamic shared memory")}, {HBA_FILE, QT_TR_NOOP("Hba file")}, - {LISTEN_ADDRESSES, QT_TR_NOOP("Listen addresses")}, {MAX_CONNECTIONS, QT_TR_NOOP("Max. connections")}, {PORT, QT_TR_NOOP("Listen port")}, - {SERVER_ENCODING, QT_TR_NOOP("Server encoding")}, {SSL, QT_TR_NOOP("SSL")}, {SSL_CA_FILE, QT_TR_NOOP("SSL ca file")}, - {SSL_CERT_FILE, QT_TR_NOOP("SSL cert file")}, {SSL_CRL_FILE, QT_TR_NOOP("SSL crl file")}, {SSL_KEY_FILE, QT_TR_NOOP("SSL key file")}, - {SERVER_VERSION, QT_TR_NOOP("Server version")}, {IDENT_FILE, QT_TR_NOOP("Ident file")}, {PASSWORD_ENCRYPTION, QT_TR_NOOP("Password encryption")}, - {CONNECTION, QT_TR_NOOP("Connection ID")}, {SERVER_PID, QT_TR_NOOP("Server PID")}, {SERVER_PROTOCOL, QT_TR_NOOP("Server protocol")}, - {REFERRERS, QT_TR_NOOP("Referrers")}, {IDENTITY_TYPE, QT_TR_NOOP("Identity")}, {COMMAND, QT_TR_NOOP("Command")}, - {USING_EXP, QT_TR_NOOP("USING expr.")}, {CHECK_EXP, QT_TR_NOOP("CHECK expr.")}, {ROLES, QT_TR_NOOP("Roles")} + {Attributes::AdminRoles, QT_TR_NOOP("Admin. roles")}, {Attributes::Alignment, QT_TR_NOOP("Alignment")}, + {Attributes::AnalyzeFunc, QT_TR_NOOP("Analyze func.")}, {Attributes::ArgCount, QT_TR_NOOP("Arg. count")}, + {Attributes::ArgDefCount, QT_TR_NOOP("Arg. default count")}, {Attributes::ArgDefaults, QT_TR_NOOP("Arg. defaults")}, + {Attributes::ArgModes, QT_TR_NOOP("Arg. modes")}, {Attributes::ArgNames, QT_TR_NOOP("Arg. names")}, + {Attributes::ArgTypes, QT_TR_NOOP("Arg. types")}, {Attributes::Attribute, QT_TR_NOOP("Attribute")}, + {Attributes::BehaviorType, QT_TR_NOOP("Behavior type")}, {Attributes::ByValue, QT_TR_NOOP("By value")}, + {Attributes::CastType, QT_TR_NOOP("Cast type")}, {Attributes::Category, QT_TR_NOOP("Category")}, + {Attributes::Collatable, QT_TR_NOOP("Collatable")}, {Attributes::Collation, QT_TR_NOOP("Collation")}, + {Attributes::Comment, QT_TR_NOOP("Comment")}, {Attributes::CommutatorOp, QT_TR_NOOP("Commutator Op.")}, + {Attributes::Configuration, QT_TR_NOOP("Configuration")}, {Attributes::ConnLimit, QT_TR_NOOP("Conn. limit")}, + {Attributes::Constraint, QT_TR_NOOP("Constraint")}, {Attributes::CreateDb, QT_TR_NOOP("Create DB")}, + {Attributes::CreateRole, QT_TR_NOOP("Create role")}, {Attributes::CurVersion, QT_TR_NOOP("Curr. version")}, + {Attributes::Default, QT_TR_NOOP("Default")}, {Attributes::DefaultValue, QT_TR_NOOP("Default value")}, + {Attributes::Definition, QT_TR_NOOP("Definition")}, {Attributes::Delimiter, QT_TR_NOOP("Delimiter")}, + {Attributes::DestType, QT_TR_NOOP("Dest. type")}, {Attributes::Dimension, QT_TR_NOOP("Dimension")}, + {Attributes::Directory, QT_TR_NOOP("Directory")}, {Attributes::DstEncoding, QT_TR_NOOP("Dest. encoding")}, + {Attributes::Element, QT_TR_NOOP("Element")}, {Attributes::Encoding, QT_TR_NOOP("Encoding")}, + {Attributes::Encrypted, QT_TR_NOOP("Encrypted")}, {Attributes::Enumerations, QT_TR_NOOP("Enumerations")}, + {Attributes::ExecutionCost, QT_TR_NOOP("Exec. cost")}, {Attributes::Expression, QT_TR_NOOP("Expression")}, + {Attributes::Family, QT_TR_NOOP("Op. family")}, {Attributes::FinalFunc, QT_TR_NOOP("Final func.")}, + {Attributes::Function, QT_TR_NOOP("Function")}, {Attributes::FunctionType, QT_TR_NOOP("Func. type")}, + {Attributes::HandlerFunc, QT_TR_NOOP("Handler func.")}, {Attributes::HandlesType, QT_TR_NOOP("Handles type")}, + {Attributes::Hashes, QT_TR_NOOP("Hashes")}, {Attributes::IndexType, QT_TR_NOOP("Index type")}, + {Attributes::Inherit, QT_TR_NOOP("Inherit")}, {Attributes::InitialCond, QT_TR_NOOP("Ini. condition")}, + {Attributes::InlineFunc, QT_TR_NOOP("Inline func.")}, {Attributes::InputFunc, QT_TR_NOOP("Input func.")}, + {Attributes::InternalLength, QT_TR_NOOP("Internal length")}, {Attributes::IntervalType, QT_TR_NOOP("Interval type")}, + {Attributes::IoCast, QT_TR_NOOP("I/O cast")}, {Attributes::JoinFunc, QT_TR_NOOP("Join func.")}, + {Attributes::Language, QT_TR_NOOP("Language")}, {Attributes::LcCollate, QT_TR_NOOP("LC COLLATE")}, + {Attributes::LcCtype, QT_TR_NOOP("LC CTYPE")}, {Attributes::LeakProof, QT_TR_NOOP("Leak proof")}, + {Attributes::LeftType, QT_TR_NOOP("Left type")}, {Attributes::Length, QT_TR_NOOP("Length")}, + {Attributes::Library, QT_TR_NOOP("Library")}, {Attributes::Login, QT_TR_NOOP("Can login")}, + {Attributes::Materialized, QT_TR_NOOP("Materialized")}, {Attributes::MemberRoles, QT_TR_NOOP("Member roles")}, + {Attributes::Merges, QT_TR_NOOP("Merges")}, {Attributes::Name, QT_TR_NOOP("Name")}, + {Attributes::NegatorOp, QT_TR_NOOP("Negator op.")}, {Attributes::NotNull, QT_TR_NOOP("Not null")}, + {Attributes::ObjectType, QT_TR_NOOP("Object type")}, {Attributes::Oid, QT_TR_NOOP("OID")}, + {Attributes::Oids, QT_TR_NOOP("With OIDs")}, {Attributes::OldVersion, QT_TR_NOOP("Old version")}, + {Attributes::Operator, QT_TR_NOOP("Operator")}, {Attributes::OperatorFunc, QT_TR_NOOP("Operator func.")}, + {Attributes::OutputFunc, QT_TR_NOOP("Output func.")}, {Attributes::Owner, QT_TR_NOOP("Owner")}, + {Attributes::OwnerColumn, QT_TR_NOOP("Owner column")}, {Attributes::Parents, QT_TR_NOOP("Parents")}, + {Attributes::Password, QT_TR_NOOP("Password")}, {Attributes::Permission, QT_TR_NOOP("Permissions")}, + {Attributes::Precision, QT_TR_NOOP("Precision")}, {Attributes::Preferred, QT_TR_NOOP("Preferred")}, + {Attributes::RangeAttribs, QT_TR_NOOP("Range attributes")}, {Attributes::RecvFunc, QT_TR_NOOP("Receive func.")}, + {Attributes::RefRoles, QT_TR_NOOP("Ref. roles")}, {Attributes::Replication, QT_TR_NOOP("Replication")}, + {Attributes::RestrictionFunc, QT_TR_NOOP("Restriction func.")}, {Attributes::ReturnType, QT_TR_NOOP("Return type")}, + {Attributes::ReturnsSetOf, QT_TR_NOOP("Returns SETOF")}, {Attributes::RightType, QT_TR_NOOP("Right type")}, + {Attributes::RowAmount, QT_TR_NOOP("Rows amount")}, {Attributes::Schema, QT_TR_NOOP("Schema")}, + {Attributes::SecurityType, QT_TR_NOOP("Security type")}, {Attributes::SendFunc, QT_TR_NOOP("Send func.")}, + {Attributes::SortOp, QT_TR_NOOP("Sort op.")}, {Attributes::SourceType, QT_TR_NOOP("Source type")}, + {Attributes::SrcEncoding, QT_TR_NOOP("Src. encoding")}, {Attributes::StateType, QT_TR_NOOP("State type")}, + {Attributes::Storage, QT_TR_NOOP("Storage")}, {Attributes::Superuser, QT_TR_NOOP("Superuser")}, + {Attributes::Tablespace, QT_TR_NOOP("Tablespace")}, {Attributes::TpmodInFunc, QT_TR_NOOP("Type mod. in func.")}, + {Attributes::TpmodOutFunc, QT_TR_NOOP("Type mod. out func.")}, {Attributes::TransitionFunc, QT_TR_NOOP("Transition func.")}, + {Attributes::Trusted, QT_TR_NOOP("Trusted")}, {Attributes::Type, QT_TR_NOOP("Type")}, + {Attributes::TypeAttribute, QT_TR_NOOP("Type attribute")}, {Attributes::Types, QT_TR_NOOP("Types")}, + {Attributes::Unlogged, QT_TR_NOOP("Unlogged")}, {Attributes::Validator, QT_TR_NOOP("Validator func.")}, + {Attributes::Validity, QT_TR_NOOP("Validity")}, {Attributes::WindowFunc, QT_TR_NOOP("Windows func.")}, + {Attributes::False, QT_TR_NOOP("false")}, {Attributes::True, QT_TR_NOOP("true")}, + {Attributes::Cache, QT_TR_NOOP("Cache value")}, {Attributes::Cycle, QT_TR_NOOP("Cycle")}, + {Attributes::Increment, QT_TR_NOOP("Increment")}, {Attributes::MaxValue, QT_TR_NOOP("Max. value")}, + {Attributes::MinValue, QT_TR_NOOP("Min. value")}, {Attributes::Start, QT_TR_NOOP("Start value")}, + {Attributes::LastValue, QT_TR_NOOP("Last value")}, {Attributes::Subtype, QT_TR_NOOP("Subtype")}, + {Attributes::OpClass, QT_TR_NOOP("Op. class")}, {Attributes::CanonicalFunc, QT_TR_NOOP("Canonical func.")}, + {Attributes::SubtypeDiffFunc, QT_TR_NOOP("Subtype diff func.")}, {Attributes::Deferrable, QT_TR_NOOP("Deferrable")}, + {Attributes::PerRow, QT_TR_NOOP("For each row")}, {Attributes::FiringType, QT_TR_NOOP("Firing")}, + {Attributes::InsEvent, QT_TR_NOOP("On insert")}, {Attributes::DelEvent, QT_TR_NOOP("On delete")}, + {Attributes::UpdEvent, QT_TR_NOOP("On update")}, {Attributes::TruncEvent, QT_TR_NOOP("On truncate")}, + {Attributes::Arguments, QT_TR_NOOP("Arguments")}, {Attributes::Table, QT_TR_NOOP("Table")}, + {Attributes::TriggerFunc, QT_TR_NOOP("Trigger func.")}, {Attributes::Columns, QT_TR_NOOP("Columns")}, + {Attributes::Condition, QT_TR_NOOP("Condition")}, {Attributes::DeferType, QT_TR_NOOP("Deferment")}, + {Attributes::EventType, QT_TR_NOOP("Event")}, {Attributes::ExecType, QT_TR_NOOP("Execution mode")}, + {Attributes::Commands, QT_TR_NOOP("Commands")}, {Attributes::Position, QT_TR_NOOP("Position")}, + {Attributes::ComparisonType, QT_TR_NOOP("Comparison type")}, {Attributes::DelAction, QT_TR_NOOP("On delete")}, + {Attributes::DstColumns, QT_TR_NOOP("Ref. columns")}, {Attributes::Expressions, QT_TR_NOOP("Expressions")}, + {Attributes::Factor, QT_TR_NOOP("Fill factor")}, {Attributes::NoInherit, QT_TR_NOOP("No inherit")}, + {Attributes::OpClasses, QT_TR_NOOP("Op. classes")}, {Attributes::Operators, QT_TR_NOOP("Operators")}, + {Attributes::RefTable, QT_TR_NOOP("Ref. table")}, {Attributes::Columns, QT_TR_NOOP("Columns")}, + {Attributes::UpdAction, QT_TR_NOOP("On update")}, {Attributes::SrcColumns, QT_TR_NOOP("Columns")}, + {Attributes::Unique, QT_TR_NOOP("Unique")}, {Attributes::Predicate, QT_TR_NOOP("Predicate")}, + {Attributes::Collations, QT_TR_NOOP("Collations")}, {Attributes::Inherited, QT_TR_NOOP("Inherited")}, + {Attributes::ClientEncoding, QT_TR_NOOP("Client encoding")}, {Attributes::ConfigFile, QT_TR_NOOP("Configuration file")}, + {Attributes::DataDirectory, QT_TR_NOOP("Data directory")}, {Attributes::DynamicLibraryPath, QT_TR_NOOP("Dynamic library path")}, + {Attributes::DynamicSharedMemory, QT_TR_NOOP("Dynamic shared memory")}, {Attributes::HbaFile, QT_TR_NOOP("Hba file")}, + {Attributes::ListenAddresses, QT_TR_NOOP("Listen addresses")}, {Attributes::MaxConnections, QT_TR_NOOP("Max. connections")}, + {Attributes::Port, QT_TR_NOOP("Listen port")}, {Attributes::ServerEncoding, QT_TR_NOOP("Server encoding")}, + {Attributes::Ssl, QT_TR_NOOP("SSL")}, {Attributes::SslCaFile, QT_TR_NOOP("SSL ca file")}, + {Attributes::SslCertFile, QT_TR_NOOP("SSL cert file")}, {Attributes::SslCrlFile, QT_TR_NOOP("SSL crl file")}, + {Attributes::SslKeyFile, QT_TR_NOOP("SSL key file")}, {Attributes::ServerVersion, QT_TR_NOOP("Server version")}, + {Attributes::IdentFile, QT_TR_NOOP("Ident file")}, {Attributes::PasswordEncryption, QT_TR_NOOP("Password encryption")}, + {Attributes::Connection, QT_TR_NOOP("Connection ID")}, {Attributes::ServerPid, QT_TR_NOOP("Server PID")}, + {Attributes::ServerProtocol, QT_TR_NOOP("Server protocol")}, {Attributes::Referrers, QT_TR_NOOP("Referrers")}, + {Attributes::IdentityType, QT_TR_NOOP("Identity")}, {Attributes::Command, QT_TR_NOOP("Command")}, + {Attributes::UsingExp, QT_TR_NOOP("USING expr.")}, {Attributes::CheckExp, QT_TR_NOOP("CHECK expr.")}, + {Attributes::Roles, QT_TR_NOOP("Roles")}, {Attributes::RlsEnabled, QT_TR_NOOP("RLS enabled")}, + {Attributes::RlsForced, QT_TR_NOOP("RLS forced")}, {Attributes::LastAnalyze, QT_TR_NOOP("Last analyze")}, + {Attributes::LastAutovacuum, QT_TR_NOOP("Last autovacuum")}, {Attributes::LastVacuum, QT_TR_NOOP("Last vacuum")}, + {Attributes::TuplesDel, QT_TR_NOOP("Tuples deleted")}, {Attributes::TyplesUpd, QT_TR_NOOP("Tuples updated")}, + {Attributes::TuplesIns, QT_TR_NOOP("Tuples inserted")}, {Attributes::IsPartitioned, QT_TR_NOOP("Partitioned")}, + {Attributes::PartitionedTable, QT_TR_NOOP("Partition of")}, {Attributes::PartitionBoundExpr, QT_TR_NOOP("Partition bound expr.")}, + {Attributes::DeadRowsAmount, QT_TR_NOOP("Dead rows amount")}, {Attributes::PartitionKey, QT_TR_NOOP("Partition keys")}, + {Attributes::Partitioning, QT_TR_NOOP("Partitioning")}, {Attributes::Options, QT_TR_NOOP("Options")}, + {Attributes::Fdw, QT_TR_NOOP("Foreign data wrapper")}, {Attributes::Server, QT_TR_NOOP("Server")} }; DatabaseExplorerWidget::DatabaseExplorerWidget(QWidget *parent): QWidget(parent) @@ -110,7 +148,6 @@ DatabaseExplorerWidget::DatabaseExplorerWidget(QWidget *parent): QWidget(parent) data_grid_tb->setToolTip(data_grid_tb->toolTip() + QString(" (%1)").arg(data_grid_tb->shortcut().toString())); runsql_tb->setToolTip(runsql_tb->toolTip() + QString(" (%1)").arg(runsql_tb->shortcut().toString())); - refresh_tb->setToolTip(refresh_tb->toolTip() + QString(" (%1)").arg(refresh_tb->shortcut().toString())); QAction *act = nullptr; @@ -147,7 +184,7 @@ DatabaseExplorerWidget::DatabaseExplorerWidget(QWidget *parent): QWidget(parent) properties_action=new QAction(QIcon(QString(":icones/icones/editar.png")), trUtf8("Reload properties"), &handle_menu); refresh_action=new QAction(QIcon(QString(":icones/icones/atualizar.png")), trUtf8("Update"), &handle_menu); - refresh_action->setShortcut(QKeySequence(Qt::Key_F5)); + refresh_action->setShortcut(QKeySequence(Qt::Key_F6)); rename_action=new QAction(QIcon(QString(":icones/icones/rename.png")), trUtf8("Rename"), &handle_menu); rename_action->setShortcut(QKeySequence(Qt::Key_F2)); @@ -187,10 +224,10 @@ DatabaseExplorerWidget::DatabaseExplorerWidget(QWidget *parent): QWidget(parent) connect(objects_trw, &QTreeWidget::itemExpanded, [&](QTreeWidgetItem *item){ - ObjectType obj_type=static_cast(item->data(DatabaseImportForm::OBJECT_TYPE, Qt::UserRole).toUInt()); - unsigned oid=item->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toUInt(); + ObjectType obj_type=static_cast(item->data(DatabaseImportForm::ObjectTypeId, Qt::UserRole).toUInt()); + unsigned oid=item->data(DatabaseImportForm::ObjectId, Qt::UserRole).toUInt(); - if((obj_type==OBJ_SCHEMA || obj_type==OBJ_TABLE || obj_type==OBJ_VIEW) && oid > 0 && item->childCount() <= 1) + if((obj_type==ObjectType::Schema || obj_type==ObjectType::Table || obj_type==ObjectType::View) && oid > 0 && item->childCount() <= 1) { updateItem(item); } @@ -198,7 +235,7 @@ DatabaseExplorerWidget::DatabaseExplorerWidget(QWidget *parent): QWidget(parent) connect(sort_by_name_tb, &QToolButton::clicked, [&]() { - sort_column = sort_by_name_tb->isChecked() ? 0 : DatabaseImportForm::OBJECT_ID; + sort_column = sort_by_name_tb->isChecked() ? 0 : DatabaseImportForm::ObjectId; objects_trw->sortByColumn(sort_column); }); @@ -223,7 +260,7 @@ bool DatabaseExplorerWidget::eventFilter(QObject *object, QEvent *event) { QKeyEvent *k_event=dynamic_cast(event); - if(k_event->key()==Qt::Key_Delete || k_event->key()==Qt::Key_F5 || + if(k_event->key()==Qt::Key_Delete || k_event->key()==Qt::Key_F6 || k_event->key()==Qt::Key_Space || k_event->key()==Qt::Key_F2 || k_event->key()==Qt::Key_Escape || k_event->key()==Qt::Key_Return || k_event->key()==Qt::Key_Enter || k_event->key()==Qt::Key_F7) @@ -231,21 +268,21 @@ bool DatabaseExplorerWidget::eventFilter(QObject *object, QEvent *event) if(k_event->key()==Qt::Key_Space) { QTreeWidgetItem *item=objects_trw->currentItem(); - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; if(item) { - unsigned oid=item->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toUInt(); - obj_type=static_cast(item->data(DatabaseImportForm::OBJECT_TYPE, Qt::UserRole).toUInt()); + unsigned oid=item->data(DatabaseImportForm::ObjectId, Qt::UserRole).toUInt(); + obj_type=static_cast(item->data(DatabaseImportForm::ObjectTypeId, Qt::UserRole).toUInt()); - if(oid!=0 && (obj_type==OBJ_TABLE || obj_type==OBJ_VIEW)) + if(oid!=0 && (obj_type==ObjectType::Table || obj_type==ObjectType::View)) { - openDataGrid(item->data(DatabaseImportForm::OBJECT_SCHEMA, Qt::UserRole).toString(), - item->text(0), obj_type!=OBJ_VIEW); + openDataGrid(item->data(DatabaseImportForm::ObjectSchema, Qt::UserRole).toString(), + item->text(0), obj_type!=ObjectType::View); } } } - else if(k_event->key()==Qt::Key_F5) + else if(k_event->key()==Qt::Key_F6) updateItem(objects_trw->currentItem()); else if(k_event->key()==Qt::Key_F2) startObjectRename(objects_trw->currentItem()); @@ -269,44 +306,47 @@ bool DatabaseExplorerWidget::eventFilter(QObject *object, QEvent *event) attribs_map DatabaseExplorerWidget::formatObjectAttribs(attribs_map &attribs) { - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; attribs_map fmt_attribs; QString attr_name, attr_value; QRegExp oid_regexp=QRegExp(QString("^[0-9]+")); - map dep_types={{ParsersAttributes::OWNER, OBJ_ROLE}, - {ParsersAttributes::SCHEMA, OBJ_SCHEMA}, - {ParsersAttributes::TABLESPACE, OBJ_TABLESPACE}, - {ParsersAttributes::COLLATION, OBJ_COLLATION}, - {ParsersAttributes::TABLE, OBJ_TABLE}}; + map dep_types={{Attributes::Owner, ObjectType::Role}, + {Attributes::Schema, ObjectType::Schema}, + {Attributes::Tablespace, ObjectType::Tablespace}, + {Attributes::Collation, ObjectType::Collation}, + {Attributes::Table, ObjectType::Table}}; - if(attribs.count(ParsersAttributes::OBJECT_TYPE)!=0) - obj_type=static_cast(attribs[ParsersAttributes::OBJECT_TYPE].toUInt()); + if(attribs.count(Attributes::ObjectType)!=0) + obj_type=static_cast(attribs[Attributes::ObjectType].toUInt()); try { switch(obj_type) { - case OBJ_CAST: formatCastAttribs(attribs); break; - case OBJ_EVENT_TRIGGER: formatEventTriggerAttribs(attribs); break; - case OBJ_LANGUAGE: formatLanguageAttribs(attribs); break; - case OBJ_ROLE: formatRoleAttribs(attribs); break; - case OBJ_AGGREGATE: formatAggregateAttribs(attribs); break; - case OBJ_CONVERSION: formatConversionAttribs(attribs); break; - case OBJ_DOMAIN: formatDomainAttribs(attribs); break; - case OBJ_EXTENSION: formatExtensionAttribs(attribs); break; - case OBJ_FUNCTION: formatFunctionAttribs(attribs); break; - case OBJ_OPERATOR: formatOperatorAttribs(attribs); break; - case OBJ_OPCLASS: formatOperatorClassAttribs(attribs); break; - case OBJ_TABLE: formatTableAttribs(attribs); break; - case OBJ_SEQUENCE: formatSequenceAttribs(attribs); break; - case OBJ_TYPE: formatTypeAttribs(attribs); break; - case OBJ_VIEW: formatViewAttribs(attribs); break; - case OBJ_TRIGGER: formatTriggerAttribs(attribs); break; - case OBJ_RULE: formatRuleAttribs(attribs); break; - case OBJ_COLUMN: formatColumnAttribs(attribs); break; - case OBJ_CONSTRAINT: formatConstraintAttribs(attribs); break; - case OBJ_INDEX: formatIndexAttribs(attribs); break; - case OBJ_POLICY: formatPolicyAttribs(attribs); break; + case ObjectType::Cast: formatCastAttribs(attribs); break; + case ObjectType::EventTrigger: formatEventTriggerAttribs(attribs); break; + case ObjectType::Language: formatLanguageAttribs(attribs); break; + case ObjectType::Role: formatRoleAttribs(attribs); break; + case ObjectType::Aggregate: formatAggregateAttribs(attribs); break; + case ObjectType::Conversion: formatConversionAttribs(attribs); break; + case ObjectType::Domain: formatDomainAttribs(attribs); break; + case ObjectType::Extension: formatExtensionAttribs(attribs); break; + case ObjectType::Function: formatFunctionAttribs(attribs); break; + case ObjectType::Operator: formatOperatorAttribs(attribs); break; + case ObjectType::OpClass: formatOperatorClassAttribs(attribs); break; + case ObjectType::Table: formatTableAttribs(attribs); break; + case ObjectType::Sequence: formatSequenceAttribs(attribs); break; + case ObjectType::Type: formatTypeAttribs(attribs); break; + case ObjectType::View: formatViewAttribs(attribs); break; + case ObjectType::Trigger: formatTriggerAttribs(attribs); break; + case ObjectType::Rule: formatRuleAttribs(attribs); break; + case ObjectType::Column: formatColumnAttribs(attribs); break; + case ObjectType::Constraint: formatConstraintAttribs(attribs); break; + case ObjectType::Index: formatIndexAttribs(attribs); break; + case ObjectType::Policy: formatPolicyAttribs(attribs); break; + case ObjectType::ForeignDataWrapper: formatForeignDataWrapperAttribs(attribs); break; + case ObjectType::ForeignServer: formatServerAttribs(attribs); break; + case ObjectType::UserMapping: formatUserMappingAttribs(attribs); break; default: break; } } @@ -317,21 +357,21 @@ attribs_map DatabaseExplorerWidget::formatObjectAttribs(attribs_map &attribs) } - if(attribs.count(ParsersAttributes::PERMISSION)!=0) - attribs[ParsersAttributes::PERMISSION]=Catalog::parseArrayValues(attribs[ParsersAttributes::PERMISSION]).join(ELEM_SEPARATOR); + if(attribs.count(Attributes::Permission)!=0) + attribs[Attributes::Permission]=Catalog::parseArrayValues(attribs[Attributes::Permission]).join(ElemSeparator); //Removing system schemas from object's name - if(attribs.count(ParsersAttributes::NAME)!=0 && - (attribs[ParsersAttributes::NAME].startsWith(QString("pg_catalog.")) || - attribs[ParsersAttributes::NAME].startsWith(QString("information_schema.")))) - attribs[ParsersAttributes::NAME]=attribs[ParsersAttributes::NAME].split('.').at(1); + if(attribs.count(Attributes::Name)!=0 && + (attribs[Attributes::Name].startsWith(QString("pg_catalog.")) || + attribs[Attributes::Name].startsWith(QString("information_schema.")))) + attribs[Attributes::Name]=attribs[Attributes::Name].split('.').at(1); for(auto &attrib : attribs) { attr_name=attrib.first; attr_value=attrib.second; - if(attr_name==ParsersAttributes::OBJECT_TYPE) + if(attr_name==Attributes::ObjectType) attr_value=BaseObject::getTypeName(static_cast(attr_value.toUInt())); //If the current attribute is related to a dependency object, retreive its real name @@ -347,18 +387,18 @@ attribs_map DatabaseExplorerWidget::formatObjectAttribs(attribs_map &attribs) fmt_attribs[attr_name]=attr_value; } - if(attribs[ParsersAttributes::OID].toUInt() > 0) + if(attribs[Attributes::Oid].toUInt() > 0) { - attribs[ParsersAttributes::SQL_OBJECT]=BaseObject::getSQLName(obj_type); - attribs[ParsersAttributes::OBJECT_TYPE]=BaseObject::getSchemaName(obj_type); + attribs[Attributes::SqlObject]=BaseObject::getSQLName(obj_type); + attribs[Attributes::ObjectType]=BaseObject::getSchemaName(obj_type); - if(attribs.count(ParsersAttributes::SIGNATURE)==0) - attribs[ParsersAttributes::SIGNATURE]=BaseObject::formatName(attribs[ParsersAttributes::NAME]); + if(attribs.count(Attributes::Signature)==0) + attribs[Attributes::Signature]=BaseObject::formatName(attribs[Attributes::Name]); - if(attribs.count(ParsersAttributes::SCHEMA)!=0) - attribs[ParsersAttributes::SIGNATURE]=QString("%1.%2") - .arg(BaseObject::formatName(attribs[ParsersAttributes::SCHEMA])) - .arg(attribs[ParsersAttributes::SIGNATURE]); + if(attribs.count(Attributes::Schema)!=0) + attribs[Attributes::Signature]=QString("%1.%2") + .arg(BaseObject::formatName(attribs[Attributes::Schema])) + .arg(attribs[Attributes::Signature]); } return(fmt_attribs); @@ -368,8 +408,8 @@ void DatabaseExplorerWidget::formatBooleanAttribs(attribs_map &attribs, QStringL { for(QString attr : bool_attrs) attribs[attr]=(attribs[attr].isEmpty() ? - attribs_i18n.at(ParsersAttributes::_FALSE_) : - attribs_i18n.at(ParsersAttributes::_TRUE_)); + attribs_i18n.at(Attributes::False) : + attribs_i18n.at(Attributes::True)); } void DatabaseExplorerWidget::formatOidAttribs(attribs_map &attribs, QStringList oid_attrs, ObjectType obj_type, bool is_oid_array) @@ -388,155 +428,178 @@ void DatabaseExplorerWidget::formatOidAttribs(attribs_map &attribs, QStringList for(QString attr : oid_attrs) { names=getObjectsNames(obj_type, Catalog::parseArrayValues(attribs[attr])); - attribs[attr]=names.join(ELEM_SEPARATOR); + attribs[attr]=names.join(ElemSeparator); } } } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } void DatabaseExplorerWidget::formatCastAttribs(attribs_map &attribs) { - formatBooleanAttribs(attribs, { ParsersAttributes::IO_CAST }); + formatBooleanAttribs(attribs, { Attributes::IoCast }); - formatOidAttribs(attribs, { ParsersAttributes::DEST_TYPE, - ParsersAttributes::SOURCE_TYPE }, OBJ_TYPE, false); + formatOidAttribs(attribs, { Attributes::DestType, + Attributes::SourceType }, ObjectType::Type, false); - attribs[ParsersAttributes::FUNCTION]=getObjectName(OBJ_FUNCTION, attribs[ParsersAttributes::FUNCTION]); + attribs[Attributes::Function]=getObjectName(ObjectType::Function, attribs[Attributes::Function]); } void DatabaseExplorerWidget::formatEventTriggerAttribs(attribs_map &attribs) { - attribs[ParsersAttributes::VALUES]=Catalog::parseArrayValues(attribs[ParsersAttributes::VALUES]).join(ELEM_SEPARATOR); - attribs[ParsersAttributes::FUNCTION]=getObjectName(OBJ_FUNCTION, attribs[ParsersAttributes::FUNCTION]); + attribs[Attributes::Values]=Catalog::parseArrayValues(attribs[Attributes::Values]).join(ElemSeparator); + attribs[Attributes::Function]=getObjectName(ObjectType::Function, attribs[Attributes::Function]); } void DatabaseExplorerWidget::formatAggregateAttribs(attribs_map &attribs) { - formatOidAttribs(attribs, { ParsersAttributes::FINAL_FUNC, - ParsersAttributes::TRANSITION_FUNC }, OBJ_FUNCTION, false); + formatOidAttribs(attribs, { Attributes::FinalFunc, + Attributes::TransitionFunc }, ObjectType::Function, false); - formatOidAttribs(attribs, { ParsersAttributes::TYPES }, OBJ_TYPE, true); - attribs[ParsersAttributes::SIGNATURE]=(QString("%1(%2)") - .arg(BaseObject::formatName(attribs[ParsersAttributes::NAME])) - .arg(attribs[ParsersAttributes::TYPES])).replace(ELEM_SEPARATOR, QString(",")); + formatOidAttribs(attribs, { Attributes::Types }, ObjectType::Type, true); + attribs[Attributes::Signature]=(QString("%1(%2)") + .arg(BaseObject::formatName(attribs[Attributes::Name])) + .arg(attribs[Attributes::Types])).replace(ElemSeparator, QString(",")); - attribs[ParsersAttributes::STATE_TYPE]=getObjectName(OBJ_TYPE, attribs[ParsersAttributes::STATE_TYPE]); - attribs[ParsersAttributes::SORT_OP]=getObjectName(OBJ_OPERATOR, attribs[ParsersAttributes::SORT_OP]); - attribs[ParsersAttributes::INITIAL_COND]=Catalog::parseArrayValues(attribs[ParsersAttributes::INITIAL_COND]).join(ELEM_SEPARATOR); + attribs[Attributes::StateType]=getObjectName(ObjectType::Type, attribs[Attributes::StateType]); + attribs[Attributes::SortOp]=getObjectName(ObjectType::Operator, attribs[Attributes::SortOp]); + attribs[Attributes::InitialCond]=Catalog::parseArrayValues(attribs[Attributes::InitialCond]).join(ElemSeparator); } void DatabaseExplorerWidget::formatLanguageAttribs(attribs_map &attribs) { - formatBooleanAttribs(attribs, { ParsersAttributes::TRUSTED }); - - formatOidAttribs(attribs, { ParsersAttributes::VALIDATOR_FUNC, - ParsersAttributes::HANDLER_FUNC, - ParsersAttributes::INLINE_FUNC }, OBJ_FUNCTION, false); + formatBooleanAttribs(attribs, { Attributes::Trusted }); + formatOidAttribs(attribs, { Attributes::ValidatorFunc, + Attributes::HandlerFunc, + Attributes::InlineFunc }, ObjectType::Function, false); } void DatabaseExplorerWidget::formatRoleAttribs(attribs_map &attribs) { - formatOidAttribs(attribs, { ParsersAttributes::ADMIN_ROLES, - ParsersAttributes::MEMBER_ROLES, - ParsersAttributes::REF_ROLES }, OBJ_ROLE, true); - - formatBooleanAttribs(attribs, { ParsersAttributes::SUPERUSER, ParsersAttributes::INHERIT, - ParsersAttributes::CREATEROLE, ParsersAttributes::CREATEDB, - ParsersAttributes::LOGIN, ParsersAttributes::ENCRYPTED, - ParsersAttributes::REPLICATION }); + formatOidAttribs(attribs, { Attributes::AdminRoles, + Attributes::MemberRoles, + Attributes::RefRoles }, ObjectType::Role, true); + + formatBooleanAttribs(attribs, { Attributes::Superuser, Attributes::Inherit, + Attributes::CreateRole, Attributes::CreateDb, + Attributes::Login, Attributes::Encrypted, + Attributes::Replication }); } void DatabaseExplorerWidget::formatConversionAttribs(attribs_map &attribs) { - formatBooleanAttribs(attribs, { ParsersAttributes::DEFAULT }); - attribs[ParsersAttributes::FUNCTION]=getObjectName(OBJ_FUNCTION, attribs[ParsersAttributes::FUNCTION]); + formatBooleanAttribs(attribs, { Attributes::Default }); + attribs[Attributes::Function]=getObjectName(ObjectType::Function, attribs[Attributes::Function]); } void DatabaseExplorerWidget::formatDomainAttribs(attribs_map &attribs) { - formatBooleanAttribs(attribs, { ParsersAttributes::NOT_NULL }); - attribs[ParsersAttributes::TYPE]=getObjectName(OBJ_TYPE, attribs[ParsersAttributes::TYPE]); + QStringList contrs = Catalog::parseArrayValues(attribs[Attributes::Constraints]); + + contrs.replaceInStrings(Table::DataSeparator, QChar(':')); + attribs[Attributes::Constraints] = contrs.join(Table::DataSeparator); + + formatBooleanAttribs(attribs, { Attributes::NotNull }); + attribs[Attributes::Type]=getObjectName(ObjectType::Type, attribs[Attributes::Type]); } void DatabaseExplorerWidget::formatExtensionAttribs(attribs_map &attribs) { - formatBooleanAttribs(attribs, { ParsersAttributes::HANDLES_TYPE }); + formatBooleanAttribs(attribs, { Attributes::HandlesType }); } void DatabaseExplorerWidget::formatFunctionAttribs(attribs_map &attribs) { - attribs[ParsersAttributes::LANGUAGE]=getObjectName(OBJ_LANGUAGE, attribs[ParsersAttributes::LANGUAGE]); - attribs[ParsersAttributes::RETURN_TYPE]=getObjectName(OBJ_TYPE, attribs[ParsersAttributes::RETURN_TYPE]); - attribs[ParsersAttributes::ARG_NAMES]=Catalog::parseArrayValues(attribs[ParsersAttributes::ARG_NAMES]).join(ELEM_SEPARATOR); - attribs[ParsersAttributes::ARG_MODES]=Catalog::parseArrayValues(attribs[ParsersAttributes::ARG_MODES]).join(ELEM_SEPARATOR); - attribs[ParsersAttributes::ARG_DEFAULTS]=Catalog::parseArrayValues(attribs[ParsersAttributes::ARG_DEFAULTS]).join(ELEM_SEPARATOR); - - formatOidAttribs(attribs, { ParsersAttributes::ARG_TYPES }, OBJ_TYPE, true); - attribs[ParsersAttributes::SIGNATURE]=(QString("%1(%2)") - .arg(BaseObject::formatName(attribs[ParsersAttributes::NAME])) - .arg(attribs[ParsersAttributes::ARG_TYPES])).replace(ELEM_SEPARATOR, QString(",")); - - formatBooleanAttribs(attribs, { ParsersAttributes::WINDOW_FUNC, - ParsersAttributes::LEAKPROOF, - ParsersAttributes::RETURNS_SETOF }); + attribs[Attributes::Language]=getObjectName(ObjectType::Language, attribs[Attributes::Language]); + attribs[Attributes::ReturnType]=getObjectName(ObjectType::Type, attribs[Attributes::ReturnType]); + attribs[Attributes::ArgNames]=Catalog::parseArrayValues(attribs[Attributes::ArgNames]).join(ElemSeparator); + attribs[Attributes::ArgModes]=Catalog::parseArrayValues(attribs[Attributes::ArgModes]).join(ElemSeparator); + attribs[Attributes::ArgDefaults]=Catalog::parseArrayValues(attribs[Attributes::ArgDefaults]).join(ElemSeparator); + + formatOidAttribs(attribs, { Attributes::ArgTypes }, ObjectType::Type, true); + attribs[Attributes::Signature]=(QString("%1(%2)") + .arg(BaseObject::formatName(attribs[Attributes::Name])) + .arg(attribs[Attributes::ArgTypes])).replace(ElemSeparator, QString(",")); + + formatBooleanAttribs(attribs, { Attributes::WindowFunc, + Attributes::LeakProof, + Attributes::ReturnsSetOf }); } void DatabaseExplorerWidget::formatOperatorAttribs(attribs_map &attribs) { - formatBooleanAttribs(attribs, { ParsersAttributes::HASHES, - ParsersAttributes::MERGES }); + formatBooleanAttribs(attribs, { Attributes::Hashes, + Attributes::Merges }); - formatOidAttribs(attribs, { ParsersAttributes::LEFT_TYPE, - ParsersAttributes::RIGHT_TYPE}, OBJ_TYPE, false); + formatOidAttribs(attribs, { Attributes::LeftType, + Attributes::RightType}, ObjectType::Type, false); - formatOidAttribs(attribs, { ParsersAttributes::COMMUTATOR_OP, - ParsersAttributes::NEGATOR_OP}, OBJ_OPERATOR, false); + formatOidAttribs(attribs, { Attributes::CommutatorOp, + Attributes::NegatorOp}, ObjectType::Operator, false); - formatOidAttribs(attribs, { ParsersAttributes::OPERATOR_FUNC, - ParsersAttributes::RESTRICTION_FUNC, - ParsersAttributes::JOIN_FUNC }, OBJ_FUNCTION, false); + formatOidAttribs(attribs, { Attributes::OperatorFunc, + Attributes::RestrictionFunc, + Attributes::JoinFunc }, ObjectType::Function, false); - attribs[ParsersAttributes::SIGNATURE]=(QString("%1(%2,%3)") - .arg(BaseObject::formatName(attribs[ParsersAttributes::NAME], true)) - .arg(attribs[ParsersAttributes::LEFT_TYPE]) - .arg(attribs[ParsersAttributes::RIGHT_TYPE])).replace(ELEM_SEPARATOR, QString(",")); + attribs[Attributes::Signature]=(QString("%1(%2,%3)") + .arg(BaseObject::formatName(attribs[Attributes::Name], true)) + .arg(attribs[Attributes::LeftType]) + .arg(attribs[Attributes::RightType])).replace(ElemSeparator, QString(",")); } void DatabaseExplorerWidget::formatTableAttribs(attribs_map &attribs) { - formatBooleanAttribs(attribs, { ParsersAttributes::OIDS, - ParsersAttributes::UNLOGGED }); + QStringList part_keys; + + formatBooleanAttribs(attribs, { Attributes::Oids, + Attributes::Unlogged, + Attributes::RlsEnabled, + Attributes::RlsForced}); + + formatOidAttribs(attribs, { Attributes::Parents }, ObjectType::Table, true); + formatOidAttribs(attribs, { Attributes::PartitionedTable }, ObjectType::Table, false); + + part_keys.push_back(getObjectsNames(ObjectType::Column, + Catalog::parseArrayValues(attribs[Attributes::PartKeyCols]), + getObjectName(ObjectType::Schema, attribs[Attributes::Schema]), + attribs[Attributes::Name]).join(ElemSeparator)); + + part_keys.push_back(Catalog::parseArrayValues(attribs[Attributes::Expressions]).join(ElemSeparator)); + part_keys.removeAll(QString()); - formatOidAttribs(attribs, { ParsersAttributes::PARENTS }, OBJ_TABLE, true); + attribs[Attributes::PartitionKey] = part_keys.join(ElemSeparator); + attribs.erase(Attributes::PartKeyColls); + attribs.erase(Attributes::PartKeyOpCls); + attribs.erase(Attributes::PartKeyExprs); + attribs.erase(Attributes::PartKeyCols); } void DatabaseExplorerWidget::formatSequenceAttribs(attribs_map &attribs) { QStringList owner_col, - seq_values=Catalog::parseArrayValues(attribs[ParsersAttributes::ATTRIBUTE]), - seq_attrs={ ParsersAttributes::START, ParsersAttributes::MIN_VALUE, - ParsersAttributes::MAX_VALUE, ParsersAttributes::INCREMENT, - ParsersAttributes::CACHE, ParsersAttributes::CYCLE }; - QString sch_name=getObjectName(OBJ_SCHEMA, attribs[ParsersAttributes::SCHEMA]); + seq_values=Catalog::parseArrayValues(attribs[Attributes::Attribute]), + seq_attrs={ Attributes::Start, Attributes::MinValue, + Attributes::MaxValue, Attributes::Increment, + Attributes::Cache, Attributes::Cycle }; + QString sch_name=getObjectName(ObjectType::Schema, attribs[Attributes::Schema]); - attribs.erase(ParsersAttributes::ATTRIBUTE); + attribs.erase(Attributes::Attribute); for(int i=0; i < seq_values.size(); i++) attribs[seq_attrs[i]]=seq_values[i]; - formatBooleanAttribs(attribs, { ParsersAttributes::CYCLE }); + formatBooleanAttribs(attribs, { Attributes::Cycle }); - owner_col=attribs[ParsersAttributes::OWNER_COLUMN].split(':'); + owner_col=attribs[Attributes::OwnerColumn].split(':'); if(owner_col.size()==2) { - QStringList names=getObjectName(OBJ_TABLE, owner_col[0]).split('.'); - vector col_attribs=catalog.getObjectsAttributes(OBJ_COLUMN, names[0], names[1], { owner_col[1].toUInt() }); + QStringList names=getObjectName(ObjectType::Table, owner_col[0]).split('.'); + vector col_attribs=catalog.getObjectsAttributes(ObjectType::Column, names[0], names[1], { owner_col[1].toUInt() }); if(!col_attribs.empty()) - attribs[ParsersAttributes::OWNER_COLUMN]=QString("%1.%2.%3").arg(names[0], names[1], col_attribs[0].at(ParsersAttributes::NAME)); + attribs[Attributes::OwnerColumn]=QString("%1.%2.%3").arg(names[0], names[1], col_attribs[0].at(Attributes::Name)); } //Retrieving the current value of the sequence by querying the database @@ -546,54 +609,54 @@ void DatabaseExplorerWidget::formatSequenceAttribs(attribs_map &attribs) ResultSet res; conn.connect(); - conn.executeDMLCommand(QString("SELECT last_value FROM \"%1\".\"%2\"").arg(sch_name).arg(BaseObject::formatName(attribs[ParsersAttributes::NAME])), res); + conn.executeDMLCommand(QString("SELECT last_value FROM \"%1\".\"%2\"").arg(sch_name).arg(BaseObject::formatName(attribs[Attributes::Name])), res); - if(res.accessTuple(ResultSet::FIRST_TUPLE)) - attribs[ParsersAttributes::LAST_VALUE]=res.getColumnValue(QString("last_value")); + if(res.accessTuple(ResultSet::FirstTuple)) + attribs[Attributes::LastValue]=res.getColumnValue(QString("last_value")); conn.close(); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } void DatabaseExplorerWidget::formatViewAttribs(attribs_map &attribs) { - formatBooleanAttribs(attribs, { ParsersAttributes::MATERIALIZED }); + formatBooleanAttribs(attribs, { Attributes::Materialized }); } void DatabaseExplorerWidget::formatTypeAttribs(attribs_map &attribs) { - QStringList range_attr=Catalog::parseArrayValues(attribs[ParsersAttributes::RANGE_ATTRIBS]), - type_attr=Catalog::parseArrayValues(attribs[ParsersAttributes::TYPE_ATTRIBUTE]); - - formatBooleanAttribs(attribs, { ParsersAttributes::BY_VALUE, - ParsersAttributes::COLLATABLE, - ParsersAttributes::PREFERRED }); - formatOidAttribs(attribs, { ParsersAttributes::ANALYZE_FUNC, - ParsersAttributes::INPUT_FUNC, - ParsersAttributes::OUTPUT_FUNC, - ParsersAttributes::RECV_FUNC, - ParsersAttributes::SEND_FUNC, - ParsersAttributes::TPMOD_IN_FUNC, - ParsersAttributes::TPMOD_OUT_FUNC }, OBJ_FUNCTION, false); - attribs[ParsersAttributes::ELEMENT]=getObjectName(OBJ_TYPE, attribs[ParsersAttributes::ELEMENT]); - - if(attribs[ParsersAttributes::ENUMERATIONS].isEmpty()) - attribs.erase(ParsersAttributes::ENUMERATIONS); + QStringList range_attr=Catalog::parseArrayValues(attribs[Attributes::RangeAttribs]), + type_attr=Catalog::parseArrayValues(attribs[Attributes::TypeAttribute]); + + formatBooleanAttribs(attribs, { Attributes::ByValue, + Attributes::Collatable, + Attributes::Preferred }); + formatOidAttribs(attribs, { Attributes::AnalyzeFunc, + Attributes::InputFunc, + Attributes::OutputFunc, + Attributes::RecvFunc, + Attributes::SendFunc, + Attributes::TpmodInFunc, + Attributes::TpmodOutFunc }, ObjectType::Function, false); + attribs[Attributes::Element]=getObjectName(ObjectType::Type, attribs[Attributes::Element]); + + if(attribs[Attributes::Enumerations].isEmpty()) + attribs.erase(Attributes::Enumerations); else - attribs[ParsersAttributes::ENUMERATIONS]=Catalog::parseArrayValues(attribs[ParsersAttributes::ENUMERATIONS]).join(ELEM_SEPARATOR); + attribs[Attributes::Enumerations]=Catalog::parseArrayValues(attribs[Attributes::Enumerations]).join(ElemSeparator); - attribs.erase(ParsersAttributes::RANGE_ATTRIBS); + attribs.erase(Attributes::RangeAttribs); if(!range_attr.isEmpty()) { - attribs[ParsersAttributes::SUBTYPE]=getObjectName(OBJ_TYPE, range_attr[0]); - attribs[ParsersAttributes::COLLATION]=getObjectName(OBJ_COLLATION, range_attr[1]); - attribs[ParsersAttributes::OP_CLASS]=getObjectName(OBJ_OPCLASS, range_attr[2]); - attribs[ParsersAttributes::CANONICAL_FUNC]=getObjectName(OBJ_FUNCTION, range_attr[3]); - attribs[ParsersAttributes::SUBTYPE_DIFF_FUNC]=getObjectName(OBJ_FUNCTION, range_attr[4]); + attribs[Attributes::Subtype]=getObjectName(ObjectType::Type, range_attr[0]); + attribs[Attributes::Collation]=getObjectName(ObjectType::Collation, range_attr[1]); + attribs[Attributes::OpClass]=getObjectName(ObjectType::OpClass, range_attr[2]); + attribs[Attributes::CanonicalFunc]=getObjectName(ObjectType::Function, range_attr[3]); + attribs[Attributes::SubtypeDiffFunc]=getObjectName(ObjectType::Function, range_attr[4]); } if(!type_attr.isEmpty()) @@ -607,36 +670,36 @@ void DatabaseExplorerWidget::formatTypeAttribs(attribs_map &attribs) fmt_attribs.push_back(list.join(QLatin1String(" "))); } - attribs[ParsersAttributes::TYPE_ATTRIBUTE]=fmt_attribs.join(ELEM_SEPARATOR); + attribs[Attributes::TypeAttribute]=fmt_attribs.join(ElemSeparator); } else - attribs.erase(ParsersAttributes::TYPE_ATTRIBUTE); + attribs.erase(Attributes::TypeAttribute); } void DatabaseExplorerWidget::formatOperatorClassAttribs(attribs_map &attribs) { QStringList list, array_vals, elems; - attribs[ParsersAttributes::FAMILY]=getObjectName(OBJ_OPFAMILY, attribs[ParsersAttributes::FAMILY]); - formatBooleanAttribs(attribs, { ParsersAttributes::DEFAULT }); - formatOidAttribs(attribs, { ParsersAttributes::STORAGE, - ParsersAttributes::TYPE }, OBJ_TYPE, false); + attribs[Attributes::Family]=getObjectName(ObjectType::OpFamily, attribs[Attributes::Family]); + formatBooleanAttribs(attribs, { Attributes::Default }); + formatOidAttribs(attribs, { Attributes::Storage, + Attributes::Type }, ObjectType::Type, false); - array_vals=Catalog::parseArrayValues(attribs[ParsersAttributes::FUNCTION]); + array_vals=Catalog::parseArrayValues(attribs[Attributes::Function]); if(!array_vals.isEmpty()) { for(int i=0; i < array_vals.size(); i++) { list=array_vals[i].split(':'); - elems.push_back(QString("[%1] %2").arg(list[0], getObjectName(OBJ_FUNCTION, list[1]))); + elems.push_back(QString("[%1] %2").arg(list[0], getObjectName(ObjectType::Function, list[1]))); } - attribs[ParsersAttributes::FUNCTION]=elems.join(ELEM_SEPARATOR); + attribs[Attributes::Function]=elems.join(ElemSeparator); elems.clear(); } - array_vals=Catalog::parseArrayValues(attribs[ParsersAttributes::OPERATOR]); + array_vals=Catalog::parseArrayValues(attribs[Attributes::Operator]); if(!array_vals.isEmpty()) { @@ -645,127 +708,145 @@ void DatabaseExplorerWidget::formatOperatorClassAttribs(attribs_map &attribs) list=array_vals[i].split(':'); elems.push_back(QString("[%1] [%2] [%3]") .arg(list[0], - getObjectName(OBJ_OPERATOR, list[1]), - getObjectName(OBJ_OPERATOR, list[2]))); + getObjectName(ObjectType::Operator, list[1]), + getObjectName(ObjectType::Operator, list[2]))); } - attribs[ParsersAttributes::OPERATOR]=elems.join(ELEM_SEPARATOR); + attribs[Attributes::Operator]=elems.join(ElemSeparator); elems.clear(); } } void DatabaseExplorerWidget::formatTriggerAttribs(attribs_map &attribs) { - formatBooleanAttribs(attribs, { ParsersAttributes::CONSTRAINT, - ParsersAttributes::DEFERRABLE, - ParsersAttributes::PER_ROW, - ParsersAttributes::INS_EVENT, - ParsersAttributes::DEL_EVENT, - ParsersAttributes::UPD_EVENT, - ParsersAttributes::TRUNC_EVENT }); - - attribs[ParsersAttributes::TRIGGER_FUNC]=getObjectName(OBJ_FUNCTION, attribs[ParsersAttributes::TRIGGER_FUNC]); - attribs[ParsersAttributes::ARGUMENTS]=Catalog::parseArrayValues(attribs[ParsersAttributes::ARGUMENTS]).join(ELEM_SEPARATOR); - attribs[ParsersAttributes::COLUMNS]=Catalog::parseArrayValues(attribs[ParsersAttributes::COLUMNS]).join(ELEM_SEPARATOR); + formatBooleanAttribs(attribs, { Attributes::Constraint, + Attributes::Deferrable, + Attributes::PerRow, + Attributes::InsEvent, + Attributes::DelEvent, + Attributes::UpdEvent, + Attributes::TruncEvent }); + + attribs[Attributes::TriggerFunc]=getObjectName(ObjectType::Function, attribs[Attributes::TriggerFunc]); + attribs[Attributes::Arguments]=Catalog::parseArrayValues(attribs[Attributes::Arguments]).join(ElemSeparator); + attribs[Attributes::Columns]=Catalog::parseArrayValues(attribs[Attributes::Columns]).join(ElemSeparator); } void DatabaseExplorerWidget::formatRuleAttribs(attribs_map &attribs) { - attribs[ParsersAttributes::COMMANDS]=Catalog::parseRuleCommands(attribs[ParsersAttributes::COMMANDS]).join(';'); + attribs[Attributes::Commands]=Catalog::parseRuleCommands(attribs[Attributes::Commands]).join(';'); } void DatabaseExplorerWidget::formatColumnAttribs(attribs_map &attribs) { - formatBooleanAttribs(attribs, { ParsersAttributes::NOT_NULL, - ParsersAttributes::INHERITED }); - attribs[ParsersAttributes::POSITION]=attribs[ParsersAttributes::OID]; - attribs.erase(ParsersAttributes::OID); - attribs.erase(ParsersAttributes::TYPE_OID); + formatBooleanAttribs(attribs, { Attributes::NotNull, + Attributes::Inherited }); + attribs[Attributes::Position]=attribs[Attributes::Oid]; + attribs.erase(Attributes::Oid); + attribs.erase(Attributes::TypeOid); } void DatabaseExplorerWidget::formatConstraintAttribs(attribs_map &attribs) { - map types={{ParsersAttributes::PK_CONSTR, ConstraintType(ConstraintType::primary_key)}, - {ParsersAttributes::FK_CONSTR, ConstraintType(ConstraintType::foreign_key)}, - {ParsersAttributes::UQ_CONSTR, ConstraintType(ConstraintType::unique)}, - {ParsersAttributes::CK_CONSTR, ConstraintType(ConstraintType::check)}, - {ParsersAttributes::EX_CONSTR, ConstraintType(ConstraintType::exclude)}}; - - ConstraintType constr_type=types[attribs[ParsersAttributes::TYPE]]; - QStringList names=getObjectName(OBJ_TABLE, attribs[ParsersAttributes::TABLE]).split('.'); - - formatBooleanAttribs(attribs, { ParsersAttributes::DEFERRABLE, - ParsersAttributes::NO_INHERIT }); - attribs[ParsersAttributes::TYPE]=~types[attribs[ParsersAttributes::TYPE]]; - attribs[ParsersAttributes::OP_CLASSES]=getObjectsNames(OBJ_OPCLASS, - Catalog::parseArrayValues(attribs[ParsersAttributes::OP_CLASSES])).join(ELEM_SEPARATOR); - attribs[ParsersAttributes::SRC_COLUMNS]=getObjectsNames(OBJ_COLUMN, - Catalog::parseArrayValues(attribs[ParsersAttributes::SRC_COLUMNS]), - names[0], names[1]).join(ELEM_SEPARATOR); - - if(constr_type==ConstraintType::foreign_key) + map types={{Attributes::PkConstr, ConstraintType(ConstraintType::PrimaryKey)}, + {Attributes::FkConstr, ConstraintType(ConstraintType::ForeignKey)}, + {Attributes::UqConstr, ConstraintType(ConstraintType::Unique)}, + {Attributes::CkConstr, ConstraintType(ConstraintType::Check)}, + {Attributes::ExConstr, ConstraintType(ConstraintType::Exclude)}}; + + ConstraintType constr_type=types[attribs[Attributes::Type]]; + QStringList names=getObjectName(ObjectType::Table, attribs[Attributes::Table]).split('.'); + + formatBooleanAttribs(attribs, { Attributes::Deferrable, + Attributes::NoInherit }); + attribs[Attributes::Type]=~types[attribs[Attributes::Type]]; + attribs[Attributes::OpClasses]=getObjectsNames(ObjectType::OpClass, + Catalog::parseArrayValues(attribs[Attributes::OpClasses])).join(ElemSeparator); + attribs[Attributes::SrcColumns]=getObjectsNames(ObjectType::Column, + Catalog::parseArrayValues(attribs[Attributes::SrcColumns]), + names[0], names[1]).join(ElemSeparator); + + if(constr_type==ConstraintType::ForeignKey) { - attribs[ParsersAttributes::REF_TABLE]=getObjectName(OBJ_TABLE, attribs[ParsersAttributes::REF_TABLE]); - names=attribs[ParsersAttributes::REF_TABLE].split('.'); - attribs[ParsersAttributes::DST_COLUMNS]=getObjectsNames(OBJ_COLUMN, - Catalog::parseArrayValues(attribs[ParsersAttributes::DST_COLUMNS]), - names[0], names[1]).join(ELEM_SEPARATOR); + attribs[Attributes::RefTable]=getObjectName(ObjectType::Table, attribs[Attributes::RefTable]); + names=attribs[Attributes::RefTable].split('.'); + attribs[Attributes::DstColumns]=getObjectsNames(ObjectType::Column, + Catalog::parseArrayValues(attribs[Attributes::DstColumns]), + names[0], names[1]).join(ElemSeparator); } else { - attribs.erase(ParsersAttributes::DST_COLUMNS); - attribs.erase(ParsersAttributes::REF_TABLE); - attribs.erase(ParsersAttributes::UPD_ACTION); - attribs.erase(ParsersAttributes::DEL_ACTION); - attribs.erase(ParsersAttributes::COMPARISON_TYPE); + attribs.erase(Attributes::DstColumns); + attribs.erase(Attributes::RefTable); + attribs.erase(Attributes::UpdAction); + attribs.erase(Attributes::DelAction); + attribs.erase(Attributes::ComparisonType); } - if(constr_type==ConstraintType::check) + if(constr_type==ConstraintType::Check) { - attribs.erase(ParsersAttributes::DEFERRABLE); - attribs.erase(ParsersAttributes::DEFER_TYPE); + attribs.erase(Attributes::Deferrable); + attribs.erase(Attributes::DeferType); } else - attribs.erase(ParsersAttributes::EXPRESSION); + attribs.erase(Attributes::Expression); - if(constr_type==ConstraintType::exclude) + if(constr_type==ConstraintType::Exclude) { - attribs[ParsersAttributes::EXPRESSIONS]=Catalog::parseArrayValues(attribs[ParsersAttributes::EXPRESSIONS]).join(ELEM_SEPARATOR); - attribs[ParsersAttributes::OPERATORS]=getObjectsNames(OBJ_OPERATOR, - Catalog::parseArrayValues(attribs[ParsersAttributes::OPERATORS])).join(ELEM_SEPARATOR); + attribs[Attributes::Expressions]=Catalog::parseArrayValues(attribs[Attributes::Expressions]).join(ElemSeparator); + attribs[Attributes::Operators]=getObjectsNames(ObjectType::Operator, + Catalog::parseArrayValues(attribs[Attributes::Operators])).join(ElemSeparator); } else { - attribs.erase(ParsersAttributes::CONDITION); - attribs.erase(ParsersAttributes::EXPRESSIONS); - attribs.erase(ParsersAttributes::OPERATORS); + attribs.erase(Attributes::Condition); + attribs.erase(Attributes::Expressions); + attribs.erase(Attributes::Operators); } } void DatabaseExplorerWidget::formatIndexAttribs(attribs_map &attribs) { - QStringList names=getObjectName(OBJ_TABLE, attribs[ParsersAttributes::TABLE]).split('.'); + QStringList names=getObjectName(ObjectType::Table, attribs[Attributes::Table]).split('.'); if(names.isEmpty() || names.size() == 1) - names=getObjectName(OBJ_VIEW, attribs[ParsersAttributes::TABLE]).split('.'); + names=getObjectName(ObjectType::View, attribs[Attributes::Table]).split('.'); - formatBooleanAttribs(attribs, { ParsersAttributes::UNIQUE }); + formatBooleanAttribs(attribs, { Attributes::Unique }); - attribs[ParsersAttributes::EXPRESSIONS]=Catalog::parseArrayValues(attribs[ParsersAttributes::EXPRESSIONS]).join(ELEM_SEPARATOR); + attribs[Attributes::Expressions]=Catalog::parseIndexExpressions(attribs[Attributes::Expressions]).join(ElemSeparator); - attribs[ParsersAttributes::COLLATIONS]=getObjectsNames(OBJ_COLLATION, - Catalog::parseArrayValues(attribs[ParsersAttributes::COLLATIONS])).join(ELEM_SEPARATOR); + attribs[Attributes::Collations]=getObjectsNames(ObjectType::Collation, + Catalog::parseArrayValues(attribs[Attributes::Collations])).join(ElemSeparator); - attribs[ParsersAttributes::OP_CLASSES]=getObjectsNames(OBJ_OPCLASS, - Catalog::parseArrayValues(attribs[ParsersAttributes::OP_CLASSES])).join(ELEM_SEPARATOR); + attribs[Attributes::OpClasses]=getObjectsNames(ObjectType::OpClass, + Catalog::parseArrayValues(attribs[Attributes::OpClasses])).join(ElemSeparator); - attribs[ParsersAttributes::COLUMNS]=getObjectsNames(OBJ_COLUMN, - Catalog::parseArrayValues(attribs[ParsersAttributes::COLUMNS]), names[0], names[1]).join(ELEM_SEPARATOR); + attribs[Attributes::Columns]=getObjectsNames(ObjectType::Column, + Catalog::parseArrayValues(attribs[Attributes::Columns]), names[0], names[1]).join(ElemSeparator); } void DatabaseExplorerWidget::formatPolicyAttribs(attribs_map &attribs) { - attribs[ParsersAttributes::ROLES] = getObjectsNames(OBJ_ROLE, Catalog::parseArrayValues(attribs[ParsersAttributes::ROLES])).join(ELEM_SEPARATOR); + attribs[Attributes::Roles] = getObjectsNames(ObjectType::Role, Catalog::parseArrayValues(attribs[Attributes::Roles])).join(ElemSeparator); +} + +void DatabaseExplorerWidget::formatForeignDataWrapperAttribs(attribs_map &attribs) +{ + attribs[Attributes::Options]=Catalog::parseArrayValues(attribs[Attributes::Options]).join(ElemSeparator); + formatOidAttribs(attribs, { Attributes::ValidatorFunc, Attributes::HandlerFunc }, ObjectType::Function, false); +} + +void DatabaseExplorerWidget::formatServerAttribs(attribs_map &attribs) +{ + attribs[Attributes::Options]=Catalog::parseArrayValues(attribs[Attributes::Options]).join(ElemSeparator); + formatOidAttribs(attribs, { Attributes::Fdw }, ObjectType::ForeignDataWrapper, false); +} + +void DatabaseExplorerWidget::formatUserMappingAttribs(attribs_map &attribs) +{ + attribs[Attributes::Options]=Catalog::parseArrayValues(attribs[Attributes::Options]).join(ElemSeparator); + formatOidAttribs(attribs, { Attributes::Server }, ObjectType::ForeignServer, false); } QString DatabaseExplorerWidget::formatObjectName(attribs_map &attribs) @@ -773,56 +854,56 @@ QString DatabaseExplorerWidget::formatObjectName(attribs_map &attribs) try { if(attribs.empty() || - attribs[ParsersAttributes::OID].isEmpty() || - attribs[ParsersAttributes::OID]==QString("0") || - attribs[ParsersAttributes::NAME].isEmpty()) - return(DEP_NOT_DEFINED); + attribs[Attributes::Oid].isEmpty() || + attribs[Attributes::Oid]==QString("0") || + attribs[Attributes::Name].isEmpty()) + return(DepNotDefined); else { - ObjectType obj_type=static_cast(attribs[ParsersAttributes::OBJECT_TYPE].toUInt()); + ObjectType obj_type=static_cast(attribs[Attributes::ObjectType].toUInt()); attribs_map aux_attribs; - QString oid=attribs[ParsersAttributes::OID], - obj_name=DEP_NOT_FOUND.arg(oid), sch_name; + QString oid=attribs[Attributes::Oid], + obj_name=DepNotFound.arg(oid), sch_name; - if(obj_type!=OBJ_TYPE) - obj_name=BaseObject::formatName(attribs[ParsersAttributes::NAME], obj_type==OBJ_OPERATOR); + if(obj_type!=ObjectType::Type) + obj_name=BaseObject::formatName(attribs[Attributes::Name], obj_type==ObjectType::Operator); else - obj_name=attribs[ParsersAttributes::NAME]; + obj_name=attribs[Attributes::Name]; //Retrieving the schema name - if(!attribs[ParsersAttributes::SCHEMA].isEmpty() && - attribs[ParsersAttributes::SCHEMA]!=QString("0")) + if(!attribs[Attributes::Schema].isEmpty() && + attribs[Attributes::Schema]!=QString("0")) { - aux_attribs=catalog.getObjectAttributes(OBJ_SCHEMA, attribs[ParsersAttributes::SCHEMA].toUInt()); - sch_name=BaseObject::formatName(aux_attribs[ParsersAttributes::NAME], false); + aux_attribs=catalog.getObjectAttributes(ObjectType::Schema, attribs[Attributes::Schema].toUInt()); + sch_name=BaseObject::formatName(aux_attribs[Attributes::Name], false); if(!sch_name.isEmpty()) obj_name=sch_name + QString(".") + obj_name; } //Formatting paramenter types for function - if(obj_type==OBJ_FUNCTION) + if(obj_type==ObjectType::Function) { - QStringList names, arg_types=Catalog::parseArrayValues(attribs[ParsersAttributes::ARG_TYPES]); + QStringList names, arg_types=Catalog::parseArrayValues(attribs[Attributes::ArgTypes]); for(int idx=0; idx < arg_types.size(); idx++) { - names=getObjectName(OBJ_TYPE, arg_types[idx]).split('.'); + names=getObjectName(ObjectType::Type, arg_types[idx]).split('.'); arg_types[idx]=names[names.size()-1]; } obj_name+=QString("(%1)").arg(arg_types.join(',')); } //Formatting paramenter types for operator - else if(obj_type==OBJ_OPERATOR) + else if(obj_type==ObjectType::Operator) { QStringList arg_types, names; QString type_name; - vector attrib_ids={ ParsersAttributes::LEFT_TYPE, ParsersAttributes::RIGHT_TYPE }; + vector attrib_ids={ Attributes::LeftType, Attributes::RightType }; for(QString attr : attrib_ids) { - names=getObjectName(OBJ_TYPE, attribs[attr]).split('.'); + names=getObjectName(ObjectType::Type, attribs[attr]).split('.'); type_name=names[names.size()-1]; if(type_name.isEmpty()) type_name=QString("-"); @@ -837,7 +918,7 @@ QString DatabaseExplorerWidget::formatObjectName(attribs_map &attribs) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -846,7 +927,7 @@ QStringList DatabaseExplorerWidget::getObjectsNames(ObjectType obj_type, const Q try { if(oids.isEmpty()) - return(QStringList{ DEP_NOT_DEFINED }); + return(QStringList{ DepNotDefined }); else { vector attribs_vect; @@ -861,7 +942,7 @@ QStringList DatabaseExplorerWidget::getObjectsNames(ObjectType obj_type, const Q //Retrieve all the objects by their oids and put them on a auxiliary map in which key is their oids attribs_vect=catalog.getObjectsAttributes(obj_type, sch_name, tab_name, oids_vect); for(attribs_map attr : attribs_vect) - attrs_map[attr[ParsersAttributes::OID]]=attr; + attrs_map[attr[Attributes::Oid]]=attr; //Retreving the names from the auxiliary map using the provided oids for(QString oid : oids) @@ -872,7 +953,7 @@ QStringList DatabaseExplorerWidget::getObjectsNames(ObjectType obj_type, const Q } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -881,7 +962,7 @@ QString DatabaseExplorerWidget::getObjectName(ObjectType obj_type, const QString try { if(oid==QString("0") || oid.isEmpty()) - return(DEP_NOT_DEFINED); + return(DepNotDefined); else { attribs_map attribs=catalog.getObjectAttributes(obj_type, oid.toUInt(), sch_name, tab_name); @@ -890,7 +971,7 @@ QString DatabaseExplorerWidget::getObjectName(ObjectType obj_type, const QString } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -936,16 +1017,17 @@ void DatabaseExplorerWidget::listObjects(void) curr_root = objects_trw->topLevelItem(0); objects_trw->takeTopLevelItem(0); root->setText(0, connection.getConnectionId(true)); - root->setIcon(0, QPixmap(PgModelerUiNS::getIconPath("server"))); - root->setData(DatabaseImportForm::OBJECT_ID, Qt::UserRole, -1); - root->setData(DatabaseImportForm::OBJECT_TYPE, Qt::UserRole, BASE_OBJECT); - root->setData(DatabaseImportForm::OBJECT_SOURCE, Qt::UserRole, trUtf8("-- Source code unavailable for this kind of object --")); + root->setIcon(0, QPixmap(PgModelerUiNs::getIconPath("server"))); + root->setData(DatabaseImportForm::ObjectId, Qt::UserRole, -1); + root->setData(DatabaseImportForm::ObjectTypeId, Qt::UserRole, enum_cast(ObjectType::BaseObject)); + root->setData(DatabaseImportForm::ObjectSource, Qt::UserRole, trUtf8("-- Source code unavailable for this kind of object --")); root->addChild(curr_root); objects_trw->addTopLevelItem(root); root->setExpanded(true); + root->setSelected(true); + objects_trw->setCurrentItem(root); QApplication::restoreOverrideCursor(); - objects_trw->blockSignals(false); import_helper.closeConnection(); @@ -954,39 +1036,39 @@ void DatabaseExplorerWidget::listObjects(void) catch(Exception &e) { QApplication::restoreOverrideCursor(); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void DatabaseExplorerWidget::configureImportHelper(void) { import_helper.setConnection(connection); - import_helper.setCurrentDatabase(connection.getConnectionParam(Connection::PARAM_DB_NAME)); + import_helper.setCurrentDatabase(connection.getConnectionParam(Connection::ParamDbName)); import_helper.setImportOptions(show_sys_objs->isChecked(), show_ext_objs->isChecked(), false, false, false, false, false); catalog.closeConnection(); - catalog.setFilter(Catalog::LIST_ALL_OBJS); + catalog.setFilter(Catalog::ListAllObjects); catalog.setConnection(connection); } void DatabaseExplorerWidget::handleObject(QTreeWidgetItem *item, int) { - if(item->data(DatabaseImportForm::OBJECT_OTHER_DATA, Qt::UserRole).toInt() < 0) + if(item->data(DatabaseImportForm::ObjectOtherData, Qt::UserRole).toInt() < 0) { updateItem(item->parent()); } - else if(QApplication::mouseButtons()==Qt::MiddleButton && item->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toInt() >= 0) + else if(QApplication::mouseButtons()==Qt::MiddleButton && item->data(DatabaseImportForm::ObjectId, Qt::UserRole).toInt() >= 0) { loadObjectSource(); } - else if(QApplication::mouseButtons()==Qt::RightButton && item->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toInt() >= 0) + else if(QApplication::mouseButtons()==Qt::RightButton && item->data(DatabaseImportForm::ObjectId, Qt::UserRole).toInt() >= 0) { - ObjectType obj_type=static_cast(item->data(DatabaseImportForm::OBJECT_TYPE, Qt::UserRole).toUInt()); - unsigned obj_id=item->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toUInt(); + ObjectType obj_type=static_cast(item->data(DatabaseImportForm::ObjectTypeId, Qt::UserRole).toUInt()); + unsigned obj_id=item->data(DatabaseImportForm::ObjectId, Qt::UserRole).toUInt(); - SnippetsConfigWidget::configureSnippetsMenu(&snippets_menu, { obj_type, BASE_OBJECT }); + SnippetsConfigWidget::configureSnippetsMenu(&snippets_menu, { obj_type, ObjectType::BaseObject }); for(auto &act : handle_menu.actions()) handle_menu.removeAction(act); @@ -995,24 +1077,24 @@ void DatabaseExplorerWidget::handleObject(QTreeWidgetItem *item, int) if(obj_id > 0) { - if(obj_type==OBJ_TABLE || obj_type==OBJ_VIEW) + if(obj_type==ObjectType::Table || obj_type==ObjectType::View) handle_menu.addAction(show_data_action); handle_menu.addAction(properties_action); handle_menu.addAction(source_action); - if(obj_type!=OBJ_CAST && obj_type!=OBJ_DATABASE) + if(obj_type!=ObjectType::Cast && obj_type!=ObjectType::Database) handle_menu.addAction(rename_action); - if(obj_type!=OBJ_DATABASE) + if(obj_type!=ObjectType::Database) { handle_menu.addSeparator(); handle_menu.addAction(drop_action); - if(obj_type!=OBJ_ROLE && obj_type!=OBJ_TABLESPACE) + if(obj_type!=ObjectType::Role && obj_type!=ObjectType::Tablespace) handle_menu.addAction(drop_cascade_action); - if(obj_type==OBJ_TABLE) + if(obj_type==ObjectType::Table) { handle_menu.addAction(truncate_action); handle_menu.addAction(trunc_cascade_action); @@ -1039,9 +1121,9 @@ void DatabaseExplorerWidget::handleObject(QTreeWidgetItem *item, int) loadObjectSource(); else if(exec_action==show_data_action) { - openDataGrid(item->data(DatabaseImportForm::OBJECT_SCHEMA, Qt::UserRole).toString(), + openDataGrid(item->data(DatabaseImportForm::ObjectSchema, Qt::UserRole).toString(), item->text(0), - item->data(DatabaseImportForm::OBJECT_TYPE, Qt::UserRole).toUInt()!=OBJ_VIEW); + item->data(DatabaseImportForm::ObjectTypeId, Qt::UserRole).toUInt() != enum_cast(ObjectType::View)); } else if(exec_action) handleSelectedSnippet(exec_action->text()); @@ -1052,45 +1134,45 @@ void DatabaseExplorerWidget::handleSelectedSnippet(const QString &snip_id) { attribs_map attribs; QTreeWidgetItem *item=objects_trw->currentItem(); - ObjectType obj_type=static_cast(item->data(DatabaseImportForm::OBJECT_TYPE, Qt::UserRole).toUInt()); + ObjectType obj_type=static_cast(item->data(DatabaseImportForm::ObjectTypeId, Qt::UserRole).toUInt()); loadObjectProperties(); - attribs=item->data(DatabaseImportForm::OBJECT_OTHER_DATA, Qt::UserRole).value(); + attribs=item->data(DatabaseImportForm::ObjectOtherData, Qt::UserRole).value(); if(attribs.empty()) { - QString sch_name=item->data(DatabaseImportForm::OBJECT_SCHEMA, Qt::UserRole).toString(), - tab_name=item->data(DatabaseImportForm::OBJECT_TABLE, Qt::UserRole).toString(); + QString sch_name=item->data(DatabaseImportForm::ObjectSchema, Qt::UserRole).toString(), + tab_name=item->data(DatabaseImportForm::ObjectTable, Qt::UserRole).toString(); //Formatting a schema qualified "table" attribute for table children objects if(TableObject::isTableObject(obj_type) && !sch_name.isEmpty() && !tab_name.isEmpty()) - attribs[ParsersAttributes::TABLE]=BaseObject::formatName(sch_name) + QString(".") + BaseObject::formatName(tab_name); + attribs[Attributes::Table]=BaseObject::formatName(sch_name) + QString(".") + BaseObject::formatName(tab_name); } //Formatting the "name" attribute if it is not schema qualified - else if(attribs.count(ParsersAttributes::SCHEMA) && - attribs.count(ParsersAttributes::NAME) && - !attribs[ParsersAttributes::NAME].contains('.')) + else if(attribs.count(Attributes::Schema) && + attribs.count(Attributes::Name) && + !attribs[Attributes::Name].contains('.')) { QString obj_name; - if(obj_type!=OBJ_OPERATOR) - obj_name=BaseObject::formatName(attribs[ParsersAttributes::NAME]); + if(obj_type!=ObjectType::Operator) + obj_name=BaseObject::formatName(attribs[Attributes::Name]); else - obj_name=attribs[ParsersAttributes::NAME]; + obj_name=attribs[Attributes::Name]; - attribs[ParsersAttributes::NAME]=BaseObject::formatName(attribs[ParsersAttributes::SCHEMA]) + QString(".") + obj_name; + attribs[Attributes::Name]=BaseObject::formatName(attribs[Attributes::Schema]) + QString(".") + obj_name; } - if(attribs.count(ParsersAttributes::SQL_OBJECT)==0) + if(attribs.count(Attributes::SqlObject)==0) { - attribs[ParsersAttributes::SQL_OBJECT]=BaseObject::getSQLName(obj_type); - attribs[ParsersAttributes::OBJECT_TYPE]=BaseObject::getSchemaName(obj_type); + attribs[Attributes::SqlObject]=BaseObject::getSQLName(obj_type); + attribs[Attributes::ObjectType]=BaseObject::getSchemaName(obj_type); } for(auto &attr : attribs) { - if(attr.second.contains(ELEM_SEPARATOR)) - attribs[attr.first]=attr.second.replace(ELEM_SEPARATOR,QString(",")); + if(attr.second.contains(ElemSeparator)) + attribs[attr.first]=attr.second.replace(ElemSeparator,QString(",")); } emit s_snippetShowRequested(SnippetsConfigWidget::getParsedSnippet(snip_id, attribs)); @@ -1099,20 +1181,20 @@ void DatabaseExplorerWidget::handleSelectedSnippet(const QString &snip_id) attribs_map DatabaseExplorerWidget::extractAttributesFromItem(QTreeWidgetItem *item) { if(!item) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); - ObjectType obj_type=static_cast(item->data(DatabaseImportForm::OBJECT_TYPE, Qt::UserRole).toUInt()); + ObjectType obj_type=static_cast(item->data(DatabaseImportForm::ObjectTypeId, Qt::UserRole).toUInt()); QString obj_name=item->text(0); int idx=0, idx1=0; attribs_map attribs; QStringList types; - attribs[ParsersAttributes::SQL_OBJECT]=BaseObject::getSQLName(obj_type); - attribs[ParsersAttributes::DECL_IN_TABLE]=QString(); - attribs[BaseObject::getSchemaName(obj_type)]=ParsersAttributes::_TRUE_; + attribs[Attributes::SqlObject]=BaseObject::getSQLName(obj_type); + attribs[Attributes::DeclInTable]=QString(); + attribs[BaseObject::getSchemaName(obj_type)]=Attributes::True; //For cast, operator and function is needed to extract the name and the params types - if(obj_type==OBJ_OPERATOR || obj_type==OBJ_FUNCTION || obj_type==OBJ_CAST) + if(obj_type==ObjectType::Operator || obj_type==ObjectType::Function || obj_type==ObjectType::Cast) { idx=obj_name.indexOf('('); idx1=obj_name.indexOf(')'); @@ -1120,51 +1202,51 @@ attribs_map DatabaseExplorerWidget::extractAttributesFromItem(QTreeWidgetItem *i types.removeAll(QString("-")); obj_name.remove(idx, obj_name.size()); } - else if(obj_type==OBJ_OPFAMILY || obj_type==OBJ_OPCLASS) + else if(obj_type==ObjectType::OpFamily || obj_type==ObjectType::OpClass) obj_name.remove(QRegExp("( )+(\\[)(.)+(\\])")); //Formatting the names - attribs[ParsersAttributes::NAME]=BaseObject::formatName(obj_name, obj_type==OBJ_OPERATOR); - attribs[ParsersAttributes::TABLE]=BaseObject::formatName(item->data(DatabaseImportForm::OBJECT_TABLE, Qt::UserRole).toString()); - attribs[ParsersAttributes::SCHEMA]=BaseObject::formatName(item->data(DatabaseImportForm::OBJECT_SCHEMA, Qt::UserRole).toString()); + attribs[Attributes::Name]=BaseObject::formatName(obj_name, obj_type==ObjectType::Operator); + attribs[Attributes::Table]=BaseObject::formatName(item->data(DatabaseImportForm::ObjectTable, Qt::UserRole).toString()); + attribs[Attributes::Schema]=BaseObject::formatName(item->data(DatabaseImportForm::ObjectSchema, Qt::UserRole).toString()); //For table objects the "table" attribute must be schema qualified - if(obj_type!=OBJ_INDEX && TableObject::isTableObject(obj_type)) + if(obj_type!=ObjectType::Index && TableObject::isTableObject(obj_type)) { - attribs[ParsersAttributes::TABLE]=attribs[ParsersAttributes::SCHEMA] + QString(".") + attribs[ParsersAttributes::TABLE]; - attribs[ParsersAttributes::SIGNATURE]=attribs[ParsersAttributes::NAME] + QString(" ON %1").arg(attribs[ParsersAttributes::TABLE]); + attribs[Attributes::Table]=attribs[Attributes::Schema] + QString(".") + attribs[Attributes::Table]; + attribs[Attributes::Signature]=attribs[Attributes::Name] + QString(" ON %1").arg(attribs[Attributes::Table]); } //For operators and functions there must exist the signature attribute - else if(obj_type==OBJ_OPERATOR || obj_type==OBJ_FUNCTION) - attribs[ParsersAttributes::SIGNATURE]=attribs[ParsersAttributes::SCHEMA] + QString(".") + attribs[ParsersAttributes::NAME] + QString("(%1)").arg(types.join(ELEM_SEPARATOR)); - else if(obj_type==OBJ_CAST) - attribs[ParsersAttributes::SIGNATURE]=QString("(%1 AS %2)").arg(types[0]).arg(types[1]); - else if(obj_type==OBJ_OPFAMILY || obj_type==OBJ_OPCLASS) + else if(obj_type==ObjectType::Operator || obj_type==ObjectType::Function) + attribs[Attributes::Signature]=attribs[Attributes::Schema] + QString(".") + attribs[Attributes::Name] + QString("(%1)").arg(types.join(ElemSeparator)); + else if(obj_type==ObjectType::Cast) + attribs[Attributes::Signature]=QString("(%1 AS %2)").arg(types[0]).arg(types[1]); + else if(obj_type==ObjectType::OpFamily || obj_type==ObjectType::OpClass) { - attribs_map aux_attribs=item->data(DatabaseImportForm::OBJECT_OTHER_DATA, Qt::UserRole).value(); - attribs[ParsersAttributes::SIGNATURE]=QString("%1 USING %2").arg(attribs[ParsersAttributes::NAME]).arg(aux_attribs[ParsersAttributes::INDEX_TYPE]); + attribs_map aux_attribs=item->data(DatabaseImportForm::ObjectOtherData, Qt::UserRole).value(); + attribs[Attributes::Signature]=QString("%1 USING %2").arg(attribs[Attributes::Name]).arg(aux_attribs[Attributes::IndexType]); } else { /* If we are handling a view we need to append the MATERIALIZED keyword in the sql-object in order * to construct DDL commands correctly for this kind of object */ - if(obj_type==OBJ_VIEW) + if(obj_type==ObjectType::View) { - attribs_map aux_attribs=item->data(DatabaseImportForm::OBJECT_OTHER_DATA, Qt::UserRole).value(); + attribs_map aux_attribs=item->data(DatabaseImportForm::ObjectOtherData, Qt::UserRole).value(); - if(aux_attribs[ParsersAttributes::MATERIALIZED] == ParsersAttributes::_TRUE_) + if(aux_attribs[Attributes::Materialized] == Attributes::True) { - attribs[ParsersAttributes::SQL_OBJECT] = - QString("%1 %2").arg(ParsersAttributes::MATERIALIZED.toUpper()) - .arg(BaseObject::getSQLName(OBJ_VIEW)); + attribs[Attributes::SqlObject] = + QString("%1 %2").arg(Attributes::Materialized.toUpper()) + .arg(BaseObject::getSQLName(ObjectType::View)); } } - if(!attribs[ParsersAttributes::SCHEMA].isEmpty() && - attribs[ParsersAttributes::NAME].indexOf(attribs[ParsersAttributes::SCHEMA] + QString(".")) < 0) - attribs[ParsersAttributes::SIGNATURE]=attribs[ParsersAttributes::SCHEMA] + QString(".") + attribs[ParsersAttributes::NAME]; + if(!attribs[Attributes::Schema].isEmpty() && + attribs[Attributes::Name].indexOf(attribs[Attributes::Schema] + QString(".")) < 0) + attribs[Attributes::Signature]=attribs[Attributes::Schema] + QString(".") + attribs[Attributes::Name]; else - attribs[ParsersAttributes::SIGNATURE]=attribs[ParsersAttributes::NAME]; + attribs[Attributes::Signature]=attribs[Attributes::Name]; } return(attribs); @@ -1176,14 +1258,14 @@ void DatabaseExplorerWidget::dropObject(QTreeWidgetItem *item, bool cascade) try { - if(item && static_cast(item->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toUInt()) > 0) + if(item && item->data(DatabaseImportForm::ObjectId, Qt::UserRole).toUInt() > 0) { - ObjectType obj_type=static_cast(item->data(DatabaseImportForm::OBJECT_TYPE, Qt::UserRole).toUInt()); + ObjectType obj_type=static_cast(item->data(DatabaseImportForm::ObjectTypeId, Qt::UserRole).toUInt()); QString msg; - QString obj_name=item->data(DatabaseImportForm::OBJECT_NAME, Qt::UserRole).toString(); + QString obj_name=item->data(DatabaseImportForm::ObjectName, Qt::UserRole).toString(); //Roles and tablespaces can't be removed in cascade mode - if(cascade && (obj_type==OBJ_ROLE || obj_type==OBJ_TABLESPACE)) + if(cascade && (obj_type==ObjectType::Role || obj_type==ObjectType::Tablespace)) return; if(!cascade) @@ -1193,7 +1275,7 @@ void DatabaseExplorerWidget::dropObject(QTreeWidgetItem *item, bool cascade) msg=trUtf8("Do you really want to cascade drop the object %1 (%2)? This action will drop all the other objects that depends on it.") .arg(obj_name).arg(BaseObject::getTypeName(obj_type)); - msg_box.show(msg, Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + msg_box.show(msg, Messagebox::ConfirmIcon, Messagebox::YesNoButtons); if(msg_box.result()==QDialog::Accepted) { @@ -1204,13 +1286,13 @@ void DatabaseExplorerWidget::dropObject(QTreeWidgetItem *item, bool cascade) attribs=extractAttributesFromItem(item); - if(obj_type==OBJ_OPERATOR || obj_type==OBJ_FUNCTION) - attribs[ParsersAttributes::SIGNATURE].replace(ELEM_SEPARATOR, QChar(',')); + if(obj_type==ObjectType::Operator || obj_type==ObjectType::Function) + attribs[Attributes::Signature].replace(ElemSeparator, QChar(',')); //Generate the drop command schparser.ignoreEmptyAttributes(true); schparser.ignoreUnkownAttributes(true); - drop_cmd=schparser.getCodeDefinition(ParsersAttributes::DROP, attribs, SchemaParser::SQL_DEFINITION); + drop_cmd=schparser.getCodeDefinition(Attributes::Drop, attribs, SchemaParser::SqlDefinition); if(cascade) drop_cmd.replace(';', QString(" CASCADE;")); @@ -1222,14 +1304,14 @@ void DatabaseExplorerWidget::dropObject(QTreeWidgetItem *item, bool cascade) //Updates the object count on the parent item parent=item->parent(); - if(parent && parent->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toUInt()==0) + if(parent && parent->data(DatabaseImportForm::ObjectId, Qt::UserRole).toUInt()==0) { - unsigned cnt=parent->data(DatabaseImportForm::OBJECT_COUNT, Qt::UserRole).toUInt(); - ObjectType parent_type=static_cast(parent->data(DatabaseImportForm::OBJECT_TYPE, Qt::UserRole).toUInt()); + unsigned cnt=parent->data(DatabaseImportForm::ObjectCount, Qt::UserRole).toUInt(); + ObjectType parent_type=static_cast(parent->data(DatabaseImportForm::ObjectTypeId, Qt::UserRole).toUInt()); cnt--; parent->setText(0, BaseObject::getTypeName(parent_type) + QString(" (%1)").arg(cnt)); - parent->setData(DatabaseImportForm::OBJECT_COUNT, Qt::UserRole, QVariant::fromValue(cnt)); + parent->setData(DatabaseImportForm::ObjectCount, Qt::UserRole, QVariant::fromValue(cnt)); } if(parent) @@ -1247,78 +1329,94 @@ void DatabaseExplorerWidget::dropObject(QTreeWidgetItem *item, bool cascade) } } -void DatabaseExplorerWidget::truncateTable(QTreeWidgetItem *item, bool cascade) +bool DatabaseExplorerWidget::truncateTable(const QString &sch_name, const QString &obj_name, bool cascade, Connection connection) { - Messagebox msg_box; - try { - if(item && static_cast(item->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toUInt()) > 0) - { - QString msg, obj_name, sch_name; + Messagebox msg_box; + QString msg; - obj_name=item->data(DatabaseImportForm::OBJECT_NAME, Qt::UserRole).toString(); - sch_name=BaseObject::formatName(item->data(DatabaseImportForm::OBJECT_SCHEMA, Qt::UserRole).toString()); + if(!cascade) + msg=trUtf8("Do you really want to truncate the table %1.%2?").arg(sch_name).arg(obj_name); + else + msg=trUtf8("Do you really want to truncate in cascade mode the table %1.%2? This action will truncate all the tables that depends on it?").arg(sch_name).arg(obj_name); - if(!cascade) - msg=trUtf8("Do you really want to truncate the table %1?").arg(obj_name); - else - msg=trUtf8("Do you really want to cascade truncate the table %1? This action will truncate all the tables that depends on it?").arg(obj_name); + msg_box.setCustomOptionText(trUtf8("Also restart sequences")); + msg_box.show(msg, Messagebox::ConfirmIcon, Messagebox::YesNoButtons); - msg_box.show(msg, Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + if(msg_box.result()==QDialog::Accepted) + { + attribs_map attribs; + QString truc_cmd; + Connection conn; + SchemaParser schparser; - if(msg_box.result()==QDialog::Accepted) - { - attribs_map attribs; - QString truc_cmd; - Connection conn; + attribs[Attributes::SqlObject]=BaseObject::getSQLName(ObjectType::Table); + attribs[Attributes::Signature]=QString("%1.%2").arg(BaseObject::formatName(sch_name)).arg(BaseObject::formatName(obj_name)); + attribs[Attributes::Cascade]=(cascade ? Attributes::True : ""); + attribs[Attributes::RestartSeq]=(msg_box.isCustomOptionChecked() ? Attributes::True : ""); - attribs[ParsersAttributes::SQL_OBJECT]=BaseObject::getSQLName(OBJ_TABLE); - attribs[ParsersAttributes::SIGNATURE]=sch_name + QString(".\"%1\"").arg(obj_name); - attribs[ParsersAttributes::CASCADE]=(cascade ? ParsersAttributes::_TRUE_ : ""); + //Generate the truncate command + schparser.ignoreEmptyAttributes(true); + schparser.ignoreUnkownAttributes(true); + truc_cmd=schparser.getCodeDefinition(GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + GlobalAttributes::AlterSchemaDir + GlobalAttributes::DirSeparator + + Attributes::Truncate + GlobalAttributes::SchemaExt, + attribs); + //Executes the truncate cmd + conn = connection; + conn.connect(); + conn.executeDDLCommand(truc_cmd); + } - //Generate the truncate command - schparser.ignoreEmptyAttributes(true); - schparser.ignoreUnkownAttributes(true); - truc_cmd=schparser.getCodeDefinition(GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::ALTER_SCHEMA_DIR + GlobalAttributes::DIR_SEPARATOR + - ParsersAttributes::TRUNCATE + GlobalAttributes::SCHEMA_EXT, - attribs); + return(msg_box.result()==QDialog::Accepted); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__); + } +} - //Executes the truncate cmd - conn=connection; - conn.connect(); - conn.executeDDLCommand(truc_cmd); - } +void DatabaseExplorerWidget::truncateTable(QTreeWidgetItem *item, bool cascade) +{ + try + { + if(item && item->data(DatabaseImportForm::ObjectId, Qt::UserRole).toUInt() > 0) + { + QString obj_name, sch_name; + obj_name=item->data(DatabaseImportForm::ObjectName, Qt::UserRole).toString(); + sch_name=BaseObject::formatName(item->data(DatabaseImportForm::ObjectSchema, Qt::UserRole).toString()); + truncateTable(sch_name, obj_name, cascade, connection); } } catch(Exception &e) { + Messagebox msg_box; msg_box.show(e); } } void DatabaseExplorerWidget::updateItem(QTreeWidgetItem *item) { - if(item && item->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toInt() >= 0) + if(item && item->data(DatabaseImportForm::ObjectId, Qt::UserRole).toInt() >= 0) { QTreeWidgetItem *root=nullptr, *parent=nullptr, *aux_item=nullptr; - ObjectType obj_type=static_cast(item->data(DatabaseImportForm::OBJECT_TYPE, Qt::UserRole).toUInt()); - unsigned obj_id=static_cast(item->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toUInt()); + ObjectType obj_type=static_cast(item->data(DatabaseImportForm::ObjectTypeId, Qt::UserRole).toUInt()); + unsigned obj_id=item->data(DatabaseImportForm::ObjectId, Qt::UserRole).toUInt(); QString sch_name, tab_name; vector gen_items; QApplication::setOverrideCursor(Qt::WaitCursor); - if(obj_type==OBJ_DATABASE) + if(obj_type==ObjectType::Database) listObjects(); else { clearObjectProperties(); parent=item->parent(); - sch_name=item->data(DatabaseImportForm::OBJECT_SCHEMA, Qt::UserRole).toString(); - tab_name=item->data(DatabaseImportForm::OBJECT_TABLE, Qt::UserRole).toString(); + sch_name=item->data(DatabaseImportForm::ObjectSchema, Qt::UserRole).toString(); + tab_name=item->data(DatabaseImportForm::ObjectTable, Qt::UserRole).toString(); if(parent) { @@ -1329,12 +1427,12 @@ void DatabaseExplorerWidget::updateItem(QTreeWidgetItem *item) } else { - if(obj_type==OBJ_SCHEMA || obj_type==OBJ_TABLE || obj_type == OBJ_VIEW) + if(obj_type==ObjectType::Schema || obj_type==ObjectType::Table || obj_type == ObjectType::View) { root=item; root->takeChildren(); - if(obj_type == OBJ_SCHEMA) + if(obj_type == ObjectType::Schema) sch_name=item->text(0); else tab_name=item->text(0); @@ -1350,7 +1448,7 @@ void DatabaseExplorerWidget::updateItem(QTreeWidgetItem *item) configureImportHelper(); //Updates the group type only - if(obj_id==0 || (obj_type!=OBJ_TABLE && obj_type!=OBJ_VIEW && obj_type!=OBJ_SCHEMA)) + if(obj_id==0 || (obj_type!=ObjectType::Table && obj_type!=ObjectType::View && obj_type!=ObjectType::Schema)) gen_items=DatabaseImportForm::updateObjectsTree(import_helper, objects_trw, { obj_type }, false, false, root, sch_name, tab_name, sort_column); else //Updates all child objcts when the selected object is a schema or table or view @@ -1358,13 +1456,13 @@ void DatabaseExplorerWidget::updateItem(QTreeWidgetItem *item) BaseObject::getChildObjectTypes(obj_type), false, false, root, sch_name, tab_name, sort_column); //Creating dummy items for schemas and tables - if(obj_type==OBJ_SCHEMA || obj_type==OBJ_TABLE || obj_type==OBJ_VIEW) + if(obj_type==ObjectType::Schema || obj_type==ObjectType::Table || obj_type==ObjectType::View) { for(auto &item : gen_items) { aux_item=new QTreeWidgetItem(item); aux_item->setText(0, QString("...")); - aux_item->setData(DatabaseImportForm::OBJECT_OTHER_DATA, Qt::UserRole, QVariant::fromValue(-1)); + aux_item->setData(DatabaseImportForm::ObjectOtherData, Qt::UserRole, QVariant::fromValue(-1)); } } @@ -1372,7 +1470,7 @@ void DatabaseExplorerWidget::updateItem(QTreeWidgetItem *item) objects_trw->sortItems(sort_column, Qt::AscendingOrder); objects_trw->setCurrentItem(nullptr); - if(obj_type==OBJ_TABLE) + if(obj_type==ObjectType::Table) { objects_trw->blockSignals(true); objects_trw->setCurrentItem(item); @@ -1391,15 +1489,15 @@ void DatabaseExplorerWidget::loadObjectProperties(bool force_reload) try { QTreeWidgetItem *item=objects_trw->currentItem(); - unsigned oid=item->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toUInt(); + unsigned oid=item->data(DatabaseImportForm::ObjectId, Qt::UserRole).toUInt(); if(oid != 0 || (item == objects_trw->topLevelItem(0))) { - ObjectType obj_type=static_cast(item->data(DatabaseImportForm::OBJECT_TYPE, Qt::UserRole).toUInt()); + ObjectType obj_type=static_cast(item->data(DatabaseImportForm::ObjectTypeId, Qt::UserRole).toUInt()); attribs_map orig_attribs, fmt_attribs; //First, retrieve the attributes stored on the item as a result of a previous properties listing - orig_attribs=item->data(DatabaseImportForm::OBJECT_ATTRIBS, Qt::UserRole).value(); + orig_attribs=item->data(DatabaseImportForm::ObjectAttribs, Qt::UserRole).value(); //In case of the cached attributes are empty if(orig_attribs.empty() || force_reload) @@ -1411,33 +1509,33 @@ void DatabaseExplorerWidget::loadObjectProperties(bool force_reload) if(item == objects_trw->topLevelItem(0)) orig_attribs=catalog.getServerAttributes(); //Retrieve them from the catalog - else if(obj_type!=OBJ_COLUMN) + else if(obj_type!=ObjectType::Column) { orig_attribs=catalog.getObjectAttributes(obj_type, oid); - if(obj_type == OBJ_TABLE) + if(obj_type == ObjectType::Table) { vector ref_fks; attribs_map ref_table, ref_schema; QStringList tab_list; - ref_fks = catalog.getObjectsAttributes(OBJ_CONSTRAINT, QString(), QString(), {}, {{ ParsersAttributes::CUSTOM_FILTER, QString("contype='f' AND cs.confrelid=%1").arg(orig_attribs[ParsersAttributes::OID])}}); + ref_fks = catalog.getObjectsAttributes(ObjectType::Constraint, QString(), QString(), {}, {{ Attributes::CustomFilter, QString("contype='f' AND cs.confrelid=%1").arg(orig_attribs[Attributes::Oid])}}); for(auto &fk : ref_fks) { - ref_table = catalog.getObjectAttributes(OBJ_TABLE, fk[ParsersAttributes::TABLE].toUInt()); - ref_schema = catalog.getObjectAttributes(OBJ_SCHEMA, ref_table[ParsersAttributes::SCHEMA].toUInt()); - tab_list.push_back(QString("%1.%2").arg(ref_schema[ParsersAttributes::NAME]).arg(ref_table[ParsersAttributes::NAME])); + ref_table = catalog.getObjectAttributes(ObjectType::Table, fk[Attributes::Table].toUInt()); + ref_schema = catalog.getObjectAttributes(ObjectType::Schema, ref_table[Attributes::Schema].toUInt()); + tab_list.push_back(QString("%1.%2").arg(ref_schema[Attributes::Name]).arg(ref_table[Attributes::Name])); } if(!tab_list.isEmpty()) - orig_attribs[ParsersAttributes::REFERRERS] = tab_list.join(Table::DATA_SEPARATOR); + orig_attribs[Attributes::Referrers] = tab_list.join(Table::DataSeparator); } } else { - QString tab_name=item->data(DatabaseImportForm::OBJECT_TABLE, Qt::UserRole).toString(), - sch_name=item->data(DatabaseImportForm::OBJECT_SCHEMA, Qt::UserRole).toString(); + QString tab_name=item->data(DatabaseImportForm::ObjectTable, Qt::UserRole).toString(), + sch_name=item->data(DatabaseImportForm::ObjectSchema, Qt::UserRole).toString(); vector vect_attribs=catalog.getObjectsAttributes(obj_type, sch_name, tab_name, { oid }); if(!vect_attribs.empty()) @@ -1446,16 +1544,16 @@ void DatabaseExplorerWidget::loadObjectProperties(bool force_reload) //Format values and translate the attribute names fmt_attribs=formatObjectAttribs(orig_attribs); - fmt_attribs.erase(ParsersAttributes::SIGNATURE); + fmt_attribs.erase(Attributes::Signature); //Store the original attributes on the item to permit value replacements when using code snippets - item->setData(DatabaseImportForm::OBJECT_OTHER_DATA, Qt::UserRole, QVariant::fromValue(orig_attribs)); + item->setData(DatabaseImportForm::ObjectOtherData, Qt::UserRole, QVariant::fromValue(orig_attribs)); //Store the attributes on the item to avoid repeatedly query the database - item->setData(DatabaseImportForm::OBJECT_ATTRIBS, Qt::UserRole, QVariant::fromValue(fmt_attribs)); + item->setData(DatabaseImportForm::ObjectAttribs, Qt::UserRole, QVariant::fromValue(fmt_attribs)); if(item != objects_trw->topLevelItem(0)) - item->setData(DatabaseImportForm::OBJECT_SOURCE, Qt::UserRole, DEFAULT_SOURCE_CODE); + item->setData(DatabaseImportForm::ObjectSource, Qt::UserRole, DefaultSourceCode); catalog.closeConnection(); QApplication::restoreOverrideCursor(); @@ -1465,7 +1563,7 @@ void DatabaseExplorerWidget::loadObjectProperties(bool force_reload) catch(Exception &e) { QApplication::restoreOverrideCursor(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -1477,7 +1575,7 @@ void DatabaseExplorerWidget::showObjectProperties(bool force_reload) clearObjectProperties(); if(item && - ((item->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toInt() >= 0) || + ((item->data(DatabaseImportForm::ObjectId, Qt::UserRole).toInt() >= 0) || (item == objects_trw->topLevelItem(0)))) { attribs_map cached_attribs; @@ -1488,7 +1586,7 @@ void DatabaseExplorerWidget::showObjectProperties(bool force_reload) loadObjectProperties(force_reload); cached_attribs=item->data((raw_attrib_names_chk->isChecked() ? - DatabaseImportForm::OBJECT_OTHER_DATA : DatabaseImportForm::OBJECT_ATTRIBS), + DatabaseImportForm::ObjectOtherData : DatabaseImportForm::ObjectAttribs), Qt::UserRole).value(); properties_tbw->setSortingEnabled(false); @@ -1506,10 +1604,10 @@ void DatabaseExplorerWidget::showObjectProperties(bool force_reload) font.setItalic(true); tab_item->setText(attrib.first); tab_item->setFont(font); - tab_item->setIcon(QPixmap(PgModelerUiNS::getIconPath("attribute"))); + tab_item->setIcon(QPixmap(PgModelerUiNs::getIconPath("attribute"))); properties_tbw->setItem(row, 0, tab_item); - values=attrib.second.split(ELEM_SEPARATOR); + values=attrib.second.split(ElemSeparator); //Creating the value item if(values.size() >= 2) @@ -1532,60 +1630,60 @@ void DatabaseExplorerWidget::showObjectProperties(bool force_reload) } } - cached_attribs=item->data(DatabaseImportForm::OBJECT_OTHER_DATA,Qt::UserRole).value(); + cached_attribs=item->data(DatabaseImportForm::ObjectOtherData,Qt::UserRole).value(); - if(cached_attribs[ParsersAttributes::OBJECT_TYPE]==BaseObject::getSchemaName(OBJ_CONSTRAINT) && item->childCount()==0) + if(cached_attribs[Attributes::ObjectType]==BaseObject::getSchemaName(ObjectType::Constraint) && item->childCount()==0) { QTreeWidgetItem *fk_item=nullptr, *src_item=nullptr; - if(cached_attribs[ParsersAttributes::TYPE]==~ConstraintType(ConstraintType::foreign_key)) + if(cached_attribs[Attributes::Type]==~ConstraintType(ConstraintType::ForeignKey)) { /* Creates two items denoting the source columns and referenced tables. These items have a negative id indicating that no popup menu will be show if user right-click them. */ src_item=new QTreeWidgetItem(item); - src_item->setData(DatabaseImportForm::OBJECT_ID, Qt::UserRole, QVariant::fromValue(-1)); - src_item->setIcon(0, QPixmap(PgModelerUiNS::getIconPath("column"))); + src_item->setData(DatabaseImportForm::ObjectId, Qt::UserRole, QVariant::fromValue(-1)); + src_item->setIcon(0, QPixmap(PgModelerUiNs::getIconPath("column"))); src_item->setText(0, QString("%1(%2)") - .arg(cached_attribs[ParsersAttributes::TABLE]) - .arg(cached_attribs[ParsersAttributes::SRC_COLUMNS])); + .arg(cached_attribs[Attributes::Table]) + .arg(cached_attribs[Attributes::SrcColumns])); src_item->setToolTip(0, trUtf8("Src. table: %1\nSrc. column(s): %2") - .arg(cached_attribs[ParsersAttributes::TABLE]) - .arg(cached_attribs[ParsersAttributes::SRC_COLUMNS])); + .arg(cached_attribs[Attributes::Table]) + .arg(cached_attribs[Attributes::SrcColumns])); src_item->setFlags(Qt::ItemIsEnabled); fk_item=new QTreeWidgetItem(item); - fk_item->setData(DatabaseImportForm::OBJECT_ID, Qt::UserRole, QVariant::fromValue(-1)); - fk_item->setIcon(0, QPixmap(PgModelerUiNS::getIconPath("referenced"))); + fk_item->setData(DatabaseImportForm::ObjectId, Qt::UserRole, QVariant::fromValue(-1)); + fk_item->setIcon(0, QPixmap(PgModelerUiNs::getIconPath("referenced"))); fk_item->setText(0, QString("%1(%2)") - .arg(cached_attribs[ParsersAttributes::REF_TABLE]) - .arg(cached_attribs[ParsersAttributes::DST_COLUMNS])); + .arg(cached_attribs[Attributes::RefTable]) + .arg(cached_attribs[Attributes::DstColumns])); fk_item->setToolTip(0, trUtf8("Ref. table: %1\nRef. column(s): %2") - .arg(cached_attribs[ParsersAttributes::REF_TABLE]) - .arg(cached_attribs[ParsersAttributes::DST_COLUMNS])); + .arg(cached_attribs[Attributes::RefTable]) + .arg(cached_attribs[Attributes::DstColumns])); fk_item->setFlags(Qt::ItemIsEnabled); } - else if(cached_attribs[ParsersAttributes::TYPE]==~ConstraintType(ConstraintType::unique) || - cached_attribs[ParsersAttributes::TYPE]==~ConstraintType(ConstraintType::primary_key)) + else if(cached_attribs[Attributes::Type]==~ConstraintType(ConstraintType::Unique) || + cached_attribs[Attributes::Type]==~ConstraintType(ConstraintType::PrimaryKey)) { - QStringList columns=cached_attribs[ParsersAttributes::SRC_COLUMNS].split(ELEM_SEPARATOR); + QStringList columns=cached_attribs[Attributes::SrcColumns].split(ElemSeparator); for(auto &col : columns) { src_item=new QTreeWidgetItem(item); - src_item->setData(DatabaseImportForm::OBJECT_ID, Qt::UserRole, QVariant::fromValue(-1)); - src_item->setIcon(0, QPixmap(PgModelerUiNS::getIconPath("column"))); + src_item->setData(DatabaseImportForm::ObjectId, Qt::UserRole, QVariant::fromValue(-1)); + src_item->setIcon(0, QPixmap(PgModelerUiNs::getIconPath("column"))); src_item->setText(0, col); src_item->setFlags(Qt::ItemIsEnabled); } } } - else if(cached_attribs[ParsersAttributes::OBJECT_TYPE] == BaseObject::getSchemaName(OBJ_TABLE) && - !cached_attribs[ParsersAttributes::REFERRERS].isEmpty() && item->childCount() == 5) + else if(cached_attribs[Attributes::ObjectType] == BaseObject::getSchemaName(ObjectType::Table) && + !cached_attribs[Attributes::Referrers].isEmpty() && item->childCount() == 5) { QTreeWidgetItem *refs_item=nullptr, *tab_item=nullptr; - QStringList ref_tab_names = cached_attribs[ParsersAttributes::REFERRERS].split(Table::DATA_SEPARATOR); + QStringList ref_tab_names = cached_attribs[Attributes::Referrers].split(Table::DataSeparator); QFont font; refs_item=new QTreeWidgetItem(item); @@ -1593,24 +1691,24 @@ void DatabaseExplorerWidget::showObjectProperties(bool force_reload) font.setItalic(true); refs_item->setFont(0, font); - refs_item->setData(DatabaseImportForm::OBJECT_ID, Qt::UserRole, QVariant::fromValue(-1)); - refs_item->setIcon(0, QPixmap(PgModelerUiNS::getIconPath("referrer"))); + refs_item->setData(DatabaseImportForm::ObjectId, Qt::UserRole, QVariant::fromValue(-1)); + refs_item->setIcon(0, QPixmap(PgModelerUiNs::getIconPath("referrer"))); refs_item->setText(0, QString("%1 (%2)") - .arg(attribs_i18n.at(ParsersAttributes::REFERRERS)) + .arg(attribs_i18n.at(Attributes::Referrers)) .arg(ref_tab_names.length())); for(QString tab_name : ref_tab_names) { tab_item=new QTreeWidgetItem(refs_item); - tab_item->setData(DatabaseImportForm::OBJECT_ID, Qt::UserRole, QVariant::fromValue(-1)); - tab_item->setIcon(0, QPixmap(PgModelerUiNS::getIconPath("table"))); + tab_item->setData(DatabaseImportForm::ObjectId, Qt::UserRole, QVariant::fromValue(-1)); + tab_item->setIcon(0, QPixmap(PgModelerUiNs::getIconPath("table"))); tab_item->setText(0, tab_name); tab_item->setFlags(Qt::ItemIsEnabled); } } } - emit s_sourceCodeShowRequested(item->data(DatabaseImportForm::OBJECT_SOURCE, Qt::UserRole).toString()); + emit s_sourceCodeShowRequested(item->data(DatabaseImportForm::ObjectSource, Qt::UserRole).toString()); properties_tbw->setSortingEnabled(true); properties_tbw->sortByColumn(0, Qt::AscendingOrder); @@ -1621,22 +1719,22 @@ void DatabaseExplorerWidget::showObjectProperties(bool force_reload) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } void DatabaseExplorerWidget::startObjectRename(QTreeWidgetItem *item) { - if(item && static_cast(item->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toUInt()) > 0) + if(item && item->data(DatabaseImportForm::ObjectId, Qt::UserRole).toUInt() > 0) { - ObjectType obj_type=static_cast(item->data(DatabaseImportForm::OBJECT_TYPE, Qt::UserRole).toUInt()); + ObjectType obj_type=static_cast(item->data(DatabaseImportForm::ObjectTypeId, Qt::UserRole).toUInt()); - if(obj_type!=OBJ_CAST && obj_type!=OBJ_DATABASE) + if(obj_type!=ObjectType::Cast && obj_type!=ObjectType::Database) { item->setFlags(item->flags() | Qt::ItemIsEditable); objects_trw->openPersistentEditor(item); rename_item=item; - rename_item->setData(DatabaseImportForm::OBJECT_OTHER_DATA, Qt::UserRole, rename_item->text(0)); + rename_item->setData(DatabaseImportForm::ObjectOtherData, Qt::UserRole, rename_item->text(0)); } } } @@ -1652,17 +1750,17 @@ void DatabaseExplorerWidget::finishObjectRename(void) QString rename_cmd; Connection conn=connection; attribs_map attribs=extractAttributesFromItem(rename_item); - ObjectType obj_type=static_cast(rename_item->data(DatabaseImportForm::OBJECT_TYPE, Qt::UserRole).toUInt()); + ObjectType obj_type=static_cast(rename_item->data(DatabaseImportForm::ObjectTypeId, Qt::UserRole).toUInt()); objects_trw->closePersistentEditor(rename_item); - attribs[ParsersAttributes::NEW_NAME]=BaseObject::formatName(rename_item->text(0), obj_type==OBJ_OPERATOR); + attribs[Attributes::NewName]=BaseObject::formatName(rename_item->text(0), obj_type==ObjectType::Operator); //Generate the drop command schparser.ignoreEmptyAttributes(true); schparser.ignoreUnkownAttributes(true); - rename_cmd=schparser.getCodeDefinition(GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::ALTER_SCHEMA_DIR + GlobalAttributes::DIR_SEPARATOR + - ParsersAttributes::RENAME + GlobalAttributes::SCHEMA_EXT, + rename_cmd=schparser.getCodeDefinition(GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + GlobalAttributes::AlterSchemaDir + GlobalAttributes::DirSeparator + + Attributes::Rename + GlobalAttributes::SchemaExt, attribs); //Executes the rename cmd @@ -1686,7 +1784,7 @@ void DatabaseExplorerWidget::cancelObjectRename(void) { objects_trw->closePersistentEditor(rename_item); rename_item->setFlags(rename_item->flags() ^ Qt::ItemIsEditable); - rename_item->setText(0, rename_item->data(DatabaseImportForm::OBJECT_OTHER_DATA, Qt::UserRole).toString()); + rename_item->setText(0, rename_item->data(DatabaseImportForm::ObjectOtherData, Qt::UserRole).toString()); rename_item=nullptr; } } @@ -1700,13 +1798,13 @@ void DatabaseExplorerWidget::loadObjectSource(void) if(item == objects_trw->topLevelItem(0)) { QString n = item->text(0); - emit s_sourceCodeShowRequested(item->data(DatabaseImportForm::OBJECT_SOURCE, Qt::UserRole).toString()); + emit s_sourceCodeShowRequested(item->data(DatabaseImportForm::ObjectSource, Qt::UserRole).toString()); } else if(item) { - QString source=item->data(DatabaseImportForm::OBJECT_SOURCE, Qt::UserRole).toString(); + QString source=item->data(DatabaseImportForm::ObjectSource, Qt::UserRole).toString(); - if(source!=DEFAULT_SOURCE_CODE) + if(source!=DefaultSourceCode) { emit s_sourceCodeShowRequested(source); } @@ -1714,24 +1812,24 @@ void DatabaseExplorerWidget::loadObjectSource(void) { DatabaseModel dbmodel; DatabaseImportHelper import_hlp; - ObjectType obj_type=static_cast(item->data(DatabaseImportForm::OBJECT_TYPE, Qt::UserRole).toUInt()); + ObjectType obj_type=static_cast(item->data(DatabaseImportForm::ObjectTypeId, Qt::UserRole).toUInt()); QString sch_name, tab_name, name; QTreeWidgetItem *sch_item=nullptr; BaseObject *object=nullptr; BaseObject *schema=nullptr; - attribs_map attribs=item->data(DatabaseImportForm::OBJECT_OTHER_DATA, Qt::UserRole).value(); + attribs_map attribs=item->data(DatabaseImportForm::ObjectOtherData, Qt::UserRole).value(); bool is_column=false; - unsigned oid=item->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toUInt(), - db_oid=objects_trw->topLevelItem(0)->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toUInt(), + unsigned oid=item->data(DatabaseImportForm::ObjectId, Qt::UserRole).toUInt(), + db_oid=objects_trw->topLevelItem(0)->child(0)->data(DatabaseImportForm::ObjectId, Qt::UserRole).toUInt(), sys_oid=0; int sbar_value=(objects_trw->verticalScrollBar() ? objects_trw->verticalScrollBar()->value() : 0); QApplication::setOverrideCursor(Qt::WaitCursor); - sch_name=item->data(DatabaseImportForm::OBJECT_SCHEMA, Qt::UserRole).toString(); - tab_name=item->data(DatabaseImportForm::OBJECT_TABLE, Qt::UserRole).toString(); - name=item->data(DatabaseImportForm::OBJECT_NAME, Qt::UserRole).toString(); + sch_name=item->data(DatabaseImportForm::ObjectSchema, Qt::UserRole).toString(); + tab_name=item->data(DatabaseImportForm::ObjectTable, Qt::UserRole).toString(); + name=item->data(DatabaseImportForm::ObjectName, Qt::UserRole).toString(); - if(!sch_name.isEmpty() && obj_type!=OBJ_EXTENSION) + if(!sch_name.isEmpty() && obj_type!=ObjectType::Extension) { if(tab_name.isEmpty()) name.prepend(sch_name + QChar('.')); @@ -1740,41 +1838,44 @@ void DatabaseExplorerWidget::loadObjectSource(void) } //Special case for columns. We will retrieve the table from database and then generate the code for the column - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) { - oid=item->parent()->parent()->data(DatabaseImportForm::OBJECT_ID, Qt::UserRole).toUInt(); + oid=item->parent()->parent()->data(DatabaseImportForm::ObjectId, Qt::UserRole).toUInt(); is_column=true; - obj_type=OBJ_TABLE; + obj_type=ObjectType::Table; } //Importing the object and its dependencies dbmodel.createSystemObjects(false); import_hlp.setConnection(connection); - import_hlp.setCurrentDatabase(connection.getConnectionParam(Connection::PARAM_DB_NAME)); - import_hlp.setImportOptions(toggle_disp_menu.actions().at(0)->isChecked(), - toggle_disp_menu.actions().at(1)->isChecked(), + import_hlp.setCurrentDatabase(connection.getConnectionParam(Connection::ParamDbName)); + + import_hlp.setImportOptions(show_sys_objs->isChecked(), + show_ext_objs->isChecked(), true, false, false, false, false); - import_hlp.setSelectedOIDs(&dbmodel, {{OBJ_DATABASE, {db_oid}}, {obj_type,{oid}}}, {}); + + import_hlp.setSelectedOIDs(&dbmodel, {{ObjectType::Database, {db_oid}}, {obj_type,{oid}}}, {}); + sys_oid=import_hlp.getLastSystemOID(); //Currently pgModeler does not support the visualization of base types and built-in ones - if(obj_type==OBJ_TYPE && - (oid <= sys_oid || attribs[ParsersAttributes::CONFIGURATION]==ParsersAttributes::BASE_TYPE)) + if(obj_type==ObjectType::Type && + (oid <= sys_oid || attribs[Attributes::Configuration]==Attributes::BaseType)) { - source=trUtf8("-- Source code genaration for buil-in and base types currently unavailable --"); + source=QString("-- %1 --").arg(trUtf8("Source code genaration for built-in and base types currently unavailable.")); emit s_sourceCodeShowRequested(source); } else { import_hlp.importDatabase(); - if(obj_type==OBJ_DATABASE) + if(obj_type==ObjectType::Database) source=getObjectSource(&dbmodel, &dbmodel); else { /* Fixing the signature of opclasses and opfamilies. The name is in form "name [index type]", so we change it to "name USING [index type]" */ - if(obj_type==OBJ_OPCLASS || obj_type==OBJ_OPFAMILY) + if(obj_type==ObjectType::OpClass || obj_type==ObjectType::OpFamily) { QString idx_type=item->text(0); @@ -1788,7 +1889,7 @@ void DatabaseExplorerWidget::loadObjectSource(void) if(TableObject::isTableObject(obj_type) || is_column) { Table *table=nullptr; - table=dynamic_cast
(dbmodel.getObject(tab_name, OBJ_TABLE)); + table=dynamic_cast
(dbmodel.getObject(tab_name, ObjectType::Table)); QTreeWidgetItem *table_item=nullptr; //If the table was imported then the source code of it will be placed on the respective item @@ -1796,14 +1897,14 @@ void DatabaseExplorerWidget::loadObjectSource(void) { table_item=item->parent()->parent(); objects_trw->setCurrentItem(item->parent()->parent()); - table_item->setData(DatabaseImportForm::OBJECT_SOURCE, Qt::UserRole, getObjectSource(table, &dbmodel)); + table_item->setData(DatabaseImportForm::ObjectSource, Qt::UserRole, getObjectSource(table, &dbmodel)); sch_item=table_item->parent()->parent(); schema=table->getSchema(); //Generate the code of table children objects as ALTER commands table->setGenerateAlterCmds(true); - object=table->getObject(name, (is_column ? OBJ_COLUMN : obj_type)); + object=table->getObject(name, (is_column ? ObjectType::Column : obj_type)); } } else @@ -1815,7 +1916,7 @@ void DatabaseExplorerWidget::loadObjectSource(void) if(object) source=getObjectSource(object, &dbmodel); else - source=trUtf8("-- Source code unavailable for the object %1 (%2). --").arg(name).arg(BaseObject::getTypeName(obj_type)); + source=QString("-- %1 --").arg(trUtf8("Source code unavailable for the object %1 (%2).").arg(name).arg(BaseObject::getTypeName(obj_type))); } } @@ -1824,17 +1925,17 @@ void DatabaseExplorerWidget::loadObjectSource(void) { if(!sch_item) sch_item=item->parent()->parent(); objects_trw->setCurrentItem(sch_item); - sch_item->setData(DatabaseImportForm::OBJECT_SOURCE, Qt::UserRole, getObjectSource(schema, &dbmodel)); + sch_item->setData(DatabaseImportForm::ObjectSource, Qt::UserRole, getObjectSource(schema, &dbmodel)); } - if(obj_type != OBJ_DATABASE) + if(obj_type != ObjectType::Database) { //Generating the code for the database itself and storing it in the first child of the root item in the tree objects_trw->setCurrentItem(objects_trw->topLevelItem(0)); - objects_trw->topLevelItem(0)->child(0)->setData(DatabaseImportForm::OBJECT_SOURCE, Qt::UserRole, getObjectSource(&dbmodel, &dbmodel)); + objects_trw->topLevelItem(0)->child(0)->setData(DatabaseImportForm::ObjectSource, Qt::UserRole, getObjectSource(&dbmodel, &dbmodel)); } - item->setData(DatabaseImportForm::OBJECT_SOURCE, Qt::UserRole, source); + item->setData(DatabaseImportForm::ObjectSource, Qt::UserRole, source); objects_trw->setCurrentItem(item); /* Restore the position of the scrollbar in the tree because the usage of setCurrentItem in previous lines @@ -1857,7 +1958,7 @@ void DatabaseExplorerWidget::loadObjectSource(void) void DatabaseExplorerWidget::filterObjects(void) { DatabaseImportForm::filterObjects(objects_trw, filter_edt->text(), - (by_oid_chk->isChecked() ? DatabaseImportForm::OBJECT_ID : 0), false); + (by_oid_chk->isChecked() ? DatabaseImportForm::ObjectId : 0), false); } QString DatabaseExplorerWidget::getObjectSource(BaseObject *object, DatabaseModel *dbmodel) @@ -1874,25 +1975,18 @@ QString DatabaseExplorerWidget::getObjectSource(BaseObject *object, DatabaseMode object->setCodeInvalidated(true); if(object!=dbmodel) - source=object->getCodeDefinition(SchemaParser::SQL_DEFINITION); + source=object->getCodeDefinition(SchemaParser::SqlDefinition); else - source=dbmodel->__getCodeDefinition(SchemaParser::SQL_DEFINITION); + source=dbmodel->__getCodeDefinition(SchemaParser::SqlDefinition); for(auto &perm : perms) - source+=perm->getCodeDefinition(SchemaParser::SQL_DEFINITION); + source+=perm->getCodeDefinition(SchemaParser::SqlDefinition); return(source); } void DatabaseExplorerWidget::openDataGrid(const QString &schema, const QString &table, bool hide_views) { -#ifdef DEMO_VERSION -#warning "DEMO VERSION: data manipulation feature disabled warning." - Messagebox msg_box; - msg_box.show(trUtf8("Warning"), - trUtf8("You're running a demonstration version! The data manipulation feature is available only in the full version!"), - Messagebox::ALERT_ICON, Messagebox::OK_BUTTON); -#else DataManipulationForm *data_manip=new DataManipulationForm; Connection conn=Connection(this->connection.getConnectionParams()); @@ -1901,27 +1995,27 @@ void DatabaseExplorerWidget::openDataGrid(const QString &schema, const QString & data_manip->hide_views_chk->setChecked(hide_views); data_manip->setAttributes(conn, schema, table); - - PgModelerUiNS::resizeDialog(data_manip); + PgModelerUiNs::resizeDialog(data_manip); + GeneralConfigWidget::restoreWidgetGeometry(data_manip); data_manip->show(); -#endif } void DatabaseExplorerWidget::dropDatabase(void) { Messagebox msg_box; - QString dbname = connection.getConnectionParam(Connection::PARAM_DB_NAME); + QString dbname = connection.getConnectionParam(Connection::ParamDbName); msg_box.show(trUtf8("Warning"), - trUtf8("CAUTION: You are about to drop the entire database %1! All data will be completely wiped out. Do you really want to proceed?").arg(dbname), - Messagebox::ALERT_ICON, Messagebox::YES_NO_BUTTONS); + trUtf8("CAUTION: You are about to drop the entire database %1 from the server %2! All data will be completely wiped out. Do you really want to proceed?") + .arg(dbname).arg(connection.getConnectionId(true)), + Messagebox::AlertIcon, Messagebox::YesNoButtons); if(msg_box.result()==QDialog::Accepted) { try { Connection conn=Connection(connection.getConnectionParams()); - conn.setConnectionParam(Connection::PARAM_DB_NAME, default_db); + conn.setConnectionParam(Connection::ParamDbName, default_db); conn.connect(); conn.executeDDLCommand(QString("DROP DATABASE \"%1\";").arg(dbname)); conn.close(); @@ -1930,12 +2024,12 @@ void DatabaseExplorerWidget::dropDatabase(void) } catch(Exception &e) { - if(connection.getConnectionParam(Connection::PARAM_DB_NAME) == default_db) - throw Exception(Exception::getErrorMessage(ERR_DROP_CURRDB_DEFAULT) - .arg(dbname).arg(connection.getConnectionParam(Connection::PARAM_ALIAS)), - ERR_DROP_CURRDB_DEFAULT,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + if(connection.getConnectionParam(Connection::ParamDbName) == default_db) + throw Exception(Exception::getErrorMessage(ErrorCode::DropCurrentDBDefault) + .arg(dbname).arg(connection.getConnectionParam(Connection::ParamAlias)), + ErrorCode::DropCurrentDBDefault,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); else - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } } diff --git a/libpgmodeler_ui/src/databaseexplorerwidget.h b/libpgmodeler_ui/src/databaseexplorerwidget.h index cd58b1c9f4..483b3615d2 100644 --- a/libpgmodeler_ui/src/databaseexplorerwidget.h +++ b/libpgmodeler_ui/src/databaseexplorerwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -34,10 +34,10 @@ class DatabaseExplorerWidget: public QWidget, public Ui::DatabaseExplorerWidget private: Q_OBJECT - static const QString DEP_NOT_DEFINED, - DEP_NOT_FOUND, - ELEM_SEPARATOR, - DEFAULT_SOURCE_CODE; + static const QString DepNotDefined, + DepNotFound, + ElemSeparator, + DefaultSourceCode; //! \brief Stores the translations of all used attributes at properties panel static const attribs_map attribs_i18n; @@ -132,6 +132,9 @@ class DatabaseExplorerWidget: public QWidget, public Ui::DatabaseExplorerWidget void formatConstraintAttribs(attribs_map &attribs); void formatIndexAttribs(attribs_map &attribs); void formatPolicyAttribs(attribs_map &attribs); + void formatForeignDataWrapperAttribs(attribs_map &attribs); + void formatServerAttribs(attribs_map &attribs); + void formatUserMappingAttribs(attribs_map &attribs); void handleSelectedSnippet(const QString &snip_id); //! \brief Extract an attribute map containing the basic attributes for drop/rename commands @@ -144,7 +147,7 @@ class DatabaseExplorerWidget: public QWidget, public Ui::DatabaseExplorerWidget QString getObjectSource(BaseObject *object, DatabaseModel *dbmodel); public: - DatabaseExplorerWidget(QWidget * parent = 0); + DatabaseExplorerWidget(QWidget * parent = nullptr); //! \brief Configures the connection used to retrieve and manipulate objects on database void setConnection(Connection conn, const QString &default_db); @@ -155,6 +158,9 @@ class DatabaseExplorerWidget: public QWidget, public Ui::DatabaseExplorerWidget //! \brief Clears the object's properties table void clearObjectProperties(void); + //! \brief Truncates a named table (in cascade mode or not) using the provided connection + static bool truncateTable(const QString &sch_name, const QString &obj_name, bool cascade, Connection connection); + public slots: //! \brief Lists all objects for the current selected database void listObjects(void); diff --git a/libpgmodeler_ui/src/databaseimportform.cpp b/libpgmodeler_ui/src/databaseimportform.cpp index a52611c7b0..a5d1dc9aec 100644 --- a/libpgmodeler_ui/src/databaseimportform.cpp +++ b/libpgmodeler_ui/src/databaseimportform.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -23,6 +23,8 @@ #include "pgmodeleruins.h" #include "pgmodelerns.h" +bool DatabaseImportForm::low_verbosity = false; + DatabaseImportForm::DatabaseImportForm(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f) { setupUi(this); @@ -103,6 +105,11 @@ void DatabaseImportForm::setModelWidget(ModelWidget *model) import_to_model_chk->setEnabled(model!=nullptr); } +void DatabaseImportForm::setLowVerbosity(bool value) +{ + low_verbosity = value; +} + void DatabaseImportForm::createThread(void) { import_thread=new QThread; @@ -141,17 +148,19 @@ void DatabaseImportForm::updateProgress(int progress, QString msg, ObjectType ob { QPixmap ico; - msg=PgModelerUiNS::formatMessage(msg); + msg=PgModelerUiNs::formatMessage(msg); progress_lbl->setText(msg); progress_pb->setValue(progress); - if(obj_type!=BASE_OBJECT) - ico=QPixmap(PgModelerUiNS::getIconPath(obj_type)); + if(obj_type!=ObjectType::BaseObject) + ico=QPixmap(PgModelerUiNs::getIconPath(obj_type)); else - ico=QPixmap(PgModelerUiNS::getIconPath("msgbox_info")); + ico=QPixmap(PgModelerUiNs::getIconPath("msgbox_info")); ico_lbl->setPixmap(ico); - PgModelerUiNS::createOutputTreeItem(output_trw, msg, ico); + + if(!low_verbosity) + PgModelerUiNs::createOutputTreeItem(output_trw, msg, ico); } void DatabaseImportForm::setItemCheckState(QTreeWidgetItem *item, int) @@ -192,7 +201,7 @@ void DatabaseImportForm::importDatabase(void) if(import_to_model_chk->isChecked()) { msg_box.show(trUtf8("ATTENTION: You are about to import objects to the current working model! This action will cause irreversible changes to it even in case of critical errors during the process. Do you want to proceed?"), - Messagebox::ALERT_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::AlertIcon, Messagebox::YesNoButtons); if(msg_box.result()==QDialog::Rejected) return; @@ -202,8 +211,12 @@ void DatabaseImportForm::importDatabase(void) settings_tbw->setTabEnabled(1, true); settings_tbw->setCurrentIndex(1); + if(low_verbosity) + PgModelerUiNs::createOutputTreeItem(output_trw, trUtf8("Low verbosity is set: only key informations and errors will be displayed."), + QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta")), nullptr, false); + getCheckedItems(obj_oids, col_oids); - obj_oids[OBJ_DATABASE].push_back(database_cmb->itemData(database_cmb->currentIndex()).value()); + obj_oids[ObjectType::Database].push_back(database_cmb->itemData(database_cmb->currentIndex()).value()); if(create_model) { @@ -225,7 +238,7 @@ void DatabaseImportForm::importDatabase(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -259,7 +272,7 @@ bool DatabaseImportForm::hasCheckedItems(void) while(*itr && !selected) { //Only valid items (OID > 0) and with Checked state are considered as selected - selected=((*itr)->checkState(0)==Qt::Checked && (*itr)->data(OBJECT_ID, Qt::UserRole).value() > 0); + selected=((*itr)->checkState(0)==Qt::Checked && (*itr)->data(ObjectId, Qt::UserRole).value() > 0); ++itr; } @@ -278,21 +291,21 @@ void DatabaseImportForm::getCheckedItems(map> &obj_ while(*itr) { //If the item is checked and its OID is valid - if((*itr)->checkState(0)==Qt::Checked && (*itr)->data(OBJECT_ID, Qt::UserRole).value() > 0) + if((*itr)->checkState(0)==Qt::Checked && (*itr)->data(ObjectId, Qt::UserRole).value() > 0) { - obj_type=static_cast((*itr)->data(OBJECT_TYPE, Qt::UserRole).value()); + obj_type=static_cast((*itr)->data(ObjectTypeId, Qt::UserRole).value()); //If the object is not a column store it on general object list - if(obj_type!=OBJ_COLUMN) - obj_oids[obj_type].push_back((*itr)->data(OBJECT_ID, Qt::UserRole).value()); + if(obj_type!=ObjectType::Column) + obj_oids[obj_type].push_back((*itr)->data(ObjectId, Qt::UserRole).value()); //If its a column else { //Get the table's oid from the parent item - tab_oid=(*itr)->parent()->parent()->data(OBJECT_ID, Qt::UserRole).value(); + tab_oid=(*itr)->parent()->parent()->data(ObjectId, Qt::UserRole).value(); //Store the column oid on the selected colums map using the table oid as key - col_oids[tab_oid].push_back((*itr)->data(OBJECT_ID, Qt::UserRole).value()); + col_oids[tab_oid].push_back((*itr)->data(ObjectId, Qt::UserRole).value()); } } @@ -329,7 +342,7 @@ void DatabaseImportForm::listObjects(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -366,7 +379,7 @@ void DatabaseImportForm::listDatabases(void) db_objects_tw->clear(); database_cmb->clear(); database_cmb->setEnabled(false); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -396,11 +409,11 @@ void DatabaseImportForm::captureThreadError(Exception e) destroyModelWidget(); finishImport(trUtf8("Importing process aborted!")); - ico=QPixmap(PgModelerUiNS::getIconPath("msgbox_erro")); + ico=QPixmap(PgModelerUiNs::getIconPath("msgbox_erro")); ico_lbl->setPixmap(ico); - item=PgModelerUiNS::createOutputTreeItem(output_trw, PgModelerUiNS::formatMessage(e.getErrorMessage()), ico, nullptr, false, true); - PgModelerUiNS::createExceptionsTree(output_trw, e, item); + item=PgModelerUiNs::createOutputTreeItem(output_trw, PgModelerUiNs::formatMessage(e.getErrorMessage()), ico, nullptr, false, true); + PgModelerUiNs::createExceptionsTree(output_trw, e, item); //Destroy the current import thread and helper to avoid reuse destroyThread(); @@ -409,25 +422,25 @@ void DatabaseImportForm::captureThreadError(Exception e) createThread(); database_cmb->setCurrentIndex(0); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } void DatabaseImportForm::filterObjects(void) { DatabaseImportForm::filterObjects(db_objects_tw, filter_edt->text(), - (by_oid_chk->isChecked() ? OBJECT_ID : 0), false); + (by_oid_chk->isChecked() ? ObjectId : 0), false); } void DatabaseImportForm::filterObjects(QTreeWidget *tree_wgt, const QString &pattern, int search_column, bool sel_single_leaf) { if(!tree_wgt) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject ,__PRETTY_FUNCTION__,__FILE__,__LINE__); QList items; QTreeWidgetItemIterator itr(tree_wgt); - if(search_column == DatabaseImportForm::OBJECT_ID) + if(search_column == DatabaseImportForm::ObjectId) items = tree_wgt->findItems(QString("^(0)*(%1)(.)*").arg(pattern), Qt::MatchRegExp | Qt::MatchRecursive, search_column); else items = tree_wgt->findItems(pattern, Qt::MatchStartsWith | Qt::MatchRecursive, search_column); @@ -504,7 +517,7 @@ void DatabaseImportForm::destroyModelWidget(void) void DatabaseImportForm::handleImportCanceled(void) { - QPixmap ico=QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta")); + QPixmap ico=QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta")); QString msg=trUtf8("Importing process canceled by user!"); if(!create_model) @@ -514,7 +527,7 @@ void DatabaseImportForm::handleImportCanceled(void) finishImport(msg); ico_lbl->setPixmap(ico); - PgModelerUiNS::createOutputTreeItem(output_trw, msg, ico); + PgModelerUiNs::createOutputTreeItem(output_trw, msg, ico); } void DatabaseImportForm::handleImportFinished(Exception e) @@ -522,15 +535,16 @@ void DatabaseImportForm::handleImportFinished(Exception e) if(!e.getErrorMessage().isEmpty()) { Messagebox msgbox; - msgbox.show(e, e.getErrorMessage(), Messagebox::ALERT_ICON); + msgbox.show(e, e.getErrorMessage(), Messagebox::AlertIcon); } + model_wgt->getDatabaseModel()->setObjectsModified(); model_wgt->rearrangeSchemasInGrid(); model_wgt->getDatabaseModel()->setInvalidated(false); finishImport(trUtf8("Importing process sucessfuly ended!")); - ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("msgbox_info"))); + ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("msgbox_info"))); import_helper->closeConnection(); import_thread->quit(); @@ -562,7 +576,7 @@ void DatabaseImportForm::finishImport(const QString &msg) void DatabaseImportForm::showEvent(QShowEvent *) { - ConnectionsConfigWidget::fillConnectionsComboBox(connections_cmb, true, Connection::OP_IMPORT); + ConnectionsConfigWidget::fillConnectionsComboBox(connections_cmb, true, Connection::OpImport); createThread(); if(connections_cmb->currentIndex() > 0) @@ -588,7 +602,7 @@ void DatabaseImportForm::listDatabases(DatabaseImportHelper &import_helper, QCom QStringList list; map oids; - db_attribs=import_helper.getObjects(OBJ_DATABASE); + db_attribs=import_helper.getObjects(ObjectType::Database); dbcombo->blockSignals(true); dbcombo->clear(); @@ -609,7 +623,7 @@ void DatabaseImportForm::listDatabases(DatabaseImportHelper &import_helper, QCom for(int i=0; i < list.count(); i++) { - dbcombo->setItemIcon(i, QPixmap(PgModelerUiNS::getIconPath(OBJ_DATABASE))); + dbcombo->setItemIcon(i, QPixmap(PgModelerUiNs::getIconPath(ObjectType::Database))); dbcombo->setItemData(i, oids[list[i]]); } @@ -621,7 +635,7 @@ void DatabaseImportForm::listDatabases(DatabaseImportHelper &import_helper, QCom } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } } @@ -637,13 +651,13 @@ void DatabaseImportForm::listObjects(DatabaseImportHelper &import_helper, QTreeW { QTreeWidgetItem *db_item=nullptr, *item=nullptr; vector sch_items, tab_items; - float inc=0, inc1=0, aux_prog=0; + double inc=0, inc1=0, aux_prog=0; if(!create_dummy_item) { task_prog_wgt.setWindowTitle(trUtf8("Retrieving objects from database...")); task_prog_wgt.show(); - task_prog_wgt.updateProgress(1, trUtf8("Retrieving cluster level objects..."), OBJ_DATABASE); + task_prog_wgt.updateProgress(1, trUtf8("Retrieving cluster level objects..."), enum_cast(ObjectType::Database)); } tree_wgt->clear(); @@ -657,19 +671,19 @@ void DatabaseImportForm::listObjects(DatabaseImportHelper &import_helper, QTreeW //Creating database item db_item=new QTreeWidgetItem; db_item->setText(0, import_helper.getCurrentDatabase()); - db_item->setIcon(0, QPixmap(PgModelerUiNS::getIconPath(OBJ_DATABASE))); - attribs=catalog.getObjectsAttributes(OBJ_DATABASE, QString(), QString(), {}, {{ParsersAttributes::NAME, import_helper.getCurrentDatabase()}}); + db_item->setIcon(0, QPixmap(PgModelerUiNs::getIconPath(ObjectType::Database))); + attribs=catalog.getObjectsAttributes(ObjectType::Database, QString(), QString(), {}, {{Attributes::Name, import_helper.getCurrentDatabase()}}); + + db_item->setData(ObjectId, Qt::UserRole, attribs[0].at(Attributes::Oid).toUInt()); + db_item->setData(ObjectTypeId, Qt::UserRole, enum_cast(ObjectType::Database)); - db_item->setData(OBJECT_ID, Qt::UserRole, attribs[0].at(ParsersAttributes::OID).toUInt()); - db_item->setData(OBJECT_TYPE, Qt::UserRole, OBJ_DATABASE); - db_item->setData(OBJECT_TYPE, Qt::UserRole, OBJ_DATABASE); - db_item->setToolTip(0, QString("OID: %1").arg(attribs[0].at(ParsersAttributes::OID))); + db_item->setToolTip(0, QString("OID: %1").arg(attribs[0].at(Attributes::Oid))); tree_wgt->addTopLevelItem(db_item); } //Retrieving and listing the cluster scoped objects sch_items=DatabaseImportForm::updateObjectsTree(import_helper, tree_wgt, - BaseObject::getChildObjectTypes(OBJ_DATABASE), + BaseObject::getChildObjectTypes(ObjectType::Database), checkable_items, disable_empty_grps, db_item); if(create_dummy_item) @@ -678,33 +692,33 @@ void DatabaseImportForm::listObjects(DatabaseImportHelper &import_helper, QTreeW { item=new QTreeWidgetItem(sch_items.back()); item->setText(0, QString("...")); - item->setData(OBJECT_OTHER_DATA, Qt::UserRole, QVariant::fromValue(-1)); + item->setData(ObjectOtherData, Qt::UserRole, QVariant::fromValue(-1)); sch_items.pop_back(); } } else { - ObjectType obj_type = BASE_OBJECT; + ObjectType obj_type = ObjectType::BaseObject; aux_prog=task_prog_wgt.progress_pb->value(); - inc=40/static_cast(sch_items.size()); + inc=40/static_cast(sch_items.size()); while(!sch_items.empty()) { - task_prog_wgt.updateProgress(static_cast(aux_prog), trUtf8("Retrieving objects of schema `%1'...").arg(sch_items.back()->text(0)), OBJ_SCHEMA); + task_prog_wgt.updateProgress(static_cast(aux_prog), trUtf8("Retrieving objects of schema `%1'...").arg(sch_items.back()->text(0)), enum_cast(ObjectType::Schema)); //Retrieving and listing the schema scoped objects tab_items=DatabaseImportForm::updateObjectsTree(import_helper, tree_wgt, - BaseObject::getChildObjectTypes(OBJ_SCHEMA), + BaseObject::getChildObjectTypes(ObjectType::Schema), checkable_items, disable_empty_grps, sch_items.back(), sch_items.back()->text(0)); - inc1=(60/static_cast(tab_items.size()))/static_cast(sch_items.size()); + inc1=(60/static_cast(tab_items.size()))/static_cast(sch_items.size()); while(!tab_items.empty()) { aux_prog+=inc1; if(aux_prog > 99) aux_prog=99; - obj_type = static_cast(tab_items.back()->data(OBJECT_TYPE, Qt::UserRole).toUInt()); - task_prog_wgt.updateProgress(static_cast(aux_prog), trUtf8("Retrieving objects of `%1' (%2)...").arg(tab_items.back()->text(0)).arg(BaseObject::getTypeName(obj_type)), obj_type); + obj_type = static_cast(tab_items.back()->data(ObjectTypeId, Qt::UserRole).toUInt()); + task_prog_wgt.updateProgress(static_cast(aux_prog), trUtf8("Retrieving objects of `%1' (%2)...").arg(tab_items.back()->text(0)).arg(BaseObject::getTypeName(obj_type)), enum_cast(obj_type)); DatabaseImportForm::updateObjectsTree(import_helper, tree_wgt, BaseObject::getChildObjectTypes(obj_type), checkable_items, disable_empty_grps, tab_items.back(), sch_items.back()->text(0), tab_items.back()->text(0)); @@ -735,7 +749,7 @@ void DatabaseImportForm::listObjects(DatabaseImportHelper &import_helper, QTreeW { task_prog_wgt.close(); tree_wgt->clear(); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -748,7 +762,7 @@ vector DatabaseImportForm::updateObjectsTree(DatabaseImportHe { QTreeWidgetItem *group=nullptr, *item=nullptr; QFont grp_fnt=tree_wgt->font(); - attribs_map extra_attribs={{ParsersAttributes::FILTER_TABLE_TYPES, ParsersAttributes::_TRUE_}}; + attribs_map extra_attribs={{Attributes::FilterTableTypes, Attributes::True}}; QString tooltip=QString("OID: %1"), name, label; bool child_checked=false; vector objects_vect; @@ -769,15 +783,15 @@ vector DatabaseImportForm::updateObjectsTree(DatabaseImportHe { //Create a group item for the current type group=new QTreeWidgetItem(root); - group->setIcon(0, QPixmap(PgModelerUiNS::getIconPath(BaseObject::getSchemaName(grp_type) + QString("_grp")))); + group->setIcon(0, QPixmap(PgModelerUiNs::getIconPath(BaseObject::getSchemaName(grp_type) + QString("_grp")))); group->setFont(0, grp_fnt); //Group items does contains a zero valued id to indicate that is not a valide object - group->setData(OBJECT_ID, Qt::UserRole, 0); - group->setData(OBJECT_TYPE, Qt::UserRole, grp_type); - group->setData(OBJECT_COUNT, Qt::UserRole, 0); - group->setData(OBJECT_SCHEMA, Qt::UserRole, schema); - group->setData(OBJECT_TABLE, Qt::UserRole, table); + group->setData(ObjectId, Qt::UserRole, 0); + group->setData(ObjectTypeId, Qt::UserRole, enum_cast(grp_type)); + group->setData(ObjectCount, Qt::UserRole, 0); + group->setData(ObjectSchema, Qt::UserRole, schema); + group->setData(ObjectTable, Qt::UserRole, table); gen_groups[grp_type]=group; groups_list.push_back(group); @@ -787,19 +801,19 @@ vector DatabaseImportForm::updateObjectsTree(DatabaseImportHe for(attribs_map &attribs : objects_vect) { - obj_type=static_cast(attribs[ParsersAttributes::OBJECT_TYPE].toUInt()); + obj_type=static_cast(attribs[Attributes::ObjectType].toUInt()); group=gen_groups[obj_type]; - group->setData(OBJECT_COUNT, Qt::UserRole, - group->data(OBJECT_COUNT, Qt::UserRole).toUInt() + 1); + group->setData(ObjectCount, Qt::UserRole, + group->data(ObjectCount, Qt::UserRole).toUInt() + 1); //Creates individual items for each object of the current type - oid=attribs[ParsersAttributes::OID].toUInt(); + oid=attribs[Attributes::Oid].toUInt(); - attribs[ParsersAttributes::NAME].remove(QRegExp(QString("( )(without)( time zone)"))); - label=name=attribs[ParsersAttributes::NAME]; + attribs[Attributes::Name].remove(QRegExp(QString("( )(without)( time zone)"))); + label=name=attribs[Attributes::Name]; //Removing the trailing type string from op. families or op. classes names - if(obj_type==OBJ_OPFAMILY || obj_type==OBJ_OPCLASS) + if(obj_type==ObjectType::OpFamily || obj_type==ObjectType::OpClass) { start=name.indexOf(QChar('[')); end=name.lastIndexOf(QChar(']')); @@ -808,17 +822,17 @@ vector DatabaseImportForm::updateObjectsTree(DatabaseImportHe } item=new QTreeWidgetItem(group); - item->setIcon(0, QPixmap(PgModelerUiNS::getIconPath(obj_type))); + item->setIcon(0, QPixmap(PgModelerUiNs::getIconPath(obj_type))); item->setText(0, label); - item->setText(OBJECT_ID, attribs[ParsersAttributes::OID].rightJustified(10, '0')); - item->setData(OBJECT_ID, Qt::UserRole, attribs[ParsersAttributes::OID].toUInt()); - item->setData(OBJECT_NAME, Qt::UserRole, name); + item->setText(ObjectId, attribs[Attributes::Oid].rightJustified(10, '0')); + item->setData(ObjectId, Qt::UserRole, attribs[Attributes::Oid].toUInt()); + item->setData(ObjectName, Qt::UserRole, name); if(checkable_items) { if((oid > import_helper.getLastSystemOID()) || - (obj_type==OBJ_SCHEMA && name==QString("public")) || - (obj_type==OBJ_COLUMN && root && root->data(0, Qt::UserRole).toUInt() > import_helper.getLastSystemOID())) + (obj_type==ObjectType::Schema && name==QString("public")) || + (obj_type==ObjectType::Column && root && root->data(0, Qt::UserRole).toUInt() > import_helper.getLastSystemOID())) { item->setCheckState(0, Qt::Checked); child_checked=true; @@ -827,27 +841,27 @@ vector DatabaseImportForm::updateObjectsTree(DatabaseImportHe item->setCheckState(0, Qt::Unchecked); //Disabling items that refers to PostgreSQL's built-in data types - if(obj_type==OBJ_TYPE && oid <= import_helper.getLastSystemOID()) + if(obj_type==ObjectType::Type && oid <= import_helper.getLastSystemOID()) { item->setDisabled(true); item->setToolTip(0, trUtf8("This is a PostgreSQL built-in data type and cannot be imported.")); } //Disabling items that refers to pgModeler's built-in system objects - else if((obj_type==OBJ_TABLESPACE && (name==QString("pg_default") || name==QString("pg_global"))) || - (obj_type==OBJ_ROLE && (name==QString("postgres"))) || - (obj_type==OBJ_SCHEMA && (name==QString("pg_catalog") || name==QString("public"))) || - (obj_type==OBJ_LANGUAGE && (name==~LanguageType(LanguageType::c) || - name==~LanguageType(LanguageType::sql) || - name==~LanguageType(LanguageType::plpgsql)))) + else if((obj_type==ObjectType::Tablespace && (name==QString("pg_default") || name==QString("pg_global"))) || + (obj_type==ObjectType::Role && (name==QString("postgres"))) || + (obj_type==ObjectType::Schema && (name==QString("pg_catalog") || name==QString("public"))) || + (obj_type==ObjectType::Language && (name==~LanguageType(LanguageType::C) || + name==~LanguageType(LanguageType::Sql) || + name==~LanguageType(LanguageType::PlPgsql)))) { item->setFont(0, grp_fnt); - item->setForeground(0, BaseObjectView::getFontStyle(ParsersAttributes::PROT_COLUMN).foreground()); + item->setForeground(0, BaseObjectView::getFontStyle(Attributes::ProtColumn).foreground()); item->setToolTip(0, trUtf8("This is a pgModeler's built-in object. It will be ignored if checked by user.")); } } //Stores the object's OID as the first data of the item - item->setData(OBJECT_ID, Qt::UserRole, oid); + item->setData(ObjectId, Qt::UserRole, oid); if(!item->toolTip(0).isEmpty()) item->setToolTip(0,item->toolTip(0) + QString("\n") + tooltip.arg(oid)); @@ -855,13 +869,13 @@ vector DatabaseImportForm::updateObjectsTree(DatabaseImportHe item->setToolTip(0,tooltip.arg(oid)); //Stores the object's type as the second data of the item - item->setData(OBJECT_TYPE, Qt::UserRole, obj_type); + item->setData(ObjectTypeId, Qt::UserRole, enum_cast(obj_type)); //Stores the schema and the table's name of the object - item->setData(OBJECT_SCHEMA, Qt::UserRole, schema); - item->setData(OBJECT_TABLE, Qt::UserRole, table); + item->setData(ObjectSchema, Qt::UserRole, schema); + item->setData(ObjectTable, Qt::UserRole, table); - if(obj_type==OBJ_SCHEMA || obj_type == OBJ_TABLE || obj_type == OBJ_VIEW) + if(obj_type==ObjectType::Schema || obj_type == ObjectType::Table || obj_type == ObjectType::View) items_vect.push_back(item); } @@ -869,8 +883,8 @@ vector DatabaseImportForm::updateObjectsTree(DatabaseImportHe for(ObjectType grp_type : types) { group=gen_groups[grp_type]; - group->setDisabled(disable_empty_grps && group->data(OBJECT_COUNT, Qt::UserRole).toUInt() == 0); - group->setText(0, BaseObject::getTypeName(grp_type) + QString(" (%1)").arg(group->data(OBJECT_COUNT, Qt::UserRole).toUInt())); + group->setDisabled(disable_empty_grps && group->data(ObjectCount, Qt::UserRole).toUInt() == 0); + group->setText(0, BaseObject::getTypeName(grp_type) + QString(" (%1)").arg(group->data(ObjectCount, Qt::UserRole).toUInt())); if(checkable_items) { @@ -882,14 +896,13 @@ vector DatabaseImportForm::updateObjectsTree(DatabaseImportHe } tree_wgt->addTopLevelItems(groups_list); - //tree_wgt->setSortingEnabled(true); tree_wgt->sortItems(sort_by, Qt::AscendingOrder); tree_wgt->setUpdatesEnabled(true); tree_wgt->blockSignals(false); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } return(items_vect); diff --git a/libpgmodeler_ui/src/databaseimportform.h b/libpgmodeler_ui/src/databaseimportform.h index ed05b44315..66f69bf309 100644 --- a/libpgmodeler_ui/src/databaseimportform.h +++ b/libpgmodeler_ui/src/databaseimportform.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -34,6 +34,10 @@ class DatabaseImportForm: public QDialog, public Ui::DatabaseImportForm { private: Q_OBJECT + + /*! \brief Indicates if the full output generated during the process should be displayed + * When this attribute is true, only errors and some key info messages are displayed. */ + static bool low_verbosity; //! \brief Custom delegate used to paint html texts in output tree HtmlItemDelegate *htmlitem_del; @@ -80,20 +84,23 @@ class DatabaseImportForm: public QDialog, public Ui::DatabaseImportForm { public: //! \brief Constants used to access the tree widget items data - static const unsigned OBJECT_ID=1, - OBJECT_TYPE=2, - OBJECT_NAME=3, - OBJECT_SCHEMA=4, - OBJECT_TABLE=5, - OBJECT_ATTRIBS=6, //Stores the object's attributes returned by catalog query - OBJECT_OTHER_DATA=7, //General purpose usage - OBJECT_COUNT=8, - OBJECT_SOURCE=9; //Only for gropus - - DatabaseImportForm(QWidget * parent = 0, Qt::WindowFlags f = 0); + static constexpr unsigned ObjectId=1, + ObjectTypeId=2, + ObjectName=3, + ObjectSchema=4, + ObjectTable=5, + ObjectAttribs=6, //Stores the object's attributes returned by catalog query + ObjectOtherData=7, //General purpose usage + ObjectCount=8, + ObjectSource=9; //Only for gropus + + DatabaseImportForm(QWidget * parent = nullptr, Qt::WindowFlags f = Qt::Widget); ~DatabaseImportForm(void); void setModelWidget(ModelWidget *model); + + //! \brief Defines if all the output generated during the import process should be displayed + static void setLowVerbosity(bool value); //! \brief Returns the configured model widget ModelWidget *getModelWidget(void); @@ -116,7 +123,7 @@ class DatabaseImportForm: public QDialog, public Ui::DatabaseImportForm { /*! \brief Retrieve the specified objects from the database and insert them onto the tree view. The "root" parameter is used to associate the group of objects as child of it. The "schema" and "table" parameter are used to filter objects by schema and/or table. - This method automatically returns a list of QTreeWidgetItem when the vector "types" contains OBJ_SCHEMA or OBJ_TABLE or OBJ_VIEW */ + This method automatically returns a list of QTreeWidgetItem when the vector "types" contains ObjectType::ObjSchema or ObjectType::Table or ObjectType::View */ static vector updateObjectsTree(DatabaseImportHelper &import_helper, QTreeWidget *tree_wgt, vector types, bool checkable_items=false, bool disable_empty_grps=true, QTreeWidgetItem *root=nullptr, const QString &schema=QString(), const QString &table=QString(), unsigned sort_by = 0); diff --git a/libpgmodeler_ui/src/databaseimporthelper.cpp b/libpgmodeler_ui/src/databaseimporthelper.cpp index 8743cae066..8453c442e0 100644 --- a/libpgmodeler_ui/src/databaseimporthelper.cpp +++ b/libpgmodeler_ui/src/databaseimporthelper.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "databaseimporthelper.h" -const QString DatabaseImportHelper::UNKNOWN_OBJECT_OID_XML=QString("\t\n"); +const QString DatabaseImportHelper::UnkownObjectOidXml=QString("\t\n"); DatabaseImportHelper::DatabaseImportHelper(QObject *parent) : QObject(parent) { @@ -27,7 +27,7 @@ DatabaseImportHelper::DatabaseImportHelper(QObject *parent) : QObject(parent) import_canceled=ignore_errors=import_sys_objs=import_ext_objs=rand_rel_colors=update_fk_rels=false; auto_resolve_deps=true; - import_filter=Catalog::LIST_ALL_OBJS | Catalog::EXCL_EXTENSION_OBJS | Catalog::EXCL_SYSTEM_OBJS; + import_filter=Catalog::ListAllObjects | Catalog::ExclExtensionObjs | Catalog::ExclSystemObjs; xmlparser=nullptr; dbmodel=nullptr; } @@ -41,7 +41,7 @@ void DatabaseImportHelper::setConnection(Connection &conn) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -60,14 +60,14 @@ void DatabaseImportHelper::setCurrentDatabase(const QString &dbname) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void DatabaseImportHelper::setSelectedOIDs(DatabaseModel *db_model, const map > &obj_oids, const map > &col_oids) { if(!db_model) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject ,__PRETTY_FUNCTION__,__FILE__,__LINE__); dbmodel=db_model; xmlparser=dbmodel->getXMLParser(); @@ -100,13 +100,13 @@ void DatabaseImportHelper::setImportOptions(bool import_sys_objs, bool import_ex Connection::setPrintSQL(debug_mode); if(!import_sys_objs && import_ext_objs) - import_filter=Catalog::LIST_ALL_OBJS | Catalog::EXCL_BUILTIN_ARRAY_TYPES | Catalog::EXCL_SYSTEM_OBJS; + import_filter=Catalog::ListAllObjects | Catalog::ExclBuiltinArrayTypes | Catalog::ExclSystemObjs; else if(import_sys_objs && !import_ext_objs) - import_filter=Catalog::LIST_ALL_OBJS | Catalog::EXCL_BUILTIN_ARRAY_TYPES | Catalog::EXCL_EXTENSION_OBJS; + import_filter=Catalog::ListAllObjects | Catalog::ExclBuiltinArrayTypes | Catalog::ExclExtensionObjs; else if(import_sys_objs && import_ext_objs) - import_filter=Catalog::LIST_ALL_OBJS | Catalog::EXCL_BUILTIN_ARRAY_TYPES; + import_filter=Catalog::ListAllObjects | Catalog::ExclBuiltinArrayTypes; else - import_filter=Catalog::LIST_ALL_OBJS | Catalog::EXCL_BUILTIN_ARRAY_TYPES | Catalog::EXCL_EXTENSION_OBJS | Catalog::EXCL_SYSTEM_OBJS; + import_filter=Catalog::ListAllObjects | Catalog::ExclBuiltinArrayTypes | Catalog::ExclExtensionObjs | Catalog::ExclSystemObjs; } unsigned DatabaseImportHelper::getLastSystemOID(void) @@ -116,7 +116,7 @@ unsigned DatabaseImportHelper::getLastSystemOID(void) QString DatabaseImportHelper::getCurrentDatabase(void) { - return(connection.getConnectionParam(Connection::PARAM_DB_NAME)); + return(connection.getConnectionParam(Connection::ParamDbName)); } Catalog DatabaseImportHelper::getCatalog(void) @@ -133,7 +133,7 @@ attribs_map DatabaseImportHelper::getObjects(ObjectType obj_type, const QString } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -146,7 +146,7 @@ vector DatabaseImportHelper::getObjects(vector obj_type } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -159,8 +159,8 @@ void DatabaseImportHelper::swapSequencesTablesIds(void) itr=seq_tab_swap.begin(); while(itr!=seq_tab_swap.end()) { - sequence=dbmodel->getObject(getObjectName(itr->first), OBJ_SEQUENCE); - table=dbmodel->getObject(getObjectName(itr->second), OBJ_TABLE); + sequence=dbmodel->getObject(getObjectName(itr->first), ObjectType::Sequence); + table=dbmodel->getObject(getObjectName(itr->second), ObjectType::Table); if(sequence && table) BaseObject::swapObjectsIds(sequence, table, false); itr++; @@ -173,8 +173,8 @@ void DatabaseImportHelper::retrieveSystemObjects(void) vector::iterator itr; map *obj_map=nullptr; vector objects; - ObjectType sys_objs[]={ OBJ_SCHEMA, OBJ_ROLE, OBJ_TABLESPACE, - OBJ_LANGUAGE, /* OBJ_COLLATION,*/ OBJ_TYPE }; + ObjectType sys_objs[]={ ObjectType::Schema, ObjectType::Role, ObjectType::Tablespace, + ObjectType::Language, /* ObjectType::ObjCollation,*/ ObjectType::Type }; unsigned i=0, oid=0, cnt=sizeof(sys_objs)/sizeof(ObjectType); for(i=0; i < cnt && !import_canceled; i++) @@ -183,19 +183,19 @@ void DatabaseImportHelper::retrieveSystemObjects(void) trUtf8("Retrieving system objects... `%1'").arg(BaseObject::getTypeName(sys_objs[i])), sys_objs[i]); - if(sys_objs[i]!=OBJ_TYPE) + if(sys_objs[i]!=ObjectType::Type) { obj_map=&system_objs; - if(sys_objs[i]!=OBJ_LANGUAGE) - catalog.setFilter(Catalog::LIST_ONLY_SYS_OBJS); + if(sys_objs[i]!=ObjectType::Language) + catalog.setFilter(Catalog::ListOnlySystemObjs); else - catalog.setFilter(Catalog::LIST_ALL_OBJS); + catalog.setFilter(Catalog::ListAllObjects); } else { obj_map=&types; - catalog.setFilter(Catalog::LIST_ALL_OBJS); + catalog.setFilter(Catalog::ListAllObjects); } //Query the objects on the catalog and put them on the map @@ -204,12 +204,12 @@ void DatabaseImportHelper::retrieveSystemObjects(void) while(itr!=objects.end() && !import_canceled) { - oid=itr->at(ParsersAttributes::OID).toUInt(); + oid=itr->at(Attributes::Oid).toUInt(); (*obj_map)[oid]=(*itr); itr++; } - progress=(i/static_cast(cnt))*10; + progress=(i/static_cast(cnt))*10; } } @@ -238,13 +238,13 @@ void DatabaseImportHelper::retrieveUserObjects(void) while(itr!=objects.end() && !import_canceled) { - oid=itr->at(ParsersAttributes::OID).toUInt(); + oid=itr->at(Attributes::Oid).toUInt(); user_objs[oid]=(*itr); itr++; } objects.clear(); - progress=(i/static_cast(object_oids.size()))*100; + progress=(i/static_cast(object_oids.size()))*100; oid_itr++; i++; } @@ -254,15 +254,15 @@ void DatabaseImportHelper::retrieveUserObjects(void) while(col_itr!=column_oids.end()) { emit s_progressUpdated(progress, - trUtf8("Retrieving objects... `%1'").arg(BaseObject::getTypeName(OBJ_COLUMN)), - OBJ_COLUMN); + trUtf8("Retrieving objects... `%1'").arg(BaseObject::getTypeName(ObjectType::Column)), + ObjectType::Column); names=getObjectName(QString::number(col_itr->first)).split("."); if(names.size() > 1) retrieveTableColumns(names[0], names[1], col_itr->second); - progress=(i/static_cast(column_oids.size()))*100; + progress=(i/static_cast(column_oids.size()))*100; col_itr++; i++; } } @@ -274,18 +274,18 @@ void DatabaseImportHelper::retrieveTableColumns(const QString &sch_name, const Q vector cols; unsigned tab_oid=0, col_oid; - cols=catalog.getObjectsAttributes(OBJ_COLUMN, sch_name, tab_name, col_ids); + cols=catalog.getObjectsAttributes(ObjectType::Column, sch_name, tab_name, col_ids); for(auto &itr : cols) { - col_oid=itr.at(ParsersAttributes::OID).toUInt(); - tab_oid=itr.at(ParsersAttributes::TABLE).toUInt(); + col_oid=itr.at(Attributes::Oid).toUInt(); + tab_oid=itr.at(Attributes::Table).toUInt(); columns[tab_oid][col_oid]=itr; } } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -303,18 +303,18 @@ void DatabaseImportHelper::createObjects(void) { oid=creation_order[i]; attribs=user_objs[oid]; - obj_type=static_cast(attribs[ParsersAttributes::OBJECT_TYPE].toUInt()); + obj_type=static_cast(attribs[Attributes::ObjectType].toUInt()); try { /* Constraints are ignored in these phase being pushed into an auxiliary list in order to be created later */ - if(obj_type!=OBJ_CONSTRAINT) + if(obj_type!=ObjectType::Constraint) { emit s_progressUpdated(progress, trUtf8("Creating object `%1' (%2), oid `%3'...") - .arg(attribs[ParsersAttributes::NAME]) + .arg(attribs[Attributes::Name]) .arg(BaseObject::getTypeName(obj_type)) - .arg(attribs[ParsersAttributes::OID]), + .arg(attribs[Attributes::Oid]), obj_type); createObject(attribs); @@ -328,7 +328,7 @@ void DatabaseImportHelper::createObjects(void) not_created_objs.push_back(oid); } - progress=(i/static_cast(creation_order.size())) * 100; + progress=(i/static_cast(creation_order.size())) * 100; } #ifdef DEMO_VERSION @@ -357,14 +357,14 @@ void DatabaseImportHelper::createObjects(void) while(itr!=itr_end && !import_canceled) { attribs=user_objs[*itr]; - obj_type=static_cast(attribs[ParsersAttributes::OBJECT_TYPE].toUInt()); + obj_type=static_cast(attribs[Attributes::ObjectType].toUInt()); itr++; emit s_progressUpdated(progress, trUtf8("Trying to recreate object `%1' (%2), oid `%3'...") - .arg(attribs[ParsersAttributes::NAME]) + .arg(attribs[Attributes::Name]) .arg(BaseObject::getTypeName(obj_type)) - .arg(attribs[ParsersAttributes::OID]), + .arg(attribs[Attributes::Oid]), obj_type); try @@ -375,10 +375,10 @@ void DatabaseImportHelper::createObjects(void) { //In case of some error store the oid and the error in separated lists not_created_objs.push_back(*itr); - aux_errors.push_back(Exception(e.getErrorMessage(), e.getErrorType(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, dumpObjectAttributes(attribs))); + aux_errors.push_back(Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, dumpObjectAttributes(attribs))); } - progress=(i/static_cast(not_created_objs.size())) * 100; + progress=(i/static_cast(not_created_objs.size())) * 100; } tries++; @@ -386,14 +386,14 @@ void DatabaseImportHelper::createObjects(void) if(tries >= max_tries) emit s_progressUpdated(progress, trUtf8("Import failed to recreate some objects in `%1' tries.").arg(max_tries), - BASE_OBJECT); + ObjectType::BaseObject); if(!import_canceled) { /* If the previous list size is the same as the not_created_object list means that no object was created in this interaction which means error */ if(prev_size==not_created_objs.size() && !ignore_errors) - throw Exception(aux_errors.back().getErrorMessage(), aux_errors.back().getErrorType(), + throw Exception(aux_errors.back().getErrorMessage(), aux_errors.back().getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, aux_errors); else if(ignore_errors) errors.insert(errors.end(), aux_errors.begin(), aux_errors.end()); @@ -420,15 +420,15 @@ void DatabaseImportHelper::createConstraints(void) try { //Check constraints are created only if they are not inherited, other types are created normally - if(attribs[ParsersAttributes::TYPE]!=ParsersAttributes::CK_CONSTR || - (attribs[ParsersAttributes::TYPE]==ParsersAttributes::CK_CONSTR && - attribs[ParsersAttributes::INHERITED]!=ParsersAttributes::_TRUE_)) + if(attribs[Attributes::Type]!=Attributes::CkConstr || + (attribs[Attributes::Type]==Attributes::CkConstr && + attribs[Attributes::Inherited]!=Attributes::True)) { emit s_progressUpdated(progress, trUtf8("Creating object `%1' (%2)...") - .arg(attribs[ParsersAttributes::NAME]) - .arg(BaseObject::getTypeName(OBJ_CONSTRAINT)), - OBJ_CONSTRAINT); + .arg(attribs[Attributes::Name]) + .arg(BaseObject::getTypeName(ObjectType::Constraint)), + ObjectType::Constraint); createObject(attribs); } @@ -436,12 +436,12 @@ void DatabaseImportHelper::createConstraints(void) catch(Exception &e) { if(ignore_errors) - errors.push_back(Exception(e.getErrorMessage(), e.getErrorType(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, dumpObjectAttributes(attribs))); + errors.push_back(Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, dumpObjectAttributes(attribs))); else - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } - progress=(i/static_cast(constr_creation_order.size())) * 100; + progress=(i/static_cast(constr_creation_order.size())) * 100; } } @@ -461,18 +461,18 @@ void DatabaseImportHelper::createPermissions(void) while(itr_obj!=obj_perms.end() && !import_canceled) { attribs=user_objs[*itr_obj]; - obj_type=static_cast(attribs[ParsersAttributes::OBJECT_TYPE].toUInt()); + obj_type=static_cast(attribs[Attributes::ObjectType].toUInt()); emit s_progressUpdated(progress, - msg.arg(getObjectName(attribs[ParsersAttributes::OID])) - .arg(BaseObject::getTypeName(obj_type)), OBJ_PERMISSION); + msg.arg(getObjectName(attribs[Attributes::Oid])) + .arg(BaseObject::getTypeName(obj_type)), ObjectType::Permission); createPermission(attribs); itr_obj++; - progress=((i++)/static_cast(obj_perms.size())) * 100; + progress=((i++)/static_cast(obj_perms.size())) * 100; } - emit s_progressUpdated(progress, trUtf8("Creating columns permissions..."), OBJ_PERMISSION); + emit s_progressUpdated(progress, trUtf8("Creating columns permissions..."), ObjectType::Permission); //Create the column level permission i=0; while(itr_cols!=col_perms.end() && !import_canceled) @@ -482,25 +482,25 @@ void DatabaseImportHelper::createPermissions(void) while(itr!=itr_cols->second.end()) { attribs=columns[itr_cols->first][*itr]; - obj_type=static_cast(attribs[ParsersAttributes::OBJECT_TYPE].toUInt()); + obj_type=static_cast(attribs[Attributes::ObjectType].toUInt()); emit s_progressUpdated(progress, - msg.arg(getObjectName(attribs[ParsersAttributes::OID])) - .arg(BaseObject::getTypeName(obj_type)), OBJ_PERMISSION); + msg.arg(getObjectName(attribs[Attributes::Oid])) + .arg(BaseObject::getTypeName(obj_type)), ObjectType::Permission); createPermission(attribs); itr++; } itr_cols++; - progress=((i++)/static_cast(col_perms.size())) * 100; + progress=((i++)/static_cast(col_perms.size())) * 100; } } catch(Exception &e) { if(ignore_errors) - errors.push_back(Exception(e.getErrorMessage(), e.getErrorType(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, dumpObjectAttributes(attribs))); + errors.push_back(Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, dumpObjectAttributes(attribs))); else - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -511,9 +511,9 @@ void DatabaseImportHelper::updateFKRelationships(void) unsigned i=0, count=0; Table *tab=nullptr; - itr_tab=dbmodel->getObjectList(OBJ_TABLE)->begin(); - itr_tab_end=dbmodel->getObjectList(OBJ_TABLE)->end(); - count=dbmodel->getObjectList(OBJ_TABLE)->size(); + itr_tab=dbmodel->getObjectList(ObjectType::Table)->begin(); + itr_tab_end=dbmodel->getObjectList(ObjectType::Table)->end(); + count=dbmodel->getObjectList(ObjectType::Table)->size(); i=0; try @@ -525,18 +525,18 @@ void DatabaseImportHelper::updateFKRelationships(void) emit s_progressUpdated(progress, trUtf8("Updating relationships of `%1' (%2)...") .arg(tab->getName()) - .arg(BaseObject::getTypeName(OBJ_TABLE)), - OBJ_TABLE); + .arg(BaseObject::getTypeName(ObjectType::Table)), + ObjectType::Table); dbmodel->updateTableFKRelationships(tab); - progress=(i/static_cast(count)) * 90; + progress=(i/static_cast(count)) * 90; itr_tab++; i++; } } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -545,12 +545,16 @@ void DatabaseImportHelper::importDatabase(void) try { if(!dbmodel) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + dbmodel->setLoadingModel(true); + dbmodel->setObjectListsCapacity(creation_order.size()); retrieveSystemObjects(); retrieveUserObjects(); createObjects(); createTableInheritances(); + createTablePartitionings(); createConstraints(); destroyDetachedColumns(); createPermissions(); @@ -560,7 +564,7 @@ void DatabaseImportHelper::importDatabase(void) if(!inherited_cols.empty()) { - emit s_progressUpdated(100, trUtf8("Validating relationships..."), OBJ_RELATIONSHIP); + emit s_progressUpdated(100, trUtf8("Validating relationships..."), ObjectType::Relationship); dbmodel->validateRelationships(); } @@ -574,8 +578,8 @@ void DatabaseImportHelper::importDatabase(void) QString log_name; //Writing the erros to log file - log_name=GlobalAttributes::TEMPORARY_DIR + - GlobalAttributes::DIR_SEPARATOR + + log_name=GlobalAttributes::TemporaryDir + + GlobalAttributes::DirSeparator + QString("%1_%2_%3.log").arg(dbmodel->getName()) .arg(QString("import")) .arg(QDateTime::currentDateTime().toString(QString("yyyy-MM-dd_hhmmss"))); @@ -597,6 +601,8 @@ void DatabaseImportHelper::importDatabase(void) else emit s_importCanceled(); + dbmodel->setLoadingModel(false); + if(!import_canceled) { //Generating random colors for relationships @@ -605,7 +611,7 @@ void DatabaseImportHelper::importDatabase(void) vector *rels=nullptr; vector::iterator itr, itr_end; std::uniform_int_distribution dist(0,255); - ObjectType rel_type[]={ OBJ_RELATIONSHIP, BASE_RELATIONSHIP }; + ObjectType rel_type[]={ ObjectType::Relationship, ObjectType::BaseRelationship }; BaseRelationship *rel=nullptr; for(unsigned i=0; i < 2; i++) @@ -625,11 +631,9 @@ void DatabaseImportHelper::importDatabase(void) } } } - - //Forcing the update of tables and views in order to correctly draw their titles without the schema's name - dbmodel->setObjectsModified({ OBJ_TABLE, OBJ_VIEW }); } + dbmodel->setObjectsModified(); resetImportParameters(); } catch(Exception &e) @@ -639,10 +643,10 @@ void DatabaseImportHelper::importDatabase(void) /* When running in a separated thread (other than the main application thread) redirects the error in form of signal */ if(this->thread() && this->thread()!=qApp->thread()) - emit s_importAborted(Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo())); + emit s_importAborted(Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo())); else //Redirects any error to the user - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo()); } } @@ -653,43 +657,47 @@ void DatabaseImportHelper::cancelImport(void) void DatabaseImportHelper::createObject(attribs_map &attribs) { - unsigned oid=attribs[ParsersAttributes::OID].toUInt(); - ObjectType obj_type=static_cast(attribs[ParsersAttributes::OBJECT_TYPE].toUInt()); - QString obj_name=getObjectName(attribs[ParsersAttributes::OID], (obj_type==OBJ_FUNCTION || obj_type==OBJ_OPERATOR)); + unsigned oid=attribs[Attributes::Oid].toUInt(); + ObjectType obj_type=static_cast(attribs[Attributes::ObjectType].toUInt()); + QString obj_name=getObjectName(attribs[Attributes::Oid], (obj_type==ObjectType::Function || obj_type==ObjectType::Operator)); //Avoiding the creation of pgModeler's temp objects created in database during the catalog reading - if(obj_name.contains(Catalog::PGMODELER_TEMP_DB_OBJ)) + if(obj_name.contains(Catalog::PgModelerTempDbObj)) return; try { if(!import_canceled && - (obj_type==OBJ_DATABASE || TableObject::isTableObject(obj_type) || + (obj_type==ObjectType::Database || TableObject::isTableObject(obj_type) || //If the object does not exists on both model and created objects vector ((std::find(created_objs.begin(), created_objs.end(), oid)==created_objs.end()) && dbmodel->getObjectIndex(obj_name, obj_type) < 0))) { if(TableObject::isTableObject(obj_type)) - attribs[ParsersAttributes::DECL_IN_TABLE]=QString(); + attribs[Attributes::DeclInTable]=QString(); //System objects will have the sql disabled by default - attribs[ParsersAttributes::SQL_DISABLED]=(catalog.isSystemObject(oid) || catalog.isExtensionObject(oid) ? ParsersAttributes::_TRUE_ : QString()); - attribs[ParsersAttributes::COMMENT]=getComment(attribs); + attribs[Attributes::SqlDisabled]=(catalog.isSystemObject(oid) || catalog.isExtensionObject(oid) ? Attributes::True : QString()); + attribs[Attributes::Comment]=getComment(attribs); - if(attribs.count(ParsersAttributes::OWNER)) - attribs[ParsersAttributes::OWNER]=getDependencyObject(attribs[ParsersAttributes::OWNER], OBJ_ROLE, false, auto_resolve_deps); + if(attribs.count(Attributes::Owner)) + attribs[Attributes::Owner]=getDependencyObject(attribs[Attributes::Owner], ObjectType::Role, false, auto_resolve_deps); - if(attribs.count(ParsersAttributes::TABLESPACE)) - attribs[ParsersAttributes::TABLESPACE]=getDependencyObject(attribs[ParsersAttributes::TABLESPACE], OBJ_TABLESPACE, false, auto_resolve_deps); + if(attribs.count(Attributes::Tablespace)) + attribs[Attributes::Tablespace]=getDependencyObject(attribs[Attributes::Tablespace], ObjectType::Tablespace, false, auto_resolve_deps); - if(attribs.count(ParsersAttributes::SCHEMA)) - attribs[ParsersAttributes::SCHEMA]=getDependencyObject(attribs[ParsersAttributes::SCHEMA], OBJ_SCHEMA, false, auto_resolve_deps); + if(attribs.count(Attributes::Schema)) + { + //Here we preserve the schema oid for latter usage in certain methods + attribs[Attributes::SchemaOid]=attribs[Attributes::Schema]; + attribs[Attributes::Schema]=getDependencyObject(attribs[Attributes::Schema], ObjectType::Schema, false, auto_resolve_deps); + } /* Due to the object recreation mechanism there are some situations when pgModeler fails to recreate them due to the duplication of permissions. So, to avoid this problem we need to check if the OID of the object was previously registered in the vector of permissions to be created */ - if(!attribs[ParsersAttributes::PERMISSION].isEmpty() && + if(!attribs[Attributes::Permission].isEmpty() && std::find(obj_perms.begin(), obj_perms.end(), oid)==obj_perms.end()) obj_perms.push_back(oid); @@ -701,31 +709,34 @@ void DatabaseImportHelper::createObject(attribs_map &attribs) switch(obj_type) { - case OBJ_DATABASE: configureDatabase(attribs); break; - case OBJ_TABLESPACE: createTablespace(attribs); break; - case OBJ_SCHEMA: createSchema(attribs); break; - case OBJ_ROLE: createRole(attribs); break; - case OBJ_DOMAIN: createDomain(attribs); break; - case OBJ_EXTENSION: createExtension(attribs); break; - case OBJ_FUNCTION: createFunction(attribs); break; - case OBJ_LANGUAGE: createLanguage(attribs); break; - case OBJ_OPFAMILY: createOperatorFamily(attribs); break; - case OBJ_OPCLASS: createOperatorClass(attribs); break; - case OBJ_OPERATOR: createOperator(attribs); break; - case OBJ_COLLATION: createCollation(attribs); break; - case OBJ_CAST: createCast(attribs); break; - case OBJ_CONVERSION: createConversion(attribs); break; - case OBJ_SEQUENCE: createSequence(attribs); break; - case OBJ_AGGREGATE: createAggregate(attribs); break; - case OBJ_TYPE: createType(attribs); break; - case OBJ_TABLE: createTable(attribs); break; - case OBJ_VIEW: createView(attribs); break; - case OBJ_RULE: createRule(attribs); break; - case OBJ_TRIGGER: createTrigger(attribs); break; - case OBJ_INDEX: createIndex(attribs); break; - case OBJ_CONSTRAINT: createConstraint(attribs); break; - case OBJ_POLICY: createPolicy(attribs); break; - case OBJ_EVENT_TRIGGER: createEventTrigger(attribs); break; + case ObjectType::Database: configureDatabase(attribs); break; + case ObjectType::Tablespace: createTablespace(attribs); break; + case ObjectType::Schema: createSchema(attribs); break; + case ObjectType::Role: createRole(attribs); break; + case ObjectType::Domain: createDomain(attribs); break; + case ObjectType::Extension: createExtension(attribs); break; + case ObjectType::Function: createFunction(attribs); break; + case ObjectType::Language: createLanguage(attribs); break; + case ObjectType::OpFamily: createOperatorFamily(attribs); break; + case ObjectType::OpClass: createOperatorClass(attribs); break; + case ObjectType::Operator: createOperator(attribs); break; + case ObjectType::Collation: createCollation(attribs); break; + case ObjectType::Cast: createCast(attribs); break; + case ObjectType::Conversion: createConversion(attribs); break; + case ObjectType::Sequence: createSequence(attribs); break; + case ObjectType::Aggregate: createAggregate(attribs); break; + case ObjectType::Type: createType(attribs); break; + case ObjectType::Table: createTable(attribs); break; + case ObjectType::View: createView(attribs); break; + case ObjectType::Rule: createRule(attribs); break; + case ObjectType::Trigger: createTrigger(attribs); break; + case ObjectType::Index: createIndex(attribs); break; + case ObjectType::Constraint: createConstraint(attribs); break; + case ObjectType::Policy: createPolicy(attribs); break; + case ObjectType::EventTrigger: createEventTrigger(attribs); break; + case ObjectType::ForeignDataWrapper: createForeignDataWrapper(attribs); break; + case ObjectType::ForeignServer: createForeignServer(attribs); break; + case ObjectType::UserMapping: createUserMapping(attribs); break; default: if(debug_mode) @@ -742,9 +753,9 @@ void DatabaseImportHelper::createObject(attribs_map &attribs) } catch(Exception &e) { - throw Exception(Exception::getErrorMessage(ERR_OBJECT_NOT_IMPORTED) - .arg(obj_name).arg(BaseObject::getTypeName(obj_type)).arg(attribs[ParsersAttributes::OID]), - ERR_OBJECT_NOT_IMPORTED,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, dumpObjectAttributes(attribs)); + throw Exception(Exception::getErrorMessage(ErrorCode::ObjectNotImported) + .arg(obj_name).arg(BaseObject::getTypeName(obj_type)).arg(attribs[Attributes::Oid]), + ErrorCode::ObjectNotImported,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, dumpObjectAttributes(attribs)); } } @@ -754,14 +765,14 @@ QString DatabaseImportHelper::getComment(attribs_map &attribs) { QString xml_def; - if(!attribs[ParsersAttributes::COMMENT].isEmpty()) - xml_def=schparser.getCodeDefinition(ParsersAttributes::COMMENT, attribs, SchemaParser::XML_DEFINITION); + if(!attribs[Attributes::Comment].isEmpty()) + xml_def=schparser.getCodeDefinition(Attributes::Comment, attribs, SchemaParser::XmlDefinition); return(xml_def); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -789,7 +800,7 @@ QString DatabaseImportHelper::getDependencyObject(const QString &oid, ObjectType (import_sys_objs && obj_oid <= catalog.getLastSysObjectOID()) || (obj_oid > catalog.getLastSysObjectOID() && !catalog.isExtensionObject(obj_oid)))) { - catalog.setFilter(Catalog::LIST_ALL_OBJS); + catalog.setFilter(Catalog::ListAllObjects); vector attribs_vect=catalog.getObjectsAttributes(obj_type,QString(),QString(), { obj_oid }); if(!attribs_vect.empty()) @@ -816,19 +827,19 @@ QString DatabaseImportHelper::getDependencyObject(const QString &oid, ObjectType /* If the attributes of the dependency exists but it was not created on the model yet, pgModeler will create it and it's dependencies recursively */ if(recursive_dep_res && !TableObject::isTableObject(obj_type) && - obj_type!=OBJ_DATABASE && dbmodel->getObjectIndex(obj_attr[ParsersAttributes::NAME], obj_type) < 0) + obj_type!=ObjectType::Database && dbmodel->getObjectIndex(obj_attr[Attributes::Name], obj_type) < 0) createObject(obj_attr); if(use_signature) - obj_name=obj_attr[ParsersAttributes::SIGNATURE]=getObjectName(oid, true); + obj_name=obj_attr[Attributes::Signature]=getObjectName(oid, true); else - obj_name=obj_attr[ParsersAttributes::NAME]=getObjectName(oid); + obj_name=obj_attr[Attributes::Name]=getObjectName(oid); if(generate_xml) { - obj_attr[ParsersAttributes::REDUCED_FORM]=ParsersAttributes::_TRUE_; + obj_attr[Attributes::ReducedForm]=Attributes::True; schparser.ignoreUnkownAttributes(true); - xml_def=schparser.getCodeDefinition(BaseObject::getSchemaName(obj_type), obj_attr, SchemaParser::XML_DEFINITION); + xml_def=schparser.getCodeDefinition(BaseObject::getSchemaName(obj_type), obj_attr, SchemaParser::XmlDefinition); schparser.ignoreUnkownAttributes(false); } else @@ -837,14 +848,14 @@ QString DatabaseImportHelper::getDependencyObject(const QString &oid, ObjectType else /* If the object oid is valid but there is no attribute set to it creates a xml definition containing an alert indicating that the object is unknown */ - xml_def=QString(UNKNOWN_OBJECT_OID_XML).arg(oid); + xml_def=QString(UnkownObjectOidXml).arg(oid); } return(xml_def); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -855,7 +866,7 @@ void DatabaseImportHelper::loadObjectXML(ObjectType obj_type, attribs_map &attri try { schparser.ignoreUnkownAttributes(true); - xml_buf=schparser.getCodeDefinition(BaseObject::getSchemaName(obj_type), attribs, SchemaParser::XML_DEFINITION); + xml_buf=schparser.getCodeDefinition(BaseObject::getSchemaName(obj_type), attribs, SchemaParser::XmlDefinition); schparser.ignoreUnkownAttributes(false); xmlparser->restartParser(); @@ -863,7 +874,7 @@ void DatabaseImportHelper::loadObjectXML(ObjectType obj_type, attribs_map &attri if(debug_mode) { QTextStream ts(stdout); - ts << QString("").arg(attribs[ParsersAttributes::NAME]).arg(attribs[ParsersAttributes::OID]) << endl; + ts << QString("").arg(attribs[Attributes::Name]).arg(attribs[Attributes::Oid]) << endl; ts << xml_buf << endl; } @@ -871,7 +882,7 @@ void DatabaseImportHelper::loadObjectXML(ObjectType obj_type, attribs_map &attri } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xml_buf); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xml_buf); } } @@ -896,6 +907,7 @@ void DatabaseImportHelper::resetImportParameters(void) connection.close(); catalog.closeConnection(); inherited_cols.clear(); + imported_tables.clear(); } QString DatabaseImportHelper::dumpObjectAttributes(attribs_map &attribs) @@ -903,8 +915,8 @@ QString DatabaseImportHelper::dumpObjectAttributes(attribs_map &attribs) QString dump_str; dump_str+=QString("-- Raw attributes: %1 (OID: %2) --\n") - .arg(attribs[ParsersAttributes::NAME]) - .arg(attribs[ParsersAttributes::OID]); + .arg(attribs[Attributes::Name]) + .arg(attribs[Attributes::Oid]); for(auto &attr : attribs) dump_str+=QString("%1: %2\n").arg(attr.first).arg(attr.second); @@ -920,14 +932,14 @@ void DatabaseImportHelper::createTablespace(attribs_map &attribs) try { - loadObjectXML(OBJ_TABLESPACE, attribs); + loadObjectXML(ObjectType::Tablespace, attribs); tabspc=dbmodel->createTablespace(); dbmodel->addObject(tabspc); } catch(Exception &e) { if(tabspc) delete(tabspc); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -938,11 +950,11 @@ void DatabaseImportHelper::createSchema(attribs_map &attribs) try { - attribs[ParsersAttributes::RECT_VISIBLE]=QString(); - attribs[ParsersAttributes::FILL_COLOR]=QColor(dist(rand_num_engine), + attribs[Attributes::RectVisible]=QString(); + attribs[Attributes::FillColor]=QColor(dist(rand_num_engine), dist(rand_num_engine), dist(rand_num_engine)).name(); - loadObjectXML(OBJ_SCHEMA, attribs); + loadObjectXML(ObjectType::Schema, attribs); schema=dbmodel->createSchema(); dbmodel->addObject(schema); @@ -950,7 +962,7 @@ void DatabaseImportHelper::createSchema(attribs_map &attribs) catch(Exception &e) { if(schema) delete(schema); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -961,21 +973,21 @@ void DatabaseImportHelper::createRole(attribs_map &attribs) try { - QString role_types[]={ ParsersAttributes::REF_ROLES, - ParsersAttributes::ADMIN_ROLES, - ParsersAttributes::MEMBER_ROLES }; + QString role_types[]={ Attributes::RefRoles, + Attributes::AdminRoles, + Attributes::MemberRoles }; for(unsigned i=0; i < 3; i++) attribs[role_types[i]]=getObjectNames(attribs[role_types[i]]).join(','); - loadObjectXML(OBJ_ROLE, attribs); + loadObjectXML(ObjectType::Role, attribs); role=dbmodel->createRole(); dbmodel->addObject(role); } catch(Exception &e) { if(role) delete(role); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -989,35 +1001,35 @@ void DatabaseImportHelper::createDomain(attribs_map &attribs) try { - constraints = Catalog::parseArrayValues(attribs[ParsersAttributes::CONSTRAINTS]); - attribs[ParsersAttributes::CONSTRAINTS].clear(); + constraints = Catalog::parseArrayValues(attribs[Attributes::Constraints]); + attribs[Attributes::Constraints].clear(); for(auto constr : constraints) { constr.remove(0, 1); constr.remove(constr.length() - 1, 1); - constr_attrs = constr.split(QChar(':')); + constr_attrs = constr.split(Table::DataSeparator); - aux_attribs[ParsersAttributes::NAME] = constr_attrs.at(0); + aux_attribs[Attributes::Name] = constr_attrs.at(0); expr = constr_attrs.at(1); expr.remove(0,1); expr.remove(expr.length() - 1,1); - aux_attribs[ParsersAttributes::EXPRESSION] = expr; + aux_attribs[Attributes::Expression] = expr; - attribs[ParsersAttributes::CONSTRAINTS]+= schparser.getCodeDefinition(ParsersAttributes::DOM_CONSTRAINT, aux_attribs, SchemaParser::XML_DEFINITION); + attribs[Attributes::Constraints]+= schparser.getCodeDefinition(Attributes::DomConstraint, aux_attribs, SchemaParser::XmlDefinition); } - attribs[ParsersAttributes::TYPE]=getType(attribs[ParsersAttributes::TYPE], true, attribs); - attribs[ParsersAttributes::COLLATION]=getDependencyObject(attribs[ParsersAttributes::COLLATION], OBJ_COLLATION); - loadObjectXML(OBJ_DOMAIN, attribs); + attribs[Attributes::Type]=getType(attribs[Attributes::Type], true, attribs); + attribs[Attributes::Collation]=getDependencyObject(attribs[Attributes::Collation], ObjectType::Collation); + loadObjectXML(ObjectType::Domain, attribs); dom=dbmodel->createDomain(); dbmodel->addDomain(dom); } catch(Exception &e) { if(dom) delete(dom); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1028,14 +1040,14 @@ void DatabaseImportHelper::createExtension(attribs_map &attribs) try { - loadObjectXML(OBJ_EXTENSION, attribs); + loadObjectXML(ObjectType::Extension, attribs); ext=dbmodel->createExtension(); dbmodel->addExtension(ext); } catch(Exception &e) { if(ext) delete(ext); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1044,7 +1056,7 @@ void DatabaseImportHelper::createFunction(attribs_map &attribs) { Function *func=nullptr; Parameter param; - PgSQLType type; + PgSqlType type; unsigned dim=0; QStringList param_types, param_names, param_modes, param_def_vals, param_xmls; QString param_tmpl_name=QString("_param%1"); @@ -1052,20 +1064,20 @@ void DatabaseImportHelper::createFunction(attribs_map &attribs) try { - param_types=getTypes(attribs[ParsersAttributes::ARG_TYPES], false); - param_names=Catalog::parseArrayValues(attribs[ParsersAttributes::ARG_NAMES]); - param_modes=Catalog::parseArrayValues(attribs[ParsersAttributes::ARG_MODES]); - param_def_vals=Catalog::parseDefaultValues(attribs[ParsersAttributes::ARG_DEFAULTS]); + param_types=getTypes(attribs[Attributes::ArgTypes], false); + param_names=Catalog::parseArrayValues(attribs[Attributes::ArgNames]); + param_modes=Catalog::parseArrayValues(attribs[Attributes::ArgModes]); + param_def_vals=Catalog::parseDefaultValues(attribs[Attributes::ArgDefaults]); for(int i=0; i < param_types.size(); i++) { /* If the function is to be used as a user-defined data type support functions the parameter type will be renamed to "any" (see rules on Type::setFunction()) */ if(i==0 && - (attribs[ParsersAttributes::REF_TYPE]==ParsersAttributes::SEND_FUNC || - attribs[ParsersAttributes::REF_TYPE]==ParsersAttributes::OUTPUT_FUNC || - attribs[ParsersAttributes::REF_TYPE]==ParsersAttributes::CANONICAL_FUNC)) - type=PgSQLType(QString("\"any\"")); + (attribs[Attributes::RefType]==Attributes::SendFunc || + attribs[Attributes::RefType]==Attributes::OutputFunc || + attribs[Attributes::RefType]==Attributes::CanonicalFunc)) + type=PgSqlType(QString("\"any\"")); else { //If the type contains array descriptor [] set the dimension to 1 @@ -1073,7 +1085,7 @@ void DatabaseImportHelper::createFunction(attribs_map &attribs) //Create the type param_types[i].remove(QString("[]")); - type=PgSQLType::parseString(param_types[i]); + type=PgSqlType::parseString(param_types[i]); type.setDimension(dim); } @@ -1103,7 +1115,7 @@ void DatabaseImportHelper::createFunction(attribs_map &attribs) //If the mode is 't' indicates that the current parameter will be used as a return table colum if(!param_modes.isEmpty() && param_modes[i]==QString("t")) - attribs[ParsersAttributes::RETURN_TABLE]+=param.getCodeDefinition(SchemaParser::XML_DEFINITION); + attribs[Attributes::ReturnTable]+=param.getCodeDefinition(SchemaParser::XmlDefinition); else parameters.push_back(param); } @@ -1127,43 +1139,43 @@ void DatabaseImportHelper::createFunction(attribs_map &attribs) param_def_vals.pop_back(); } - param_xmls.push_front(param.getCodeDefinition(SchemaParser::XML_DEFINITION)); + param_xmls.push_front(param.getCodeDefinition(SchemaParser::XmlDefinition)); } - attribs[ParsersAttributes::PARAMETERS]+=param_xmls.join(QChar('\n')); + attribs[Attributes::Parameters]+=param_xmls.join(QChar('\n')); } //Case the function's language is C the symbol is the 'definition' attribute - if(getObjectName(attribs[ParsersAttributes::LANGUAGE])==~LanguageType("c")) + if(getObjectName(attribs[Attributes::Language])==~LanguageType("c")) { - attribs[ParsersAttributes::SYMBOL]=attribs[ParsersAttributes::DEFINITION]; - attribs[ParsersAttributes::DEFINITION]=QString(); + attribs[Attributes::Symbol]=attribs[Attributes::Definition]; + attribs[Attributes::Definition]=QString(); } //Get the language reference code - attribs[ParsersAttributes::LANGUAGE]=getDependencyObject(attribs[ParsersAttributes::LANGUAGE], OBJ_LANGUAGE); + attribs[Attributes::Language]=getDependencyObject(attribs[Attributes::Language], ObjectType::Language); //Get the return type if there is no return table configured - if(attribs[ParsersAttributes::RETURN_TABLE].isEmpty()) + if(attribs[Attributes::ReturnTable].isEmpty()) { /* If the function is to be used as a user-defined data type support functions the return type will be renamed to "any" (see rules on Type::setFunction()) */ - if(attribs[ParsersAttributes::REF_TYPE]==ParsersAttributes::INPUT_FUNC || - attribs[ParsersAttributes::REF_TYPE]==ParsersAttributes::RECV_FUNC || - attribs[ParsersAttributes::REF_TYPE]==ParsersAttributes::CANONICAL_FUNC) - attribs[ParsersAttributes::RETURN_TYPE]=PgSQLType(QString("\"any\"")).getCodeDefinition(SchemaParser::XML_DEFINITION); + if(attribs[Attributes::RefType]==Attributes::InputFunc || + attribs[Attributes::RefType]==Attributes::RecvFunc || + attribs[Attributes::RefType]==Attributes::CanonicalFunc) + attribs[Attributes::ReturnType]=PgSqlType(QString("\"any\"")).getCodeDefinition(SchemaParser::XmlDefinition); else - attribs[ParsersAttributes::RETURN_TYPE]=getType(attribs[ParsersAttributes::RETURN_TYPE], true); + attribs[Attributes::ReturnType]=getType(attribs[Attributes::ReturnType], true); } - loadObjectXML(OBJ_FUNCTION, attribs); + loadObjectXML(ObjectType::Function, attribs); func=dbmodel->createFunction(); dbmodel->addFunction(func); } catch(Exception &e) { if(func) delete(func); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1175,11 +1187,11 @@ void DatabaseImportHelper::createLanguage(attribs_map &attribs) try { unsigned lang_oid, func_oid; - QString func_types[]={ ParsersAttributes::VALIDATOR_FUNC, - ParsersAttributes::HANDLER_FUNC, - ParsersAttributes::INLINE_FUNC }; + QString func_types[]={ Attributes::ValidatorFunc, + Attributes::HandlerFunc, + Attributes::InlineFunc }; - lang_oid=attribs[ParsersAttributes::OID].toUInt(); + lang_oid=attribs[Attributes::Oid].toUInt(); for(unsigned i=0; i < 3; i++) { func_oid=attribs[func_types[i]].toUInt(); @@ -1188,19 +1200,19 @@ void DatabaseImportHelper::createLanguage(attribs_map &attribs) function is defined after the language pgModeler will raise errors so in order to continue the import these fuctions are simply ignored */ if(func_oid < lang_oid) - attribs[func_types[i]]=getDependencyObject(attribs[func_types[i]], OBJ_FUNCTION, true , true, true, {{ParsersAttributes::REF_TYPE, func_types[i]}}); + attribs[func_types[i]]=getDependencyObject(attribs[func_types[i]], ObjectType::Function, true , true, true, {{Attributes::RefType, func_types[i]}}); else attribs[func_types[i]]=QString(); } - loadObjectXML(OBJ_LANGUAGE, attribs); + loadObjectXML(ObjectType::Language, attribs); lang=dbmodel->createLanguage(); dbmodel->addLanguage(lang); } catch(Exception &e) { if(lang) delete(lang); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1211,14 +1223,14 @@ void DatabaseImportHelper::createOperatorFamily(attribs_map &attribs) try { - loadObjectXML(OBJ_OPFAMILY, attribs); + loadObjectXML(ObjectType::OpFamily, attribs); opfam=dbmodel->createOperatorFamily(); dbmodel->addOperatorFamily(opfam); } catch(Exception &e) { if(opfam) delete(opfam); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1233,54 +1245,54 @@ void DatabaseImportHelper::createOperatorClass(attribs_map &attribs) vector elems; QStringList array_vals, list; - attribs[ParsersAttributes::FAMILY]=getObjectName(attribs[ParsersAttributes::FAMILY], true); - attribs[ParsersAttributes::TYPE]=getType(attribs[ParsersAttributes::TYPE], true, attribs); + attribs[Attributes::Family]=getObjectName(attribs[Attributes::Family], true); + attribs[Attributes::Type]=getType(attribs[Attributes::Type], true, attribs); //Generating attributes for STORAGE elements - if(attribs[ParsersAttributes::STORAGE]!=QString("0")) + if(attribs[Attributes::Storage]!=QString("0")) { - elem_attr[ParsersAttributes::STORAGE]=ParsersAttributes::_TRUE_; - elem_attr[ParsersAttributes::DEFINITION]=getType(attribs[ParsersAttributes::STORAGE], true); + elem_attr[Attributes::Storage]=Attributes::True; + elem_attr[Attributes::Definition]=getType(attribs[Attributes::Storage], true); elems.push_back(elem_attr); } - else if(attribs[ParsersAttributes::FUNCTION].isEmpty() && - attribs[ParsersAttributes::OPERATOR].isEmpty()) + else if(attribs[Attributes::Function].isEmpty() && + attribs[Attributes::Operator].isEmpty()) { - elem_attr[ParsersAttributes::STORAGE]=ParsersAttributes::_TRUE_; - elem_attr[ParsersAttributes::DEFINITION]=attribs[ParsersAttributes::TYPE]; + elem_attr[Attributes::Storage]=Attributes::True; + elem_attr[Attributes::Definition]=attribs[Attributes::Type]; elems.push_back(elem_attr); } //Generating attributes for FUNCTION elements - if(!attribs[ParsersAttributes::FUNCTION].isEmpty()) + if(!attribs[Attributes::Function].isEmpty()) { elem_attr.clear(); - elem_attr[ParsersAttributes::FUNCTION]=ParsersAttributes::_TRUE_; - array_vals=Catalog::parseArrayValues(attribs[ParsersAttributes::FUNCTION]); + elem_attr[Attributes::Function]=Attributes::True; + array_vals=Catalog::parseArrayValues(attribs[Attributes::Function]); for(int i=0; i < array_vals.size(); i++) { list=array_vals[i].split(':'); - elem_attr[ParsersAttributes::STRATEGY_NUM]=list[0]; - elem_attr[ParsersAttributes::DEFINITION]=getDependencyObject(list[1], OBJ_FUNCTION, true); + elem_attr[Attributes::StrategyNum]=list[0]; + elem_attr[Attributes::Definition]=getDependencyObject(list[1], ObjectType::Function, true); elems.push_back(elem_attr); } } //Generating attributes for OPERATOR elements - if(!attribs[ParsersAttributes::OPERATOR].isEmpty()) + if(!attribs[Attributes::Operator].isEmpty()) { elem_attr.clear(); - elem_attr[ParsersAttributes::OPERATOR]=ParsersAttributes::_TRUE_; - array_vals=Catalog::parseArrayValues(attribs[ParsersAttributes::OPERATOR]); + elem_attr[Attributes::Operator]=Attributes::True; + array_vals=Catalog::parseArrayValues(attribs[Attributes::Operator]); for(int i=0; i < array_vals.size(); i++) { list=array_vals[i].split(':'); - elem_attr[ParsersAttributes::DEFINITION]=""; - elem_attr[ParsersAttributes::STRATEGY_NUM]=list[0]; - elem_attr[ParsersAttributes::DEFINITION]+=getDependencyObject(list[1], OBJ_OPERATOR, true); - elem_attr[ParsersAttributes::DEFINITION]+=getDependencyObject(list[2], OBJ_OPFAMILY, true); + elem_attr[Attributes::Definition]=""; + elem_attr[Attributes::StrategyNum]=list[0]; + elem_attr[Attributes::Definition]+=getDependencyObject(list[1], ObjectType::Operator, true); + elem_attr[Attributes::Definition]+=getDependencyObject(list[2], ObjectType::OpFamily, true); elems.push_back(elem_attr); } } @@ -1289,18 +1301,18 @@ void DatabaseImportHelper::createOperatorClass(attribs_map &attribs) for(unsigned i=0; i < elems.size(); i++) { schparser.ignoreUnkownAttributes(true); - attribs[ParsersAttributes::ELEMENTS]+=schparser.getCodeDefinition(ParsersAttributes::ELEMENT, elems[i], SchemaParser::XML_DEFINITION); + attribs[Attributes::Elements]+=schparser.getCodeDefinition(Attributes::Element, elems[i], SchemaParser::XmlDefinition); schparser.ignoreUnkownAttributes(false); } - loadObjectXML(OBJ_OPCLASS, attribs); + loadObjectXML(ObjectType::OpClass, attribs); opclass=dbmodel->createOperatorClass(); dbmodel->addOperatorClass(opclass); } catch(Exception &e) { if(opclass) delete(opclass); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1315,26 +1327,26 @@ void DatabaseImportHelper::createOperator(attribs_map &attribs) QRegExp regexp; QString op_signature, - func_types[]={ ParsersAttributes::OPERATOR_FUNC, - ParsersAttributes::RESTRICTION_FUNC, - ParsersAttributes::JOIN_FUNC }, + func_types[]={ Attributes::OperatorFunc, + Attributes::RestrictionFunc, + Attributes::JoinFunc }, - arg_types[]= { ParsersAttributes::LEFT_TYPE, - ParsersAttributes::RIGHT_TYPE }, + arg_types[]= { Attributes::LeftType, + Attributes::RightType }, - op_types[]= { ParsersAttributes::COMMUTATOR_OP, - ParsersAttributes::NEGATOR_OP }; + op_types[]= { Attributes::CommutatorOp, + Attributes::NegatorOp }; for(unsigned i=0; i < 3; i++) - attribs[func_types[i]]=getDependencyObject(attribs[func_types[i]], OBJ_FUNCTION, true, true, true, {{ParsersAttributes::REF_TYPE, func_types[i]}}); + attribs[func_types[i]]=getDependencyObject(attribs[func_types[i]], ObjectType::Function, true, true, true, {{Attributes::RefType, func_types[i]}}); for(unsigned i=0; i < 2; i++) - attribs[arg_types[i]]=getType(attribs[arg_types[i]], true, {{ParsersAttributes::REF_TYPE, arg_types[i]}}); + attribs[arg_types[i]]=getType(attribs[arg_types[i]], true, {{Attributes::RefType, arg_types[i]}}); - regexp.setPattern(ParsersAttributes::SIGNATURE + QString("(=)(\")")); + regexp.setPattern(Attributes::Signature + QString("(=)(\")")); for(unsigned i=0; i < 2; i++) { - attribs[op_types[i]]=getDependencyObject(attribs[op_types[i]], OBJ_OPERATOR, true, false, true, {{ParsersAttributes::REF_TYPE, op_types[i]}}); + attribs[op_types[i]]=getDependencyObject(attribs[op_types[i]], ObjectType::Operator, true, false, true, {{Attributes::RefType, op_types[i]}}); if(!attribs[op_types[i]].isEmpty()) { @@ -1347,19 +1359,19 @@ void DatabaseImportHelper::createOperator(attribs_map &attribs) op_signature=attribs[op_types[i]].mid(pos, (attribs[op_types[i]].indexOf('"',pos) - pos)); //If the operator is not defined clear up the reference to it - if(dbmodel->getObjectIndex(op_signature, OBJ_OPERATOR) < 0) + if(dbmodel->getObjectIndex(op_signature, ObjectType::Operator) < 0) attribs[op_types[i]].clear(); } } - loadObjectXML(OBJ_OPERATOR, attribs); + loadObjectXML(ObjectType::Operator, attribs); oper=dbmodel->createOperator(); dbmodel->addOperator(oper); } catch(Exception &e) { if(oper) delete(oper); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1370,14 +1382,14 @@ void DatabaseImportHelper::createCollation(attribs_map &attribs) try { - loadObjectXML(OBJ_COLLATION, attribs); + loadObjectXML(ObjectType::Collation, attribs); coll=dbmodel->createCollation(); dbmodel->addCollation(coll); } catch(Exception &e) { if(coll) delete(coll); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1388,17 +1400,17 @@ void DatabaseImportHelper::createCast(attribs_map &attribs) try { - attribs[ParsersAttributes::FUNCTION]=getDependencyObject(attribs[ParsersAttributes::FUNCTION], OBJ_FUNCTION, true); - attribs[ParsersAttributes::SOURCE_TYPE]=getType(attribs[ParsersAttributes::SOURCE_TYPE], true); - attribs[ParsersAttributes::DEST_TYPE]=getType(attribs[ParsersAttributes::DEST_TYPE], true); - loadObjectXML(OBJ_CAST, attribs); + attribs[Attributes::Function]=getDependencyObject(attribs[Attributes::Function], ObjectType::Function, true); + attribs[Attributes::SourceType]=getType(attribs[Attributes::SourceType], true); + attribs[Attributes::DestType]=getType(attribs[Attributes::DestType], true); + loadObjectXML(ObjectType::Cast, attribs); cast=dbmodel->createCast(); dbmodel->addCast(cast); } catch(Exception &e) { if(cast) delete(cast); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1409,15 +1421,15 @@ void DatabaseImportHelper::createConversion(attribs_map &attribs) try { - attribs[ParsersAttributes::FUNCTION]=getDependencyObject(attribs[ParsersAttributes::FUNCTION], OBJ_FUNCTION, true, auto_resolve_deps); - loadObjectXML(OBJ_CONVERSION, attribs); + attribs[Attributes::Function]=getDependencyObject(attribs[Attributes::Function], ObjectType::Function, true, auto_resolve_deps); + loadObjectXML(ObjectType::Conversion, attribs); conv=dbmodel->createConversion(); dbmodel->addConversion(conv); } catch(Exception &e) { if(conv) delete(conv); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1429,13 +1441,13 @@ void DatabaseImportHelper::createSequence(attribs_map &attribs) try { - QStringList owner_col=attribs[ParsersAttributes::OWNER_COLUMN].split(':'), - seq_attribs=Catalog::parseArrayValues(attribs[ParsersAttributes::ATTRIBUTE]); - QString attr[]={ ParsersAttributes::START, ParsersAttributes::MIN_VALUE, - ParsersAttributes::MAX_VALUE, ParsersAttributes::INCREMENT, - ParsersAttributes::CACHE, ParsersAttributes::CYCLE }; + QStringList owner_col=attribs[Attributes::OwnerColumn].split(':'), + seq_attribs=Catalog::parseArrayValues(attribs[Attributes::Attribute]); + QString attr[]={ Attributes::Start, Attributes::MinValue, + Attributes::MaxValue, Attributes::Increment, + Attributes::Cache, Attributes::Cycle }; - attribs[ParsersAttributes::OWNER_COLUMN]=QString(); + attribs[Attributes::OwnerColumn]=QString(); /* If there are owner columns and the oid of sequence is greater than the owner column's table oid stores the oid of both (sequence and table) in order to swap it's ids at the end of import to @@ -1445,17 +1457,17 @@ void DatabaseImportHelper::createSequence(attribs_map &attribs) Table *tab = nullptr; QString col_name, tab_name; attribs_map pos_attrib={ - { ParsersAttributes::X_POS, QString("0") }, - { ParsersAttributes::Y_POS, QString("0") }}; + { Attributes::XPos, QString("0") }, + { Attributes::YPos, QString("0") }}; - if(attribs[ParsersAttributes::OID].toUInt() > owner_col[0].toUInt()) - seq_tab_swap[attribs[ParsersAttributes::OID]]=owner_col[0]; + if(attribs[Attributes::Oid].toUInt() > owner_col[0].toUInt()) + seq_tab_swap[attribs[Attributes::Oid]]=owner_col[0]; /* Get the table and the owner column instances so the sequence code can be disabled if the column is an identity one */ - tab_name = getDependencyObject(owner_col[0], OBJ_TABLE, true, auto_resolve_deps, false, - {{ ParsersAttributes::POSITION, - schparser.getCodeDefinition(ParsersAttributes::POSITION, pos_attrib, SchemaParser::XML_DEFINITION)}}); + tab_name = getDependencyObject(owner_col[0], ObjectType::Table, true, auto_resolve_deps, false, + {{ Attributes::Position, + schparser.getCodeDefinition(Attributes::Position, pos_attrib, SchemaParser::XmlDefinition)}}); col_name=getColumnName(owner_col[0], owner_col[1]); tab = dbmodel->getTable(tab_name); @@ -1467,18 +1479,22 @@ void DatabaseImportHelper::createSequence(attribs_map &attribs) for(int i=0; i < seq_attribs.size(); i++) attribs[attr[i]]=seq_attribs[i]; - loadObjectXML(OBJ_SEQUENCE, attribs); + loadObjectXML(ObjectType::Sequence, attribs); seq=dbmodel->createSequence(); dbmodel->addSequence(seq); //Disable the sequence's SQL when the owner column is identity if(col && col->isIdentity()) + { + col->setIdSeqAttributes(seq->getMinValue(), seq->getMaxValue(), seq->getIncrement(), + seq->getStart(), seq->getCache(), seq->isCycle()); seq->setSQLDisabled(true); + } } catch(Exception &e) { if(seq) delete(seq); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1490,27 +1506,27 @@ void DatabaseImportHelper::createAggregate(attribs_map &attribs) try { QStringList types; - QString func_types[]={ ParsersAttributes::TRANSITION_FUNC, - ParsersAttributes::FINAL_FUNC }, + QString func_types[]={ Attributes::TransitionFunc, + Attributes::FinalFunc }, sch_name; for(unsigned i=0; i < 2; i++) - attribs[func_types[i]]=getDependencyObject(attribs[func_types[i]], OBJ_FUNCTION, true, auto_resolve_deps, true, {{ParsersAttributes::REF_TYPE, func_types[i]}}); + attribs[func_types[i]]=getDependencyObject(attribs[func_types[i]], ObjectType::Function, true, auto_resolve_deps, true, {{Attributes::RefType, func_types[i]}}); - types=getTypes(attribs[ParsersAttributes::TYPES], true); - attribs[ParsersAttributes::TYPES]=QString(); + types=getTypes(attribs[Attributes::Types], true); + attribs[Attributes::Types]=QString(); if(!types.isEmpty()) { for(int i=0; i < types.size(); i++) - attribs[ParsersAttributes::TYPES]+=types[i]; + attribs[Attributes::Types]+=types[i]; } - attribs[ParsersAttributes::STATE_TYPE]=getType(attribs[ParsersAttributes::STATE_TYPE], true, - {{ParsersAttributes::REF_TYPE, ParsersAttributes::STATE_TYPE}}); - attribs[ParsersAttributes::SORT_OP]=getDependencyObject(attribs[ParsersAttributes::SORT_OP], OBJ_OPERATOR, true); + attribs[Attributes::StateType]=getType(attribs[Attributes::StateType], true, + {{Attributes::RefType, Attributes::StateType}}); + attribs[Attributes::SortOp]=getDependencyObject(attribs[Attributes::SortOp], ObjectType::Operator, true); - loadObjectXML(OBJ_AGGREGATE, attribs); + loadObjectXML(ObjectType::Aggregate, attribs); agg=dbmodel->createAggregate(); dbmodel->addAggregate(agg); @@ -1525,7 +1541,7 @@ void DatabaseImportHelper::createAggregate(attribs_map &attribs) catch(Exception &e) { if(agg) delete(agg); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1536,20 +1552,20 @@ void DatabaseImportHelper::createType(attribs_map &attribs) try { - attribs[attribs[ParsersAttributes::CONFIGURATION]]=ParsersAttributes::_TRUE_; + attribs[attribs[Attributes::Configuration]]=Attributes::True; - if(!attribs[ParsersAttributes::ENUM_TYPE].isEmpty()) + if(!attribs[Attributes::EnumType].isEmpty()) { - attribs[ParsersAttributes::ENUMERATIONS]=Catalog::parseArrayValues(attribs[ParsersAttributes::ENUMERATIONS]).join(','); - attribs[ParsersAttributes::ENUMERATIONS].remove('"'); + attribs[Attributes::Enumerations]=Catalog::parseArrayValues(attribs[Attributes::Enumerations]).join(','); + attribs[Attributes::Enumerations].remove('"'); } - else if(!attribs[ParsersAttributes::COMPOSITE_TYPE].isEmpty()) + else if(!attribs[Attributes::CompositeType].isEmpty()) { QStringList comp_attribs, values; TypeAttribute type_attrib; - comp_attribs=Catalog::parseArrayValues(attribs[ParsersAttributes::TYPE_ATTRIBUTE]); - attribs[ParsersAttributes::TYPE_ATTRIBUTE]=QString(); + comp_attribs=Catalog::parseArrayValues(attribs[Attributes::TypeAttribute]); + attribs[Attributes::TypeAttribute]=QString(); for(int i=0; i < comp_attribs.size(); i++) { @@ -1558,43 +1574,43 @@ void DatabaseImportHelper::createType(attribs_map &attribs) if(values.size() >= 2) { type_attrib.setName(values[0].remove('"')); - type_attrib.setType(PgSQLType::parseString(values[1].remove('\\'))); - type_attrib.setCollation(dbmodel->getObject(getObjectName(values[2].remove('"')), OBJ_COLLATION)); - attribs[ParsersAttributes::TYPE_ATTRIBUTE]+=type_attrib.getCodeDefinition(SchemaParser::XML_DEFINITION); + type_attrib.setType(PgSqlType::parseString(values[1].remove('\\'))); + type_attrib.setCollation(dbmodel->getObject(getObjectName(values[2].remove('"')), ObjectType::Collation)); + attribs[Attributes::TypeAttribute]+=type_attrib.getCodeDefinition(SchemaParser::XmlDefinition); } } } - else if(!attribs[ParsersAttributes::RANGE_TYPE].isEmpty()) + else if(!attribs[Attributes::RangeType].isEmpty()) { - QStringList range_attr=Catalog::parseArrayValues(attribs[ParsersAttributes::RANGE_ATTRIBS]); + QStringList range_attr=Catalog::parseArrayValues(attribs[Attributes::RangeAttribs]); - attribs[ParsersAttributes::SUBTYPE]=getType(range_attr[0], true); - attribs[ParsersAttributes::COLLATION]=getDependencyObject(range_attr[1], OBJ_COLLATION, true); - attribs[ParsersAttributes::OP_CLASS]=getDependencyObject(range_attr[2], OBJ_OPCLASS, true); - attribs[ParsersAttributes::CANONICAL_FUNC]=getDependencyObject(range_attr[3], OBJ_FUNCTION, true); - attribs[ParsersAttributes::SUBTYPE_DIFF_FUNC]=getDependencyObject(range_attr[4], OBJ_FUNCTION, true); + attribs[Attributes::Subtype]=getType(range_attr[0], true); + attribs[Attributes::Collation]=getDependencyObject(range_attr[1], ObjectType::Collation, true); + attribs[Attributes::OpClass]=getDependencyObject(range_attr[2], ObjectType::OpClass, true); + attribs[Attributes::CanonicalFunc]=getDependencyObject(range_attr[3], ObjectType::Function, true); + attribs[Attributes::SubtypeDiffFunc]=getDependencyObject(range_attr[4], ObjectType::Function, true); } else { - QString type_name=getObjectName(attribs[ParsersAttributes::OID]), - func_types[]={ ParsersAttributes::INPUT_FUNC, - ParsersAttributes::OUTPUT_FUNC, - ParsersAttributes::RECV_FUNC, - ParsersAttributes::SEND_FUNC, - ParsersAttributes::TPMOD_IN_FUNC, - ParsersAttributes::TPMOD_OUT_FUNC, - ParsersAttributes::ANALYZE_FUNC }; + QString type_name=getObjectName(attribs[Attributes::Oid]), + func_types[]={ Attributes::InputFunc, + Attributes::OutputFunc, + Attributes::RecvFunc, + Attributes::SendFunc, + Attributes::TpmodInFunc, + Attributes::TpmodOutFunc, + Attributes::AnalyzeFunc }; unsigned i, count=sizeof(func_types)/sizeof(QString); - attribs[ParsersAttributes::ELEMENT]=getType(attribs[ParsersAttributes::ELEMENT], false); + attribs[Attributes::Element]=getType(attribs[Attributes::Element], false); /* Workaround: if importing a datatype that is part of an extension we avoid the importing of * its supporting functions (since they will not be necessary here because the type will be sql-disabled)*/ - if(!catalog.isExtensionObject(attribs[ParsersAttributes::OID].toUInt())) + if(!catalog.isExtensionObject(attribs[Attributes::Oid].toUInt())) { for(i=0; i < count; i++) { - attribs[func_types[i]]=getDependencyObject(attribs[func_types[i]], OBJ_FUNCTION, true, true, true, {{ParsersAttributes::REF_TYPE, func_types[i]}}); + attribs[func_types[i]]=getDependencyObject(attribs[func_types[i]], ObjectType::Function, true, true, true, {{Attributes::RefType, func_types[i]}}); /* Since pgModeler requires that type functions refers to the constructing type as "any" it's necessary to replace the function parameter types names */ @@ -1603,14 +1619,14 @@ void DatabaseImportHelper::createType(attribs_map &attribs) } } - loadObjectXML(OBJ_TYPE, attribs); + loadObjectXML(ObjectType::Type, attribs); type=dbmodel->createType(); dbmodel->addType(type); } catch(Exception &e) { if(type) delete(type); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1621,47 +1637,43 @@ void DatabaseImportHelper::createTable(attribs_map &attribs) try { - unsigned tab_oid=attribs[ParsersAttributes::OID].toUInt(), type_oid=0, col_idx=0; + unsigned tab_oid=attribs[Attributes::Oid].toUInt(), type_oid=0, col_idx=0; bool is_type_registered=false; Column col; vector inh_cols; QString type_def, unknown_obj_xml, type_name, def_val; map::iterator itr, itr1, itr_end; attribs_map pos_attrib={ - { ParsersAttributes::X_POS, QString("0") }, - { ParsersAttributes::Y_POS, QString("0") }}; + { Attributes::XPos, QString("0") }, + { Attributes::YPos, QString("0") }}; - attribs[ParsersAttributes::COLUMNS]=QString(); - attribs[ParsersAttributes::POSITION]=schparser.getCodeDefinition(ParsersAttributes::POSITION, pos_attrib, SchemaParser::XML_DEFINITION); + attribs[Attributes::Columns]=QString(); + attribs[Attributes::Position]=schparser.getCodeDefinition(Attributes::Position, pos_attrib, SchemaParser::XmlDefinition); //Retrieving columns if they were not retrieved yet - if(columns[attribs[ParsersAttributes::OID].toUInt()].empty() && auto_resolve_deps) + if(columns[attribs[Attributes::Oid].toUInt()].empty() && auto_resolve_deps) { - /* Since the schema name sometimes comes in form os tag - it is needed extract only the name from before retrieve the columns of the table */ - QString sch_name=attribs[ParsersAttributes::SCHEMA]; - sch_name.replace(QRegExp(QString("(\\t)*(<)(schema)( )+(name)( )*(=)")), QString()); - sch_name.replace(QRegExp(QString("(/)(>)(\n)*")), QString()); - sch_name.replace('"', QString()); - sch_name=sch_name.trimmed(); - retrieveTableColumns(sch_name, attribs[ParsersAttributes::NAME]); + QString sch_name; + sch_name = getDependencyObject(attribs[Attributes::SchemaOid], ObjectType::Schema, true, auto_resolve_deps, false); + retrieveTableColumns(sch_name, attribs[Attributes::Name]); } - itr=itr1=columns[attribs[ParsersAttributes::OID].toUInt()].begin(); - itr_end=columns[attribs[ParsersAttributes::OID].toUInt()].end(); + itr=itr1=columns[attribs[Attributes::Oid].toUInt()].begin(); + itr_end=columns[attribs[Attributes::Oid].toUInt()].end(); + attribs[Attributes::MaxObjCount]=QString::number(columns[attribs[Attributes::Oid].toUInt()].size()); //Creating columns while(itr!=itr_end) { - if(itr->second.count(ParsersAttributes::PERMISSION) && - !itr->second.at(ParsersAttributes::PERMISSION).isEmpty()) - col_perms[tab_oid].push_back(itr->second[ParsersAttributes::OID].toUInt()); + if(itr->second.count(Attributes::Permission) && + !itr->second.at(Attributes::Permission).isEmpty()) + col_perms[tab_oid].push_back(itr->second[Attributes::Oid].toUInt()); - if(itr->second[ParsersAttributes::INHERITED]==ParsersAttributes::_TRUE_) + if(itr->second[Attributes::Inherited]==Attributes::True) inh_cols.push_back(col_idx); - col.setName(itr->second[ParsersAttributes::NAME]); - type_oid=itr->second[ParsersAttributes::TYPE_OID].toUInt(); + col.setName(itr->second[Attributes::Name]); + type_oid=itr->second[Attributes::TypeOid].toUInt(); /* If the type has an entry on the types map and its OID is greater than system object oids, means that it's a user defined type, thus, there is the need to check if the type @@ -1669,15 +1681,26 @@ void DatabaseImportHelper::createTable(attribs_map &attribs) if(types.count(type_oid)!=0 && type_oid > catalog.getLastSysObjectOID()) { /* Building the type name prepending the schema name in order to search it on - the user defined types list at PgSQLType class */ - type_name=getObjectName(types[type_oid][ParsersAttributes::SCHEMA], true); - type_name+=QString(".") + types[type_oid][ParsersAttributes::NAME]; - is_type_registered=PgSQLType::isRegistered(type_name, dbmodel); + * the user defined types list at PgSQLType class */ + type_name=BaseObject::formatName(getObjectName(types[type_oid][Attributes::Schema], true), false); + type_name+=QString("."); + + if(types[type_oid][Attributes::Category] == ~CategoryType(CategoryType::Array)) + { + int dim = types[type_oid][Attributes::Name].count(QString("[]")); + QString aux_name = types[type_oid][Attributes::Name].remove(QString("[]")); + type_name+=BaseObject::formatName(aux_name, false); + type_name+=QString("[]").repeated(dim); + } + else + type_name+=BaseObject::formatName(types[type_oid][Attributes::Name], false); + + is_type_registered=PgSqlType::isRegistered(type_name, dbmodel); } else { is_type_registered=(types.count(type_oid)!=0); - type_name=itr->second[ParsersAttributes::TYPE]; + type_name=itr->second[Attributes::Type]; } /* Checking if the type used by the column exists (is registered), @@ -1686,22 +1709,23 @@ void DatabaseImportHelper::createTable(attribs_map &attribs) the non-array type, this way, if the original type is created there is no need to create the array form */ if(auto_resolve_deps && !is_type_registered && !type_name.contains(QString("[]"))) { - type_def=getDependencyObject(itr->second[ParsersAttributes::TYPE_OID], OBJ_TYPE); - unknown_obj_xml=UNKNOWN_OBJECT_OID_XML.arg(type_oid); + type_def=getDependencyObject(itr->second[Attributes::TypeOid], ObjectType::Type); + unknown_obj_xml=UnkownObjectOidXml.arg(type_oid); /* If the type still doesn't exists means that the column maybe is referencing a domain this way pgModeler will try to retrieve the mentionend object */ if(type_def==unknown_obj_xml) - type_def=getDependencyObject(itr->second[ParsersAttributes::TYPE_OID], OBJ_DOMAIN); + type_def=getDependencyObject(itr->second[Attributes::TypeOid], ObjectType::Domain); } - col.setType(PgSQLType::parseString(type_name)); - col.setNotNull(!itr->second[ParsersAttributes::NOT_NULL].isEmpty()); - col.setComment(itr->second[ParsersAttributes::COMMENT]); + col.setIdentityType(BaseType::Null); + col.setType(PgSqlType::parseString(type_name)); + col.setNotNull(!itr->second[Attributes::NotNull].isEmpty()); + col.setComment(itr->second[Attributes::Comment]); //Overriding the default value if the column is identity - if(!itr->second[ParsersAttributes::IDENTITY_TYPE].isEmpty()) - col.setIdentityType(itr->second[ParsersAttributes::IDENTITY_TYPE]); + if(!itr->second[Attributes::IdentityType].isEmpty()) + col.setIdentityType(itr->second[Attributes::IdentityType]); else { /* Removing extra/forced type casting in the retrieved default value. @@ -1717,7 +1741,7 @@ void DatabaseImportHelper::createTable(attribs_map &attribs) varchar to character varying) we remove the '::character varying'. The idea here is to eliminate the cast if the casting is equivalent to the column type. */ - def_val = itr->second[ParsersAttributes::DEFAULT_VALUE]; + def_val = itr->second[Attributes::DefaultValue]; if(!def_val.startsWith(QString("nextval(")) && def_val.contains(QString("::"))) { @@ -1734,27 +1758,111 @@ void DatabaseImportHelper::createTable(attribs_map &attribs) } //Checking if the collation used by the column exists, if not it'll be created when auto_resolve_deps is checked - if(auto_resolve_deps && !itr->second[ParsersAttributes::COLLATION].isEmpty()) - getDependencyObject(itr->second[ParsersAttributes::COLLATION], OBJ_COLLATION); + if(auto_resolve_deps && !itr->second[Attributes::Collation].isEmpty()) + getDependencyObject(itr->second[Attributes::Collation], ObjectType::Collation); - col.setCollation(dbmodel->getObject(getObjectName(itr->second[ParsersAttributes::COLLATION]),OBJ_COLLATION)); - attribs[ParsersAttributes::COLUMNS]+=col.getCodeDefinition(SchemaParser::XML_DEFINITION); + col.setCollation(dbmodel->getObject(getObjectName(itr->second[Attributes::Collation]),ObjectType::Collation)); + attribs[Attributes::Columns]+=col.getCodeDefinition(SchemaParser::XmlDefinition); itr++; col_idx++; } - loadObjectXML(OBJ_TABLE, attribs); + loadObjectXML(ObjectType::Table, attribs); table=dbmodel->createTable(); for(unsigned col_idx : inh_cols) inherited_cols.push_back(table->getColumn(col_idx)); + // Storing the partition bound expression temporarily in the table in order to configure the partition hierarchy later + table->setPartitionBoundingExpr(attribs[Attributes::PartitionBoundExpr].remove(QRegExp("^(FOR)( )+(VALUES)( )*", Qt::CaseInsensitive))); + + // Retrieving the partitioned table related to the partition table being created + if(!attribs[Attributes::PartitionedTable].isEmpty()) + { + Table *partitioned_tab = nullptr; + + attribs[Attributes::PartitionedTable] = + getDependencyObject(attribs[Attributes::PartitionedTable], ObjectType::Table, true, auto_resolve_deps, false); + + partitioned_tab = dbmodel->getTable(attribs[Attributes::PartitionedTable]); + table->setPartionedTable(partitioned_tab); + + if(!partitioned_tab) + { + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(attribs[Attributes::Name]).arg(BaseObject::getTypeName(ObjectType::Table)) + .arg(attribs[Attributes::PartitionedTable]).arg(BaseObject::getTypeName(ObjectType::Table)), + ErrorCode::RefObjectInexistsModel ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + } + + // Creating partition keys if present + if(attribs[Attributes::IsPartitioned] == Attributes::True) + { + QStringList cols, collations, opclasses, exprs; + PartitionKey part_key; + PartitioningType part_type; + QString coll_name, opc_name; + Collation *coll = nullptr; + OperatorClass *opclass = nullptr; + vector part_keys; + + part_type = PartitioningType(attribs[Attributes::Partitioning]); + table->setPartitioningType(part_type); + + cols=Catalog::parseArrayValues(attribs[Attributes::PartKeyCols]); + collations=Catalog::parseArrayValues(attribs[Attributes::PartKeyColls]); + opclasses=Catalog::parseArrayValues(attribs[Attributes::PartKeyOpCls]); + exprs = Catalog::parseIndexExpressions(attribs[Attributes::PartKeyExprs]); + + for(int i = 0; i < cols.size(); i++) + { + part_key = PartitionKey(); + + // Retrieving the column used by the partition key + if(cols[i] != QString("0")) + part_key.setColumn(table->getColumn(getColumnName(attribs[Attributes::Oid], cols[i]))); + else if(!exprs.isEmpty()) + { + part_key.setExpression(exprs.front()); + exprs.pop_front(); + } + + // Retriving the collation for the partion key + if(i < collations.size() && collations[i] != QString("0")) + { + coll_name = getDependencyObject(collations[i], ObjectType::Collation, false, true, false); + coll = dynamic_cast(dbmodel->getObject(coll_name, ObjectType::Collation)); + + //Even if the collation exists we'll ignore it when it is the "pg_catalog.default" + if(coll && (!coll->isSystemObject() || + (coll->isSystemObject() && coll->getName() != QString("default")))) + part_key.setCollation(coll); + } + + // Retriving the operator class for the partion key + if(i < opclasses.size() && opclasses[i] != QString("0")) + { + opc_name = getDependencyObject(opclasses[i], ObjectType::OpClass, true, true, false); + opclass = dynamic_cast(dbmodel->getObject(opc_name, ObjectType::OpClass)); + + if(opclass) + part_key.setOperatorClass(opclass); + } + + part_keys.push_back(part_key); + } + + table->addPartitionKeys(part_keys); + } + dbmodel->addTable(table); + imported_tables[tab_oid] = table; } catch(Exception &e) { if(table) delete(table); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1763,28 +1871,96 @@ void DatabaseImportHelper::createView(attribs_map &attribs) { View *view=nullptr; Reference ref; + Column col; + unsigned type_oid = 0; + QString type_name, type_def, unknown_obj_xml, sch_name; + bool is_type_registered = false; + QStringList ref_tab_oids; + Table *ref_tab = nullptr; try { - attribs_map pos_attrib={{ ParsersAttributes::X_POS, QString("0") }, - { ParsersAttributes::Y_POS, QString("0") }}; + attribs_map pos_attrib={{ Attributes::XPos, QString("0") }, + { Attributes::YPos, QString("0") }}; - attribs[ParsersAttributes::POSITION]=schparser.getCodeDefinition(ParsersAttributes::POSITION, pos_attrib, SchemaParser::XML_DEFINITION); + attribs[Attributes::Position]=schparser.getCodeDefinition(Attributes::Position, pos_attrib, SchemaParser::XmlDefinition); - ref=Reference(attribs[ParsersAttributes::DEFINITION], QString()); - ref.setDefinitionExpression(true); - attribs[ParsersAttributes::REFERENCES]=ref.getXMLDefinition(); + ref=Reference(attribs[Attributes::Definition], QString()); + ref.setDefinitionExpression(true); - loadObjectXML(OBJ_VIEW, attribs); - view=dbmodel->createView(); - dbmodel->addView(view); + sch_name = getDependencyObject(attribs[Attributes::SchemaOid], ObjectType::Schema, true, auto_resolve_deps, false); + retrieveTableColumns(sch_name, attribs[Attributes::Name]); + + //Creating columns + for(auto &itr : columns[attribs[Attributes::Oid].toUInt()]) + { + col.setName(itr.second[Attributes::Name]); + type_oid=itr.second[Attributes::TypeOid].toUInt(); - retrieveTableColumns(view->getSchema()->getName(), view->getName()); + /* If the type has an entry on the types map and its OID is greater than system object oids, + * means that it's a user defined type, thus, there is the need to check if the type + * is registered. */ + if(types.count(type_oid)!=0 && type_oid > catalog.getLastSysObjectOID()) + { + /* Building the type name prepending the schema name in order to search it on + * the user defined types list at PgSQLType class */ + type_name=BaseObject::formatName(getObjectName(types[type_oid][Attributes::Schema], true), false); + type_name+=QString("."); + + if(types[type_oid][Attributes::Category] == ~CategoryType(CategoryType::Array)) + { + int dim = types[type_oid][Attributes::Name].count(QString("[]")); + QString aux_name = types[type_oid][Attributes::Name].remove(QString("[]")); + type_name+=BaseObject::formatName(aux_name, false); + type_name+=QString("[]").repeated(dim); + } + else + type_name+=BaseObject::formatName(types[type_oid][Attributes::Name], false); + + is_type_registered=PgSqlType::isRegistered(type_name, dbmodel); + } + else + { + is_type_registered=(types.count(type_oid)!=0); + type_name=itr.second[Attributes::Type]; + } + + /* Checking if the type used by the column exists (is registered), + * if not it'll be created when auto_resolve_deps is checked. The only exception here if for + * array types [] that will not be automatically created because they are derivated from + * the non-array type, this way, if the original type is created there is no need to create the array form */ + if(auto_resolve_deps && !is_type_registered && !type_name.contains(QString("[]"))) + { + type_def = getDependencyObject(itr.second[Attributes::TypeOid], ObjectType::Type); + unknown_obj_xml = UnkownObjectOidXml.arg(type_oid); + + /* If the type still doesn't exists means that the column maybe is referencing a domain + * this way pgModeler will try to retrieve the mentionend object */ + if(type_def==unknown_obj_xml) + type_def=getDependencyObject(itr.second[Attributes::TypeOid], ObjectType::Domain); + } + + col.setType(PgSqlType::parseString(type_name)); + ref.addColumn(&col); + } + + // Configuring the reference tables + for(auto &tab_oid : Catalog::parseArrayValues(attribs[Attributes::RefTables])) + { + ref_tab = dbmodel->getTable(getDependencyObject(tab_oid, ObjectType::Table, true, true, false)); + ref.addReferencedTable(ref_tab); + } + + attribs[Attributes::References]=ref.getXMLDefinition(); + + loadObjectXML(ObjectType::View, attribs); + view = dbmodel->createView(); + dbmodel->addView(view); } catch(Exception &e) { if(view) delete(view); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1792,34 +1968,34 @@ void DatabaseImportHelper::createView(attribs_map &attribs) void DatabaseImportHelper::createRule(attribs_map &attribs) { Rule *rule=nullptr; - QString cmds=attribs[ParsersAttributes::COMMANDS]; + QString cmds=attribs[Attributes::Commands]; int start=-1; QRegExp cond_regexp(QString("(WHERE)(.)+(DO)")); - ObjectType table_type=OBJ_TABLE; + ObjectType table_type=ObjectType::Table; try { start=cond_regexp.indexIn(cmds); if(start >=0) { - attribs[ParsersAttributes::CONDITION]=cmds.mid(start, cond_regexp.matchedLength()); - attribs[ParsersAttributes::CONDITION].remove(QRegExp(QString("(DO)|(WHERE)"))); + attribs[Attributes::Condition]=cmds.mid(start, cond_regexp.matchedLength()); + attribs[Attributes::Condition].remove(QRegExp(QString("(DO)|(WHERE)"))); } - attribs[ParsersAttributes::COMMANDS]=Catalog::parseRuleCommands(attribs[ParsersAttributes::COMMANDS]).join(';'); + attribs[Attributes::Commands]=Catalog::parseRuleCommands(attribs[Attributes::Commands]).join(';'); - if(attribs[ParsersAttributes::TABLE_TYPE]==BaseObject::getSchemaName(OBJ_VIEW)) - table_type=OBJ_VIEW; + if(attribs[Attributes::TableType]==BaseObject::getSchemaName(ObjectType::View)) + table_type=ObjectType::View; - attribs[ParsersAttributes::TABLE]=getDependencyObject(attribs[ParsersAttributes::TABLE], table_type, true, auto_resolve_deps, false); + attribs[Attributes::Table]=getDependencyObject(attribs[Attributes::Table], table_type, true, auto_resolve_deps, false); - loadObjectXML(OBJ_RULE, attribs); + loadObjectXML(ObjectType::Rule, attribs); rule=dbmodel->createRule(); } catch(Exception &e) { if(rule) delete(rule); - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1828,68 +2004,25 @@ void DatabaseImportHelper::createTrigger(attribs_map &attribs) { try { - ObjectType table_type=OBJ_TABLE; + ObjectType table_type=ObjectType::Table; - if(attribs[ParsersAttributes::TABLE_TYPE]==BaseObject::getSchemaName(OBJ_VIEW)) - table_type=OBJ_VIEW; + if(attribs[Attributes::TableType]==BaseObject::getSchemaName(ObjectType::View)) + table_type=ObjectType::View; - attribs[ParsersAttributes::TABLE]=getDependencyObject(attribs[ParsersAttributes::TABLE], table_type, true, auto_resolve_deps, false); - attribs[ParsersAttributes::TRIGGER_FUNC]=getDependencyObject(attribs[ParsersAttributes::TRIGGER_FUNC], OBJ_FUNCTION, true, true); - attribs[ParsersAttributes::ARGUMENTS]=Catalog::parseArrayValues(attribs[ParsersAttributes::ARGUMENTS].remove(QString(",\"\""))).join(','); + attribs[Attributes::Table]=getDependencyObject(attribs[Attributes::Table], table_type, true, auto_resolve_deps, false); + attribs[Attributes::TriggerFunc]=getDependencyObject(attribs[Attributes::TriggerFunc], ObjectType::Function, true, true); + attribs[Attributes::Arguments]=Catalog::parseArrayValues(attribs[Attributes::Arguments].remove(QString(",\"\""))).join(','); - loadObjectXML(OBJ_TRIGGER, attribs); + loadObjectXML(ObjectType::Trigger, attribs); dbmodel->createTrigger(); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } -QStringList DatabaseImportHelper::parseIndexExpressions(const QString &expr) -{ - int open_paren = 0, close_paren = 0, pos = 0; - QStringList expressions; - QChar chr; - QString word; - bool open_apos = false; - - if(!expr.isEmpty()) - { - while(pos < expr.length()) - { - chr = expr[pos++]; - word += chr; - - if(chr == QChar('\'')) - open_apos = !open_apos; - - if(!open_apos && chr == QChar('(')) - open_paren++; - else if(!open_apos && chr == QChar(')')) - close_paren++; - - if(chr == QChar(',') || pos == expr.length()) - { - if(open_paren == close_paren) - { - if(word.endsWith(QChar(','))) - word.remove(word.length() - 1, 1); - - if(word.contains('(') && word.contains(')')) - expressions.push_back(word.trimmed()); - - word.clear(); - open_paren = close_paren = 0; - } - } - } - } - - return(expressions); -} - void DatabaseImportHelper::createIndex(attribs_map &attribs) { try @@ -1902,26 +2035,26 @@ void DatabaseImportHelper::createIndex(attribs_map &attribs) QString tab_name, coll_name, opc_name; int i; - attribs[ParsersAttributes::FACTOR]=QString("90"); - tab_name=getDependencyObject(attribs[ParsersAttributes::TABLE], OBJ_TABLE, true, auto_resolve_deps, false); - parent_tab=dynamic_cast(dbmodel->getObject(tab_name, OBJ_TABLE)); + attribs[Attributes::Factor]=QString("90"); + tab_name=getDependencyObject(attribs[Attributes::Table], ObjectType::Table, true, auto_resolve_deps, false); + parent_tab=dynamic_cast(dbmodel->getObject(tab_name, ObjectType::Table)); if(!parent_tab) { - tab_name=getDependencyObject(attribs[ParsersAttributes::TABLE], OBJ_VIEW, true, auto_resolve_deps, false); - parent_tab=dynamic_cast(dbmodel->getObject(tab_name, OBJ_VIEW)); + tab_name=getDependencyObject(attribs[Attributes::Table], ObjectType::View, true, auto_resolve_deps, false); + parent_tab=dynamic_cast(dbmodel->getObject(tab_name, ObjectType::View)); if(!parent_tab) - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) - .arg(attribs[ParsersAttributes::NAME]).arg(BaseObject::getTypeName(OBJ_INDEX)) - .arg(tab_name).arg(BaseObject::getTypeName(OBJ_TABLE)), - ERR_REF_OBJ_INEXISTS_MODEL ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(attribs[Attributes::Name]).arg(BaseObject::getTypeName(ObjectType::Index)) + .arg(tab_name).arg(BaseObject::getTypeName(ObjectType::Table)), + ErrorCode::RefObjectInexistsModel ,__PRETTY_FUNCTION__,__FILE__,__LINE__); } - cols=Catalog::parseArrayValues(attribs[ParsersAttributes::COLUMNS]); - collations=Catalog::parseArrayValues(attribs[ParsersAttributes::COLLATIONS]); - opclasses=Catalog::parseArrayValues(attribs[ParsersAttributes::OP_CLASSES]); - exprs = parseIndexExpressions(attribs[ParsersAttributes::EXPRESSIONS]); + cols=Catalog::parseArrayValues(attribs[Attributes::Columns]); + collations=Catalog::parseArrayValues(attribs[Attributes::Collations]); + opclasses=Catalog::parseArrayValues(attribs[Attributes::OpClasses]); + exprs = Catalog::parseIndexExpressions(attribs[Attributes::Expressions]); for(i=0; i < cols.size(); i++) { @@ -1929,10 +2062,10 @@ void DatabaseImportHelper::createIndex(attribs_map &attribs) if(cols[i]!=QString("0")) { - if(parent_tab->getObjectType() == OBJ_TABLE) - elem.setColumn(dynamic_cast
(parent_tab)->getColumn(getColumnName(attribs[ParsersAttributes::TABLE], cols[i]))); + if(parent_tab->getObjectType() == ObjectType::Table) + elem.setColumn(dynamic_cast
(parent_tab)->getColumn(getColumnName(attribs[Attributes::Table], cols[i]))); else - elem.setExpression(getColumnName(attribs[ParsersAttributes::TABLE], cols[i])); + elem.setExpression(getColumnName(attribs[Attributes::Table], cols[i])); } else if(!exprs.isEmpty()) { @@ -1942,8 +2075,8 @@ void DatabaseImportHelper::createIndex(attribs_map &attribs) if(i < collations.size() && collations[i]!=QString("0")) { - coll_name=getDependencyObject(collations[i], OBJ_COLLATION, false, true, false); - coll=dynamic_cast(dbmodel->getObject(coll_name, OBJ_COLLATION)); + coll_name=getDependencyObject(collations[i], ObjectType::Collation, false, true, false); + coll=dynamic_cast(dbmodel->getObject(coll_name, ObjectType::Collation)); //Even if the collation exists we'll ignore it when it is the "pg_catalog.default" if(coll && (!coll->isSystemObject() || @@ -1953,24 +2086,24 @@ void DatabaseImportHelper::createIndex(attribs_map &attribs) if(i < opclasses.size() && opclasses[i]!=QString("0")) { - opc_name=getDependencyObject(opclasses[i], OBJ_OPCLASS, true, true, false); - opclass=dynamic_cast(dbmodel->getObject(opc_name, OBJ_OPCLASS)); + opc_name=getDependencyObject(opclasses[i], ObjectType::OpClass, true, true, false); + opclass=dynamic_cast(dbmodel->getObject(opc_name, ObjectType::OpClass)); if(opclass) elem.setOperatorClass(opclass); } if(elem.getColumn() || !elem.getExpression().isEmpty()) - attribs[ParsersAttributes::ELEMENTS]+=elem.getCodeDefinition(SchemaParser::XML_DEFINITION); + attribs[Attributes::Elements]+=elem.getCodeDefinition(SchemaParser::XmlDefinition); } - attribs[ParsersAttributes::TABLE]=tab_name; - loadObjectXML(OBJ_INDEX, attribs); + attribs[Attributes::Table]=tab_name; + loadObjectXML(ObjectType::Index, attribs); dbmodel->createIndex(); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -1981,26 +2114,26 @@ void DatabaseImportHelper::createConstraint(attribs_map &attribs) try { - QString table_oid=attribs[ParsersAttributes::TABLE], - ref_tab_oid=attribs[ParsersAttributes::REF_TABLE], + QString table_oid=attribs[Attributes::Table], + ref_tab_oid=attribs[Attributes::RefTable], tab_name; Table *table=nullptr; //If the table oid is 0 indicates that the constraint is part of a data type like domains if(!table_oid.isEmpty() && table_oid!=QString("0")) { - QStringList factor=Catalog::parseArrayValues(attribs[ParsersAttributes::FACTOR]); + QStringList factor=Catalog::parseArrayValues(attribs[Attributes::Factor]); //Retrieving the table is it was not imported yet and auto_resolve_deps is true - tab_name=getDependencyObject(table_oid, OBJ_TABLE, true, auto_resolve_deps, false); + tab_name=getDependencyObject(table_oid, ObjectType::Table, true, auto_resolve_deps, false); if(!factor.isEmpty() && factor[0].startsWith(QString("fillfactor="))) - attribs[ParsersAttributes::FACTOR]=factor[0].remove(QString("fillfactor=")); + attribs[Attributes::Factor]=factor[0].remove(QString("fillfactor=")); - attribs[attribs[ParsersAttributes::TYPE]]=ParsersAttributes::_TRUE_; - table=dynamic_cast
(dbmodel->getObject(tab_name, OBJ_TABLE)); + attribs[attribs[Attributes::Type]]=Attributes::True; + table=dynamic_cast
(dbmodel->getObject(tab_name, ObjectType::Table)); - if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::EX_CONSTR) + if(attribs[Attributes::Type]==Attributes::ExConstr) { QStringList cols, opclasses, opers, exprs; ExcludeElement elem; @@ -2008,12 +2141,12 @@ void DatabaseImportHelper::createConstraint(attribs_map &attribs) OperatorClass *opclass=nullptr; Operator *oper=nullptr; - attribs[ParsersAttributes::SRC_COLUMNS]=QString(); - attribs[ParsersAttributes::EXPRESSION]=attribs[ParsersAttributes::CONDITION]; + attribs[Attributes::SrcColumns]=QString(); + attribs[Attributes::Expression]=attribs[Attributes::Condition]; - cols=Catalog::parseArrayValues(attribs[ParsersAttributes::COLUMNS]); - opers=Catalog::parseArrayValues(attribs[ParsersAttributes::OPERATORS]); - opclasses=Catalog::parseArrayValues(attribs[ParsersAttributes::OP_CLASSES]); + cols=Catalog::parseArrayValues(attribs[Attributes::Columns]); + opers=Catalog::parseArrayValues(attribs[Attributes::Operators]); + opclasses=Catalog::parseArrayValues(attribs[Attributes::OpClasses]); /* Due to the way exclude constraints are constructed (similar to indexes), * we get the constraint's definition in for of expressions. Internally we use pg_get_constraintdef. @@ -2021,8 +2154,8 @@ void DatabaseImportHelper::createConstraint(attribs_map &attribs) * which we work to separate column only references from complex expression. Only complex expression will be used * and assigned to their exclude constraint elements. Column references are used in exclude elements but relying in * the cols list above */ - exprs=attribs[ParsersAttributes::EXPRESSIONS] - .replace(QString("EXCLUDE USING %1 (").arg(attribs[ParsersAttributes::INDEX_TYPE]), QString()) + exprs=attribs[Attributes::Expressions] + .replace(QString("EXCLUDE USING %1 (").arg(attribs[Attributes::IndexType]), QString()) .split(QRegExp("(WITH )(\\+|\\-|\\*|\\/|\\<|\\>|\\=|\\~|\\!|\\@|\\#|\\%|\\^|\\&|\\||\\'|\\?)+((,)?|(\\))?)"), QString::SkipEmptyParts); @@ -2039,8 +2172,8 @@ void DatabaseImportHelper::createConstraint(attribs_map &attribs) if(i < opclasses.size() && opclasses[i]!=QString("0")) { - opc_name=getDependencyObject(opclasses[i], OBJ_OPCLASS, true, true, false); - opclass=dynamic_cast(dbmodel->getObject(opc_name, OBJ_OPCLASS)); + opc_name=getDependencyObject(opclasses[i], ObjectType::OpClass, true, true, false); + opclass=dynamic_cast(dbmodel->getObject(opc_name, ObjectType::OpClass)); if(opclass) elem.setOperatorClass(opclass); @@ -2048,33 +2181,33 @@ void DatabaseImportHelper::createConstraint(attribs_map &attribs) if(i < opers.size() && opers[i]!=QString("0")) { - op_name=getDependencyObject(opers[i], OBJ_OPERATOR, true, true, false); - oper=dynamic_cast(dbmodel->getObject(op_name, OBJ_OPERATOR)); + op_name=getDependencyObject(opers[i], ObjectType::Operator, true, true, false); + oper=dynamic_cast(dbmodel->getObject(op_name, ObjectType::Operator)); if(oper) elem.setOperator(oper); } - attribs[ParsersAttributes::ELEMENTS]+=elem.getCodeDefinition(SchemaParser::XML_DEFINITION); + attribs[Attributes::Elements]+=elem.getCodeDefinition(SchemaParser::XmlDefinition); } } else { //Clears the tablespace attribute when the constraint is fk avoiding errors - if(attribs[ParsersAttributes::TYPE]==ParsersAttributes::FK_CONSTR) - attribs[ParsersAttributes::TABLESPACE]=QString(); + if(attribs[Attributes::Type]==Attributes::FkConstr) + attribs[Attributes::Tablespace]=QString(); - attribs[ParsersAttributes::SRC_COLUMNS]=getColumnNames(attribs[ParsersAttributes::TABLE], attribs[ParsersAttributes::SRC_COLUMNS]).join(','); + attribs[Attributes::SrcColumns]=getColumnNames(attribs[Attributes::Table], attribs[Attributes::SrcColumns]).join(','); } - attribs[ParsersAttributes::REF_TABLE]=getDependencyObject(ref_tab_oid, OBJ_TABLE, false, true, false); - attribs[ParsersAttributes::DST_COLUMNS]=getColumnNames(ref_tab_oid, attribs[ParsersAttributes::DST_COLUMNS]).join(','); - attribs[ParsersAttributes::TABLE]=tab_name; + attribs[Attributes::RefTable]=getDependencyObject(ref_tab_oid, ObjectType::Table, false, true, false); + attribs[Attributes::DstColumns]=getColumnNames(ref_tab_oid, attribs[Attributes::DstColumns]).join(','); + attribs[Attributes::Table]=tab_name; - loadObjectXML(OBJ_CONSTRAINT, attribs); + loadObjectXML(ObjectType::Constraint, attribs); constr=dbmodel->createConstraint(nullptr); - if(table && constr->getConstraintType()==ConstraintType::primary_key) + if(table && constr->getConstraintType()==ConstraintType::PrimaryKey) { table->addConstraint(constr); table->setModified(true); @@ -2083,7 +2216,7 @@ void DatabaseImportHelper::createConstraint(attribs_map &attribs) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -2092,14 +2225,14 @@ void DatabaseImportHelper::createPolicy(attribs_map &attribs) { try { - attribs[ParsersAttributes::TABLE]=getDependencyObject(attribs[ParsersAttributes::TABLE], OBJ_TABLE, true, auto_resolve_deps, false); - attribs[ParsersAttributes::ROLES]=getObjectNames(attribs[ParsersAttributes::ROLES]).join(','); - loadObjectXML(OBJ_POLICY, attribs); + attribs[Attributes::Table]=getDependencyObject(attribs[Attributes::Table], ObjectType::Table, true, auto_resolve_deps, false); + attribs[Attributes::Roles]=getObjectNames(attribs[Attributes::Roles]).join(','); + loadObjectXML(ObjectType::Policy, attribs); dbmodel->createPolicy(); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -2108,30 +2241,97 @@ void DatabaseImportHelper::createEventTrigger(attribs_map &attribs) { try { - attribs[ParsersAttributes::FUNCTION]=getDependencyObject(attribs[ParsersAttributes::FUNCTION], OBJ_FUNCTION, true, true); - attribs[ParsersAttributes::FILTER]=QString("\t<%1 %2=\"%3\" %4=\"%5\"/>\n") - .arg(ParsersAttributes::FILTER) - .arg(ParsersAttributes::VARIABLE).arg(ParsersAttributes::TAG.toUpper()) - .arg(ParsersAttributes::VALUES) - .arg(Catalog::parseArrayValues(attribs[ParsersAttributes::VALUES].remove('"')).join(',')); + attribs[Attributes::Function]=getDependencyObject(attribs[Attributes::Function], ObjectType::Function, true, true); + attribs[Attributes::Filter]=QString("\t<%1 %2=\"%3\" %4=\"%5\"/>\n") + .arg(Attributes::Filter) + .arg(Attributes::Variable).arg(Attributes::Tag.toUpper()) + .arg(Attributes::Values) + .arg(Catalog::parseArrayValues(attribs[Attributes::Values].remove('"')).join(',')); - loadObjectXML(OBJ_EVENT_TRIGGER, attribs); + loadObjectXML(ObjectType::EventTrigger, attribs); dbmodel->addEventTrigger(dbmodel->createEventTrigger()); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } +void DatabaseImportHelper::createForeignDataWrapper(attribs_map &attribs) +{ + ForeignDataWrapper *fdw=nullptr; + + try + { + QStringList func_types={ Attributes::ValidatorFunc, Attributes::HandlerFunc }; + + for(auto &func_tp : func_types) + attribs[func_tp] = getDependencyObject(attribs[func_tp], ObjectType::Function, true , true, true, {{Attributes::RefType, func_tp}}); + + attribs[Attributes::Options] = Catalog::parseArrayValues(attribs[Attributes::Options]).join(ForeignDataWrapper::OptionsSeparator); + + loadObjectXML(ObjectType::ForeignDataWrapper, attribs); + fdw = dbmodel->createForeignDataWrapper(); + dbmodel->addForeignDataWrapper(fdw); + } + catch(Exception &e) + { + if(fdw) delete(fdw); + throw Exception(e.getErrorMessage(), e.getErrorCode(), + __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); + } +} + +void DatabaseImportHelper::createForeignServer(attribs_map &attribs) +{ + ForeignServer *server=nullptr; + + try + { + attribs[Attributes::Fdw] = getDependencyObject(attribs[Attributes::Fdw], ObjectType::ForeignDataWrapper, true , true, true); + attribs[Attributes::Options] = Catalog::parseArrayValues(attribs[Attributes::Options]).join(ForeignDataWrapper::OptionsSeparator); + + loadObjectXML(ObjectType::ForeignServer, attribs); + server = dbmodel->createForeignServer(); + dbmodel->addForeignServer(server); + } + catch(Exception &e) + { + if(server) delete(server); + throw Exception(e.getErrorMessage(), e.getErrorCode(), + __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); + } +} + +void DatabaseImportHelper::createUserMapping(attribs_map &attribs) +{ + UserMapping *usr_map=nullptr; + + try + { + attribs[Attributes::Server] = getDependencyObject(attribs[Attributes::Server], ObjectType::ForeignServer, true , true, true); + attribs[Attributes::Options] = Catalog::parseArrayValues(attribs[Attributes::Options]).join(ForeignDataWrapper::OptionsSeparator); + + loadObjectXML(ObjectType::UserMapping, attribs); + usr_map = dbmodel->createUserMapping(); + dbmodel->addUserMapping(usr_map); + } + catch(Exception &e) + { + if(usr_map) delete(usr_map); + throw Exception(e.getErrorMessage(), e.getErrorCode(), + __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); + } +} + void DatabaseImportHelper::createPermission(attribs_map &attribs) { - ObjectType obj_type=static_cast(attribs[ParsersAttributes::OBJECT_TYPE].toUInt()); + ObjectType obj_type=static_cast(attribs[Attributes::ObjectType].toUInt()); Permission *perm=nullptr; QString sig; - if(Permission::objectAcceptsPermission(obj_type)) + if(Permission::acceptsPermission(obj_type)) { QStringList perm_list; vector privs, gop_privs; @@ -2141,25 +2341,25 @@ void DatabaseImportHelper::createPermission(attribs_map &attribs) Table *table=nullptr; //Parses the permissions vector string - perm_list=Catalog::parseArrayValues(attribs[ParsersAttributes::PERMISSION]); + perm_list=Catalog::parseArrayValues(attribs[Attributes::Permission]); if(!perm_list.isEmpty()) { - if(obj_type!=OBJ_COLUMN) + if(obj_type!=ObjectType::Column) { - if(obj_type==OBJ_DATABASE) + if(obj_type==ObjectType::Database) object=dbmodel; else { - sig=getObjectName(attribs[ParsersAttributes::OID], true); - object=dbmodel->getObject(getObjectName(attribs[ParsersAttributes::OID], true), obj_type); + sig=getObjectName(attribs[Attributes::Oid], true); + object=dbmodel->getObject(getObjectName(attribs[Attributes::Oid], true), obj_type); } } else { //If the object is column it's necessary to retrive the parent table to get the valid reference to column - table=dynamic_cast
(dbmodel->getObject(getObjectName(attribs[ParsersAttributes::TABLE]), OBJ_TABLE)); - object=table->getObject(getColumnName(attribs[ParsersAttributes::TABLE], attribs[ParsersAttributes::OID]), OBJ_COLUMN); + table=dynamic_cast
(dbmodel->getObject(getObjectName(attribs[Attributes::Table]), ObjectType::Table)); + object=table->getObject(getColumnName(attribs[Attributes::Table], attribs[Attributes::Oid]), ObjectType::Column); } } @@ -2173,21 +2373,21 @@ void DatabaseImportHelper::createPermission(attribs_map &attribs) if(!privs.empty() || gop_privs.empty()) { - role=dynamic_cast(dbmodel->getObject(role_name, OBJ_ROLE)); + role=dynamic_cast(dbmodel->getObject(role_name, ObjectType::Role)); if(auto_resolve_deps && !role_name.isEmpty() && !role) { - QString oid = catalog.getObjectOID(role_name, OBJ_ROLE); - getDependencyObject(oid, OBJ_ROLE); - role=dynamic_cast(dbmodel->getObject(role_name, OBJ_ROLE)); + QString oid = catalog.getObjectOID(role_name, ObjectType::Role); + getDependencyObject(oid, ObjectType::Role); + role=dynamic_cast(dbmodel->getObject(role_name, ObjectType::Role)); } /* If the role doesn't exists and there is a name defined, throws an error because the roles wasn't found on the model */ if(!role && !role_name.isEmpty()) - throw Exception(Exception::getErrorMessage(ERR_REF_OBJ_INEXISTS_MODEL) - .arg(QString("permission_%1").arg(perm_list[i])).arg(BaseObject::getTypeName(OBJ_PERMISSION)) - .arg(role_name).arg(BaseObject::getTypeName(OBJ_ROLE)) + throw Exception(Exception::getErrorMessage(ErrorCode::RefObjectInexistsModel) + .arg(QString("permission_%1").arg(perm_list[i])).arg(BaseObject::getTypeName(ObjectType::Permission)) + .arg(role_name).arg(BaseObject::getTypeName(ObjectType::Role)) ,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { @@ -2220,9 +2420,9 @@ void DatabaseImportHelper::createPermission(attribs_map &attribs) if(perm) delete(perm); if(ignore_errors) - errors.push_back(Exception(e.getErrorMessage(), e.getErrorType(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, dumpObjectAttributes(attribs))); + errors.push_back(Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, dumpObjectAttributes(attribs))); else - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } } @@ -2233,13 +2433,13 @@ void DatabaseImportHelper::createPermission(attribs_map &attribs) void DatabaseImportHelper::createTableInheritances(void) { //Creating table inheiritances - if(dbmodel->getObjectCount(OBJ_TABLE) > 0 && !import_canceled) + if(dbmodel->getObjectCount(ObjectType::Table) > 0 && !import_canceled) { try { emit s_progressUpdated(90, trUtf8("Creating table inheritances..."), - OBJ_RELATIONSHIP); + ObjectType::Relationship); __createTableInheritances(); } catch(Exception &e) @@ -2247,9 +2447,51 @@ void DatabaseImportHelper::createTableInheritances(void) if(ignore_errors) errors.push_back(e); else - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } + } +} + +void DatabaseImportHelper::createTablePartitionings(void) +{ + if(imported_tables.empty()) + return; + + try + { + Table *table = nullptr, *part_table = nullptr; + QString part_bound_expr; + Relationship *rel_part = nullptr; + + emit s_progressUpdated(95, + trUtf8("Creating table partitionings..."), + ObjectType::Relationship); + + // Creating the paritioning relationships + for(auto &itr : imported_tables) + { + table = itr.second; + + if(table->isPartition()) + { + part_bound_expr = table->getPartitionBoundingExpr(); + part_table = table->getPartitionedTable(); + + /* Here, we force the detaching of the partition table so when + * creating the relationship below all the needed validations can be done correctly */ + table->setPartionedTable(nullptr); + table->setPartitionBoundingExpr(QString()); + + rel_part = new Relationship(BaseRelationship::RelationshipPart, table, part_table); + rel_part->setPartitionBoundingExpr(part_bound_expr); + dbmodel->addRelationship(rel_part); + } } } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } } void DatabaseImportHelper::destroyDetachedColumns(void) @@ -2264,7 +2506,7 @@ void DatabaseImportHelper::destroyDetachedColumns(void) emit s_progressUpdated(100, trUtf8("Destroying unused detached columns..."), - OBJ_COLUMN); + ObjectType::Column); //Destroying detached columns before create inheritances for(Column *col : inherited_cols) @@ -2285,7 +2527,7 @@ void DatabaseImportHelper::destroyDetachedColumns(void) if(ignore_errors) errors.push_back(e); else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } } @@ -2301,13 +2543,13 @@ void DatabaseImportHelper::assignSequencesToColumns(void) Column *col=nullptr; emit s_progressUpdated(100, trUtf8("Assigning sequences to columns..."), - OBJ_SEQUENCE); + ObjectType::Sequence); - for(auto &object : *dbmodel->getObjectList(OBJ_TABLE)) + for(auto &object : *dbmodel->getObjectList(ObjectType::Table)) { table=dynamic_cast
(object); - for(auto &tab_obj : *table->getObjectList(OBJ_COLUMN)) + for(auto &tab_obj : *table->getObjectList(ObjectType::Column)) { col=dynamic_cast(tab_obj); @@ -2350,43 +2592,44 @@ void DatabaseImportHelper::__createTableInheritances(void) QStringList inh_list; unsigned oid; - itr=object_oids[OBJ_TABLE].begin(); - itr_end=object_oids[OBJ_TABLE].end(); + itr=object_oids[ObjectType::Table].begin(); + itr_end=object_oids[ObjectType::Table].end(); while(itr!=itr_end) { //Get the list of parent table's oids oid=(*itr); - inh_list=Catalog::parseArrayValues(user_objs[oid][ParsersAttributes::PARENTS]); + inh_list=Catalog::parseArrayValues(user_objs[oid][Attributes::Parents]); itr++; if(!inh_list.isEmpty()) { //Get the child table resolving it's name from the oid - child_tab=dynamic_cast
(dbmodel->getObject(getObjectName(user_objs[oid][ParsersAttributes::OID]), OBJ_TABLE)); + child_tab=dynamic_cast
(dbmodel->getObject(getObjectName(user_objs[oid][Attributes::Oid]), ObjectType::Table)); while(!inh_list.isEmpty()) { //Get the parent table resolving it's name from the oid - parent_tab=dynamic_cast
(dbmodel->getObject(getObjectName(inh_list.front()), OBJ_TABLE)); + parent_tab=dynamic_cast
(dbmodel->getObject(getObjectName(inh_list.front()), ObjectType::Table)); try { if(!parent_tab && auto_resolve_deps) { - getDependencyObject(inh_list.front(), OBJ_TABLE); - parent_tab=dynamic_cast
(dbmodel->getObject(getObjectName(inh_list.front()), OBJ_TABLE)); + getDependencyObject(inh_list.front(), ObjectType::Table); + parent_tab=dynamic_cast
(dbmodel->getObject(getObjectName(inh_list.front()), ObjectType::Table)); } if(!parent_tab) - throw Exception(Exception::getErrorMessage(ERR_INV_INH_PARENT_TAB_NOT_FOUND).arg(child_tab->getSignature()).arg(inh_list.front()), - ERR_INV_INH_PARENT_TAB_NOT_FOUND,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::InvInheritParentTableNotFound) + .arg(child_tab->getSignature()).arg(inh_list.front()), + ErrorCode::InvInheritParentTableNotFound,__PRETTY_FUNCTION__,__FILE__,__LINE__); inh_list.pop_front(); //Create the inheritance relationship - rel=new Relationship(Relationship::RELATIONSHIP_GEN, child_tab, parent_tab); - rel->setName(PgModelerNS::generateUniqueName(rel, (*dbmodel->getObjectList(OBJ_RELATIONSHIP)))); + rel=new Relationship(Relationship::RelationshipGen, child_tab, parent_tab); + rel->setName(PgModelerNs::generateUniqueName(rel, (*dbmodel->getObjectList(ObjectType::Relationship)))); dbmodel->addRelationship(rel); rel=nullptr; @@ -2398,7 +2641,7 @@ void DatabaseImportHelper::__createTableInheritances(void) if(ignore_errors) errors.push_back(e); else - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } } @@ -2409,13 +2652,15 @@ void DatabaseImportHelper::configureDatabase(attribs_map &attribs) { try { - attribs[ParsersAttributes::APPEND_AT_EOD]=QString(); - loadObjectXML(OBJ_DATABASE, attribs); + attribs[Attributes::AppendAtEod]=QString(); + attribs[Attributes::Layers]=QString(); + attribs[Attributes::ActiveLayers]=QString(); + loadObjectXML(ObjectType::Database, attribs); dbmodel->configureDatabase(attribs); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(), + throw Exception(e.getErrorMessage(), e.getErrorCode(), __PRETTY_FUNCTION__,__FILE__,__LINE__, &e, xmlparser->getXMLBuffer()); } } @@ -2441,25 +2686,25 @@ QString DatabaseImportHelper::getObjectName(const QString &oid, bool signature_f else { QString sch_name, - obj_name=obj_attr[ParsersAttributes::NAME]; - ObjectType obj_type=static_cast(obj_attr[ParsersAttributes::OBJECT_TYPE].toUInt()); + obj_name=obj_attr[Attributes::Name]; + ObjectType obj_type=static_cast(obj_attr[Attributes::ObjectType].toUInt()); //If the object accepts an schema retrieve the schema name too if(BaseObject::acceptsSchema(obj_type)) - sch_name=getObjectName(obj_attr[ParsersAttributes::SCHEMA]); + sch_name=getObjectName(obj_attr[Attributes::Schema]); if(!sch_name.isEmpty()) obj_name.prepend(sch_name + QString(".")); //Formatting the name in form of signature (only for functions and operators) - if(signature_form && (obj_type==OBJ_FUNCTION || obj_type==OBJ_OPERATOR || obj_type==OBJ_AGGREGATE || obj_type==OBJ_OPFAMILY || obj_type==OBJ_OPCLASS)) + if(signature_form && (obj_type==ObjectType::Function || obj_type==ObjectType::Operator || obj_type==ObjectType::Aggregate || obj_type==ObjectType::OpFamily || obj_type==ObjectType::OpClass)) { QStringList params; - if(obj_type==OBJ_FUNCTION) + if(obj_type==ObjectType::Function) { - QStringList arg_types=getTypes(obj_attr[ParsersAttributes::ARG_TYPES], false), - arg_modes=Catalog::parseArrayValues(obj_attr[ParsersAttributes::ARG_MODES]); + QStringList arg_types=getTypes(obj_attr[Attributes::ArgTypes], false), + arg_modes=Catalog::parseArrayValues(obj_attr[Attributes::ArgModes]); for(int i=0; i < arg_types.size(); i++) { @@ -2476,31 +2721,31 @@ QString DatabaseImportHelper::getObjectName(const QString &oid, bool signature_f } } } - else if(obj_type==OBJ_AGGREGATE) + else if(obj_type==ObjectType::Aggregate) { - QStringList params=getTypes(obj_attr[ParsersAttributes::TYPES], false); + QStringList params=getTypes(obj_attr[Attributes::Types], false); if(params.isEmpty()) params.push_back(QString("*")); } - else if(obj_type==OBJ_OPERATOR) + else if(obj_type==ObjectType::Operator) { - if(obj_attr[ParsersAttributes::LEFT_TYPE].toUInt() > 0) - params.push_back(getType(obj_attr[ParsersAttributes::LEFT_TYPE], false)); + if(obj_attr[Attributes::LeftType].toUInt() > 0) + params.push_back(getType(obj_attr[Attributes::LeftType], false)); else params.push_back(QString("NONE")); - if(obj_attr[ParsersAttributes::RIGHT_TYPE].toUInt() > 0) - params.push_back(getType(obj_attr[ParsersAttributes::RIGHT_TYPE], false)); + if(obj_attr[Attributes::RightType].toUInt() > 0) + params.push_back(getType(obj_attr[Attributes::RightType], false)); else params.push_back(QString("NONE")); } else { - obj_name += QString(" USING %1").arg(obj_attr[ParsersAttributes::INDEX_TYPE]); + obj_name += QString(" USING %1").arg(obj_attr[Attributes::IndexType]); } - if(obj_type != OBJ_OPFAMILY && obj_type != OBJ_OPCLASS) + if(obj_type != ObjectType::OpFamily && obj_type != ObjectType::OpClass) obj_name+=QString("(") + params.join(',') + QString(")"); } @@ -2532,7 +2777,7 @@ QString DatabaseImportHelper::getColumnName(const QString &tab_oid_str, const QS if(prepend_tab_name) col_name=getObjectName(tab_oid_str) + QString("."); - col_name+=columns[tab_oid][col_id].at(ParsersAttributes::NAME); + col_name+=columns[tab_oid][col_id].at(Attributes::Name); } return(col_name); @@ -2556,7 +2801,7 @@ QStringList DatabaseImportHelper::getColumnNames(const QString &tab_oid_str, con col_id=col_ids[i].toUInt(); if(columns[tab_oid].count(col_id)) - col_names.push_back(tab_name + columns[tab_oid][col_id].at(ParsersAttributes::NAME)); + col_names.push_back(tab_name + columns[tab_oid][col_id].at(Attributes::Name)); } } @@ -2570,7 +2815,7 @@ QString DatabaseImportHelper::getType(const QString &oid_str, bool generate_xml, attribs_map type_attr; QString xml_def, sch_name, obj_name, aux_name; unsigned type_oid=oid_str.toUInt(), elem_tp_oid = 0, - dimension=0, object_id=type_attr[ParsersAttributes::OBJECT_ID].toUInt(); + dimension=0, object_id=type_attr[Attributes::ObjectId].toUInt(); bool is_derivated_from_obj = false; if(type_oid > 0) @@ -2579,39 +2824,39 @@ QString DatabaseImportHelper::getType(const QString &oid_str, bool generate_xml, type_attr=types[type_oid]; //Special treatment for array types. Removes the [] descriptor when generating XML code for the type - if(!type_attr.empty() && type_attr[ParsersAttributes::CATEGORY]==QString("A") && - type_attr[ParsersAttributes::NAME].contains(QString("[]"))) + if(!type_attr.empty() && type_attr[Attributes::Category]==QString("A") && + type_attr[Attributes::Name].contains(QString("[]"))) { - obj_name=type_attr[ParsersAttributes::NAME]; - elem_tp_oid=type_attr[ParsersAttributes::ELEMENT].toUInt(); + obj_name=type_attr[Attributes::Name]; + elem_tp_oid=type_attr[Attributes::Element].toUInt(); if(generate_xml) { - dimension=type_attr[ParsersAttributes::NAME].count(QString("[]")); + dimension=type_attr[Attributes::Name].count(QString("[]")); obj_name.remove(QString("[]")); } } else - obj_name=type_attr[ParsersAttributes::NAME]; + obj_name=type_attr[Attributes::Name]; /* If the type was generated from a table/sequence/view/domain and the source object is not yet imported and the auto resolve deps is enabled, we need to import it */ - if(!type_attr[ParsersAttributes::TYPE_CLASS].isEmpty() && auto_resolve_deps && + if(!type_attr[Attributes::TypeClass].isEmpty() && auto_resolve_deps && (!user_objs.count(object_id) && !system_objs.count(object_id))) { ObjectType obj_type; - if(type_attr[ParsersAttributes::TYPE_CLASS]==BaseObject::getSchemaName(OBJ_TABLE)) - obj_type=OBJ_TABLE; - else if(type_attr[ParsersAttributes::TYPE_CLASS]==BaseObject::getSchemaName(OBJ_VIEW)) - obj_type=OBJ_VIEW; - else if(type_attr[ParsersAttributes::TYPE_CLASS]==BaseObject::getSchemaName(OBJ_DOMAIN)) - obj_type=OBJ_DOMAIN; + if(type_attr[Attributes::TypeClass]==BaseObject::getSchemaName(ObjectType::Table)) + obj_type=ObjectType::Table; + else if(type_attr[Attributes::TypeClass]==BaseObject::getSchemaName(ObjectType::View)) + obj_type=ObjectType::View; + else if(type_attr[Attributes::TypeClass]==BaseObject::getSchemaName(ObjectType::Domain)) + obj_type=ObjectType::Domain; else - obj_type=OBJ_SEQUENCE; + obj_type=ObjectType::Sequence; is_derivated_from_obj = true; - getDependencyObject(type_attr[ParsersAttributes::OBJECT_ID], obj_type, true, true, false); + getDependencyObject(type_attr[Attributes::ObjectId], obj_type, true, true, false); } /* Removing the optional modifier "without time zone" from date/time types. @@ -2622,7 +2867,7 @@ QString DatabaseImportHelper::getType(const QString &oid_str, bool generate_xml, /* Prepend the schema name only if it is not a system schema ('pg_catalog' or 'information_schema') and if the schema's names is already present in the type's name (in case of table types) */ - sch_name=getObjectName(type_attr[ParsersAttributes::SCHEMA]); + sch_name=getObjectName(type_attr[Attributes::Schema]); if(!sch_name.isEmpty() && ((sch_name!=QString("pg_catalog") && sch_name!=QString("information_schema")) || type_oid > catalog.getLastSysObjectOID()) && @@ -2637,7 +2882,7 @@ QString DatabaseImportHelper::getType(const QString &oid_str, bool generate_xml, type_oid > catalog.getLastSysObjectOID() && !dbmodel->getType(aux_name)) { //If the type is not an array one we simply use the current type attributes map - if(type_attr[ParsersAttributes::CATEGORY] != QString("A")) + if(type_attr[Attributes::Category] != QString("A")) createObject(type_attr); /* In case the type is an array one we should use the oid held by "element" attribute to create the type related to current one */ @@ -2647,11 +2892,11 @@ QString DatabaseImportHelper::getType(const QString &oid_str, bool generate_xml, if(generate_xml) { - extra_attribs[ParsersAttributes::NAME]=obj_name; - extra_attribs[ParsersAttributes::DIMENSION]=(dimension > 0 ? QString::number(dimension) : QString()); + extra_attribs[Attributes::Name]=obj_name; + extra_attribs[Attributes::Dimension]=(dimension > 0 ? QString::number(dimension) : QString()); schparser.ignoreUnkownAttributes(true); - xml_def=schparser.getCodeDefinition(ParsersAttributes::PGSQL_BASE_TYPE, extra_attribs, SchemaParser::XML_DEFINITION); + xml_def=schparser.getCodeDefinition(Attributes::PgSqlBaseType, extra_attribs, SchemaParser::XmlDefinition); schparser.ignoreUnkownAttributes(false); } else @@ -2662,7 +2907,7 @@ QString DatabaseImportHelper::getType(const QString &oid_str, bool generate_xml, } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/databaseimporthelper.h b/libpgmodeler_ui/src/databaseimporthelper.h index 9288430758..00b5ef6eec 100644 --- a/libpgmodeler_ui/src/databaseimporthelper.h +++ b/libpgmodeler_ui/src/databaseimporthelper.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -38,7 +38,7 @@ class DatabaseImportHelper: public QObject { //! \brief Random number generator engine used to generate random colors for imported schemas default_random_engine rand_num_engine; - static const QString UNKNOWN_OBJECT_OID_XML; + static const QString UnkownObjectOidXml; /*! \brief File handle to log the import process. This file is opened for writing only when the 'ignore_errors' is true */ @@ -125,8 +125,11 @@ class DatabaseImportHelper: public QObject { //! \brief Reference for the database model instance of the model widget DatabaseModel *dbmodel; - - XMLParser *xmlparser; + + //! \brief Stored the table created (value) from the oid (key) so the partitioning hierarchy (if existent) can be reconstructed + map imported_tables; + + XmlParser *xmlparser; SchemaParser schparser; @@ -157,10 +160,14 @@ class DatabaseImportHelper: public QObject { void createPolicy(attribs_map &attribs); void createPermission(attribs_map &attribs); void createEventTrigger(attribs_map &attribs); + void createForeignDataWrapper(attribs_map &attribs); + void createForeignServer(attribs_map &attribs); + void createUserMapping(attribs_map &attribs); void __createTableInheritances(void); void createTableInheritances(void); + void createTablePartitionings(void); void destroyDetachedColumns(void); - + //! \brief Tries to assign imported sequences that are related to nextval() calls used in columns default values void assignSequencesToColumns(void); @@ -204,13 +211,9 @@ class DatabaseImportHelper: public QObject { //! \brief Return a string containing all attributes and their values in a formatted way QString dumpObjectAttributes(attribs_map &attribs); - - /*! \brief Parse a set of expressions related to an index returned by the pg_get_expr(oid) and separates - * them as a string list. */ - QStringList parseIndexExpressions(const QString &expr); public: - DatabaseImportHelper(QObject *parent=0); + DatabaseImportHelper(QObject *parent = nullptr); //! \brief Set the connection used to access the PostgreSQL server void setConnection(Connection &conn); @@ -268,7 +271,7 @@ class DatabaseImportHelper: public QObject { signals: //! \brief This singal is emitted whenever the export progress changes - void s_progressUpdated(int progress, QString msg, ObjectType obj_type=BASE_OBJECT); + void s_progressUpdated(int progress, QString msg, ObjectType obj_type=ObjectType::BaseObject); //! \brief This signal is emited when the import has finished void s_importFinished(Exception e=Exception()); diff --git a/libpgmodeler_ui/src/databasewidget.cpp b/libpgmodeler_ui/src/databasewidget.cpp index 2c8fbb2ac0..bf650bc1a7 100644 --- a/libpgmodeler_ui/src/databasewidget.cpp +++ b/libpgmodeler_ui/src/databasewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "databasewidget.h" -DatabaseWidget::DatabaseWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_DATABASE) +DatabaseWidget::DatabaseWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Database) { try { @@ -27,12 +27,12 @@ DatabaseWidget::DatabaseWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_DA QGridLayout *grid=nullptr; Ui_DatabaseWidget::setupUi(this); - configureFormLayout(database_grid, OBJ_DATABASE); + configureFormLayout(database_grid, ObjectType::Database); - def_schema_sel=new ObjectSelectorWidget(OBJ_SCHEMA, true, this); - def_collation_sel=new ObjectSelectorWidget(OBJ_COLLATION, true, this); - def_owner_sel=new ObjectSelectorWidget(OBJ_ROLE, true, this); - def_tablespace_sel=new ObjectSelectorWidget(OBJ_TABLESPACE, true, this); + def_schema_sel=new ObjectSelectorWidget(ObjectType::Schema, true, this); + def_collation_sel=new ObjectSelectorWidget(ObjectType::Collation, true, this); + def_owner_sel=new ObjectSelectorWidget(ObjectType::Role, true, this); + def_tablespace_sel=new ObjectSelectorWidget(ObjectType::Tablespace, true, this); frame=generateInformationFrame(trUtf8("The fields LC_COLLATE and LC_CTYPE have pre-configured values based upon the running system. You can freely modify those values if you intend to export the model to another host.")); grid=dynamic_cast(attributes_twg->widget(0)->layout()); @@ -73,7 +73,7 @@ DatabaseWidget::DatabaseWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_DA } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -91,23 +91,23 @@ void DatabaseWidget::setAttributes(DatabaseModel *model) if(idx < 0) idx=0; encoding_cmb->setCurrentIndex(idx); - if(!model->getLocalization(Collation::_LC_COLLATE).isEmpty()) - lccollate_cmb->setCurrentText(model->getLocalization(Collation::_LC_COLLATE)); + if(!model->getLocalization(Collation::LcCollate).isEmpty()) + lccollate_cmb->setCurrentText(model->getLocalization(Collation::LcCollate)); - if(!model->getLocalization(Collation::_LC_CTYPE).isEmpty()) - lcctype_cmb->setCurrentText(model->getLocalization(Collation::_LC_CTYPE)); + if(!model->getLocalization(Collation::LcCtype).isEmpty()) + lcctype_cmb->setCurrentText(model->getLocalization(Collation::LcCtype)); def_schema_sel->setModel(model); - def_schema_sel->setSelectedObject(model->getDefaultObject(OBJ_SCHEMA)); + def_schema_sel->setSelectedObject(model->getDefaultObject(ObjectType::Schema)); def_collation_sel->setModel(model); - def_collation_sel->setSelectedObject(model->getDefaultObject(OBJ_COLLATION)); + def_collation_sel->setSelectedObject(model->getDefaultObject(ObjectType::Collation)); def_owner_sel->setModel(model); - def_owner_sel->setSelectedObject(model->getDefaultObject(OBJ_ROLE)); + def_owner_sel->setSelectedObject(model->getDefaultObject(ObjectType::Role)); def_tablespace_sel->setModel(model); - def_tablespace_sel->setSelectedObject(model->getDefaultObject(OBJ_TABLESPACE)); + def_tablespace_sel->setSelectedObject(model->getDefaultObject(ObjectType::Tablespace)); allow_conn_chk->setChecked(model->isAllowConnections()); is_template_chk->setChecked(model->isTemplate()); @@ -130,22 +130,22 @@ void DatabaseWidget::applyConfiguration(void) if(encoding_cmb->currentIndex() > 0) model->setEncoding(EncodingType(encoding_cmb->currentText())); else - model->setEncoding(EncodingType(BaseType::null)); + model->setEncoding(EncodingType(BaseType::Null)); if(lccollate_cmb->currentText()!=trUtf8("Default")) - model->setLocalization(Collation::_LC_COLLATE, lccollate_cmb->currentText()); + model->setLocalization(Collation::LcCollate, lccollate_cmb->currentText()); else - model->setLocalization(Collation::_LC_COLLATE, QString()); + model->setLocalization(Collation::LcCollate, QString()); if(lcctype_cmb->currentText()!=trUtf8("Default")) - model->setLocalization(Collation::_LC_CTYPE, lcctype_cmb->currentText()); + model->setLocalization(Collation::LcCtype, lcctype_cmb->currentText()); else - model->setLocalization(Collation::_LC_CTYPE, QString()); + model->setLocalization(Collation::LcCtype, QString()); - model->setDefaultObject(def_schema_sel->getSelectedObject(), OBJ_SCHEMA); - model->setDefaultObject(def_owner_sel->getSelectedObject(), OBJ_ROLE); - model->setDefaultObject(def_collation_sel->getSelectedObject(), OBJ_COLLATION); - model->setDefaultObject(def_tablespace_sel->getSelectedObject(), OBJ_TABLESPACE); + model->setDefaultObject(def_schema_sel->getSelectedObject(), ObjectType::Schema); + model->setDefaultObject(def_owner_sel->getSelectedObject(), ObjectType::Role); + model->setDefaultObject(def_collation_sel->getSelectedObject(), ObjectType::Collation); + model->setDefaultObject(def_tablespace_sel->getSelectedObject(), ObjectType::Tablespace); model->setIsTemplate(is_template_chk->isChecked()); model->setAllowConnections(allow_conn_chk->isChecked()); @@ -153,6 +153,6 @@ void DatabaseWidget::applyConfiguration(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/databasewidget.h b/libpgmodeler_ui/src/databasewidget.h index dbc7b1aefe..43094bf17e 100644 --- a/libpgmodeler_ui/src/databasewidget.h +++ b/libpgmodeler_ui/src/databasewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -38,7 +38,7 @@ class DatabaseWidget: public BaseObjectWidget, public Ui::DatabaseWidget { *def_tablespace_sel; public: - DatabaseWidget(QWidget * parent = 0); + DatabaseWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model); diff --git a/libpgmodeler_ui/src/datamanipulationform.cpp b/libpgmodeler_ui/src/datamanipulationform.cpp index 64ab8b381e..40b395f92b 100644 --- a/libpgmodeler_ui/src/datamanipulationform.cpp +++ b/libpgmodeler_ui/src/datamanipulationform.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -23,27 +23,42 @@ #include "plaintextitemdelegate.h" #include "baseform.h" #include "bulkdataeditwidget.h" +#include "databaseexplorerwidget.h" +#include "generalconfigwidget.h" -const QColor DataManipulationForm::ROW_COLORS[3]={ QColor(QString("#C0FFC0")), QColor(QString("#FFFFC0")), QColor(QString("#FFC0C0")) }; -const unsigned DataManipulationForm::NO_OPERATION=0; -const unsigned DataManipulationForm::OP_INSERT=1; -const unsigned DataManipulationForm::OP_UPDATE=2; -const unsigned DataManipulationForm::OP_DELETE=3; -bool DataManipulationForm::has_csv_clipboard=false; +const QColor DataManipulationForm::RowColors[3]={ QColor(QString("#C0FFC0")), QColor(QString("#FFFFC0")), QColor(QString("#FFC0C0")) }; +constexpr unsigned DataManipulationForm::NoOperation; +constexpr unsigned DataManipulationForm::OpInsert; +constexpr unsigned DataManipulationForm::OpUpdate; +constexpr unsigned DataManipulationForm::OpDelete; DataManipulationForm::DataManipulationForm(QWidget * parent, Qt::WindowFlags f): QDialog(parent, f) { QAction *act = nullptr; + QToolButton *btn = nullptr; + QFont fnt; + setupUi(this); setWindowFlags(Qt::Dialog | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint); - table_oid=0; + for(auto &obj : bnts_parent_wgt->children()) + { + btn = dynamic_cast(obj); + if(!btn) continue; + + fnt = btn->font(); + fnt.setBold(true); + btn->setFont(fnt); + PgModelerUiNs::createDropShadow(btn); + PgModelerUiNs::configureWidgetFont(btn, PgModelerUiNs::SmallFontFactor); + } - PgModelerUiNS::configureWidgetFont(hint_lbl, PgModelerUiNS::MEDIUM_FONT_FACTOR); - PgModelerUiNS::configureWidgetFont(warning_lbl, PgModelerUiNS::MEDIUM_FONT_FACTOR); + table_oid=0; + PgModelerUiNs::configureWidgetFont(hint_lbl, PgModelerUiNs::MediumFontFactor); + PgModelerUiNs::configureWidgetFont(warning_lbl, PgModelerUiNs::MediumFontFactor); filter_hl=new SyntaxHighlighter(filter_txt); - filter_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + filter_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); code_compl_wgt=new CodeCompletionWidget(filter_txt); code_compl_wgt->configureCompletion(nullptr, filter_hl); @@ -53,9 +68,9 @@ DataManipulationForm::DataManipulationForm(QWidget * parent, Qt::WindowFlags f): act = copy_menu.addAction(trUtf8("Copy as CSV")); act->setShortcut(QKeySequence("Ctrl+C")); + connect(act, &QAction::triggered, [&](){ SQLExecutionWidget::copySelection(results_tbw, false, true); - has_csv_clipboard = true; paste_tb->setEnabled(true); }); @@ -63,24 +78,47 @@ DataManipulationForm::DataManipulationForm(QWidget * parent, Qt::WindowFlags f): act->setShortcut(QKeySequence("Ctrl+Shift+C")); connect(act, &QAction::triggered, [&](){ SQLExecutionWidget::copySelection(results_tbw, false, false); - has_csv_clipboard = false; paste_tb->setEnabled(true); }); + act = paste_menu.addAction(trUtf8("Paste as text")); + act->setShortcut(QKeySequence("Ctrl+V")); + connect(act, &QAction::triggered, [&](){ + loadDataFromCsv(true, false); + paste_tb->setEnabled(false); + }); + + act = paste_menu.addAction(trUtf8("Paste as CSV")); + act->setShortcut(QKeySequence("Ctrl+Shift+V")); + connect(act, &QAction::triggered, [&](){ + loadDataFromCsv(true, true); + paste_tb->setEnabled(false); + }); + + paste_tb->setMenu(&paste_menu); + truncate_tb->setMenu(&truncate_menu); + truncate_menu.addAction(QIcon(PgModelerUiNs::getIconPath("truncate")), trUtf8("Truncate"), this, SLOT(truncateTable()), QKeySequence("Ctrl+Del"))->setData(QVariant::fromValue(false)); + truncate_menu.addAction(QIcon(PgModelerUiNs::getIconPath("trunccascade")), trUtf8("Truncate cascade"), this, SLOT(truncateTable()), QKeySequence("Ctrl+Shift+Del"))->setData(QVariant::fromValue(true)); + copy_tb->setMenu(©_menu); refresh_tb->setToolTip(refresh_tb->toolTip() + QString(" (%1)").arg(refresh_tb->shortcut().toString())); save_tb->setToolTip(save_tb->toolTip() + QString(" (%1)").arg(save_tb->shortcut().toString())); - undo_tb->setToolTip(undo_tb->toolTip() + QString(" (%1)").arg(undo_tb->shortcut().toString())); + paste_tb->setToolTip(paste_tb->toolTip() + QString(" (%1)").arg(paste_tb->shortcut().toString())); export_tb->setToolTip(export_tb->toolTip() + QString(" (%1)").arg(export_tb->shortcut().toString())); - delete_tb->setToolTip(delete_tb->toolTip() + QString(" (%1)").arg(delete_tb->shortcut().toString())); + undo_tb->setToolTip(undo_tb->toolTip() + QString(" (%1)").arg(undo_tb->shortcut().toString())); add_tb->setToolTip(add_tb->toolTip() + QString(" (%1)").arg(add_tb->shortcut().toString())); + delete_tb->setToolTip(delete_tb->toolTip() + QString(" (%1)").arg(delete_tb->shortcut().toString())); + bulkedit_tb->setToolTip(bulkedit_tb->toolTip() + QString(" (%1)").arg(bulkedit_tb->shortcut().toString())); duplicate_tb->setToolTip(duplicate_tb->toolTip() + QString(" (%1)").arg(duplicate_tb->shortcut().toString())); - paste_tb->setToolTip(paste_tb->toolTip() + QString(" (%1)").arg(paste_tb->shortcut().toString())); + csv_load_tb->setToolTip(csv_load_tb->toolTip() + QString(" (%1)").arg(csv_load_tb->shortcut().toString())); + filter_tb->setToolTip(filter_tb->toolTip() + QString(" (%1)").arg(filter_tb->shortcut().toString())); + new_window_tb->setToolTip(new_window_tb->toolTip() + QString(" (%1)").arg(new_window_tb->shortcut().toString())); + clear_tb->setToolTip(clear_tb->toolTip() + QString(" (%1)").arg(clear_tb->shortcut().toString())); result_info_wgt->setVisible(false); //Forcing the splitter that handles the bottom widgets to resize its children to their minimum size h_splitter->setSizes({500, 250, 500}); - v_splitter->setVisible(false); + filter_tbw->setVisible(false); csv_load_parent->setVisible(false); csv_load_wgt = new CsvLoadWidget(this, false); @@ -91,11 +129,25 @@ DataManipulationForm::DataManipulationForm(QWidget * parent, Qt::WindowFlags f): csv_load_parent->setLayout(layout); csv_load_parent->setMinimumSize(csv_load_wgt->minimumSize()); - connect(paste_tb, &QToolButton::clicked, [&]{ - loadDataFromCsv(true); - paste_tb->setEnabled(false); + connect(columns_lst, &QListWidget::itemDoubleClicked, [&](QListWidgetItem *item){ + if(item->checkState() == Qt::Checked) + item->setCheckState(Qt::Unchecked); + else + item->setCheckState(Qt::Checked); + + toggleColumnDisplay(item); + }); + + connect(select_all_tb, &QToolButton::clicked, [&](){ + setColumnsCheckState(Qt::Checked); }); + connect(clear_all_tb, &QToolButton::clicked, [&](){ + setColumnsCheckState(Qt::Unchecked); + }); + + connect(clear_tb, SIGNAL(clicked(bool)), this, SLOT(clearItemsText())); + connect(columns_lst, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(toggleColumnDisplay(QListWidgetItem*))); connect(csv_load_tb, SIGNAL(toggled(bool)), csv_load_parent, SLOT(setVisible(bool))); connect(close_btn, SIGNAL(clicked()), this, SLOT(reject())); connect(schema_cmb, SIGNAL(currentIndexChanged(int)), this, SLOT(listTables())); @@ -116,11 +168,16 @@ DataManipulationForm::DataManipulationForm(QWidget * parent, Qt::WindowFlags f): connect(duplicate_tb, SIGNAL(clicked()), this, SLOT(duplicateRows())); connect(undo_tb, SIGNAL(clicked()), this, SLOT(undoOperations())); connect(save_tb, SIGNAL(clicked()), this, SLOT(saveChanges())); - connect(bulkedit_tb, SIGNAL(clicked()), this, SLOT(bulkDataEdit())); connect(ord_columns_lst, SIGNAL(currentRowChanged(int)), this, SLOT(enableColumnControlButtons())); connect(move_down_tb, SIGNAL(clicked()), this, SLOT(swapColumns())); connect(move_up_tb, SIGNAL(clicked()), this, SLOT(swapColumns())); - connect(filter_tb, SIGNAL(toggled(bool)), v_splitter, SLOT(setVisible(bool))); + connect(filter_tb, SIGNAL(toggled(bool)), filter_tbw, SLOT(setVisible(bool))); + connect(truncate_tb, SIGNAL(clicked(bool)), this, SLOT(truncateTable())); + connect(new_window_tb, SIGNAL(clicked(bool)), this, SLOT(openNewWindow())); + + connect(bulkedit_tb, &QToolButton::clicked, [&](){ + PgModelerUiNs::bulkDataEdit(results_tbw); + }); connect(filter_tb, &QToolButton::toggled, [&](bool checked){ @@ -134,44 +191,7 @@ DataManipulationForm::DataManipulationForm(QWidget * parent, Qt::WindowFlags f): //Using the QueuedConnection here to avoid the "edit: editing failed" when editing and navigating through items using tab key connect(results_tbw, SIGNAL(currentCellChanged(int,int,int,int)), this, SLOT(insertRowOnTabPress(int,int,int,int)), Qt::QueuedConnection); - connect(results_tbw, &QTableWidget::itemPressed, - [&](){ - if(QApplication::mouseButtons()==Qt::RightButton) - { - QMenu item_menu; - QAction *act = nullptr; - ObjectType obj_type=static_cast(table_cmb->currentData().toUInt()); - - act = item_menu.addAction(QIcon(PgModelerUiNS::getIconPath("copiar")), trUtf8("Copy items")); - act->setMenu(©_menu); - - act = item_menu.addAction(QIcon(PgModelerUiNS::getIconPath("colar")), trUtf8("Pase items")); - act->setShortcut(paste_tb->shortcut()); - connect(act, SIGNAL(triggered(bool)), paste_tb, SLOT(click())); - act->setEnabled(!qApp->clipboard()->text().isEmpty() && obj_type == OBJ_TABLE); - - if(obj_type == OBJ_TABLE) - { - item_menu.addSeparator(); - act = item_menu.addAction(browse_tabs_tb->icon(), trUtf8("Browse tables")); - act->setMenu(&fks_menu); - act->setEnabled(browse_tabs_tb->isEnabled()); - - item_menu.addSeparator(); - act = item_menu.addAction(duplicate_tb->icon(), trUtf8("Duplicate row(s)"), this, SLOT(duplicateRows()), duplicate_tb->shortcut()); - act->setEnabled(duplicate_tb->isEnabled()); - - act = item_menu.addAction(delete_tb->icon(), trUtf8("Delete row(s)"), this, SLOT(markDeleteOnRows()), delete_tb->shortcut()); - act->setEnabled(delete_tb->isEnabled()); - - act = item_menu.addAction(bulkedit_tb->icon(), trUtf8("Edit cell(s)"), this, SLOT(bulkDataEdit()), bulkedit_tb->shortcut()); - act->setEnabled(bulkedit_tb->isEnabled()); - } - - item_menu.exec(QCursor::pos()); - } - }); - + connect(results_tbw, SIGNAL(itemPressed(QTableWidgetItem *)), this, SLOT(showPopupMenu())); connect(export_tb, &QToolButton::clicked, [&](){ SQLExecutionWidget::exportResults(results_tbw); }); @@ -187,17 +207,17 @@ void DataManipulationForm::setAttributes(Connection conn, const QString curr_sch QString db_name; tmpl_conn_params=conn.getConnectionParams(); - db_name=QString("%1@%2:%3").arg(conn.getConnectionParam(Connection::PARAM_DB_NAME)) - .arg(conn.getConnectionParam(Connection::PARAM_SERVER_IP).isEmpty() ? - conn.getConnectionParam(Connection::PARAM_SERVER_FQDN) : conn.getConnectionParam(Connection::PARAM_SERVER_IP)) - .arg(conn.getConnectionParam(Connection::PARAM_PORT)); + db_name=QString("%1@%2:%3").arg(conn.getConnectionParam(Connection::ParamDbName)) + .arg(conn.getConnectionParam(Connection::ParamServerIp).isEmpty() ? + conn.getConnectionParam(Connection::ParamServerFqdn) : conn.getConnectionParam(Connection::ParamServerIp)) + .arg(conn.getConnectionParam(Connection::ParamPort)); db_name_lbl->setText(db_name); db_name.remove(QRegExp("<(/)?(strong|em)>")); this->setWindowTitle(this->windowTitle() + QString(" - ") + db_name); schema_cmb->clear(); - listObjects(schema_cmb, { OBJ_SCHEMA }); + listObjects(schema_cmb, { ObjectType::Schema }); disableControlButtons(); schema_cmb->setCurrentText(curr_schema); @@ -218,13 +238,26 @@ void DataManipulationForm::setAttributes(Connection conn, const QString curr_sch } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } -void DataManipulationForm::setHasCsvClipboard(bool value) +void DataManipulationForm::reject(void) { - has_csv_clipboard = value; + GeneralConfigWidget::saveWidgetGeometry(this); + QDialog::reject(); +} + +void DataManipulationForm::clearItemsText(void) +{ + for(auto &sel : results_tbw->selectedRanges()) + { + for(int row = sel.topRow(); row <= sel.bottomRow(); row++) + { + for(int col = sel.leftColumn(); col <= sel.rightColumn(); col++) + results_tbw->item(row,col)->setText(""); + } + } } void DataManipulationForm::listTables(void) @@ -235,9 +268,9 @@ void DataManipulationForm::listTables(void) if(schema_cmb->currentIndex() > 0) { if(hide_views_chk->isChecked()) - listObjects(table_cmb, { OBJ_TABLE }, schema_cmb->currentText()); + listObjects(table_cmb, { ObjectType::Table }, schema_cmb->currentText()); else - listObjects(table_cmb, { OBJ_TABLE, OBJ_VIEW }, schema_cmb->currentText()); + listObjects(table_cmb, { ObjectType::Table, ObjectType::View }, schema_cmb->currentText()); } table_lbl->setEnabled(table_cmb->count() > 0); @@ -261,13 +294,13 @@ void DataManipulationForm::listColumns(void) vector cols; catalog.setConnection(conn); - cols=catalog.getObjectsAttributes(OBJ_COLUMN, schema_cmb->currentText(), table_cmb->currentText()); + cols=catalog.getObjectsAttributes(ObjectType::Column, schema_cmb->currentText(), table_cmb->currentText()); for(auto &col : cols) { - col_names.push_back(col[ParsersAttributes::NAME]); - code_compl_wgt->insertCustomItem(col[ParsersAttributes::NAME], {}, - QPixmap(PgModelerUiNS::getIconPath("column"))); + col_names.push_back(col[Attributes::Name]); + code_compl_wgt->insertCustomItem(col[Attributes::Name], {}, + QPixmap(PgModelerUiNs::getIconPath("column"))); } ord_column_cmb->addItems(col_names); @@ -279,7 +312,7 @@ void DataManipulationForm::listColumns(void) catch(Exception &e) { catalog.closeConnection(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -299,7 +332,7 @@ void DataManipulationForm::retrieveData(void) if(!changed_rows.empty()) { msg_box.show(trUtf8("WARNING: There are some changed rows waiting the commit! Do you really want to discard them and retrieve the data now?"), - Messagebox::ALERT_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::AlertIcon, Messagebox::YesNoButtons); if(msg_box.result()==QDialog::Rejected) return; @@ -353,12 +386,12 @@ void DataManipulationForm::retrieveData(void) clearChangedRows(); //If the table is empty automatically creates a new row - if(results_tbw->rowCount()==0 && table_cmb->currentData(Qt::UserRole).toUInt()==OBJ_TABLE) + if(results_tbw->rowCount()==0 && table_cmb->currentData(Qt::UserRole).toUInt()== enum_cast(ObjectType::Table)) addRow(); else results_tbw->setFocus(); - if(table_cmb->currentData(Qt::UserRole).toUInt()==OBJ_TABLE) + if(table_cmb->currentData(Qt::UserRole).toUInt()== enum_cast(ObjectType::Table)) csv_load_tb->setEnabled(!col_names.isEmpty()); else { @@ -372,15 +405,38 @@ void DataManipulationForm::retrieveData(void) QApplication::restoreOverrideCursor(); paste_tb->setEnabled(!qApp->clipboard()->text().isEmpty() && - table_cmb->currentData().toUInt() == OBJ_TABLE && + table_cmb->currentData().toUInt() == enum_cast(ObjectType::Table) && !col_names.isEmpty()); + + truncate_tb->setEnabled(table_cmb->currentData().toUInt() == enum_cast(ObjectType::Table) && + res.getTupleCount() > 0 && + !col_names.isEmpty()); + + code_compl_wgt->clearCustomItems(); + code_compl_wgt->insertCustomItems(col_names, trUtf8("Column"), ObjectType::Column); + + columns_lst->clear(); + QListWidgetItem *item = nullptr; + + for(auto &col : col_names) + { + columns_lst->addItem(col); + item = columns_lst->item(columns_lst->count() - 1); + item->setFlags(item->flags() | Qt::ItemIsUserCheckable); + item->setCheckState(Qt::Checked); + item->setData(Qt::UserRole, item->checkState()); + } + + //Restoring the visibily of the columns + for(int idx = 0; idx < results_tbw->horizontalHeader()->count(); idx++) + results_tbw->horizontalHeader()->setSectionHidden(idx, false); } catch(Exception &e) { QApplication::restoreOverrideCursor(); conn_sql.close(); catalog.closeConnection(); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -394,6 +450,8 @@ void DataManipulationForm::disableControlButtons(void) add_tb->setEnabled(false); duplicate_tb->setEnabled(false); export_tb->setEnabled(false); + paste_tb->setEnabled(false); + truncate_tb->setEnabled(false); csv_load_tb->setEnabled(false); csv_load_tb->setChecked(false); clearChangedRows(); @@ -414,9 +472,10 @@ void DataManipulationForm::enableRowControlButtons(void) delete_tb->setEnabled(cols_selected); duplicate_tb->setEnabled(cols_selected); - copy_tb->setEnabled(sel_ranges.count() == 1); + copy_tb->setEnabled(sel_ranges.count() != 0); + clear_tb->setEnabled(sel_ranges.count() != 0); paste_tb->setEnabled(!qApp->clipboard()->text().isEmpty() && - table_cmb->currentData().toUInt() == OBJ_TABLE && + table_cmb->currentData().toUInt() == enum_cast(ObjectType::Table) && !col_names.isEmpty()); browse_tabs_tb->setEnabled((!fk_infos.empty() || !ref_fk_infos.empty()) && sel_ranges.count() == 1 && sel_ranges.at(0).rowCount() == 1); bulkedit_tb->setEnabled(sel_ranges.count() != 0); @@ -454,8 +513,8 @@ void DataManipulationForm::enableColumnControlButtons(void) rem_ord_col_tb->setEnabled(ord_columns_lst->currentRow() >= 0); move_up_tb->setEnabled(ord_columns_lst->count() > 1 && ord_columns_lst->currentRow() > 0); move_down_tb->setEnabled(ord_columns_lst->count() > 1 && - ord_columns_lst->currentRow() >= 0 && - ord_columns_lst->currentRow() <= ord_columns_lst->count() - 2); + ord_columns_lst->currentRow() >= 0 && + ord_columns_lst->currentRow() <= ord_columns_lst->count() - 2); } void DataManipulationForm::swapColumns(void) @@ -481,7 +540,7 @@ void DataManipulationForm::swapColumns(void) ord_columns_lst->setCurrentRow(new_idx); } -void DataManipulationForm::loadDataFromCsv(bool load_from_clipboard) +void DataManipulationForm::loadDataFromCsv(bool load_from_clipboard, bool force_csv_parsing) { QList rows; QStringList cols; @@ -492,13 +551,22 @@ void DataManipulationForm::loadDataFromCsv(bool load_from_clipboard) if(qApp->clipboard()->text().isEmpty()) return; - if(has_csv_clipboard) - rows = CsvLoadWidget::loadCsvFromBuffer(qApp->clipboard()->text(), QString(";"), QString("\""), true, cols); - else - rows = CsvLoadWidget::loadCsvFromBuffer(qApp->clipboard()->text(), QString("\t"), QString(), false, cols); + QString csv_pattern="(%1)(.)*(%1)(;)"; + QString separator="\t", delimiter="", text=qApp->clipboard()->text(); - has_csv_clipboard = false; - qApp->clipboard()->clear(); + if(force_csv_parsing) + { + if(text.contains(QRegExp(csv_pattern.arg("\"")))) + delimiter="\""; + else if(text.contains(QRegExp(csv_pattern.arg("'")))) + delimiter="'"; + + // If one of the patterns matched the buffer we configure the right delimiter for csv buffer + if(!delimiter.isEmpty()) + separator=";"; + } + + rows = CsvLoadWidget::loadCsvFromBuffer(text, separator, delimiter, false, cols); } else { @@ -532,6 +600,9 @@ void DataManipulationForm::loadDataFromCsv(bool load_from_clipboard) for(int i = 0; i < values.count(); i++) { + if(i > values.count()) + break; + if((!load_from_clipboard && csv_load_wgt->isColumnsInFirstRow()) || (load_from_clipboard && !cols.isEmpty())) { @@ -611,7 +682,7 @@ void DataManipulationForm::listObjects(QComboBox *combo, vector obj_ QApplication::setOverrideCursor(Qt::WaitCursor); catalog.setConnection(conn); - catalog.setFilter(Catalog::LIST_ALL_OBJS); + catalog.setFilter(Catalog::ListAllObjects); combo->blockSignals(true); combo->clear(); @@ -629,8 +700,8 @@ void DataManipulationForm::listObjects(QComboBox *combo, vector obj_ for(; idx < count; idx++) { - combo->setItemIcon(idx, QPixmap(PgModelerUiNS::getIconPath(obj_type))); - combo->setItemData(idx, obj_type); + combo->setItemIcon(idx, QPixmap(PgModelerUiNs::getIconPath(obj_type))); + combo->setItemData(idx, enum_cast(obj_type)); } idx=count; @@ -650,7 +721,7 @@ void DataManipulationForm::listObjects(QComboBox *combo, vector obj_ catch(Exception &e) { catalog.closeConnection(); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -666,7 +737,7 @@ void DataManipulationForm::retrievePKColumns(const QString &schema, const QStrin table_oid = 0; - if(obj_type==OBJ_VIEW) + if(obj_type==ObjectType::View) { warning_frm->setVisible(true); warning_lbl->setText(trUtf8("Views can't have their data handled through this grid, this way, all operations are disabled.")); @@ -675,38 +746,38 @@ void DataManipulationForm::retrievePKColumns(const QString &schema, const QStrin { catalog.setConnection(conn); //Retrieving the constraints from catalog using a custom filter to select only primary keys (contype=p) - pks=catalog.getObjectsAttributes(OBJ_CONSTRAINT, schema, table, {}, {{ParsersAttributes::CUSTOM_FILTER, QString("contype='p'")}}); + pks=catalog.getObjectsAttributes(ObjectType::Constraint, schema, table, {}, {{Attributes::CustomFilter, QString("contype='p'")}}); warning_frm->setVisible(pks.empty()); if(pks.empty()) warning_lbl->setText(trUtf8("The selected table doesn't owns a primary key! Updates and deletes will be performed by considering all columns as primary key. WARNING: those operations can affect more than one row.")); else - table_oid = pks[0][ParsersAttributes::TABLE].toUInt(); + table_oid = pks[0][Attributes::Table].toUInt(); } - hint_frm->setVisible(obj_type==OBJ_TABLE); - add_tb->setEnabled(obj_type==OBJ_TABLE && !col_names.empty()); + hint_frm->setVisible(obj_type==ObjectType::Table); + add_tb->setEnabled(obj_type==ObjectType::Table && !col_names.empty()); pk_col_names.clear(); if(!pks.empty()) { - QStringList col_str_ids=Catalog::parseArrayValues(pks[0][ParsersAttributes::COLUMNS]); + QStringList col_str_ids=Catalog::parseArrayValues(pks[0][Attributes::Columns]); vector col_ids; for(QString id : col_str_ids) col_ids.push_back(id.toUInt()); - columns=catalog.getObjectsAttributes(OBJ_COLUMN, schema, table, col_ids); + columns=catalog.getObjectsAttributes(ObjectType::Column, schema, table, col_ids); for(auto &col : columns) - pk_col_names.push_back(col[ParsersAttributes::NAME]); + pk_col_names.push_back(col[Attributes::Name]); } catalog.closeConnection(); //For tables, even if there is no pk the user can manipulate data - if(obj_type==OBJ_TABLE) + if(obj_type==ObjectType::Table) results_tbw->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::AnyKeyPressed); else results_tbw->setEditTriggers(QAbstractItemView::NoEditTriggers); @@ -714,7 +785,7 @@ void DataManipulationForm::retrievePKColumns(const QString &schema, const QStrin catch(Exception &e) { catalog.closeConnection(); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -734,14 +805,14 @@ void DataManipulationForm::retrieveFKColumns(const QString &schema, const QStrin ref_fk_infos.clear(); fk_infos.clear(); - if(obj_type==OBJ_VIEW) + if(obj_type==ObjectType::View) return; catalog.setConnection(conn); //Retrieving the constraints from catalog using a custom filter to select only foreign keys (contype=f) - fks=catalog.getObjectsAttributes(OBJ_CONSTRAINT, schema, table, {}, {{ParsersAttributes::CUSTOM_FILTER, QString("contype='f'")}}); - ref_fks=catalog.getObjectsAttributes(OBJ_CONSTRAINT, QString(), QString(), {}, {{ParsersAttributes::CUSTOM_FILTER, QString("contype='f' AND cs.confrelid=%1").arg(table_oid)}}); + fks=catalog.getObjectsAttributes(ObjectType::Constraint, schema, table, {}, {{Attributes::CustomFilter, QString("contype='f'")}}); + ref_fks=catalog.getObjectsAttributes(ObjectType::Constraint, QString(), QString(), {}, {{Attributes::CustomFilter, QString("contype='f' AND cs.confrelid=%1").arg(table_oid)}}); if(!fks.empty() || !ref_fks.empty()) { @@ -752,56 +823,56 @@ void DataManipulationForm::retrieveFKColumns(const QString &schema, const QStrin QStringList name_list; submenu = new QMenu(this); - fks_menu.addAction(QPixmap(PgModelerUiNS::getIconPath("referenced")), trUtf8("Referenced tables"))->setMenu(submenu); + fks_menu.addAction(QPixmap(PgModelerUiNs::getIconPath("referenced")), trUtf8("Referenced tables"))->setMenu(submenu); if(fks.empty()) submenu->addAction(trUtf8("(none)"))->setEnabled(false); for(auto &fk : fks) { - aux_table = catalog.getObjectAttributes(OBJ_TABLE, fk[ParsersAttributes::REF_TABLE].toUInt()); - aux_schema = catalog.getObjectAttributes(OBJ_SCHEMA, aux_table[ParsersAttributes::SCHEMA].toUInt()); + aux_table = catalog.getObjectAttributes(ObjectType::Table, fk[Attributes::RefTable].toUInt()); + aux_schema = catalog.getObjectAttributes(ObjectType::Schema, aux_table[Attributes::Schema].toUInt()); fk_name = QString("%1.%2.%3") - .arg(aux_schema[ParsersAttributes::NAME]) - .arg(aux_table[ParsersAttributes::NAME]) - .arg(fk[ParsersAttributes::NAME]); + .arg(aux_schema[Attributes::Name]) + .arg(aux_table[Attributes::Name]) + .arg(fk[Attributes::Name]); //Store the referenced schema and table names - fk_infos[fk_name][ParsersAttributes::REF_TABLE] = aux_table[ParsersAttributes::NAME]; - fk_infos[fk_name][ParsersAttributes::SCHEMA] = aux_schema[ParsersAttributes::NAME]; - action = submenu->addAction(QPixmap(PgModelerUiNS::getIconPath("table")), - QString("%1.%2 (%3)").arg(aux_schema[ParsersAttributes::NAME]) - .arg(aux_table[ParsersAttributes::NAME]) - .arg(fk[ParsersAttributes::NAME]), this, SLOT(browseReferencedTable())); + fk_infos[fk_name][Attributes::RefTable] = aux_table[Attributes::Name]; + fk_infos[fk_name][Attributes::Schema] = aux_schema[Attributes::Name]; + action = submenu->addAction(QPixmap(PgModelerUiNs::getIconPath("table")), + QString("%1.%2 (%3)").arg(aux_schema[Attributes::Name]) + .arg(aux_table[Attributes::Name]) + .arg(fk[Attributes::Name]), this, SLOT(browseReferencedTable())); action->setData(fk_name); col_ids.clear(); name_list.clear(); //Storing the source columns in a string - for(QString id : Catalog::parseArrayValues(fk[ParsersAttributes::SRC_COLUMNS])) + for(QString id : Catalog::parseArrayValues(fk[Attributes::SrcColumns])) col_ids.push_back(id.toUInt()); - for(auto &col : catalog.getObjectsAttributes(OBJ_COLUMN, schema, table, col_ids)) - name_list.push_back(BaseObject::formatName(col[ParsersAttributes::NAME])); + for(auto &col : catalog.getObjectsAttributes(ObjectType::Column, schema, table, col_ids)) + name_list.push_back(BaseObject::formatName(col[Attributes::Name])); - fk_infos[fk_name][ParsersAttributes::SRC_COLUMNS] = name_list.join(Table::DATA_SEPARATOR); + fk_infos[fk_name][Attributes::SrcColumns] = name_list.join(Table::DataSeparator); col_ids.clear(); name_list.clear(); //Storing the referenced columns in a string - for(QString id : Catalog::parseArrayValues(fk[ParsersAttributes::DST_COLUMNS])) + for(QString id : Catalog::parseArrayValues(fk[Attributes::DstColumns])) col_ids.push_back(id.toUInt()); - for(auto &col : catalog.getObjectsAttributes(OBJ_COLUMN, aux_schema[ParsersAttributes::NAME], aux_table[ParsersAttributes::NAME], col_ids)) - name_list.push_back(BaseObject::formatName(col[ParsersAttributes::NAME])); + for(auto &col : catalog.getObjectsAttributes(ObjectType::Column, aux_schema[Attributes::Name], aux_table[Attributes::Name], col_ids)) + name_list.push_back(BaseObject::formatName(col[Attributes::Name])); - fk_infos[fk_name][ParsersAttributes::DST_COLUMNS] = name_list.join(Table::DATA_SEPARATOR); + fk_infos[fk_name][Attributes::DstColumns] = name_list.join(Table::DataSeparator); } submenu = new QMenu(this); - fks_menu.addAction(QPixmap(PgModelerUiNS::getIconPath("referrer")), trUtf8("Referrer tables"))->setMenu(submenu); + fks_menu.addAction(QPixmap(PgModelerUiNs::getIconPath("referrer")), trUtf8("Referrer tables"))->setMenu(submenu); if(ref_fks.empty()) submenu->addAction(trUtf8("(none)"))->setEnabled(false); @@ -811,29 +882,29 @@ void DataManipulationForm::retrieveFKColumns(const QString &schema, const QStrin col_ids.clear(); name_list.clear(); - aux_table = catalog.getObjectAttributes(OBJ_TABLE, fk[ParsersAttributes::TABLE].toUInt()); - aux_schema = catalog.getObjectAttributes(OBJ_SCHEMA, aux_table[ParsersAttributes::SCHEMA].toUInt()); + aux_table = catalog.getObjectAttributes(ObjectType::Table, fk[Attributes::Table].toUInt()); + aux_schema = catalog.getObjectAttributes(ObjectType::Schema, aux_table[Attributes::Schema].toUInt()); fk_name = QString("%1.%2.%3") - .arg(aux_schema[ParsersAttributes::NAME]) - .arg(aux_table[ParsersAttributes::NAME]) - .arg(fk[ParsersAttributes::NAME]); + .arg(aux_schema[Attributes::Name]) + .arg(aux_table[Attributes::Name]) + .arg(fk[Attributes::Name]); //Storing the source columns in a string - for(QString id : Catalog::parseArrayValues(fk[ParsersAttributes::SRC_COLUMNS])) + for(QString id : Catalog::parseArrayValues(fk[Attributes::SrcColumns])) col_ids.push_back(id.toUInt()); - for(auto &col : catalog.getObjectsAttributes(OBJ_COLUMN, aux_schema[ParsersAttributes::NAME], aux_table[ParsersAttributes::NAME], col_ids)) - name_list.push_back(BaseObject::formatName(col[ParsersAttributes::NAME])); + for(auto &col : catalog.getObjectsAttributes(ObjectType::Column, aux_schema[Attributes::Name], aux_table[Attributes::Name], col_ids)) + name_list.push_back(BaseObject::formatName(col[Attributes::Name])); - action = submenu->addAction(QPixmap(PgModelerUiNS::getIconPath("table")), - QString("%1.%2 (%3)").arg(aux_schema[ParsersAttributes::NAME]) - .arg(aux_table[ParsersAttributes::NAME]) - .arg(fk[ParsersAttributes::NAME]), this, SLOT(browseReferrerTable())); + action = submenu->addAction(QPixmap(PgModelerUiNs::getIconPath("table")), + QString("%1.%2 (%3)").arg(aux_schema[Attributes::Name]) + .arg(aux_table[Attributes::Name]) + .arg(fk[Attributes::Name]), this, SLOT(browseReferrerTable())); action->setData(fk_name); - ref_fk_infos[fk_name][ParsersAttributes::SRC_COLUMNS] = name_list.join(Table::DATA_SEPARATOR); - ref_fk_infos[fk_name][ParsersAttributes::TABLE] = aux_table[ParsersAttributes::NAME]; - ref_fk_infos[fk_name][ParsersAttributes::SCHEMA] = aux_schema[ParsersAttributes::NAME]; + ref_fk_infos[fk_name][Attributes::SrcColumns] = name_list.join(Table::DataSeparator); + ref_fk_infos[fk_name][Attributes::Table] = aux_table[Attributes::Name]; + ref_fk_infos[fk_name][Attributes::Schema] = aux_schema[Attributes::Name]; } } @@ -842,25 +913,25 @@ void DataManipulationForm::retrieveFKColumns(const QString &schema, const QStrin catch(Exception &e) { catalog.closeConnection(); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void DataManipulationForm::markOperationOnRow(unsigned operation, int row) { if(row < results_tbw->rowCount() && - (operation==NO_OPERATION || results_tbw->verticalHeaderItem(row)->data(Qt::UserRole)!=OP_INSERT)) + (operation==NoOperation || results_tbw->verticalHeaderItem(row)->data(Qt::UserRole)!=OpInsert)) { QTableWidgetItem *item=nullptr, *header_item=results_tbw->verticalHeaderItem(row); QString tooltip=trUtf8("This row is marked to be %1"); QFont fnt=results_tbw->font(); int marked_cols=0; - if(operation==OP_DELETE) + if(operation==OpDelete) tooltip=tooltip.arg(trUtf8("deleted")); - else if(operation==OP_UPDATE) + else if(operation==OpUpdate) tooltip=tooltip.arg(trUtf8("updated")); - else if(operation==OP_INSERT) + else if(operation==OpInsert) tooltip=tooltip.arg(trUtf8("inserted")); else tooltip.clear(); @@ -876,24 +947,24 @@ void DataManipulationForm::markOperationOnRow(unsigned operation, int row) item->setToolTip(tooltip); //Restore the item's font and text when the operation is delete or none - if(operation==NO_OPERATION || operation==OP_DELETE) + if(operation==NoOperation || operation==OpDelete) { item->setFont(fnt); item->setText(item->data(Qt::UserRole).toString()); } - if(operation==NO_OPERATION) + if(operation==NoOperation) //Restore the item's background item->setBackground(prev_row_colors[row]); else { //Saves the item's background if it isn't already marked - if(header_item->data(Qt::UserRole)!=OP_DELETE && - header_item->data(Qt::UserRole)!=OP_UPDATE) + if(header_item->data(Qt::UserRole)!=OpDelete && + header_item->data(Qt::UserRole)!=OpUpdate) prev_row_colors[row]=item->background(); //Changes the item's background according to the operation - item->setBackground(ROW_COLORS[operation - 1]); + item->setBackground(RowColors[operation - 1]); } marked_cols++; @@ -904,12 +975,12 @@ void DataManipulationForm::markOperationOnRow(unsigned operation, int row) { auto itr=std::find(changed_rows.begin(), changed_rows.end(), row); - if(operation==NO_OPERATION && itr!=changed_rows.end()) + if(operation==NoOperation && itr!=changed_rows.end()) { changed_rows.erase(std::find(changed_rows.begin(), changed_rows.end(), row)); prev_row_colors.erase(row); } - else if(operation!=NO_OPERATION && itr==changed_rows.end()) + else if(operation!=NoOperation && itr==changed_rows.end()) changed_rows.push_back(row); header_item->setData(Qt::UserRole, operation); @@ -924,7 +995,7 @@ void DataManipulationForm::markOperationOnRow(unsigned operation, int row) void DataManipulationForm::markUpdateOnRow(QTableWidgetItem *item) { - if(results_tbw->verticalHeaderItem(item->row())->data(Qt::UserRole)!=OP_INSERT) + if(results_tbw->verticalHeaderItem(item->row())->data(Qt::UserRole)!=OpInsert) { bool items_changed=false; QTableWidgetItem *aux_item=nullptr; @@ -943,7 +1014,7 @@ void DataManipulationForm::markUpdateOnRow(QTableWidgetItem *item) fnt.setBold(items_changed); item->setFont(fnt); - markOperationOnRow((items_changed ? OP_UPDATE : NO_OPERATION), item->row()); + markOperationOnRow((items_changed ? OpUpdate : NoOperation), item->row()); } } @@ -959,10 +1030,10 @@ void DataManipulationForm::markDeleteOnRows(void) { item=results_tbw->verticalHeaderItem(row); - if(item->data(Qt::UserRole)==OP_INSERT) + if(item->data(Qt::UserRole)==OpInsert) ins_rows.push_back(row); else - markOperationOnRow(OP_DELETE, row); + markOperationOnRow(OpDelete, row); } } @@ -997,7 +1068,7 @@ void DataManipulationForm::addRow(bool focus_new_row) results_tbw->setVerticalHeaderItem(row, new QTableWidgetItem(QString::number(row + 1))); results_tbw->blockSignals(false); - markOperationOnRow(OP_INSERT, row); + markOperationOnRow(OpInsert, row); item=results_tbw->item(row, 0); hint_frm->setVisible(true); @@ -1033,7 +1104,7 @@ void DataManipulationForm::duplicateRows(void) } } -void DataManipulationForm::removeNewRows(const vector &ins_rows) +void DataManipulationForm::removeNewRows(vector ins_rows) { if(!ins_rows.empty()) { @@ -1043,11 +1114,15 @@ void DataManipulationForm::removeNewRows(const vector &ins_rows) //Mark the rows as no-op to remove their indexes from changed rows set for(idx=0; idx < cnt; idx++) - markOperationOnRow(NO_OPERATION, ins_rows[idx]); + markOperationOnRow(NoOperation, ins_rows[idx]); //Remove the rows - for(idx=0; idx < cnt; idx++) - results_tbw->removeRow(ins_rows[0]); + std::sort(ins_rows.begin(), ins_rows.end()); + while(!ins_rows.empty()) + { + results_tbw->removeRow(ins_rows.back()); + ins_rows.pop_back(); + } //Reorganizing the changed rows vector to avoid row index out-of-bound errors row_idx=results_tbw->rowCount() - 1; @@ -1087,16 +1162,16 @@ void DataManipulationForm::browseTable(const QString &fk_name, bool browse_ref_t if(browse_ref_tab) { src_cols = pk_col_names; - ref_cols = ref_fk_infos[fk_name][ParsersAttributes::SRC_COLUMNS].split(Table::DATA_SEPARATOR); - schema = ref_fk_infos[fk_name][ParsersAttributes::SCHEMA]; - table = ref_fk_infos[fk_name][ParsersAttributes::TABLE]; + ref_cols = ref_fk_infos[fk_name][Attributes::SrcColumns].split(Table::DataSeparator); + schema = ref_fk_infos[fk_name][Attributes::Schema]; + table = ref_fk_infos[fk_name][Attributes::Table]; } else { - src_cols = fk_infos[fk_name][ParsersAttributes::SRC_COLUMNS].split(Table::DATA_SEPARATOR); - ref_cols = fk_infos[fk_name][ParsersAttributes::DST_COLUMNS].split(Table::DATA_SEPARATOR); - schema = fk_infos[fk_name][ParsersAttributes::SCHEMA]; - table = fk_infos[fk_name][ParsersAttributes::REF_TABLE]; + src_cols = fk_infos[fk_name][Attributes::SrcColumns].split(Table::DataSeparator); + ref_cols = fk_infos[fk_name][Attributes::DstColumns].split(Table::DataSeparator); + schema = fk_infos[fk_name][Attributes::Schema]; + table = fk_infos[fk_name][Attributes::RefTable]; } for(QString col_name : src_cols) @@ -1115,7 +1190,7 @@ void DataManipulationForm::browseTable(const QString &fk_name, bool browse_ref_t data_manip->setAttribute(Qt::WA_DeleteOnClose, true); data_manip->setAttributes(conn, schema, table, filter.join(QString("AND"))); - PgModelerUiNS::resizeDialog(data_manip); + PgModelerUiNs::resizeDialog(data_manip); data_manip->show(); } @@ -1124,31 +1199,6 @@ void DataManipulationForm::browseReferrerTable(void) browseTable(qobject_cast(sender())->data().toString(), true); } -void DataManipulationForm::bulkDataEdit(void) -{ - BaseForm base_frm; - BulkDataEditWidget *bulkedit_wgt = new BulkDataEditWidget; - - base_frm.setMainWidget(bulkedit_wgt); - base_frm.setButtonConfiguration(Messagebox::OK_CANCEL_BUTTONS); - - if(base_frm.exec() == QDialog::Accepted) - { - QList sel_ranges=results_tbw->selectedRanges(); - - for(auto range : sel_ranges) - { - for(int row = range.topRow(); row <= range.bottomRow(); row++) - { - for(int col = range.leftColumn(); col <= range.rightColumn(); col++) - { - results_tbw->item(row, col)->setText(bulkedit_wgt->value_edt->toPlainText()); - } - } - } - } -} - void DataManipulationForm::browseReferencedTable(void) { browseTable(qobject_cast(sender())->data().toString(), false); @@ -1164,7 +1214,7 @@ void DataManipulationForm::undoOperations(void) { for(int row=sel_range[0].topRow(); row <= sel_range[0].bottomRow(); row++) { - if(results_tbw->verticalHeaderItem(row)->data(Qt::UserRole).toUInt()==OP_INSERT) + if(results_tbw->verticalHeaderItem(row)->data(Qt::UserRole).toUInt()==OpInsert) ins_rows.push_back(row); else rows.push_back(row); @@ -1180,22 +1230,22 @@ void DataManipulationForm::undoOperations(void) for(auto &row : rows) { item=results_tbw->verticalHeaderItem(row); - if(item->data(Qt::UserRole).toUInt()!=OP_INSERT) - markOperationOnRow(NO_OPERATION, row); + if(item->data(Qt::UserRole).toUInt()!=OpInsert) + markOperationOnRow(NoOperation, row); } //If there is no selection, remove all new rows if(sel_range.isEmpty()) { if(results_tbw->rowCount() > 0 && - results_tbw->verticalHeaderItem(results_tbw->rowCount()-1)->data(Qt::UserRole)==OP_INSERT) + results_tbw->verticalHeaderItem(results_tbw->rowCount()-1)->data(Qt::UserRole)==OpInsert) { do { results_tbw->removeRow(results_tbw->rowCount()-1); item=results_tbw->verticalHeaderItem(results_tbw->rowCount()-1); } - while(item && item->data(Qt::UserRole)==OP_INSERT); + while(item && item->data(Qt::UserRole)==OpInsert); } clearChangedRows(); @@ -1219,6 +1269,13 @@ void DataManipulationForm::insertRowOnTabPress(int curr_row, int curr_col, int p void DataManipulationForm::saveChanges(void) { +#ifdef DEMO_VERSION +#warning "DEMO VERSION: data manipulation save feature disabled warning." + Messagebox msg_box; + msg_box.show(trUtf8("Warning"), + trUtf8("You're running a demonstration version! The save feature of the data manipulation form is available only in the full version!"), + Messagebox::AlertIcon, Messagebox::OkButton); +#else int row=0; Connection conn=Connection(tmpl_conn_params); @@ -1228,8 +1285,8 @@ void DataManipulationForm::saveChanges(void) Messagebox msg_box; msg_box.show(trUtf8("WARNING: Once commited its not possible to undo the changes! Proceed with saving?"), - Messagebox::ALERT_ICON, - Messagebox::YES_NO_BUTTONS); + Messagebox::AlertIcon, + Messagebox::YesNoButtons); if(msg_box.result()==QDialog::Accepted) { @@ -1258,9 +1315,9 @@ void DataManipulationForm::saveChanges(void) } catch(Exception &e) { - map op_names={{ OP_DELETE, trUtf8("delete") }, - { OP_UPDATE, trUtf8("update") }, - { OP_INSERT, trUtf8("insert") }}; + map op_names={{ OpDelete, trUtf8("delete") }, + { OpUpdate, trUtf8("update") }, + { OpInsert, trUtf8("insert") }}; QString tab_name=QString("%1.%2") .arg(schema_cmb->currentText()) @@ -1277,10 +1334,11 @@ void DataManipulationForm::saveChanges(void) results_tbw->selectRow(row); results_tbw->scrollToItem(results_tbw->item(row, 0)); - throw Exception(Exception::getErrorMessage(ERR_ROW_DATA_NOT_MANIPULATED) + throw Exception(Exception::getErrorMessage(ErrorCode::RowDataNotManipulated) .arg(op_names[op_type]).arg(tab_name).arg(row + 1).arg(e.getErrorMessage()), - ERR_ROW_DATA_NOT_MANIPULATED,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + ErrorCode::RowDataNotManipulated,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } +#endif } QString DataManipulationForm::getDMLCommand(int row) @@ -1299,7 +1357,7 @@ QString DataManipulationForm::getDMLCommand(int row) QString col_name, value; QVariant data; - if(op_type==OP_DELETE || op_type==OP_UPDATE) + if(op_type==OpDelete || op_type==OpUpdate) { if(pk_col_names.isEmpty()) { @@ -1316,20 +1374,20 @@ QString DataManipulationForm::getDMLCommand(int row) { data = results_tbw->item(row, col_names.indexOf(pk_col))->data(Qt::UserRole); - if(data.toString() == SQLExecutionWidget::COLUMN_NULL_VALUE) + if(data.toString() == SQLExecutionWidget::ColumnNullValue) flt_list.push_back(QString("\"%1\" IS NULL").arg(pk_col)); else flt_list.push_back(QString("\"%1\"='%2'").arg(pk_col).arg(data.toString().replace("\'","''"))); } } - if(op_type==OP_DELETE) + if(op_type==OpDelete) { fmt_cmd=QString(del_cmd).arg(tab_name).arg(flt_list.join(QString(" AND "))); } - else if(op_type==OP_UPDATE || op_type==OP_INSERT) + else if(op_type==OpUpdate || op_type==OpInsert) { - fmt_cmd=(op_type==OP_UPDATE ? upd_cmd : ins_cmd); + fmt_cmd=(op_type==OpUpdate ? upd_cmd : ins_cmd); for(int col=0; col < results_tbw->columnCount(); col++) { @@ -1341,15 +1399,15 @@ QString DataManipulationForm::getDMLCommand(int row) value=item->text(); col_name=results_tbw->horizontalHeaderItem(col)->text(); - if(op_type==OP_INSERT || (op_type==OP_UPDATE && value!=item->data(Qt::UserRole))) + if(op_type==OpInsert || (op_type==OpUpdate && value!=item->data(Qt::UserRole))) { //Checking if the value is a malformed unescaped value, e.g., {value, value}, {value\} - if((value.startsWith(PgModelerNS::UNESC_VALUE_START) && value.endsWith(QString("\\") + PgModelerNS::UNESC_VALUE_END)) || - (value.startsWith(PgModelerNS::UNESC_VALUE_START) && !value.endsWith(PgModelerNS::UNESC_VALUE_END)) || - (!value.startsWith(PgModelerNS::UNESC_VALUE_START) && !value.endsWith(QString("\\") + PgModelerNS::UNESC_VALUE_END) && value.endsWith(PgModelerNS::UNESC_VALUE_END))) - throw Exception(Exception::getErrorMessage(ERR_MALFORMED_UNESCAPED_VALUE) + if((value.startsWith(PgModelerNs::UnescValueStart) && value.endsWith(QString("\\") + PgModelerNs::UnescValueEnd)) || + (value.startsWith(PgModelerNs::UnescValueStart) && !value.endsWith(PgModelerNs::UnescValueEnd)) || + (!value.startsWith(PgModelerNs::UnescValueStart) && !value.endsWith(QString("\\") + PgModelerNs::UnescValueEnd) && value.endsWith(PgModelerNs::UnescValueEnd))) + throw Exception(Exception::getErrorMessage(ErrorCode::MalformedUnescapedValue) .arg(row + 1).arg(col_name), - ERR_MALFORMED_UNESCAPED_VALUE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::MalformedUnescapedValue,__PRETTY_FUNCTION__,__FILE__,__LINE__); col_list.push_back(QString("\"%1\"").arg(col_name)); @@ -1359,7 +1417,7 @@ QString DataManipulationForm::getDMLCommand(int row) value=QString("DEFAULT"); } //Unescaped values will not be enclosed in quotes - else if(value.startsWith(PgModelerNS::UNESC_VALUE_START) && value.endsWith(PgModelerNS::UNESC_VALUE_END)) + else if(value.startsWith(PgModelerNs::UnescValueStart) && value.endsWith(PgModelerNs::UnescValueEnd)) { value.remove(0,1); value.remove(value.length()-1, 1); @@ -1367,13 +1425,13 @@ QString DataManipulationForm::getDMLCommand(int row) //Quoting value else { - value.replace(QString("\\") + PgModelerNS::UNESC_VALUE_START, PgModelerNS::UNESC_VALUE_START); - value.replace(QString("\\") + PgModelerNS::UNESC_VALUE_END, PgModelerNS::UNESC_VALUE_END); + value.replace(QString("\\") + PgModelerNs::UnescValueStart, PgModelerNs::UnescValueStart); + value.replace(QString("\\") + PgModelerNs::UnescValueEnd, PgModelerNs::UnescValueEnd); value.replace("\'","''"); value=QString("E'") + value + QString("'"); } - if(op_type==OP_INSERT) + if(op_type==OpInsert) val_list.push_back(value); else val_list.push_back(QString("\"%1\"=%2").arg(col_name).arg(value)); @@ -1385,7 +1443,7 @@ QString DataManipulationForm::getDMLCommand(int row) return(QString()); else { - if(op_type==OP_UPDATE) + if(op_type==OpUpdate) fmt_cmd=fmt_cmd.arg(tab_name).arg(val_list.join(QString(", "))).arg(flt_list.join(QString(" AND "))); else fmt_cmd=fmt_cmd.arg(tab_name).arg(col_list.join(QString(", "))).arg(val_list.join(QString(", "))); @@ -1394,3 +1452,126 @@ QString DataManipulationForm::getDMLCommand(int row) return(fmt_cmd); } + +void DataManipulationForm::resizeEvent(QResizeEvent *event) +{ + Qt::ToolButtonStyle style = Qt::ToolButtonIconOnly; + QToolButton *btn = nullptr; + + if(event->size().height() > this->baseSize().height()) + style = Qt::ToolButtonTextUnderIcon; + + if(refresh_tb->toolButtonStyle() != style) + { + for(auto obj : bnts_parent_wgt->children()) + { + btn = qobject_cast(obj); + + if(btn) + btn->setToolButtonStyle(style); + } + } +} + +void DataManipulationForm::closeEvent(QCloseEvent *) +{ + GeneralConfigWidget::saveWidgetGeometry(this); +} + +void DataManipulationForm::setColumnsCheckState(Qt::CheckState state) +{ + QListWidgetItem *item = nullptr; + + results_tbw->blockSignals(true); + + for(int idx = 0; idx < columns_lst->count(); idx++) + { + item = columns_lst->item(idx); + item->setCheckState(state); + toggleColumnDisplay(item); + } + + results_tbw->blockSignals(false); +} + +void DataManipulationForm::truncateTable(void) +{ + try + { + QAction *act = dynamic_cast(sender()); + + if(DatabaseExplorerWidget::truncateTable(schema_cmb->currentText(), table_cmb->currentText(), + act->data().toBool(), Connection(tmpl_conn_params))) + retrieveData(); + } + catch(Exception &e) + { + Messagebox msg_box; + msg_box.show(e); + } +} + +void DataManipulationForm::toggleColumnDisplay(QListWidgetItem *item) +{ + if(!item) + return; + + if(item->checkState() != static_cast(item->data(Qt::UserRole).toInt())) + { + int idx = 0; + bool hide = false; + + idx = col_names.indexOf(item->text()); + hide = item->checkState() == Qt::Unchecked; + results_tbw->horizontalHeader()->setSectionHidden(idx, hide); + item->setCheckState(hide ? Qt::Unchecked : Qt::Checked); + item->setData(Qt::UserRole, item->checkState()); + } +} + +void DataManipulationForm::openNewWindow(void) +{ + DataManipulationForm *data_manip = new DataManipulationForm; + data_manip->setAttributes(tmpl_conn_params, QString()); + data_manip->show(); +} + +void DataManipulationForm::showPopupMenu(void) +{ + if(QApplication::mouseButtons()==Qt::RightButton) + { + QMenu item_menu; + QAction *act = nullptr; + ObjectType obj_type=static_cast(table_cmb->currentData().toUInt()); + + act = item_menu.addAction(QIcon(PgModelerUiNs::getIconPath("copiar")), trUtf8("Copy items")); + act->setMenu(©_menu); + + act = item_menu.addAction(QIcon(PgModelerUiNs::getIconPath("colar")), trUtf8("Pase items")); + act->setMenu(&paste_menu); + act->setEnabled(paste_tb->isEnabled()); + + act = item_menu.addAction(QIcon(PgModelerUiNs::getIconPath("limpar")), trUtf8("Clear items")); + act->setEnabled(!results_tbw->selectedRanges().isEmpty()); + + if(obj_type == ObjectType::Table) + { + item_menu.addSeparator(); + act = item_menu.addAction(browse_tabs_tb->icon(), trUtf8("Browse tables")); + act->setMenu(&fks_menu); + act->setEnabled(browse_tabs_tb->isEnabled()); + + item_menu.addSeparator(); + act = item_menu.addAction(duplicate_tb->icon(), trUtf8("Duplicate row(s)"), this, SLOT(duplicateRows()), duplicate_tb->shortcut()); + act->setEnabled(duplicate_tb->isEnabled()); + + act = item_menu.addAction(delete_tb->icon(), trUtf8("Delete row(s)"), this, SLOT(markDeleteOnRows()), delete_tb->shortcut()); + act->setEnabled(delete_tb->isEnabled()); + + act = item_menu.addAction(bulkedit_tb->icon(), trUtf8("Edit cell(s)"), bulkedit_tb, SLOT(click()), bulkedit_tb->shortcut()); + act->setEnabled(bulkedit_tb->isEnabled()); + } + + item_menu.exec(QCursor::pos()); + } +} diff --git a/libpgmodeler_ui/src/datamanipulationform.h b/libpgmodeler_ui/src/datamanipulationform.h index 30f91b75ec..342a3b354a 100644 --- a/libpgmodeler_ui/src/datamanipulationform.h +++ b/libpgmodeler_ui/src/datamanipulationform.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -36,21 +36,22 @@ class DataManipulationForm: public QDialog, public Ui::DataManipulationForm { Q_OBJECT //! \brief Constants used to mark the type of operation performed on rows - static const unsigned NO_OPERATION, OP_INSERT, OP_UPDATE, OP_DELETE; - + static constexpr unsigned NoOperation=0, + OpInsert=1, + OpUpdate=2, + OpDelete=3; + //! \brief Default row colors for each operation type - static const QColor ROW_COLORS[3]; + static const QColor RowColors[3]; - static bool has_csv_clipboard; - CsvLoadWidget *csv_load_wgt; SyntaxHighlighter *filter_hl; CodeCompletionWidget *code_compl_wgt; - QMenu fks_menu, copy_menu; - + QMenu fks_menu, copy_menu, truncate_menu, paste_menu; + //! \brief Store the template connection params to be used by catalogs and command execution connections attribs_map tmpl_conn_params; @@ -94,7 +95,7 @@ class DataManipulationForm: public QDialog, public Ui::DataManipulationForm { QString getDMLCommand(int row); //! \brief Remove the rows marked as OP_INSERT which ids are specified on the parameter vector - void removeNewRows(const vector &ins_rows); + void removeNewRows(vector ins_rows); //! \brief Reset the state of changed rows, clearing all attributes used to control the modifications on them void clearChangedRows(void); @@ -102,15 +103,23 @@ class DataManipulationForm: public QDialog, public Ui::DataManipulationForm { //! brief Browse a referenced or referencing table by the provided foreign key name void browseTable(const QString &fk_name, bool browse_ref_tab); + void resizeEvent(QResizeEvent *event); + + void closeEvent(QCloseEvent *); + + void setColumnsCheckState(Qt::CheckState state); + public: - DataManipulationForm(QWidget * parent = 0, Qt::WindowFlags f = 0); + DataManipulationForm(QWidget * parent = nullptr, Qt::WindowFlags f = Qt::Widget); //! \brief Defines the connection and current schema and table to be handled, this method should be called before show the dialog void setAttributes(Connection conn, const QString curr_schema=QString("public"), const QString curr_table=QString(), const QString &filter=QString()); - static void setHasCsvClipboard(bool value); - private slots: + void reject(void); + + void clearItemsText(void); + //! \brief List the tables based upon the current schema void listTables(void); @@ -169,16 +178,25 @@ class DataManipulationForm: public QDialog, public Ui::DataManipulationForm { void swapColumns(void); //! \brief Add new rows to the grid based upon the CSV loaded - void loadDataFromCsv(bool load_from_clipboard = false); + void loadDataFromCsv(bool load_from_clipboard = false, bool force_csv_parsing = false); - //! brief Browse the referenced table data using the selected row in the results grid + //! \brief Browse the referenced table data using the selected row in the results grid void browseReferencedTable(void); - //! brief Browse the referencing table data using the selected row in the results grid + //! \brief Browse the referencing table data using the selected row in the results grid void browseReferrerTable(void); - //! brief Changes the values of the grid selection at once - void bulkDataEdit(void); + //! \brief Truncates the browsed table + void truncateTable(void); + + //! \brief Display or hides a column when the related item is interacted in the column list at filter section + void toggleColumnDisplay(QListWidgetItem *item); + + //! \brief Opens a new data manipulation windows + void openNewWindow(void); + + //! \brief Shows the popup menu over the current selection + void showPopupMenu(void); }; #endif diff --git a/libpgmodeler_ui/src/domainwidget.cpp b/libpgmodeler_ui/src/domainwidget.cpp index a25e8c4ba5..6f0e593c66 100644 --- a/libpgmodeler_ui/src/domainwidget.cpp +++ b/libpgmodeler_ui/src/domainwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -19,7 +19,7 @@ #include "domainwidget.h" #include "numberedtexteditor.h" -DomainWidget::DomainWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_DOMAIN) +DomainWidget::DomainWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Domain) { try { @@ -27,7 +27,7 @@ DomainWidget::DomainWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_DOMAIN check_expr_hl=nullptr; check_expr_hl=new SyntaxHighlighter(check_expr_txt, false, true); - check_expr_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + check_expr_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); data_type=nullptr; data_type=new PgSQLTypeWidget(this); @@ -36,14 +36,14 @@ DomainWidget::DomainWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_DOMAIN grid->addWidget(data_type, 1, 0, 1, 2); grid->addItem(new QSpacerItem(10, 1, QSizePolicy::Fixed,QSizePolicy::Expanding), 2, 0, 1, 1); - constr_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ (ObjectsTableWidget::DUPLICATE_BUTTON), true, this); + constr_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ (ObjectsTableWidget::DuplicateButton), true, this); constr_tab->setColumnCount(2); constr_tab->setHeaderLabel(trUtf8("Name"), 0); - constr_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("constraint_ck")), 0); + constr_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("constraint_ck")), 0); constr_tab->setHeaderLabel(trUtf8("Expression"), 1); - constr_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("codigofonte")), 1); + constr_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("codigofonte")), 1); grid = dynamic_cast(dom_attribs_tbw->widget(1)->layout()); grid->addWidget(constr_tab, 2, 0, 1, 2); @@ -52,7 +52,7 @@ DomainWidget::DomainWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_DOMAIN connect(constr_tab, SIGNAL(s_rowUpdated(int)), this, SLOT(handleConstraint(int))); connect(constr_tab, SIGNAL(s_rowEdited(int)), this, SLOT(editConstraint(int))); - configureFormLayout(domain_grid, OBJ_DOMAIN); + configureFormLayout(domain_grid, ObjectType::Domain); setRequiredField(data_type); configureTabOrder({ def_value_edt, not_null_chk, data_type, constr_name_edt, check_expr_txt }); @@ -60,13 +60,13 @@ DomainWidget::DomainWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_DOMAIN } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void DomainWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, Domain *domain) { - PgSQLType type; + PgSqlType type; BaseObjectWidget::setAttributes(model, op_list, domain, schema); @@ -133,7 +133,7 @@ void DomainWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/domainwidget.h b/libpgmodeler_ui/src/domainwidget.h index 1f538bc855..2167e3e98e 100644 --- a/libpgmodeler_ui/src/domainwidget.h +++ b/libpgmodeler_ui/src/domainwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -39,7 +39,7 @@ class DomainWidget: public BaseObjectWidget, public Ui::DomainWidget { ObjectsTableWidget *constr_tab; public: - DomainWidget(QWidget * parent = 0); + DomainWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, Domain *domain); private slots: diff --git a/libpgmodeler_ui/src/donatewidget.cpp b/libpgmodeler_ui/src/donatewidget.cpp index 41371f6f95..bbc2a81dfd 100644 --- a/libpgmodeler_ui/src/donatewidget.cpp +++ b/libpgmodeler_ui/src/donatewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -40,11 +40,11 @@ DonateWidget::DonateWidget(QWidget *parent) : QWidget(parent) connect(donate_tb, &QToolButton::clicked, [&](){ - QDesktopServices::openUrl(QUrl(GlobalAttributes::PGMODELER_DONATE_URL)); + QDesktopServices::openUrl(QUrl(GlobalAttributes::PgModelerDonateURL)); this->close(); emit s_visibilityChanged(false); }); - PgModelerUiNS::configureWidgetFont(title_lbl, PgModelerUiNS::BIG_FONT_FACTOR); + PgModelerUiNs::configureWidgetFont(title_lbl, PgModelerUiNs::BigFontFactor); this->adjustSize(); } diff --git a/libpgmodeler_ui/src/donatewidget.h b/libpgmodeler_ui/src/donatewidget.h index 764e945378..aa0cb97b0f 100644 --- a/libpgmodeler_ui/src/donatewidget.h +++ b/libpgmodeler_ui/src/donatewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -34,7 +34,7 @@ class DonateWidget: public QWidget, public Ui::DonateWidget { Q_OBJECT public: - DonateWidget(QWidget *parent = 0); + DonateWidget(QWidget *parent = nullptr); signals: void s_visibilityChanged(bool value); diff --git a/libpgmodeler_ui/src/elementstablewidget.cpp b/libpgmodeler_ui/src/elementstablewidget.cpp new file mode 100644 index 0000000000..84af5f4d64 --- /dev/null +++ b/libpgmodeler_ui/src/elementstablewidget.cpp @@ -0,0 +1,186 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "elementstablewidget.h" +#include "generalconfigwidget.h" + +ElementsTableWidget::ElementsTableWidget(QWidget *parent) : QWidget(parent) +{ + try + { + handled_elem = nullptr; + model = nullptr; + parent_obj = nullptr; + + element_wgt = new ElementWidget; + element_form.setMainWidget(element_wgt); + element_form.setButtonConfiguration(); + connect(&element_form, SIGNAL(accepted()), element_wgt, SLOT(applyConfiguration())); + + QVBoxLayout *vbox = new QVBoxLayout(this); + elements_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + (ObjectsTableWidget::UpdateButton | ObjectsTableWidget::DuplicateButton), true, this); + + elements_tab->setColumnCount(7); + elements_tab->setHeaderLabel(trUtf8("Element"), 0); + elements_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("column")),0); + elements_tab->setHeaderLabel(trUtf8("Type"), 1); + elements_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("usertype")),1); + elements_tab->setHeaderLabel(trUtf8("Operator"), 2); + elements_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("operator")),2); + elements_tab->setHeaderLabel(trUtf8("Operator Class"), 3); + elements_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("opclass")),3); + elements_tab->setHeaderLabel(trUtf8("Collation"), 4); + elements_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("collation")),4); + elements_tab->setHeaderLabel(trUtf8("Sorting"), 5); + elements_tab->setHeaderLabel(trUtf8("Nulls First"), 6); + + vbox->setContentsMargins(4,4,4,4); + vbox->addWidget(elements_tab); + + connect(elements_tab, SIGNAL(s_rowAdded(int)), this, SLOT(addElement(int))); + connect(elements_tab, SIGNAL(s_rowEdited(int)), this, SLOT(editElement(int))); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +ElementsTableWidget::~ElementsTableWidget(void) +{ + if(handled_elem) + delete(handled_elem); +} + +void ElementsTableWidget::showElementData(Element *elem, int elem_idx) +{ + if(!elem) + return; + + if(elem->getColumn()) + { + elements_tab->setCellText(elem->getColumn()->getName(), elem_idx, 0); + elements_tab->setCellText(elem->getColumn()->getTypeName(), elem_idx, 1); + } + else + { + elements_tab->setCellText(elem->getExpression(), elem_idx, 0); + elements_tab->setCellText(trUtf8("Expression"), elem_idx, 1); + } + + elements_tab->clearCellText(elem_idx, 2); + if(elem->getOperator()) + elements_tab->setCellText(elem->getOperator()->getSignature(true), elem_idx, 2); + + elements_tab->clearCellText(elem_idx, 3); + if(elem->getOperatorClass()) + elements_tab->setCellText(elem->getOperatorClass()->getName(true), elem_idx, 3); + + elements_tab->clearCellText(elem_idx, 4); + if(elem->getCollation()) + elements_tab->setCellText(elem->getCollation()->getName(true), elem_idx, 4); + + if(elem->isSortingEnabled()) + { + if(elem->getSortingAttribute(IndexElement::AscOrder)) + elements_tab->setCellText(trUtf8("Ascending"), elem_idx, 5); + else + elements_tab->setCellText(trUtf8("Descending"), elem_idx, 5); + + if(elem->getSortingAttribute(IndexElement::NullsFirst)) + elements_tab->setCellText(trUtf8("Yes"), elem_idx, 6); + else + elements_tab->setCellText(trUtf8("No"), elem_idx, 6); + } + else + { + elements_tab->clearCellText(elem_idx, 4); + elements_tab->clearCellText(elem_idx, 5); + } + + elements_tab->setRowData(copyElementData(elem), elem_idx); +} + +QVariant ElementsTableWidget::copyElementData(Element *elem) +{ + if(dynamic_cast(elem)) + return(QVariant::fromValue(*dynamic_cast(elem))); + + if(dynamic_cast(elem)) + return(QVariant::fromValue(*dynamic_cast(elem))); + + if(dynamic_cast(elem)) + return(QVariant::fromValue(*dynamic_cast(elem))); + + return(QVariant()); +} + +int ElementsTableWidget::openElementForm(Element *elem) +{ + int res = 0; + + GeneralConfigWidget::restoreWidgetGeometry(&element_form, element_wgt->metaObject()->className()); + element_wgt->setAttributes(model, parent_obj, elem); + element_form.setWindowTitle(element_wgt->windowTitle()); + res = element_form.exec(); + GeneralConfigWidget::saveWidgetGeometry(&element_form, element_wgt->metaObject()->className()); + + return(res); +} + +void ElementsTableWidget::editElement(int elem_idx) +{ + QVariant data = elements_tab->getRowData(elem_idx); + Element *elem = nullptr; + IndexElement idx_elem; + ExcludeElement exc_elem; + PartitionKey part_key; + int res = 0; + + if(data.canConvert()) + { + idx_elem = data.value(); + elem = &idx_elem; + } + + if(data.canConvert()) + { + exc_elem = data.value(); + elem = &exc_elem; + } + + if(data.canConvert()) + { + part_key = data.value(); + elem = &part_key; + } + + res = openElementForm(elem); + + if(elem && res == QDialog::Accepted) + showElementData(element_wgt->getElement(), elem_idx); +} + +void ElementsTableWidget::addElement(int elem_idx) +{ + if(openElementForm(handled_elem) == QDialog::Accepted) + showElementData(element_wgt->getElement(), elem_idx); + else + elements_tab->removeRow(elem_idx); +} diff --git a/libpgmodeler_ui/src/elementstablewidget.h b/libpgmodeler_ui/src/elementstablewidget.h new file mode 100644 index 0000000000..e2c907d3b9 --- /dev/null +++ b/libpgmodeler_ui/src/elementstablewidget.h @@ -0,0 +1,140 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +/** +\ingroup libpgmodeler_ui +\class ElementsTableWidget +\brief Implements the operations to create/edit constraints (exclude), indexes and partition keys elements via form storing them on a objects table (grid). +*/ + +#ifndef ELEMENTS_TABLES_WIDGET_H +#define ELEMENTS_TABLES_WIDGET_H + +#include +#include "objectstablewidget.h" +#include "indexelement.h" +#include "excludeelement.h" +#include "partitionkey.h" +#include "baseform.h" +#include "elementwidget.h" + +/* Declaring the IndexElement and ExcludeElement class as a Qt metatype in order to permit + * that instances of the class be used as data of QVariant and QMetaType */ +#include +Q_DECLARE_METATYPE(IndexElement) +Q_DECLARE_METATYPE(ExcludeElement) +Q_DECLARE_METATYPE(PartitionKey) + +class ElementsTableWidget: public QWidget { + private: + Q_OBJECT + + /*! \brief Store an instance of the element being handled (see setAttributes()) + * This one is used to determine the settings of the element widget open when the user + * wants to create new elements on the grid */ + Element *handled_elem; + + ElementWidget *element_wgt; + + BaseForm element_form; + + DatabaseModel *model; + + BaseObject *parent_obj; + + //! \brief Table widget used to control the index elements + ObjectsTableWidget *elements_tab; + + //! \brief Shows the element data on the elements table at the specified line + void showElementData(Element *elem, int elem_idx); + + //! \brief Copies the provided element storing it on a QVariant according to its real type (class) + QVariant copyElementData(Element *elem); + + //! \brief Opens the element editing form using the attributes of the provided element + int openElementForm(Element *elem); + + public: + ElementsTableWidget(QWidget *parent = nullptr); + ~ElementsTableWidget(void); + + //! \brief Configures the grid based upon the template Class in use + template + void setAttributes(DatabaseModel *model, BaseObject *parent_obj) + { + if(handled_elem && !dynamic_cast(handled_elem)) + { + delete(handled_elem); + handled_elem = nullptr; + } + + if(!handled_elem) + handled_elem = new Class; + + this->model = model; + this->parent_obj = parent_obj; + + if(dynamic_cast(handled_elem)) + elements_tab->setHeaderVisible(2, false); + + if(dynamic_cast(handled_elem)) + elements_tab->setHeaderVisible(4, false); + + if(dynamic_cast(handled_elem)) + { + elements_tab->setHeaderVisible(2, false); + elements_tab->setHeaderVisible(5, false); + elements_tab->setHeaderVisible(6, false); + } + } + + //! \brief Fills the grid with the elements on the vector vector + template + void setElements(vector elems) + { + elements_tab->blockSignals(true); + for(auto &elem : elems) + { + elements_tab->addRow(); + showElementData(&elem, elements_tab->getRowCount() - 1); + } + elements_tab->clearSelection(); + elements_tab->blockSignals(false); + } + + //! \brief Fills the provided vector with the elements on the grid + template + void getElements(vector &elems) + { + if(elements_tab->getRowCount() > 0) + { + if(elements_tab->getRowData(0).canConvert()) + { + elems.clear(); + for(unsigned i=0; i < elements_tab->getRowCount(); i++) + elems.push_back(elements_tab->getRowData(i).value()); + } + } + } + + private slots: + void addElement(int elem_idx); + void editElement(int elem_idx); +}; + +#endif diff --git a/libpgmodeler_ui/src/elementswidget.cpp b/libpgmodeler_ui/src/elementswidget.cpp deleted file mode 100644 index e4f7b34799..0000000000 --- a/libpgmodeler_ui/src/elementswidget.cpp +++ /dev/null @@ -1,435 +0,0 @@ -/* -# PostgreSQL Database Modeler (pgModeler) -# -# Copyright 2006-2018 - Raphael Araújo e Silva -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation version 3. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# The complete text of GPLv3 is at LICENSE file on source code root directory. -# Also, you can get the complete GNU General Public License at -*/ - -#include "elementswidget.h" - -ElementsWidget::ElementsWidget(QWidget *parent) : QWidget(parent) -{ - try - { - map > fields_map; - QFrame *frame=nullptr; - - setupUi(this); - elem_expr_hl=new SyntaxHighlighter(elem_expr_txt, false, true); - elem_expr_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); - - parent_obj=nullptr; - elements_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ ObjectsTableWidget::DUPLICATE_BUTTON, true, this); - op_class_sel=new ObjectSelectorWidget(OBJ_OPCLASS, true, this); - collation_sel=new ObjectSelectorWidget(OBJ_COLLATION, true, this); - operator_sel=new ObjectSelectorWidget(OBJ_OPERATOR, true, this); - - - elements_tab->setColumnCount(6); - elements_tab->setHeaderLabel(trUtf8("Element"), 0); - elements_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("column")),0); - elements_tab->setHeaderLabel(trUtf8("Type"), 1); - elements_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("usertype")),1); - elements_tab->setHeaderLabel(trUtf8("Operator Class"), 3); - elements_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("opclass")),3); - elements_tab->setHeaderLabel(trUtf8("Sorting"), 4); - elements_tab->setHeaderLabel(trUtf8("Nulls First"), 5); - - element_grid->addWidget(collation_sel, 3,1,1,2); - element_grid->addWidget(op_class_sel, 4,1,1,2); - element_grid->addWidget(operator_sel, 5,1,1,2); - element_grid->addWidget(elements_tab, 7,0,1,3); - - fields_map[BaseObjectWidget::generateVersionsInterval(BaseObjectWidget::AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_91)].push_back(collation_lbl); - frame=BaseObjectWidget::generateVersionWarningFrame(fields_map); - element_grid->addWidget(frame, element_grid->count()+1, 0, 1, 3); - frame->setParent(this); - - connect(elements_tab, SIGNAL(s_rowAdded(int)), this, SLOT(handleElement(int))); - connect(elements_tab, SIGNAL(s_rowUpdated(int)), this, SLOT(handleElement(int))); - connect(elements_tab, SIGNAL(s_rowEdited(int)), this, SLOT(editElement(int))); - connect(column_rb, SIGNAL(toggled(bool)), this, SLOT(selectElementObject(void))); - connect(expression_rb, SIGNAL(toggled(bool)), this, SLOT(selectElementObject(void))); - connect(sorting_chk, SIGNAL(toggled(bool)), ascending_rb, SLOT(setEnabled(bool))); - connect(sorting_chk, SIGNAL(toggled(bool)), descending_rb, SLOT(setEnabled(bool))); - connect(sorting_chk, SIGNAL(toggled(bool)), nulls_first_chk, SLOT(setEnabled(bool))); - - this->setEnabled(false); - collation_sel->setVisible(false); - collation_lbl->setVisible(false); - operator_sel->setVisible(false); - operator_lbl->setVisible(false); - - BaseObjectWidget::setRequiredField(operator_sel); - BaseObjectWidget::setRequiredField(operator_lbl); - - setTabOrder(column_rb, column_cmb); - setTabOrder(column_cmb, expression_rb); - setTabOrder(expression_rb, elem_expr_txt); - setTabOrder(elem_expr_txt, collation_sel); - setTabOrder(collation_sel, collation_sel->rem_object_tb); - setTabOrder(collation_sel->rem_object_tb, collation_sel->sel_object_tb); - setTabOrder(collation_sel->sel_object_tb, op_class_sel); - - setTabOrder(op_class_sel, op_class_sel->rem_object_tb); - setTabOrder(op_class_sel->rem_object_tb, op_class_sel->sel_object_tb); - setTabOrder(op_class_sel->sel_object_tb, sorting_chk); - - setTabOrder(sorting_chk, ascending_rb); - setTabOrder(ascending_rb, descending_rb); - setTabOrder(descending_rb, nulls_first_chk); - } - catch(Exception &e) - { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); - } -} - -void ElementsWidget::setAttributes(DatabaseModel *model, BaseObject *parent_obj) -{ - if(!model || !parent_obj) - { - this->setEnabled(false); - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); - } - else if(parent_obj->getObjectType()!=OBJ_TABLE && - parent_obj->getObjectType()!=OBJ_VIEW && - parent_obj->getObjectType()!=OBJ_RELATIONSHIP) - throw Exception(ERR_OPR_OBJ_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); - - this->setEnabled(true); - this->parent_obj=parent_obj; - - op_class_sel->setModel(model); - collation_sel->setModel(model); - operator_sel->setModel(model); - - cols_combo_parent->setVisible(parent_obj->getObjectType() == OBJ_TABLE); - column_rb->setVisible(parent_obj->getObjectType() == OBJ_TABLE); - expression_rb->setChecked(parent_obj->getObjectType() == OBJ_VIEW); - - if(parent_obj->getObjectType() == OBJ_TABLE) - updateColumnsCombo(); -} - -void ElementsWidget::setAttributes(DatabaseModel *model, BaseTable *table, vector &elems) -{ - setAttributes(model, table); - collation_sel->setVisible(true); - collation_lbl->setVisible(true); - - elements_tab->setHeaderLabel(trUtf8("Collation"), 2); - elements_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("collation")),2); - elements_tab->blockSignals(true); - - for(unsigned i=0; i < elems.size(); i++) - { - elements_tab->addRow(); - showElementData(elems[i], i); - } - - elements_tab->blockSignals(false); -} - -void ElementsWidget::setAttributes(DatabaseModel *model, BaseObject *parent_obj, vector &elems) -{ - setAttributes(model, parent_obj); - operator_sel->setVisible(true); - operator_lbl->setVisible(true); - - elements_tab->setHeaderLabel(trUtf8("Operator"), 2); - elements_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("operator")),2); - elements_tab->blockSignals(true); - - for(unsigned i=0; i < elems.size(); i++) - { - elements_tab->addRow(); - showElementData(elems[i], i); - } - - elements_tab->blockSignals(false); -} - -void ElementsWidget::clear(void) -{ - column_cmb->clear(); - sorting_chk->setEnabled(true); - - elements_tab->blockSignals(true); - elements_tab->removeRows(); - elements_tab->blockSignals(false); - - op_class_sel->clearSelector(); - operator_sel->clearSelector(); - elem_expr_txt->clear(); - ascending_rb->setChecked(true); - column_rb->setChecked(true); - - collation_sel->setVisible(false); - collation_lbl->setVisible(false); - operator_sel->setVisible(false); - operator_lbl->setVisible(false); -} - -void ElementsWidget::updateColumnsCombo(void) -{ - Table *table = dynamic_cast
(parent_obj); - Relationship *rel = dynamic_cast(parent_obj); - Column *column=nullptr; - unsigned i, col_count=0; - - try - { - column_cmb->clear(); - column_cmb->setVisible(true); - column_rb->setVisible(true); - - if(table) - { - col_count=table->getColumnCount(); - for(i=0; i < col_count; i++) - { - column=table->getColumn(i); - column_cmb->addItem(column->getName(), - QVariant::fromValue(column)); - } - } - else if(rel) - { - col_count=rel->getAttributeCount(); - for(i=0; i < col_count; i++) - { - column=rel->getAttribute(i); - column_cmb->addItem(column->getName(), - QVariant::fromValue(column)); - } - } - } - catch(Exception &e) - { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); - } -} - -void ElementsWidget::showElementData(IndexElement elem, int elem_idx) -{ - showElementData(&elem, elem_idx); -} - -void ElementsWidget::showElementData(ExcludeElement elem, int elem_idx) -{ - showElementData(&elem, elem_idx); -} - -void ElementsWidget::showElementData(Element *elem, int elem_idx) -{ - IndexElement *idxelem = dynamic_cast(elem); - ExcludeElement *excelem = dynamic_cast(elem); - - if(elem->getColumn()) - { - elements_tab->setCellText(elem->getColumn()->getName(), elem_idx, 0); - elements_tab->setCellText(elem->getColumn()->getTypeName(), elem_idx, 1); - } - else - { - elements_tab->setCellText(elem->getExpression(), elem_idx, 0); - elements_tab->setCellText(trUtf8("Expression"), elem_idx, 1); - } - - elements_tab->clearCellText(elem_idx, 2); - if(idxelem && idxelem->getCollation()) - elements_tab->setCellText(idxelem->getCollation()->getName(true), elem_idx, 2); - else if(excelem && excelem->getOperator()) - elements_tab->setCellText(excelem->getOperator()->getSignature(true), elem_idx, 2); - - elements_tab->clearCellText(elem_idx, 3); - if(elem->getOperatorClass()) - elements_tab->setCellText(elem->getOperatorClass()->getName(true), elem_idx, 3); - - if(elem->isSortingEnabled()) - { - if(elem->getSortingAttribute(IndexElement::ASC_ORDER)) - elements_tab->setCellText(ascending_rb->text(), elem_idx, 4); - else - elements_tab->setCellText(descending_rb->text(), elem_idx, 4); - - if(elem->getSortingAttribute(IndexElement::NULLS_FIRST)) - elements_tab->setCellText(trUtf8("Yes"), elem_idx, 5); - else - elements_tab->setCellText(trUtf8("No"), elem_idx, 5); - } - else - { - elements_tab->clearCellText(elem_idx, 4); - elements_tab->clearCellText(elem_idx, 5); - } - - if(dynamic_cast(elem)) - elements_tab->setRowData(QVariant::fromValue(*dynamic_cast(elem)), elem_idx); - else - elements_tab->setRowData(QVariant::fromValue(*dynamic_cast(elem)), elem_idx); -} - -void ElementsWidget::handleElement(int elem_idx) -{ - if(column_rb->isChecked() || - (expression_rb->isChecked() && !elem_expr_txt->toPlainText().isEmpty())) - { - IndexElement idxelem; - ExcludeElement excelem; - - /* Selects the correct element based upon the visibility of operator - selector (available only for ExcludeElement) */ - Element *elem = (operator_sel->isVisible() ? - dynamic_cast(&excelem) : - dynamic_cast(&idxelem)); - - elem->setSortingEnabled(sorting_chk->isChecked()); - elem->setSortingAttribute(IndexElement::NULLS_FIRST, nulls_first_chk->isChecked()); - elem->setSortingAttribute(IndexElement::ASC_ORDER, ascending_rb->isChecked()); - elem->setOperatorClass(dynamic_cast(op_class_sel->getSelectedObject())); - - if(collation_sel->isVisible()) - idxelem.setCollation(dynamic_cast(collation_sel->getSelectedObject())); - - if(operator_sel->isVisible()) - excelem.setOperator(dynamic_cast(operator_sel->getSelectedObject())); - - if(expression_rb->isChecked()) - elem->setExpression(elem_expr_txt->toPlainText().toUtf8()); - else - elem->setColumn(reinterpret_cast(column_cmb->itemData(column_cmb->currentIndex()).value())); - - showElementData(elem, elem_idx); - - elem_expr_txt->clear(); - ascending_rb->setChecked(true); - sorting_chk->setChecked(true); - op_class_sel->clearSelector(); - operator_sel->clearSelector(); - collation_sel->clearSelector(); - nulls_first_chk->setChecked(false); - } - else if(elements_tab->getCellText(elem_idx,0).isEmpty()) - elements_tab->removeRow(elem_idx); - - emit s_elementHandled(elem_idx); -} - -void ElementsWidget::editElement(int elem_idx) -{ - Element *elem = nullptr; - IndexElement idxelem; - ExcludeElement excelem; - QVariant data = elements_tab->getRowData(elem_idx); - - //If the data is an IndexElement - if(data.canConvert()) - { - idxelem = data.value(); - elem = &idxelem; - } - else - { - excelem = data.value(); - elem = &excelem; - } - - if(elem->getColumn()) - { - column_rb->setChecked(true); - column_cmb->setCurrentIndex(column_cmb->findText(elem->getColumn()->getName())); - } - else - { - expression_rb->setChecked(true); - elem_expr_txt->setPlainText(elem->getExpression()); - } - - if(elem->getSortingAttribute(IndexElement::ASC_ORDER)) - ascending_rb->setChecked(true); - else - descending_rb->setChecked(true); - - nulls_first_chk->setChecked(elem->getSortingAttribute(IndexElement::NULLS_FIRST)); - sorting_chk->setChecked(elem->isSortingEnabled()); - op_class_sel->setSelectedObject(elem->getOperatorClass()); - - //Specific for IndexElement - if(collation_sel->isVisible()) - collation_sel->setSelectedObject(idxelem.getCollation()); - - //Specific for ExcludeElement - if(operator_sel->isVisible()) - operator_sel->setSelectedObject(excelem.getOperator()); -} - -void ElementsWidget::selectElementObject(void) -{ - QObject *obj_sender=sender(); - - column_rb->blockSignals(true); - expression_rb->blockSignals(true); - - if(obj_sender==column_rb) - { - elem_expr_txt->clear(); - column_cmb->setEnabled(true); - expression_rb->setChecked(false); - column_rb->setChecked(true); - elem_expr_txt->setEnabled(false); - } - else - { - column_cmb->setEnabled(false); - column_rb->setChecked(false); - expression_rb->setChecked(true); - elem_expr_txt->setEnabled(true); - } - - column_rb->blockSignals(false); - expression_rb->blockSignals(false); -} - -void ElementsWidget::getElements(vector &elems) -{ - if(elements_tab->getRowCount() > 0) - { - //Confirming if the data on elements table is IndexElement - if(elements_tab->getRowData(0).canConvert()) - { - elems.clear(); - - for(unsigned i=0; i < elements_tab->getRowCount(); i++) - elems.push_back(elements_tab->getRowData(i).value()); - } - } -} - -void ElementsWidget::getElements(vector &elems) -{ - if(elements_tab->getRowCount() > 0) - { - //Confirming if the data on elements table is ExcludeElement - if(elements_tab->getRowData(0).canConvert()) - { - elems.clear(); - - for(unsigned i=0; i < elements_tab->getRowCount(); i++) - elems.push_back(elements_tab->getRowData(i).value()); - } - } -} - diff --git a/libpgmodeler_ui/src/elementwidget.cpp b/libpgmodeler_ui/src/elementwidget.cpp new file mode 100644 index 0000000000..186df506e1 --- /dev/null +++ b/libpgmodeler_ui/src/elementwidget.cpp @@ -0,0 +1,287 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "elementwidget.h" + +ElementWidget::ElementWidget(QWidget *parent) : QWidget(parent) +{ + try + { + map > fields_map; + + warning_frame=nullptr; + element = nullptr; + + setupUi(this); + elem_expr_hl=new SyntaxHighlighter(elem_expr_txt, false, true); + elem_expr_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); + + parent_obj=nullptr; + op_class_sel=new ObjectSelectorWidget(ObjectType::OpClass, true, this); + collation_sel=new ObjectSelectorWidget(ObjectType::Collation, true, this); + operator_sel=new ObjectSelectorWidget(ObjectType::Operator, true, this); + + element_grid->addWidget(collation_sel, 3,1,1,2); + element_grid->addWidget(op_class_sel, 4,1,1,2); + element_grid->addWidget(operator_sel, 5,1,1,2); + + fields_map[BaseObjectWidget::generateVersionsInterval(BaseObjectWidget::AfterVersion, PgSqlVersions::PgSqlVersion91)].push_back(collation_lbl); + warning_frame=BaseObjectWidget::generateVersionWarningFrame(fields_map); + element_grid->addWidget(warning_frame, element_grid->count()+1, 0, 1, 3); + warning_frame->setParent(this); + + connect(column_rb, SIGNAL(toggled(bool)), this, SLOT(selectElementObject(void))); + connect(expression_rb, SIGNAL(toggled(bool)), this, SLOT(selectElementObject(void))); + connect(sorting_chk, SIGNAL(toggled(bool)), ascending_rb, SLOT(setEnabled(bool))); + connect(sorting_chk, SIGNAL(toggled(bool)), descending_rb, SLOT(setEnabled(bool))); + connect(sorting_chk, SIGNAL(toggled(bool)), nulls_first_chk, SLOT(setEnabled(bool))); + + this->setEnabled(false); + collation_sel->setVisible(false); + collation_lbl->setVisible(false); + operator_sel->setVisible(false); + operator_lbl->setVisible(false); + + BaseObjectWidget::setRequiredField(operator_sel); + BaseObjectWidget::setRequiredField(operator_lbl); + + setTabOrder(column_rb, column_cmb); + setTabOrder(column_cmb, expression_rb); + setTabOrder(expression_rb, elem_expr_txt); + setTabOrder(elem_expr_txt, collation_sel); + setTabOrder(collation_sel, collation_sel->rem_object_tb); + setTabOrder(collation_sel->rem_object_tb, collation_sel->sel_object_tb); + setTabOrder(collation_sel->sel_object_tb, op_class_sel); + + setTabOrder(op_class_sel, op_class_sel->rem_object_tb); + setTabOrder(op_class_sel->rem_object_tb, op_class_sel->sel_object_tb); + setTabOrder(op_class_sel->sel_object_tb, sorting_chk); + + setTabOrder(sorting_chk, ascending_rb); + setTabOrder(ascending_rb, descending_rb); + setTabOrder(descending_rb, nulls_first_chk); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +void ElementWidget::setAttributes(DatabaseModel *model, BaseObject *parent_obj, Element *elem) +{ + if(!elem) + this->setEnabled(false); + else + { + IndexElement *idx_elem = dynamic_cast(elem); + ExcludeElement *exc_elem = dynamic_cast(elem); + PartitionKey *part_key = dynamic_cast(elem); + Column *column = elem->getColumn(); + + setAttributes(model, parent_obj); + + if(idx_elem) + setIndexElement(idx_elem); + else if(exc_elem) + setExcludeElement(exc_elem); + else + setPartitionKey(part_key); + + if(parent_obj->getObjectType() == ObjectType::Table && + (column || (!column && elem->getExpression().isEmpty()))) + { + column_rb->setChecked(true); + + if(column) + column_cmb->setCurrentIndex(column_cmb->findText(column->getName())); + } + else + { + expression_rb->setChecked(true); + elem_expr_txt->setPlainText(elem->getExpression()); + } + + if(elem->getSortingAttribute(IndexElement::AscOrder)) + ascending_rb->setChecked(true); + else + descending_rb->setChecked(true); + + nulls_first_chk->setChecked(elem->getSortingAttribute(IndexElement::NullsFirst)); + sorting_chk->setChecked(elem->isSortingEnabled()); + op_class_sel->setSelectedObject(elem->getOperatorClass()); + collation_sel->setSelectedObject(elem->getCollation()); + operator_sel->setSelectedObject(elem->getOperator()); + } +} + +void ElementWidget::setAttributes(DatabaseModel *model, BaseObject *parent_obj) +{ + if(!model || !parent_obj) + { + this->setEnabled(false); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + else if(parent_obj->getObjectType()!=ObjectType::Table && + parent_obj->getObjectType()!=ObjectType::View && + parent_obj->getObjectType()!=ObjectType::Relationship) + throw Exception(ErrorCode::OprObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + this->setEnabled(true); + this->parent_obj=parent_obj; + + op_class_sel->setModel(model); + collation_sel->setModel(model); + operator_sel->setModel(model); + + cols_combo_parent->setVisible(parent_obj->getObjectType() == ObjectType::Table); + column_rb->setVisible(parent_obj->getObjectType() == ObjectType::Table); + expression_rb->setChecked(parent_obj->getObjectType() == ObjectType::View); + + if(parent_obj->getObjectType() == ObjectType::Table) + updateColumnsCombo(); +} + +void ElementWidget::setIndexElement(IndexElement *elem) +{ + createElement(elem); + setWindowTitle(trUtf8("Index element properties")); + collation_sel->setVisible(true); + collation_lbl->setVisible(true); + warning_frame->setVisible(true); +} + +void ElementWidget::setExcludeElement(ExcludeElement *elem) +{ + createElement(elem); + setWindowTitle(trUtf8("Exclude element properties")); + operator_sel->setVisible(true); + operator_lbl->setVisible(true); + warning_frame->setVisible(false); +} + +void ElementWidget::setPartitionKey(PartitionKey *elem) +{ + createElement(elem); + setWindowTitle(trUtf8("Partition key properties")); + collation_sel->setVisible(true); + collation_lbl->setVisible(true); + sorting_chk->setVisible(false); + ascending_rb->setVisible(false); + descending_rb->setVisible(false); + nulls_first_chk->setVisible(false); + warning_frame->setVisible(true); +} + +Element *ElementWidget::getElement(void) +{ + return(element); +} + +void ElementWidget::applyConfiguration(void) +{ + element->setSortingEnabled(sorting_chk->isChecked()); + element->setSortingAttribute(IndexElement::NullsFirst, nulls_first_chk->isChecked()); + element->setSortingAttribute(IndexElement::AscOrder, ascending_rb->isChecked()); + element->setOperatorClass(dynamic_cast(op_class_sel->getSelectedObject())); + element->setCollation(dynamic_cast(collation_sel->getSelectedObject())); + element->setOperator(dynamic_cast(operator_sel->getSelectedObject())); + + if(expression_rb->isChecked()) + element->setExpression(elem_expr_txt->toPlainText().toUtf8()); + else + element->setColumn(reinterpret_cast(column_cmb->itemData(column_cmb->currentIndex()).value())); +} + +void ElementWidget::updateColumnsCombo(void) +{ + Table *table = dynamic_cast
(parent_obj); + Relationship *rel = dynamic_cast(parent_obj); + Column *column=nullptr; + unsigned i, col_count=0; + + try + { + column_cmb->clear(); + column_cmb->setVisible(true); + column_rb->setVisible(true); + + if(table) + { + col_count=table->getColumnCount(); + for(i=0; i < col_count; i++) + { + column=table->getColumn(i); + column_cmb->addItem(column->getName(), + QVariant::fromValue(column)); + } + } + else if(rel) + { + col_count=rel->getAttributeCount(); + for(i=0; i < col_count; i++) + { + column=rel->getAttribute(i); + column_cmb->addItem(column->getName(), + QVariant::fromValue(column)); + } + } + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +void ElementWidget::selectElementObject(void) +{ + QObject *obj_sender=sender(); + + column_rb->blockSignals(true); + expression_rb->blockSignals(true); + + if(obj_sender==column_rb) + { + elem_expr_txt->clear(); + column_cmb->setEnabled(true); + expression_rb->setChecked(false); + column_rb->setChecked(true); + elem_expr_txt->setEnabled(false); + } + else + { + column_cmb->setEnabled(false); + column_rb->setChecked(false); + expression_rb->setChecked(true); + elem_expr_txt->setEnabled(true); + } + + column_rb->blockSignals(false); + expression_rb->blockSignals(false); +} + +template +void ElementWidget::createElement(Class *elem) +{ + if(element && !dynamic_cast(element)) + delete(element); + + if(!element) + element = new Class; + + *element = *elem; +} diff --git a/libpgmodeler_ui/src/elementswidget.h b/libpgmodeler_ui/src/elementwidget.h similarity index 56% rename from libpgmodeler_ui/src/elementswidget.h rename to libpgmodeler_ui/src/elementwidget.h index a14045141d..e51093b97d 100644 --- a/libpgmodeler_ui/src/elementswidget.h +++ b/libpgmodeler_ui/src/elementwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -19,35 +19,31 @@ /** \ingroup libpgmodeler_ui \class ElementWidget -\brief Implements the operations to create/edit constraints (exclude) and indexes elements via form. +\brief Implements the operations to create/edit constraints (exclude) and indexes elements, and partition keys via form. */ #ifndef ELEMENT_WIDGET_H #define ELEMENT_WIDGET_H #include -#include "ui_elementswidget.h" +#include "ui_elementwidget.h" #include "objectstablewidget.h" #include "objectselectorwidget.h" -#include "baseobjectwidget.h" +#include "partitionkey.h" -/* Declaring the IndexElement and ExcludeElement class as a Qt metatype in order to permit - that instances of the class be used as data of QVariant and QMetaType */ -#include -Q_DECLARE_METATYPE(IndexElement) -Q_DECLARE_METATYPE(ExcludeElement) - -class ElementsWidget: public QWidget, public Ui::ElementsWidget { +class ElementWidget: public QWidget, public Ui::ElementWidget { private: Q_OBJECT + + QFrame *warning_frame; + + Element *element; + //! \brief Parent object (table or relationship) from which the columns will be referenced on the elements BaseObject *parent_obj; //! \brief Syntax highlighter for element expression - SyntaxHighlighter *elem_expr_hl; - - //! \brief Table widget used to control the index elements - ObjectsTableWidget *elements_tab; + SyntaxHighlighter *elem_expr_hl; //! \brief Operator class selector ObjectSelectorWidget *op_class_sel, @@ -61,37 +57,35 @@ class ElementsWidget: public QWidget, public Ui::ElementsWidget { //! \brief Updates the column combobox with the existent columns on parent table void updateColumnsCombo(void); - //! \brief Shows the element data on the elements table at the specified line - void showElementData(Element *elem, int elem_idx); - void showElementData(IndexElement elem, int elem_idx); - void showElementData(ExcludeElement elem, int elem_idx); void setAttributes(DatabaseModel *model, BaseObject *parent_obj); - - public: - ElementsWidget(QWidget *parent = 0); - + //! \brief Enables the widget to handle index elements - void setAttributes(DatabaseModel *model, BaseTable *table, vector &elems); - + void setIndexElement(IndexElement *elem); + //! \brief Enables the widget to handle exclude constraint elements - void setAttributes(DatabaseModel *model, BaseObject *parent_obj, vector &elems); - - //! \brief Copy the current elements into the list - void getElements(vector &elems); + void setExcludeElement(ExcludeElement *elem); + + //! \brief Enables the widget to handle partition key elements + void setPartitionKey(PartitionKey *elem); + + //! \brief Allocates the handled element based upon the provided Class (should be child of Element) + template + void createElement(Class *elem); - //! \brief Copy the current elements into the list - void getElements(vector &elems); + public: + ElementWidget(QWidget *parent = nullptr); + //! \brief Configures the widget to handle the element considering its type (IndexElement, ExcludeElement, PartitionKey) + void setAttributes(DatabaseModel *model, BaseObject *parent_obj, Element *elem); + + //! \brief Returns the configured element + Element *getElement(void); + public slots: - void clear(void); - + void applyConfiguration(void); + private slots: void selectElementObject(void); - void handleElement(int elem_idx); - void editElement(int elem_idx); - - signals: - void s_elementHandled(int elem_idx); }; #endif diff --git a/libpgmodeler_ui/src/eventtriggerwidget.cpp b/libpgmodeler_ui/src/eventtriggerwidget.cpp index 5286c6c496..4fa8e17d4b 100644 --- a/libpgmodeler_ui/src/eventtriggerwidget.cpp +++ b/libpgmodeler_ui/src/eventtriggerwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "eventtriggerwidget.h" -EventTriggerWidget::EventTriggerWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_EVENT_TRIGGER) +EventTriggerWidget::EventTriggerWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::EventTrigger) { map > fields_map; map > values_map; @@ -26,24 +26,24 @@ EventTriggerWidget::EventTriggerWidget(QWidget *parent): BaseObjectWidget(parent Ui_EventTriggerWidget::setupUi(this); - function_sel=new ObjectSelectorWidget(OBJ_FUNCTION, true, this); - filter_tab=new ObjectsTableWidget(ObjectsTableWidget::ADD_BUTTON | - ObjectsTableWidget::EDIT_BUTTON | - ObjectsTableWidget::UPDATE_BUTTON | - ObjectsTableWidget::REMOVE_BUTTON | - ObjectsTableWidget::REMOVE_ALL_BUTTON | - ObjectsTableWidget::MOVE_BUTTONS, false, this); + function_sel=new ObjectSelectorWidget(ObjectType::Function, true, this); + filter_tab=new ObjectsTableWidget(ObjectsTableWidget::AddButton | + ObjectsTableWidget::EditButton | + ObjectsTableWidget::UpdateButton | + ObjectsTableWidget::RemoveButton | + ObjectsTableWidget::RemoveAllButton | + ObjectsTableWidget::MoveButtons, false, this); filter_tab->setColumnCount(1); filter_tab->setHeaderLabel(trUtf8("Tag command"), 0); eventtrigger_grid->addWidget(function_sel, 1, 1); filter_layout->addWidget(filter_tab); - configureFormLayout(eventtrigger_grid, OBJ_EVENT_TRIGGER); + configureFormLayout(eventtrigger_grid, ObjectType::EventTrigger); setRequiredField(function_lbl); - fields_map[BaseObjectWidget::generateVersionsInterval(BaseObjectWidget::AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_95)].push_back(event_lbl); - values_map[event_lbl].push_back(~EventTriggerType(EventTriggerType::table_rewrite)); + fields_map[BaseObjectWidget::generateVersionsInterval(BaseObjectWidget::AfterVersion, PgSqlVersions::PgSqlVersion95)].push_back(event_lbl); + values_map[event_lbl].push_back(~EventTriggerType(EventTriggerType::TableRewrite)); frame=BaseObjectWidget::generateVersionWarningFrame(fields_map, &values_map); frame->setParent(this); @@ -59,15 +59,15 @@ EventTriggerWidget::EventTriggerWidget(QWidget *parent): BaseObjectWidget(parent connect(filter_tab, SIGNAL(s_rowUpdated(int)), this, SLOT(handleTagValue(int))); connect(filter_tab, &ObjectsTableWidget::s_rowsRemoved, - [&](){ filter_tab->setButtonsEnabled(ObjectsTableWidget::ADD_BUTTON, false); }); + [&](){ filter_tab->setButtonsEnabled(ObjectsTableWidget::AddButton, false); }); connect(filter_tab, &ObjectsTableWidget::s_rowEdited, [&](int row){ tag_edt->setText(filter_tab->getCellText(row, 0)); }); connect(tag_edt, &QLineEdit::textChanged, [&](){ - filter_tab->setButtonsEnabled(ObjectsTableWidget::ADD_BUTTON, !tag_edt->text().isEmpty()); - filter_tab->setButtonsEnabled(ObjectsTableWidget::UPDATE_BUTTON, !tag_edt->text().isEmpty()); + filter_tab->setButtonsEnabled(ObjectsTableWidget::AddButton, !tag_edt->text().isEmpty()); + filter_tab->setButtonsEnabled(ObjectsTableWidget::UpdateButton, !tag_edt->text().isEmpty()); }); setMinimumSize(500, 440); @@ -83,10 +83,10 @@ void EventTriggerWidget::setAttributes(DatabaseModel *model, OperationList *op_l event_cmb->setCurrentText(~event_trig->getEvent()); function_sel->setSelectedObject(event_trig->getFunction()); - QStringList filter=event_trig->getFilter(ParsersAttributes::TAG.toUpper()); + QStringList filter=event_trig->getFilter(Attributes::Tag.toUpper()); if(filter.isEmpty()) - filter=event_trig->getFilter(ParsersAttributes::TAG); + filter=event_trig->getFilter(Attributes::Tag); filter_tab->blockSignals(true); @@ -100,7 +100,7 @@ void EventTriggerWidget::setAttributes(DatabaseModel *model, OperationList *op_l filter_tab->clearSelection(); } - filter_tab->setButtonsEnabled(ObjectsTableWidget::ADD_BUTTON, false); + filter_tab->setButtonsEnabled(ObjectsTableWidget::AddButton, false); } void EventTriggerWidget::applyConfiguration(void) @@ -118,14 +118,14 @@ void EventTriggerWidget::applyConfiguration(void) event_trig->clearFilter(); for(unsigned row=0; row < filter_tab->getRowCount(); row++) - event_trig->setFilter(ParsersAttributes::TAG.toUpper(), filter_tab->getCellText(row, 0)); + event_trig->setFilter(Attributes::Tag.toUpper(), filter_tab->getCellText(row, 0)); finishConfiguration(); } catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -136,7 +136,7 @@ void EventTriggerWidget::handleTagValue(int row) filter_tab->setCellText(tag_edt->text().simplified(), row, 0); tag_edt->clear(); filter_tab->clearSelection(); - filter_tab->setButtonsEnabled(ObjectsTableWidget::ADD_BUTTON, false); + filter_tab->setButtonsEnabled(ObjectsTableWidget::AddButton, false); } else if(filter_tab->getCellText(row, 0).isEmpty()) filter_tab->removeRow(row); diff --git a/libpgmodeler_ui/src/eventtriggerwidget.h b/libpgmodeler_ui/src/eventtriggerwidget.h index b6dfb1e41c..09094a4284 100644 --- a/libpgmodeler_ui/src/eventtriggerwidget.h +++ b/libpgmodeler_ui/src/eventtriggerwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -38,7 +38,7 @@ class EventTriggerWidget: public BaseObjectWidget, public Ui::EventTriggerWidget ObjectSelectorWidget *function_sel; public: - EventTriggerWidget(QWidget * parent = 0); + EventTriggerWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, EventTrigger *event_trig); public slots: diff --git a/libpgmodeler_ui/src/extensionwidget.cpp b/libpgmodeler_ui/src/extensionwidget.cpp index 80de47971c..969acf99c3 100644 --- a/libpgmodeler_ui/src/extensionwidget.cpp +++ b/libpgmodeler_ui/src/extensionwidget.cpp @@ -1,9 +1,9 @@ #include "extensionwidget.h" -ExtensionWidget::ExtensionWidget(QWidget * parent) : BaseObjectWidget(parent, OBJ_EXTENSION) +ExtensionWidget::ExtensionWidget(QWidget * parent) : BaseObjectWidget(parent, ObjectType::Extension) { Ui_ExtensionWidget::setupUi(this); - configureFormLayout(extension_grid, OBJ_EXTENSION); + configureFormLayout(extension_grid, ObjectType::Extension); extension_grid->addItem(new QSpacerItem(10,10,QSizePolicy::Minimum,QSizePolicy::Expanding), extension_grid->count()+1, 0, 1, 0); configureTabOrder({ cur_ver_edt, old_ver_edt, handles_type_chk }); @@ -17,8 +17,8 @@ void ExtensionWidget::setAttributes(DatabaseModel *model, OperationList *op_list if(ext) { - cur_ver_edt->setText(ext->getVersion(Extension::CUR_VERSION)); - old_ver_edt->setText(ext->getVersion(Extension::OLD_VERSION)); + cur_ver_edt->setText(ext->getVersion(Extension::CurVersion)); + old_ver_edt->setText(ext->getVersion(Extension::OldVersion)); handles_type_chk->setEnabled(false); handles_type_chk->setChecked(ext->handlesType()); @@ -35,14 +35,14 @@ void ExtensionWidget::applyConfiguration(void) extension=dynamic_cast(this->object); BaseObjectWidget::applyConfiguration(); extension->setHandlesType(handles_type_chk->isChecked()); - extension->setVersion(Extension::CUR_VERSION, cur_ver_edt->text()); - extension->setVersion(Extension::OLD_VERSION, old_ver_edt->text()); + extension->setVersion(Extension::CurVersion, cur_ver_edt->text()); + extension->setVersion(Extension::OldVersion, old_ver_edt->text()); finishConfiguration(); } catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/extensionwidget.h b/libpgmodeler_ui/src/extensionwidget.h index a665234e34..1f42fec4ac 100644 --- a/libpgmodeler_ui/src/extensionwidget.h +++ b/libpgmodeler_ui/src/extensionwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -33,7 +33,7 @@ class ExtensionWidget: public BaseObjectWidget, public Ui::ExtensionWidget { Q_OBJECT public: - ExtensionWidget(QWidget * parent = 0); + ExtensionWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, Extension *ext); diff --git a/libpgmodeler_ui/src/findreplacewidget.cpp b/libpgmodeler_ui/src/findreplacewidget.cpp index 25726970ee..42ebafb815 100644 --- a/libpgmodeler_ui/src/findreplacewidget.cpp +++ b/libpgmodeler_ui/src/findreplacewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -21,7 +21,7 @@ FindReplaceWidget::FindReplaceWidget(QPlainTextEdit *txt_edit, QWidget *parent): QWidget(parent) { if(!txt_edit) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); setupUi(this); text_edt=txt_edit; diff --git a/libpgmodeler_ui/src/findreplacewidget.h b/libpgmodeler_ui/src/findreplacewidget.h index 1c5fbcd17c..9571e98833 100644 --- a/libpgmodeler_ui/src/findreplacewidget.h +++ b/libpgmodeler_ui/src/findreplacewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -45,7 +45,7 @@ class FindReplaceWidget: public QWidget, public Ui::FindReplaceWidget { void showEvent(QShowEvent *); public: - FindReplaceWidget(QPlainTextEdit *txt_edit, QWidget * parent = 0); + FindReplaceWidget(QPlainTextEdit *txt_edit, QWidget * parent = nullptr); public slots: void replaceText(void); diff --git a/libpgmodeler_ui/src/foreigndatawrapperwidget.cpp b/libpgmodeler_ui/src/foreigndatawrapperwidget.cpp new file mode 100644 index 0000000000..6387e9585c --- /dev/null +++ b/libpgmodeler_ui/src/foreigndatawrapperwidget.cpp @@ -0,0 +1,128 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "foreigndatawrapperwidget.h" + +ForeignDataWrapperWidget::ForeignDataWrapperWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::ForeignDataWrapper) +{ + try + { + QHBoxLayout *hbox = nullptr; + + Ui_ForeignDataWrapperWidget::setupUi(this); + + func_handler_sel=nullptr; + func_validator_sel=nullptr; + + func_handler_ht = new HintTextWidget(func_handler_hint, this); + func_handler_ht->setText(trUtf8("The handler function must have the following signature: fdw_handler function_name()")); + + func_validator_ht = new HintTextWidget(func_validator_hint, this); + func_validator_ht->setText(trUtf8("The validator function must have the following signature: function_name(text[],oid). The return type of ths function is ignored.")); + + func_handler_sel=new ObjectSelectorWidget(ObjectType::Function, true, this); + func_validator_sel=new ObjectSelectorWidget(ObjectType::Function, true, this); + + hbox = new QHBoxLayout; + hbox->setContentsMargins(0,0,0,0); + hbox->addWidget(func_handler_sel); + func_handler_wgt->setLayout(hbox); + + hbox = new QHBoxLayout; + hbox->setContentsMargins(0,0,0,0); + hbox->addWidget(func_validator_sel); + func_validator_wgt->setLayout(hbox); + + options_tab = new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + (ObjectsTableWidget::EditButton | ObjectsTableWidget::UpdateButton), true, this); + options_tab->setCellsEditable(true); + options_tab->setColumnCount(2); + options_tab->setHeaderLabel(trUtf8("Option"), 0); + options_tab->setHeaderLabel(trUtf8("Value"), 1); + + hbox = new QHBoxLayout; + hbox->setContentsMargins(4,4,4,4); + hbox->addWidget(options_tab); + options_gb->setLayout(hbox); + + configureFormLayout(fdw_grid, ObjectType::ForeignDataWrapper); + + configureTabOrder({ func_handler_sel, func_handler_ht, + func_validator_sel, func_validator_ht, + options_tab }); + + setMinimumSize(600, 420); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +void ForeignDataWrapperWidget::setAttributes(DatabaseModel *model, OperationList *op_list, ForeignDataWrapper *fdw) +{ + BaseObjectWidget::setAttributes(model, op_list, fdw); + + func_handler_sel->setModel(model); + func_validator_sel->setModel(model); + + if(fdw) + { + func_handler_sel->setSelectedObject(fdw->getHandlerFunction()); + func_validator_sel->setSelectedObject(fdw->getValidatorFunction()); + + options_tab->blockSignals(true); + + for(auto &itr : fdw->getOptions()) + { + options_tab->addRow(); + options_tab->setCellText(itr.first, options_tab->getRowCount() - 1, 0); + options_tab->setCellText(itr.second, options_tab->getRowCount() - 1, 1); + } + + options_tab->clearSelection(); + options_tab->blockSignals(false); + } +} + +void ForeignDataWrapperWidget::applyConfiguration(void) +{ + try + { + ForeignDataWrapper *fdw=nullptr; + + startConfiguration(); + + fdw=dynamic_cast(this->object); + fdw->setHandlerFunction(dynamic_cast(func_handler_sel->getSelectedObject())); + fdw->setValidatorFunction(dynamic_cast(func_validator_sel->getSelectedObject())); + + fdw->removeOptions(); + for(unsigned row = 0; row < options_tab->getRowCount(); row++) + fdw->setOption(options_tab->getCellText(row, 0), options_tab->getCellText(row, 1)); + + BaseObjectWidget::applyConfiguration(); + finishConfiguration(); + } + catch(Exception &e) + { + cancelConfiguration(); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + diff --git a/libpgmodeler_ui/src/foreigndatawrapperwidget.h b/libpgmodeler_ui/src/foreigndatawrapperwidget.h new file mode 100644 index 0000000000..182de72449 --- /dev/null +++ b/libpgmodeler_ui/src/foreigndatawrapperwidget.h @@ -0,0 +1,53 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +/** +\ingroup libpgmodeler_ui +\class ForeignDataWrapperWidget +\brief Implements the operations to create/edit foreign data wrappers via form. +*/ + +#ifndef FOREIGN_DATA_WRAPPER_WIDGET_H +#define FOREIGN_DATA_WRAPPER_WIDGET_H + +#include "baseobjectwidget.h" +#include "ui_foreigndatawrapperwidget.h" +#include "hinttextwidget.h" +#include "objectstablewidget.h" + +class ForeignDataWrapperWidget: public BaseObjectWidget, public Ui::ForeignDataWrapperWidget { + private: + Q_OBJECT + + ObjectSelectorWidget *func_handler_sel, + *func_validator_sel; + + HintTextWidget *func_handler_ht, + *func_validator_ht; + + ObjectsTableWidget *options_tab; + + public: + ForeignDataWrapperWidget(QWidget * parent = nullptr); + void setAttributes(DatabaseModel *model, OperationList *op_list, ForeignDataWrapper *fdw); + + public slots: + void applyConfiguration(void); +}; + +#endif diff --git a/libpgmodeler_ui/src/foreignserverwidget.cpp b/libpgmodeler_ui/src/foreignserverwidget.cpp new file mode 100644 index 0000000000..4940e32047 --- /dev/null +++ b/libpgmodeler_ui/src/foreignserverwidget.cpp @@ -0,0 +1,115 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "foreignserverwidget.h" + +ForeignServerWidget::ForeignServerWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::ForeignServer) +{ + try + { + QHBoxLayout *hbox = nullptr; + + Ui_ForeignServerWidget::setupUi(this); + + fdw_sel=nullptr; + fdw_sel=new ObjectSelectorWidget(ObjectType::ForeignDataWrapper, true, this); + + hbox = new QHBoxLayout; + hbox->setContentsMargins(0,0,0,0); + hbox->addWidget(fdw_sel); + fdw_wgt->setLayout(hbox); + + options_tab = new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + (ObjectsTableWidget::EditButton | ObjectsTableWidget::UpdateButton), true, this); + options_tab->setCellsEditable(true); + options_tab->setColumnCount(2); + options_tab->setHeaderLabel(trUtf8("Option"), 0); + options_tab->setHeaderLabel(trUtf8("Value"), 1); + + hbox = new QHBoxLayout; + hbox->setContentsMargins(4,4,4,4); + hbox->addWidget(options_tab); + options_gb->setLayout(hbox); + + configureFormLayout(server_grid, ObjectType::ForeignServer); + + setRequiredField(fdw_sel); + setRequiredField(fdw_lbl); + configureTabOrder({ type_edt, version_edt, fdw_sel, options_tab }); + + setMinimumSize(600, 420); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +void ForeignServerWidget::setAttributes(DatabaseModel *model, OperationList *op_list, ForeignServer *server) +{ + BaseObjectWidget::setAttributes(model, op_list, server); + + fdw_sel->setModel(model); + + if(server) + { + version_edt->setText(server->getVersion()); + type_edt->setText(server->getType()); + fdw_sel->setSelectedObject(server->getForeignDataWrapper()); + options_tab->blockSignals(true); + + for(auto &itr : server->getOptions()) + { + options_tab->addRow(); + options_tab->setCellText(itr.first, options_tab->getRowCount() - 1, 0); + options_tab->setCellText(itr.second, options_tab->getRowCount() - 1, 1); + } + + options_tab->clearSelection(); + options_tab->blockSignals(false); + } +} + +void ForeignServerWidget::applyConfiguration(void) +{ + try + { + ForeignServer *server = nullptr; + + startConfiguration(); + + server = dynamic_cast(this->object); + server->setForeignDataWrapper(dynamic_cast(fdw_sel->getSelectedObject())); + + server->removeOptions(); + for(unsigned row = 0; row < options_tab->getRowCount(); row++) + server->setOption(options_tab->getCellText(row, 0), options_tab->getCellText(row, 1)); + + server->setVersion(version_edt->text()); + server->setType(type_edt->text()); + + BaseObjectWidget::applyConfiguration(); + finishConfiguration(); + } + catch(Exception &e) + { + cancelConfiguration(); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + diff --git a/libpgmodeler_ui/src/foreignserverwidget.h b/libpgmodeler_ui/src/foreignserverwidget.h new file mode 100644 index 0000000000..08232b46eb --- /dev/null +++ b/libpgmodeler_ui/src/foreignserverwidget.h @@ -0,0 +1,48 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +/** +\ingroup libpgmodeler_ui +\class ForeignServerWidget +\brief Implements the operations to create/edit foreign servers via form. +*/ + +#ifndef FOREIGN_SERVER_WIDGET_H +#define FOREIGN_SERVER_WIDGET_H + +#include "baseobjectwidget.h" +#include "ui_foreignserverwidget.h" +#include "objectstablewidget.h" + +class ForeignServerWidget: public BaseObjectWidget, public Ui::ForeignServerWidget { + private: + Q_OBJECT + + ObjectSelectorWidget *fdw_sel; + + ObjectsTableWidget *options_tab; + + public: + ForeignServerWidget(QWidget * parent = nullptr); + void setAttributes(DatabaseModel *model, OperationList *op_list, ForeignServer *server); + + public slots: + void applyConfiguration(void); +}; + +#endif diff --git a/libpgmodeler_ui/src/functionwidget.cpp b/libpgmodeler_ui/src/functionwidget.cpp index 329a66c001..1ea0bff99c 100644 --- a/libpgmodeler_ui/src/functionwidget.cpp +++ b/libpgmodeler_ui/src/functionwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -19,7 +19,7 @@ #include "functionwidget.h" #include "baseform.h" -FunctionWidget::FunctionWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_FUNCTION) +FunctionWidget::FunctionWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Function) { try { @@ -34,7 +34,7 @@ FunctionWidget::FunctionWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_FU Ui_FunctionWidget::setupUi(this); - configureFormLayout(function_grid, OBJ_FUNCTION); + configureFormLayout(function_grid, ObjectType::Function); source_code_txt=new NumberedTextEditor(this, true); dynamic_cast(source_code_frm->layout())->addWidget(source_code_txt, 1, 0, 1, 2); @@ -47,21 +47,21 @@ FunctionWidget::FunctionWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_FU vlayout->addWidget(ret_type); vlayout->addSpacerItem(spacer); - return_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ - ObjectsTableWidget::UPDATE_BUTTON, true, this); + return_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + ObjectsTableWidget::UpdateButton, true, this); return_tab->setColumnCount(2); return_tab->setHeaderLabel(trUtf8("Column"), 0); - return_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("column")),0); + return_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("column")),0); return_tab->setHeaderLabel(trUtf8("Type"), 1); - return_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("usertype")),1); + return_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("usertype")),1); - parameters_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ - ObjectsTableWidget::UPDATE_BUTTON, true, this); + parameters_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + ObjectsTableWidget::UpdateButton, true, this); parameters_tab->setColumnCount(4); parameters_tab->setHeaderLabel(trUtf8("Name"),0); - parameters_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("parameter")),0); + parameters_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("parameter")),0); parameters_tab->setHeaderLabel(trUtf8("Type"),1); - parameters_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("usertype")),1); + parameters_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("usertype")),1); parameters_tab->setHeaderLabel(trUtf8("Mode"),2); parameters_tab->setHeaderLabel(trUtf8("Default Value"),3); @@ -80,7 +80,7 @@ FunctionWidget::FunctionWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_FU ret_table_gb->setLayout(grid1); ret_table_gb->setVisible(false); - fields_map[generateVersionsInterval(AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_92)].push_back(leakproof_chk); + fields_map[generateVersionsInterval(AfterVersion, PgSqlVersions::PgSqlVersion92)].push_back(leakproof_chk); frame=generateVersionWarningFrame(fields_map, &value_map); grid->addWidget(frame, grid->count()+1, 0, 1, 5); frame->setParent(func_config_twg->widget(0)); @@ -118,7 +118,7 @@ FunctionWidget::FunctionWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_FU } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -212,7 +212,7 @@ Parameter FunctionWidget::getParameter(ObjectsTableWidget *tab, unsigned row) try { param.setName(tab->getCellText(row,0)); - param.setType(tab->getRowData(row).value()); + param.setType(tab->getRowData(row).value()); if(tab==parameters_tab) { @@ -225,7 +225,7 @@ Parameter FunctionWidget::getParameter(ObjectsTableWidget *tab, unsigned row) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -240,7 +240,7 @@ void FunctionWidget::showParameterData(Parameter param, ObjectsTableWidget *tab, tab->setCellText(param.getName(),row,0); tab->setCellText(*param.getType(),row,1); - tab->setRowData(QVariant::fromValue(param.getType()), row); + tab->setRowData(QVariant::fromValue(param.getType()), row); if(tab==parameters_tab) { @@ -265,10 +265,10 @@ void FunctionWidget::setAttributes(DatabaseModel *model, OperationList *op_list, QStringList list; unsigned count=0, i; Parameter param; - PgSQLType aux_type; + PgSqlType aux_type; BaseObjectWidget::setAttributes(model, op_list, func, schema); - languages=model->getObjects(OBJ_LANGUAGE); + languages=model->getObjects(ObjectType::Language); while(!languages.empty()) { @@ -279,7 +279,7 @@ void FunctionWidget::setAttributes(DatabaseModel *model, OperationList *op_list, list.sort(); language_cmb->addItems(list); - language_cmb->setCurrentText(~LanguageType(LanguageType::sql)); + language_cmb->setCurrentText(~LanguageType(LanguageType::Sql)); if(func) { @@ -358,7 +358,7 @@ void FunctionWidget::selectLanguage(void) { bool c_lang; - c_lang=(language_cmb->currentText()==~LanguageType(LanguageType::c)); + c_lang=(language_cmb->currentText()==~LanguageType(LanguageType::C)); source_code_frm->setVisible(!c_lang); library_frm->setVisible(c_lang); @@ -366,15 +366,15 @@ void FunctionWidget::selectLanguage(void) { try { - source_code_hl->loadConfiguration(GlobalAttributes::CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + + source_code_hl->loadConfiguration(GlobalAttributes::ConfigurationsDir + + GlobalAttributes::DirSeparator + language_cmb->currentText() + - GlobalAttributes::HIGHLIGHT_FILE_SUF + - GlobalAttributes::CONFIGURATION_EXT); + GlobalAttributes::HighlightFileSuffix + + GlobalAttributes::ConfigurationExt); } catch(Exception &) { - source_code_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + source_code_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); } source_code_hl->rehighlight(); @@ -420,62 +420,62 @@ void FunctionWidget::validateConfiguredFunction(void) If the function is invalid the instances raises exceptions accusing the error that is enough to check the validity of the function in relation to objects that reference it. */ - if(obj_type==OBJ_CONVERSION) + if(obj_type==ObjectType::Conversion) { conv=dynamic_cast(object); if(conv->getConversionFunction()==func) conv->setConversionFunction(func); } - else if(obj_type==OBJ_CAST) + else if(obj_type==ObjectType::Cast) { cast=dynamic_cast(object); if(cast->getCastFunction()==func) cast->setCastFunction(func); } - else if(obj_type==OBJ_AGGREGATE) + else if(obj_type==ObjectType::Aggregate) { aggr=dynamic_cast(object); - if(aggr->getFunction(Aggregate::FINAL_FUNC)==func) - aggr->setFunction(Aggregate::FINAL_FUNC, func); - else if(aggr->getFunction(Aggregate::TRANSITION_FUNC)==func) - aggr->setFunction(Aggregate::TRANSITION_FUNC, func); + if(aggr->getFunction(Aggregate::FinalFunc)==func) + aggr->setFunction(Aggregate::FinalFunc, func); + else if(aggr->getFunction(Aggregate::TransitionFunc)==func) + aggr->setFunction(Aggregate::TransitionFunc, func); } - else if(obj_type==OBJ_TRIGGER) + else if(obj_type==ObjectType::Trigger) { dynamic_cast(object)->setFunction(func); } - else if(obj_type==OBJ_LANGUAGE) + else if(obj_type==ObjectType::Language) { lang=dynamic_cast(object); - for(i1=Language::VALIDATOR_FUNC; i1 <= Language::INLINE_FUNC; i1++) + for(i1=Language::ValidatorFunc; i1 <= Language::InlineFunc; i1++) { if(lang->getFunction(i1)==func) lang->setFunction(func, i1); } } - else if(obj_type==OBJ_OPERATOR) + else if(obj_type==ObjectType::Operator) { oper=dynamic_cast(object); - for(i1=Operator::FUNC_OPERATOR; i1 <= Operator::FUNC_RESTRICT; i1++) + for(i1=Operator::FuncOperator; i1 <= Operator::FuncRestrict; i1++) { if(oper->getFunction(i1)==func) oper->setFunction(func, i1); } } - else if(obj_type==OBJ_TYPE) + else if(obj_type==ObjectType::Type) { type=dynamic_cast(object); - if(type->getConfiguration()==Type::BASE_TYPE) + if(type->getConfiguration()==Type::BaseType) { - for(i1=Type::INPUT_FUNC; i1 <=Type::ANALYZE_FUNC; i1++) + for(i1=Type::InputFunc; i1 <=Type::AnalyzeFunc; i1++) { if(type->getFunction(i1)==func) type->setFunction(i1, func); } } } - else if(obj_type==OBJ_EVENT_TRIGGER) + else if(obj_type==ObjectType::EventTrigger) { dynamic_cast(object)->setFunction(func); } @@ -483,10 +483,10 @@ void FunctionWidget::validateConfiguredFunction(void) } catch(Exception &e) { - throw Exception(Exception::getErrorMessage(ERR_FUNC_CONFIG_INV_OBJECT) + throw Exception(Exception::getErrorMessage(ErrorCode::InvFuncConfigInvalidatesObject) .arg(object->getName(true)) .arg(object->getTypeName()), - ERR_FUNC_CONFIG_INV_OBJECT, + ErrorCode::InvFuncConfigInvalidatesObject, __PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -504,7 +504,7 @@ void FunctionWidget::applyConfiguration(void) startConfiguration(); func=dynamic_cast(this->object); - func->setLanguage(model->getObject(language_cmb->currentText(), OBJ_LANGUAGE)); + func->setLanguage(model->getObject(language_cmb->currentText(), ObjectType::Language)); func->setFunctionType(func_type_cmb->currentText()); func->setWindowFunction(window_func_chk->isChecked()); func->setLeakProof(leakproof_chk->isChecked()); @@ -519,7 +519,7 @@ void FunctionWidget::applyConfiguration(void) for(i=0; i < count; i++) { param.setName(parameters_tab->getCellText(i,0)); - param.setType(parameters_tab->getRowData(i).value()); + param.setType(parameters_tab->getRowData(i).value()); str_aux=parameters_tab->getCellText(i,2); param.setIn(str_aux.indexOf(QString("IN")) >= 0); @@ -532,7 +532,7 @@ void FunctionWidget::applyConfiguration(void) } - if(language_cmb->currentText()==~LanguageType(LanguageType::c)) + if(language_cmb->currentText()==~LanguageType(LanguageType::C)) { func->setLibrary(library_edt->text()); func->setSymbol(symbol_edt->text()); @@ -553,7 +553,7 @@ void FunctionWidget::applyConfiguration(void) for(i=0; iaddReturnedTableColumn(return_tab->getCellText(i,0), - return_tab->getRowData(i).value()); + return_tab->getRowData(i).value()); } } @@ -565,7 +565,7 @@ void FunctionWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/functionwidget.h b/libpgmodeler_ui/src/functionwidget.h index 491863c282..1600acd1af 100644 --- a/libpgmodeler_ui/src/functionwidget.h +++ b/libpgmodeler_ui/src/functionwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -64,7 +64,7 @@ class FunctionWidget: public BaseObjectWidget, public Ui::FunctionWidget { void validateConfiguredFunction(void); public: - FunctionWidget(QWidget * parent = 0); + FunctionWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, Function *func); diff --git a/libpgmodeler_ui/src/generalconfigwidget.cpp b/libpgmodeler_ui/src/generalconfigwidget.cpp index 80bd4c378a..2af9814b0c 100644 --- a/libpgmodeler_ui/src/generalconfigwidget.cpp +++ b/libpgmodeler_ui/src/generalconfigwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -25,8 +25,12 @@ #include "numberedtexteditor.h" #include "linenumberswidget.h" #include "sqlexecutionwidget.h" +#include "modeldatabasediffform.h" +#include "databaseimportform.h" +#include "modelexportform.h" map GeneralConfigWidget::config_params; +map GeneralConfigWidget::widgets_geom; GeneralConfigWidget::GeneralConfigWidget(QWidget * parent) : BaseConfigWidget(parent) { @@ -86,50 +90,53 @@ GeneralConfigWidget::GeneralConfigWidget(QWidget * parent) : BaseConfigWidget(pa connect(tab_width_chk, SIGNAL(toggled(bool)), tab_width_spb, SLOT(setEnabled(bool))); connect(tab_width_chk, SIGNAL(toggled(bool)), this, SLOT(updateFontPreview())); - connect(max_result_rows_chk, SIGNAL(toggled(bool)), max_result_rows_spb, SLOT(setEnabled(bool))); - connect(font_preview_txt, SIGNAL(cursorPositionChanged()), this, SLOT(updateFontPreview())); connect(select_editor_btn, SIGNAL(clicked(bool)), this, SLOT(selectSourceEditor())); - - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::GRID_SIZE]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::OP_LIST_SIZE]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::AUTOSAVE_INTERVAL]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PAPER_TYPE]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PAPER_ORIENTATION]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PAPER_MARGIN]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PAPER_CUSTOM_SIZE]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::_FILE_]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::RECENT_MODELS]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PRINT_PG_NUM]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PRINT_GRID]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::HIDE_REL_NAME]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::HIDE_EXT_ATTRIBS]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::HIDE_TABLE_TAGS]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::FILE_ASSOCIATED]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_FONT]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_FONT_SIZE]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CANVAS_CORNER_MOVE]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::INVERT_RANGESEL_TRIGGER]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CHECK_UPDATE]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SAVE_LAST_POSITION]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SHOW_MAIN_MENU]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::DISABLE_SMOOTHNESS]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SIMPLIFIED_OBJ_CREATION]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CONFIRM_VALIDATION]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SHOW_MAIN_MENU]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_COMPLETION]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::DISPLAY_LINE_NUMBERS]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::LINE_NUMBERS_COLOR]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::LINE_NUMBERS_BG_COLOR]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::LINE_HIGHLIGHT_COLOR]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::HIGHLIGHT_LINES]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::USE_PLACEHOLDERS]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::MIN_OBJECT_OPACITY]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::HISTORY_MAX_LENGTH]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SOURCE_EDITOR_APP]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::UI_LANGUAGE]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::USE_CURVED_LINES]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::MAX_RESULT_ROWS]=QString(); + connect(save_restore_geometry_chk, SIGNAL(toggled(bool)), reset_sizes_tb, SLOT(setEnabled(bool))); + connect(reset_sizes_tb, SIGNAL(clicked(bool)), this, SLOT(resetDialogsSizes())); + + config_params[Attributes::Configuration][Attributes::GridSize]=QString(); + config_params[Attributes::Configuration][Attributes::OpListSize]=QString(); + config_params[Attributes::Configuration][Attributes::AutoSaveInterval]=QString(); + config_params[Attributes::Configuration][Attributes::PaperType]=QString(); + config_params[Attributes::Configuration][Attributes::PaperOrientation]=QString(); + config_params[Attributes::Configuration][Attributes::PaperMargin]=QString(); + config_params[Attributes::Configuration][Attributes::PaperCustomSize]=QString(); + config_params[Attributes::Configuration][Attributes::File]=QString(); + config_params[Attributes::Configuration][Attributes::RecentModels]=QString(); + config_params[Attributes::Configuration][Attributes::PrintPgNum]=QString(); + config_params[Attributes::Configuration][Attributes::PrintGrid]=QString(); + config_params[Attributes::Configuration][Attributes::HideRelName]=QString(); + config_params[Attributes::Configuration][Attributes::HideExtAttribs]=QString(); + config_params[Attributes::Configuration][Attributes::HideTableTags]=QString(); + config_params[Attributes::Configuration][Attributes::FileAssociated]=QString(); + config_params[Attributes::Configuration][Attributes::CodeFont]=QString(); + config_params[Attributes::Configuration][Attributes::CodeFontSize]=QString(); + config_params[Attributes::Configuration][Attributes::CanvasCornerMove]=QString(); + config_params[Attributes::Configuration][Attributes::InvertRangeSelTrigger]=QString(); + config_params[Attributes::Configuration][Attributes::CheckUpdate]=QString(); + config_params[Attributes::Configuration][Attributes::SaveLastPosition]=QString(); + config_params[Attributes::Configuration][Attributes::ShowMainMenu]=QString(); + config_params[Attributes::Configuration][Attributes::DisableSmoothness]=QString(); + config_params[Attributes::Configuration][Attributes::SimplifiedObjCreation]=QString(); + config_params[Attributes::Configuration][Attributes::ConfirmValidation]=QString(); + config_params[Attributes::Configuration][Attributes::ShowMainMenu]=QString(); + config_params[Attributes::Configuration][Attributes::CodeCompletion]=QString(); + config_params[Attributes::Configuration][Attributes::DisplayLineNumbers]=QString(); + config_params[Attributes::Configuration][Attributes::LineNumbersColor]=QString(); + config_params[Attributes::Configuration][Attributes::LineNumbersBgColor]=QString(); + config_params[Attributes::Configuration][Attributes::LineHighlightColor]=QString(); + config_params[Attributes::Configuration][Attributes::HighlightLines]=QString(); + config_params[Attributes::Configuration][Attributes::UsePlaceholders]=QString(); + config_params[Attributes::Configuration][Attributes::MinObjectOpacity]=QString(); + config_params[Attributes::Configuration][Attributes::HistoryMaxLength]=QString(); + config_params[Attributes::Configuration][Attributes::SourceEditorApp]=QString(); + config_params[Attributes::Configuration][Attributes::UiLanguage]=QString(); + config_params[Attributes::Configuration][Attributes::UseCurvedLines]=QString(); + config_params[Attributes::Configuration][Attributes::SaveRestoreGeometry]=QString(); + config_params[Attributes::Configuration][Attributes::AttribsPerPage]=QString(); + config_params[Attributes::Configuration][Attributes::ExtAttribsPerPage]=QString(); + config_params[Attributes::Configuration][Attributes::LowVerbosity]=QString(); simp_obj_creation_ht=new HintTextWidget(simp_obj_creation_hint, this); simp_obj_creation_ht->setText(simple_obj_creation_chk->statusTip()); @@ -182,8 +189,11 @@ GeneralConfigWidget::GeneralConfigWidget(QWidget * parent) : BaseConfigWidget(pa use_curved_lines_ht=new HintTextWidget(use_curved_lines_hint, this); use_curved_lines_ht->setText(use_curved_lines_chk->statusTip()); - max_result_rows_ht=new HintTextWidget(max_result_rows_hint, this); - max_result_rows_ht->setText(max_result_rows_spb->statusTip()); + attribs_per_page_ht=new HintTextWidget(attributes_per_page_hint, this); + attribs_per_page_ht->setText(attribs_per_page_spb->statusTip()); + + reduce_verbosity_ht = new HintTextWidget(low_verbosity_hint, this); + reduce_verbosity_ht->setText(low_verbosity_chk->statusTip()); selectPaperSize(); @@ -223,7 +233,7 @@ GeneralConfigWidget::GeneralConfigWidget(QWidget * parent) : BaseConfigWidget(pa connect(radio, SIGNAL(clicked()), this, SLOT(setConfigurationChanged())); } - confs_dir_edt->setText(GlobalAttributes::CONFIGURATIONS_DIR); + confs_dir_edt->setText(GlobalAttributes::ConfigurationsDir); connect(open_dir_tb, &QToolButton::clicked, [&](){ QDesktopServices::openUrl(QUrl(QString("file://") + confs_dir_edt->text())); @@ -239,8 +249,8 @@ GeneralConfigWidget::GeneralConfigWidget(QWidget * parent) : BaseConfigWidget(pa #endif //Retrieving the available UI dictionaries - QStringList langs = QDir(GlobalAttributes::LANGUAGES_DIR + - GlobalAttributes::DIR_SEPARATOR, + QStringList langs = QDir(GlobalAttributes::LanguagesDir + + GlobalAttributes::DirSeparator, QString("*.qm"), QDir::Name, QDir::AllEntries | QDir::NoDotAndDotDot).entryList(); langs.replaceInStrings(QString(".qm"), QString()); @@ -265,20 +275,20 @@ void GeneralConfigWidget::loadConfiguration(void) QStringList margin, custom_size; vector key_attribs; unsigned interv=0; - int tab_width=0; + int tab_width=0, x=0, y=0, w=0, h=0; for(QWidget *wgt : child_wgts) wgt->blockSignals(true); - key_attribs.push_back(ParsersAttributes::ID); - BaseConfigWidget::loadConfiguration(GlobalAttributes::GENERAL_CONF, config_params, key_attribs); + key_attribs.push_back(Attributes::Id); + BaseConfigWidget::loadConfiguration(GlobalAttributes::GeneralConf, config_params, key_attribs); - grid_size_spb->setValue((config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::GRID_SIZE]).toUInt()); - oplist_size_spb->setValue((config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::OP_LIST_SIZE]).toUInt()); - history_max_length_spb->setValue(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::HISTORY_MAX_LENGTH].toUInt()); + grid_size_spb->setValue((config_params[Attributes::Configuration][Attributes::GridSize]).toUInt()); + oplist_size_spb->setValue((config_params[Attributes::Configuration][Attributes::OpListSize]).toUInt()); + history_max_length_spb->setValue(config_params[Attributes::Configuration][Attributes::HistoryMaxLength].toUInt()); - interv=(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::AUTOSAVE_INTERVAL]).toUInt(); - tab_width=(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_TAB_WIDTH]).toInt(); + interv=(config_params[Attributes::Configuration][Attributes::AutoSaveInterval]).toUInt(); + tab_width=(config_params[Attributes::Configuration][Attributes::CodeTabWidth]).toInt(); autosave_interv_chk->setChecked(interv > 0); autosave_interv_spb->setValue(interv); @@ -288,33 +298,30 @@ void GeneralConfigWidget::loadConfiguration(void) tab_width_spb->setEnabled(tab_width_chk->isChecked()); tab_width_spb->setValue(tab_width); - corner_move_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CANVAS_CORNER_MOVE]==ParsersAttributes::_TRUE_); - invert_rangesel_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::INVERT_RANGESEL_TRIGGER]==ParsersAttributes::_TRUE_); - check_upd_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CHECK_UPDATE]==ParsersAttributes::_TRUE_); - save_last_pos_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SAVE_LAST_POSITION]==ParsersAttributes::_TRUE_); - disable_smooth_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::DISABLE_SMOOTHNESS]==ParsersAttributes::_TRUE_); - simple_obj_creation_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SIMPLIFIED_OBJ_CREATION]==ParsersAttributes::_TRUE_); - confirm_validation_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CONFIRM_VALIDATION]==ParsersAttributes::_TRUE_); - code_completion_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_COMPLETION]==ParsersAttributes::_TRUE_); - use_placeholders_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::USE_PLACEHOLDERS]==ParsersAttributes::_TRUE_); - use_curved_lines_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::USE_CURVED_LINES]==ParsersAttributes::_TRUE_); + corner_move_chk->setChecked(config_params[Attributes::Configuration][Attributes::CanvasCornerMove]==Attributes::True); + invert_rangesel_chk->setChecked(config_params[Attributes::Configuration][Attributes::InvertRangeSelTrigger]==Attributes::True); + check_upd_chk->setChecked(config_params[Attributes::Configuration][Attributes::CheckUpdate]==Attributes::True); + save_last_pos_chk->setChecked(config_params[Attributes::Configuration][Attributes::SaveLastPosition]==Attributes::True); + disable_smooth_chk->setChecked(config_params[Attributes::Configuration][Attributes::DisableSmoothness]==Attributes::True); + simple_obj_creation_chk->setChecked(config_params[Attributes::Configuration][Attributes::SimplifiedObjCreation]==Attributes::True); + confirm_validation_chk->setChecked(config_params[Attributes::Configuration][Attributes::ConfirmValidation]==Attributes::True); + code_completion_chk->setChecked(config_params[Attributes::Configuration][Attributes::CodeCompletion]==Attributes::True); + use_placeholders_chk->setChecked(config_params[Attributes::Configuration][Attributes::UsePlaceholders]==Attributes::True); + use_curved_lines_chk->setChecked(config_params[Attributes::Configuration][Attributes::UseCurvedLines]==Attributes::True); - print_grid_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PRINT_GRID]==ParsersAttributes::_TRUE_); - print_pg_num_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PRINT_PG_NUM]==ParsersAttributes::_TRUE_); + print_grid_chk->setChecked(config_params[Attributes::Configuration][Attributes::PrintGrid]==Attributes::True); + print_pg_num_chk->setChecked(config_params[Attributes::Configuration][Attributes::PrintPgNum]==Attributes::True); - paper_cmb->setCurrentIndex((config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PAPER_TYPE]).toUInt()); - portrait_rb->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PAPER_ORIENTATION]==ParsersAttributes::PORTRAIT); - landscape_rb->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PAPER_ORIENTATION]==ParsersAttributes::LANDSCAPE); + paper_cmb->setCurrentIndex((config_params[Attributes::Configuration][Attributes::PaperType]).toUInt()); + portrait_rb->setChecked(config_params[Attributes::Configuration][Attributes::PaperOrientation]==Attributes::Portrait); + landscape_rb->setChecked(config_params[Attributes::Configuration][Attributes::PaperOrientation]==Attributes::Landscape); - min_obj_opacity_spb->setValue(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::MIN_OBJECT_OPACITY].toUInt()); + min_obj_opacity_spb->setValue(config_params[Attributes::Configuration][Attributes::MinObjectOpacity].toUInt()); + attribs_per_page_spb->setValue(config_params[Attributes::Configuration][Attributes::AttribsPerPage].toUInt()); + ext_attribs_per_page_spb->setValue(config_params[Attributes::Configuration][Attributes::ExtAttribsPerPage].toUInt()); - int value = config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::MAX_RESULT_ROWS].toInt(); - max_result_rows_chk->setChecked(value > 0); - max_result_rows_spb->setEnabled(value > 0); - max_result_rows_spb->setValue(value); - - margin=config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PAPER_MARGIN].split(','); - custom_size=config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PAPER_CUSTOM_SIZE].split(','); + margin=config_params[Attributes::Configuration][Attributes::PaperMargin].split(','); + custom_size=config_params[Attributes::Configuration][Attributes::PaperCustomSize].split(','); left_marg->setValue((margin.count() >= 4 ? margin[0].toDouble() : 2)); top_marg->setValue((margin.count()>= 4 ? margin[1].toDouble() : 2)); @@ -324,33 +331,51 @@ void GeneralConfigWidget::loadConfiguration(void) width_spb->setValue((custom_size.count() >= 2 ? custom_size[0].toDouble() : 500)); height_spb->setValue((custom_size.count() >= 2 ? custom_size[1].toDouble() : 500)); - hide_ext_attribs_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::HIDE_EXT_ATTRIBS]==ParsersAttributes::_TRUE_); - hide_rel_name_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::HIDE_REL_NAME]==ParsersAttributes::_TRUE_); - hide_table_tags_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::HIDE_TABLE_TAGS]==ParsersAttributes::_TRUE_); + hide_ext_attribs_chk->setChecked(config_params[Attributes::Configuration][Attributes::HideExtAttribs]==Attributes::True); + hide_rel_name_chk->setChecked(config_params[Attributes::Configuration][Attributes::HideRelName]==Attributes::True); + hide_table_tags_chk->setChecked(config_params[Attributes::Configuration][Attributes::HideTableTags]==Attributes::True); + + font_cmb->setCurrentFont(QFont(config_params[Attributes::Configuration][Attributes::CodeFont])); + font_size_spb->setValue(config_params[Attributes::Configuration][Attributes::CodeFontSize].toDouble()); + disp_line_numbers_chk->setChecked(config_params[Attributes::Configuration][Attributes::DisplayLineNumbers]==Attributes::True); + hightlight_lines_chk->setChecked(config_params[Attributes::Configuration][Attributes::HighlightLines]==Attributes::True); + line_numbers_cp->setColor(0, config_params[Attributes::Configuration][Attributes::LineNumbersColor]); + line_numbers_bg_cp->setColor(0, config_params[Attributes::Configuration][Attributes::LineNumbersBgColor]); + line_highlight_cp->setColor(0, config_params[Attributes::Configuration][Attributes::LineHighlightColor]); - font_cmb->setCurrentFont(QFont(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_FONT])); - font_size_spb->setValue(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_FONT_SIZE].toDouble()); - disp_line_numbers_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::DISPLAY_LINE_NUMBERS]==ParsersAttributes::_TRUE_); - hightlight_lines_chk->setChecked(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::HIGHLIGHT_LINES]==ParsersAttributes::_TRUE_); - line_numbers_cp->setColor(0, config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::LINE_NUMBERS_COLOR]); - line_numbers_bg_cp->setColor(0, config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::LINE_NUMBERS_BG_COLOR]); - line_highlight_cp->setColor(0, config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::LINE_HIGHLIGHT_COLOR]); + source_editor_edt->setText(config_params[Attributes::Configuration][Attributes::SourceEditorApp]); + source_editor_args_edt->setText(config_params[Attributes::Configuration][Attributes::SourceEditorArgs]); - source_editor_edt->setText(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SOURCE_EDITOR_APP]); - source_editor_args_edt->setText(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SOURCE_EDITOR_ARGS]); + save_restore_geometry_chk->setChecked(config_params[Attributes::Configuration][Attributes::SaveRestoreGeometry]==Attributes::True); + reset_sizes_tb->setEnabled(save_restore_geometry_chk->isChecked()); + low_verbosity_chk->setChecked(config_params[Attributes::Configuration][Attributes::LowVerbosity]==Attributes::True); - int ui_idx = ui_language_cmb->findData(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::UI_LANGUAGE]); + int ui_idx = ui_language_cmb->findData(config_params[Attributes::Configuration][Attributes::UiLanguage]); ui_language_cmb->setCurrentIndex(ui_idx >= 0 ? ui_idx : 0); for(QWidget *wgt : child_wgts) wgt->blockSignals(false); + widgets_geom.clear(); + for(auto itr : config_params) + { + if(itr.second.count(Attributes::XPos)) + { + x = itr.second[Attributes::XPos].toInt(); + y = itr.second[Attributes::YPos].toInt(); + w = itr.second[Attributes::Width].toInt(); + h = itr.second[Attributes::Height].toInt(); + widgets_geom[itr.first].geometry = QRect(QPoint(x,y), QSize(w, h)); + widgets_geom[itr.first].maximized = itr.second[Attributes::Maximized] == Attributes::True; + } + } + updateFontPreview(); this->applyConfiguration(); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo()); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo()); } } @@ -361,22 +386,22 @@ void GeneralConfigWidget::addConfigurationParam(const QString ¶m, const attr void GeneralConfigWidget::removeConfigurationParam(const QRegExp ¶m_reg) { - map::iterator itr, itr_end; + map::iterator itr, itr_end; - itr=config_params.begin(); - itr_end=config_params.end(); + itr=config_params.begin(); + itr_end=config_params.end(); - while(itr!=itr_end) + while(itr!=itr_end) + { + if(param_reg.exactMatch(itr->first)) { - if(param_reg.exactMatch(itr->first)) - { - config_params.erase(itr); - itr=config_params.begin(); - itr_end=config_params.end(); - } - - itr++; + config_params.erase(itr); + itr=config_params.begin(); + itr_end=config_params.end(); } + + itr++; + } } map GeneralConfigWidget::getConfigurationParams(void) @@ -386,133 +411,200 @@ map GeneralConfigWidget::getConfigurationParams(void) QString GeneralConfigWidget::getConfigurationParam(const QString §ion_id, const QString ¶m_name) { - if(config_params.count(section_id) && - config_params[section_id].count(param_name)) - return(config_params[section_id][param_name]); - else - return(QString()); + if(config_params.count(section_id) && + config_params[section_id].count(param_name)) + return(config_params[section_id][param_name]); + else + return(QString()); +} + +void GeneralConfigWidget::saveWidgetGeometry(QWidget *widget, const QString &custom_wgt_name) +{ + if(!widget || + config_params[Attributes::Configuration][Attributes::SaveRestoreGeometry] != Attributes::True) + return; + + QString dlg_name = custom_wgt_name.isEmpty() ? widget->metaObject()->className() : custom_wgt_name; + + widgets_geom[dlg_name.toLower()].geometry = widget->geometry(); + widgets_geom[dlg_name.toLower()].maximized = widget->isMaximized(); +} + +bool GeneralConfigWidget::restoreWidgetGeometry(QWidget *widget, const QString &custom_wgt_name) +{ + if(!widget || + config_params[Attributes::Configuration][Attributes::SaveRestoreGeometry] != Attributes::True) + return(false); + + QString dlg_name = custom_wgt_name.isEmpty() ? widget->metaObject()->className() : custom_wgt_name; + dlg_name = dlg_name.toLower(); + + if(widgets_geom.count(dlg_name) && + (widgets_geom[dlg_name].maximized || + (widgets_geom[dlg_name].geometry.width() > 0 && widgets_geom[dlg_name].geometry.height() > 0))) + { + if(widgets_geom[dlg_name].maximized) + { + widget->move(widgets_geom[dlg_name].geometry.topLeft()); + widget->setWindowState(Qt::WindowMaximized); + } + else + widget->setGeometry(widgets_geom[dlg_name].geometry); + + return(true); + } + + return(false); } void GeneralConfigWidget::saveConfiguration(void) { try { + attribs_map attribs; map::iterator itr, itr_end; QString file_sch, root_dir, widget_sch; - bool show_grid=false, show_delim=false, align_grid=false; + int recent_mdl_idx = 0; - root_dir=GlobalAttributes::TMPL_CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR; + root_dir=GlobalAttributes::TmplConfigurationDir + + GlobalAttributes::DirSeparator; file_sch=root_dir + - GlobalAttributes::SCHEMAS_DIR + - GlobalAttributes::DIR_SEPARATOR + - ParsersAttributes::_FILE_ + - GlobalAttributes::SCHEMA_EXT; + GlobalAttributes::SchemasDir + + GlobalAttributes::DirSeparator + + Attributes::File + + GlobalAttributes::SchemaExt; widget_sch=root_dir + - GlobalAttributes::SCHEMAS_DIR + - GlobalAttributes::DIR_SEPARATOR + - ParsersAttributes::WIDGET + - GlobalAttributes::SCHEMA_EXT; - - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::GRID_SIZE]=QString::number(grid_size_spb->value()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::OP_LIST_SIZE]=QString::number(oplist_size_spb->value()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::AUTOSAVE_INTERVAL]=QString::number(autosave_interv_chk->isChecked() ? autosave_interv_spb->value() : 0); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PAPER_TYPE]=QString::number(paper_cmb->currentIndex()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PAPER_ORIENTATION]=(portrait_rb->isChecked() ? ParsersAttributes::PORTRAIT : ParsersAttributes::LANDSCAPE); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CANVAS_CORNER_MOVE]=(corner_move_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::INVERT_RANGESEL_TRIGGER]=(invert_rangesel_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CHECK_UPDATE]=(check_upd_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SAVE_LAST_POSITION]=(save_last_pos_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::DISABLE_SMOOTHNESS]=(disable_smooth_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SIMPLIFIED_OBJ_CREATION]=(simple_obj_creation_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CONFIRM_VALIDATION]=(confirm_validation_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_COMPLETION]=(code_completion_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_TAB_WIDTH]=QString::number(tab_width_chk->isChecked() ? tab_width_spb->value() : 0); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::MIN_OBJECT_OPACITY]=QString::number(min_obj_opacity_spb->value()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::USE_PLACEHOLDERS]=(use_placeholders_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::HISTORY_MAX_LENGTH]=QString::number(history_max_length_spb->value()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::MAX_RESULT_ROWS]=QString::number(max_result_rows_chk->isChecked() ? max_result_rows_spb->value() : 0); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::USE_CURVED_LINES]=(use_curved_lines_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - - ObjectsScene::getGridOptions(show_grid, align_grid, show_delim); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SHOW_CANVAS_GRID]=(show_grid ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SHOW_PAGE_DELIMITERS]=(show_delim ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::ALIGN_OBJS_TO_GRID]=(align_grid ? ParsersAttributes::_TRUE_ : QString()); - - unity_cmb->setCurrentIndex(UNIT_MILIMETERS); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PAPER_MARGIN]=QString("%1,%2,%3,%4").arg(left_marg->value()) + GlobalAttributes::SchemasDir + + GlobalAttributes::DirSeparator + + Attributes::Widget + + GlobalAttributes::SchemaExt; + + config_params[Attributes::Configuration][Attributes::GridSize]=QString::number(grid_size_spb->value()); + config_params[Attributes::Configuration][Attributes::OpListSize]=QString::number(oplist_size_spb->value()); + config_params[Attributes::Configuration][Attributes::AutoSaveInterval]=QString::number(autosave_interv_chk->isChecked() ? autosave_interv_spb->value() : 0); + config_params[Attributes::Configuration][Attributes::PaperType]=QString::number(paper_cmb->currentIndex()); + config_params[Attributes::Configuration][Attributes::PaperOrientation]=(portrait_rb->isChecked() ? Attributes::Portrait : Attributes::Landscape); + config_params[Attributes::Configuration][Attributes::CanvasCornerMove]=(corner_move_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::InvertRangeSelTrigger]=(invert_rangesel_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::CheckUpdate]=(check_upd_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::SaveLastPosition]=(save_last_pos_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::DisableSmoothness]=(disable_smooth_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::SimplifiedObjCreation]=(simple_obj_creation_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::ConfirmValidation]=(confirm_validation_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::CodeCompletion]=(code_completion_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::CodeTabWidth]=QString::number(tab_width_chk->isChecked() ? tab_width_spb->value() : 0); + config_params[Attributes::Configuration][Attributes::MinObjectOpacity]=QString::number(min_obj_opacity_spb->value()); + config_params[Attributes::Configuration][Attributes::UsePlaceholders]=(use_placeholders_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::HistoryMaxLength]=QString::number(history_max_length_spb->value()); + config_params[Attributes::Configuration][Attributes::UseCurvedLines]=(use_curved_lines_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::AttribsPerPage]=QString::number(attribs_per_page_spb->value()); + config_params[Attributes::Configuration][Attributes::ExtAttribsPerPage]=QString::number(ext_attribs_per_page_spb->value()); + + config_params[Attributes::Configuration][Attributes::ShowCanvasGrid]=(ObjectsScene::isShowGrid() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::ShowPageDelimiters]=(ObjectsScene::isShowPageDelimiters() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::AlignObjsToGrid]=(ObjectsScene::isAlignObjectsToGrid() ? Attributes::True : QString()); + + unity_cmb->setCurrentIndex(UnitMilimeters); + config_params[Attributes::Configuration][Attributes::PaperMargin]=QString("%1,%2,%3,%4").arg(left_marg->value()) .arg(top_marg->value()) .arg(right_marg->value()) .arg(bottom_marg->value()); if(paper_cmb->currentIndex()!=paper_cmb->count()-1) - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PAPER_CUSTOM_SIZE]=QString(); + config_params[Attributes::Configuration][Attributes::PaperCustomSize]=QString(); else - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PAPER_CUSTOM_SIZE]=QString("%1,%2").arg(width_spb->value()).arg(height_spb->value()); + config_params[Attributes::Configuration][Attributes::PaperCustomSize]=QString("%1,%2").arg(width_spb->value()).arg(height_spb->value()); + + config_params[Attributes::Configuration][Attributes::PrintPgNum]=(print_pg_num_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::PrintGrid]=(print_grid_chk->isChecked() ? Attributes::True : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PRINT_PG_NUM]=(print_pg_num_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::PRINT_GRID]=(print_grid_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); + config_params[Attributes::Configuration][Attributes::HideExtAttribs]=(hide_ext_attribs_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::HideRelName]=(hide_rel_name_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::HideTableTags]=(hide_table_tags_chk->isChecked() ? Attributes::True : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::HIDE_EXT_ATTRIBS]=(hide_ext_attribs_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::HIDE_REL_NAME]=(hide_rel_name_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::HIDE_TABLE_TAGS]=(hide_table_tags_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); + config_params[Attributes::Configuration][Attributes::CodeFont]=font_cmb->currentText(); + config_params[Attributes::Configuration][Attributes::CodeFontSize]=QString::number(font_size_spb->value()); + config_params[Attributes::Configuration][Attributes::DisplayLineNumbers]=(disp_line_numbers_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::HighlightLines]=(hightlight_lines_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::LineNumbersColor]=line_numbers_cp->getColor(0).name(); + config_params[Attributes::Configuration][Attributes::LineNumbersBgColor]=line_numbers_bg_cp->getColor(0).name(); + config_params[Attributes::Configuration][Attributes::LineHighlightColor]=line_highlight_cp->getColor(0).name(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_FONT]=font_cmb->currentText(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_FONT_SIZE]=QString::number(font_size_spb->value()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::DISPLAY_LINE_NUMBERS]=(disp_line_numbers_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::HIGHLIGHT_LINES]=(hightlight_lines_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::LINE_NUMBERS_COLOR]=line_numbers_cp->getColor(0).name(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::LINE_NUMBERS_BG_COLOR]=line_numbers_bg_cp->getColor(0).name(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::LINE_HIGHLIGHT_COLOR]=line_highlight_cp->getColor(0).name(); + config_params[Attributes::Configuration][Attributes::SourceEditorApp]=source_editor_edt->text(); + config_params[Attributes::Configuration][Attributes::SourceEditorArgs]=source_editor_args_edt->text(); + config_params[Attributes::Configuration][Attributes::UiLanguage]=ui_language_cmb->currentData().toString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SOURCE_EDITOR_APP]=source_editor_edt->text(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SOURCE_EDITOR_ARGS]=source_editor_args_edt->text(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::UI_LANGUAGE]=ui_language_cmb->currentData().toString(); + config_params[Attributes::Configuration][Attributes::CompactView]=(BaseObjectView::isCompactViewEnabled() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::SaveRestoreGeometry]=(save_restore_geometry_chk->isChecked() ? Attributes::True : QString()); + config_params[Attributes::Configuration][Attributes::LowVerbosity]=(low_verbosity_chk->isChecked() ? Attributes::True : QString()); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::_FILE_]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::RECENT_MODELS]=QString(); + config_params[Attributes::Configuration][Attributes::File]=QString(); + config_params[Attributes::Configuration][Attributes::RecentModels]=QString(); itr=config_params.begin(); itr_end=config_params.end(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::DOCK_WIDGETS]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::RECENT_MODELS]=QString(); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::_FILE_]=QString(); + config_params[Attributes::Configuration][Attributes::DockWidgets]=QString(); + config_params[Attributes::Configuration][Attributes::WidgetsGeometry]=QString(); + config_params[Attributes::Configuration][Attributes::RecentModels]=QString(); + config_params[Attributes::Configuration][Attributes::File]=QString(); while(itr!=itr_end) { //Checking if the current attribute is a file to be stored in a tag - if((itr->first).contains(QRegExp(QString("(") + ParsersAttributes::_FILE_ + QString(")([0-9]+)")))) + if((itr->first).contains(QRegExp(QString("(") + Attributes::File + QString(")([0-9]+)")))) { - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::_FILE_]+= + config_params[Attributes::Configuration][Attributes::File]+= schparser.convertCharsToXMLEntities(schparser.getCodeDefinition(file_sch, itr->second)); } //Checking if the current attribute is a file to be stored in a tag - else if((itr->first).contains(QRegExp(QString("(") + ParsersAttributes::RECENT + QString(")([0-9]+)")))) + else if(recent_mdl_idx < MaxRecentModels && (itr->first).contains(QRegExp(QString("(") + Attributes::Recent + QString(")([0-9]+)")))) { - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::RECENT_MODELS]+= + config_params[Attributes::Configuration][Attributes::RecentModels]+= schparser.convertCharsToXMLEntities(schparser.getCodeDefinition(file_sch, itr->second)); + + recent_mdl_idx++; } - else if(itr->first==ParsersAttributes::VALIDATOR || - itr->first==ParsersAttributes::OBJECT_FINDER || - itr->first==ParsersAttributes::SQL_TOOL) + else if(itr->first==Attributes::Validator || + itr->first==Attributes::ObjectFinder || + itr->first==Attributes::SqlTool) { schparser.ignoreUnkownAttributes(true); - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::DOCK_WIDGETS]+= + schparser.ignoreEmptyAttributes(true); + config_params[Attributes::Configuration][Attributes::DockWidgets]+= schparser.getCodeDefinition(widget_sch, itr->second); schparser.ignoreUnkownAttributes(false); + schparser.ignoreEmptyAttributes(false); } itr++; } - BaseConfigWidget::saveConfiguration(GlobalAttributes::GENERAL_CONF, config_params); + if(save_restore_geometry_chk->isChecked()) + { + for(auto &itr : widgets_geom) + { + attribs[Attributes::Id] = itr.first; + attribs[Attributes::XPos] = QString::number(itr.second.geometry.left()); + attribs[Attributes::YPos] = QString::number(itr.second.geometry.top()); + attribs[Attributes::Width] = QString::number(itr.second.geometry.width()); + attribs[Attributes::Height] = QString::number(itr.second.geometry.height()); + attribs[Attributes::Maximized] = itr.second.maximized ? Attributes::True : QString(); + + schparser.ignoreUnkownAttributes(true); + config_params[Attributes::Configuration][Attributes::WidgetsGeometry]+= + schparser.getCodeDefinition(widget_sch, attribs); + schparser.ignoreUnkownAttributes(false); + } + } + + BaseConfigWidget::saveConfiguration(GlobalAttributes::GeneralConf, config_params); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -520,12 +612,15 @@ void GeneralConfigWidget::applyConfiguration(void) { int unit=unity_cmb->currentIndex(); QFont fnt; - double fnt_size=config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_FONT_SIZE].toDouble(); + double fnt_size=config_params[Attributes::Configuration][Attributes::CodeFontSize].toDouble(); + + if(fnt_size < 5.0) + fnt_size=5.0; - if(fnt_size < 5.0f) - fnt_size=5.0f; + if(!save_restore_geometry_chk->isChecked()) + widgets_geom.clear(); - unity_cmb->setCurrentIndex(UNIT_POINT); + unity_cmb->setCurrentIndex(UnitPoint); ObjectsScene::setPaperConfiguration(static_cast(paper_cmb->itemData(paper_cmb->currentIndex()).toInt()), (portrait_rb->isChecked() ? QPrinter::Portrait : QPrinter::Landscape), QRectF(left_marg->value(), top_marg->value(), right_marg->value(), bottom_marg->value()), @@ -536,13 +631,15 @@ void GeneralConfigWidget::applyConfiguration(void) ObjectsScene::setInvertRangeSelectionTrigger(invert_rangesel_chk->isChecked()); ObjectsScene::setGridSize(grid_size_spb->value()); - ObjectsScene::setGridOptions(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SHOW_CANVAS_GRID]==ParsersAttributes::_TRUE_, - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::ALIGN_OBJS_TO_GRID]==ParsersAttributes::_TRUE_, - config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::SHOW_PAGE_DELIMITERS]==ParsersAttributes::_TRUE_); + ObjectsScene::setGridOptions(config_params[Attributes::Configuration][Attributes::ShowCanvasGrid]==Attributes::True, + config_params[Attributes::Configuration][Attributes::AlignObjsToGrid]==Attributes::True, + config_params[Attributes::Configuration][Attributes::ShowPageDelimiters]==Attributes::True); OperationList::setMaximumSize(oplist_size_spb->value()); BaseTableView::setHideExtAttributes(hide_ext_attribs_chk->isChecked()); BaseTableView::setHideTags(hide_table_tags_chk->isChecked()); + BaseTableView::setAttributesPerPage(BaseTable::AttribsSection, attribs_per_page_spb->value()); + BaseTableView::setAttributesPerPage(BaseTable::ExtAttribsSection, ext_attribs_per_page_spb->value()); RelationshipView::setHideNameLabel(hide_rel_name_chk->isChecked()); RelationshipView::setCurvedLines(use_curved_lines_chk->isChecked()); ModelWidget::setSaveLastCanvasPosition(save_last_pos_chk->isChecked()); @@ -552,10 +649,9 @@ void GeneralConfigWidget::applyConfiguration(void) MainWindow::setConfirmValidation(confirm_validation_chk->isChecked()); BaseObjectView::setPlaceholderEnabled(use_placeholders_chk->isChecked()); SQLExecutionWidget::setSQLHistoryMaxLength(history_max_length_spb->value()); - SQLExecutionWidget::setMaxResultRows(max_result_rows_chk->isChecked()? max_result_rows_spb->value() : 0); - fnt.setFamily(config_params[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_FONT]); - fnt.setPointSize(fnt_size); + fnt.setFamily(config_params[Attributes::Configuration][Attributes::CodeFont]); + fnt.setPointSizeF(fnt_size); NumberedTextEditor::setLineNumbersVisible(disp_line_numbers_chk->isChecked()); NumberedTextEditor::setLineHighlightColor(line_highlight_cp->getColor(0)); NumberedTextEditor::setHighlightLines(hightlight_lines_chk->isChecked()); @@ -564,29 +660,34 @@ void GeneralConfigWidget::applyConfiguration(void) NumberedTextEditor::setSourceEditorAppArgs(source_editor_args_edt->text()); LineNumbersWidget::setColors(line_numbers_cp->getColor(0), line_numbers_bg_cp->getColor(0)); SyntaxHighlighter::setDefaultFont(fnt); + + ModelDatabaseDiffForm::setLowVerbosity(low_verbosity_chk->isChecked()); + DatabaseImportForm::setLowVerbosity(low_verbosity_chk->isChecked()); + ModelExportForm::setLowVerbosity(low_verbosity_chk->isChecked()); } void GeneralConfigWidget::restoreDefaults(void) { try { - BaseConfigWidget::restoreDefaults(GlobalAttributes::GENERAL_CONF); - BaseConfigWidget::restoreDefaults(GlobalAttributes::XML_HIGHLIGHT_CONF); - BaseConfigWidget::restoreDefaults(GlobalAttributes::SQL_HIGHLIGHT_CONF); + BaseConfigWidget::restoreDefaults(GlobalAttributes::GeneralConf, false); + BaseConfigWidget::restoreDefaults(GlobalAttributes::XMLHighlightConf, true); + BaseConfigWidget::restoreDefaults(GlobalAttributes::SQLHighlightConf, true); + BaseConfigWidget::restoreDefaults(GlobalAttributes::UiStyleConf, true); this->loadConfiguration(); this->applyConfiguration(); setConfigurationChanged(true); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void GeneralConfigWidget::convertMarginUnity(void) { - static int prev_unity=UNIT_MILIMETERS; - double conv_factor[]={1.0f, 2.83f, 0.04f, 0.1f}, + static int prev_unity=UnitMilimeters; + double conv_factor[]={1.0, 2.83, 0.04, 0.1}, left, right, top, bottom, width, height; left=left_marg->value() / conv_factor[prev_unity]; @@ -654,3 +755,13 @@ void GeneralConfigWidget::selectSourceEditor(void) if(sel_editor_dlg.result()==QDialog::Accepted) source_editor_edt->setText(sel_editor_dlg.selectedFiles().at(0)); } + +void GeneralConfigWidget::resetDialogsSizes(void) +{ + Messagebox msg_box; + msg_box.show(trUtf8("This action will reset all dialogs to their default size and positions on the screen! Do you really want to proceed?"), + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); + + if(msg_box.result() == QDialog::Accepted) + widgets_geom.clear(); +} diff --git a/libpgmodeler_ui/src/generalconfigwidget.h b/libpgmodeler_ui/src/generalconfigwidget.h index 48fbc01281..2bd75c551d 100644 --- a/libpgmodeler_ui/src/generalconfigwidget.h +++ b/libpgmodeler_ui/src/generalconfigwidget.h @@ -1,7 +1,7 @@ -/* +/* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -36,28 +36,43 @@ class GeneralConfigWidget: public BaseConfigWidget, public Ui::GeneralConfigWidg private: Q_OBJECT + /* This simple struct is used to store the widgets geometry and maximized state + * in order to save this info to configuration file being possible to restore + * it when reloading the application */ + struct WidgetState + { + QRect geometry; + bool maximized; + WidgetState() { maximized = false; } + }; + QWidgetList child_wgts; NumberedTextEditor *font_preview_txt; + static map widgets_geom; + static map config_params; - static const unsigned UNIT_MILIMETERS=0, - UNIT_POINT=1, - UNIT_INCHS=2, - UNIT_CENTIMETERS=3; + static constexpr unsigned UnitMilimeters=0, + UnitPoint=1, + UnitInches=2, + UnitCentimeters=3; HintTextWidget *simp_obj_creation_ht, *confirm_validation_ht, *corner_move_ht, *save_last_pos_ht, *invert_rangesel_ht, *disable_smooth_ht, *hide_ext_attribs_ht, *hide_table_tags_ht, *hide_rel_name_ht, *code_completion_ht, *use_placeholders_ht, *min_obj_opacity_ht, *autosave_ht, *op_history_ht, *ui_language_ht, *grid_size_ht, - *use_curved_lines_ht, *max_result_rows_ht; + *use_curved_lines_ht, *max_result_rows_ht, *attribs_per_page_ht, *reduce_verbosity_ht; ColorPickerWidget *line_numbers_cp, *line_numbers_bg_cp, *line_highlight_cp; public: - GeneralConfigWidget(QWidget * parent=0); + //! \brief Maximum number of files listed as recent models + static constexpr int MaxRecentModels=15; + + GeneralConfigWidget(QWidget * parent = nullptr); void saveConfiguration(void); void loadConfiguration(void); @@ -69,6 +84,9 @@ class GeneralConfigWidget: public BaseConfigWidget, public Ui::GeneralConfigWidg Section id can be , , or */ static QString getConfigurationParam(const QString §ion_id, const QString ¶m_name); + static void saveWidgetGeometry(QWidget *widget, const QString &custom_wgt_name = QString()); + static bool restoreWidgetGeometry(QWidget *widget, const QString &custom_wgt_name = QString()); + public slots: void applyConfiguration(void); void restoreDefaults(void); @@ -78,6 +96,7 @@ class GeneralConfigWidget: public BaseConfigWidget, public Ui::GeneralConfigWidg private slots: void convertMarginUnity(void); void updateFontPreview(void); + void resetDialogsSizes(void); }; #endif diff --git a/libpgmodeler_ui/src/genericsqlwidget.cpp b/libpgmodeler_ui/src/genericsqlwidget.cpp index e68af13bbb..6e82fc797a 100644 --- a/libpgmodeler_ui/src/genericsqlwidget.cpp +++ b/libpgmodeler_ui/src/genericsqlwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,32 +18,209 @@ #include "genericsqlwidget.h" -GenericSQLWidget::GenericSQLWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_GENERIC_SQL) +const QRegExp GenericSQLWidget::AttrDelimRegexp = QRegExp(QString("(\\%1)+|(\\%2)+") + .arg(SchemaParser::CharIniAttribute) + .arg(SchemaParser::CharEndAttribute)); + +GenericSQLWidget::GenericSQLWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::GenericSql) { + vector types; + Ui_GenericSQLWidget::setupUi(this); - configureFormLayout(genericsql_grid, OBJ_GENERIC_SQL); + configureFormLayout(genericsql_grid, ObjectType::GenericSql); - definition_txt = PgModelerUiNS::createNumberedTextEditor(sqlcode_grp, true); - definition_hl = new SyntaxHighlighter(definition_txt); - definition_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + ref_name_ht = new HintTextWidget(ref_name_hint, this); + ref_name_ht->setText(ref_name_edt->statusTip()); + + use_signature_ht = new HintTextWidget(use_signature_hint, this); + use_signature_ht->setText(use_signature_chk->statusTip()); + + format_name_ht = new HintTextWidget(format_name_hint, this); + format_name_ht->setText(format_name_chk->statusTip()); + definition_txt = PgModelerUiNs::createNumberedTextEditor(attribs_tbw->widget(0), true); + definition_hl = new SyntaxHighlighter(definition_txt); + definition_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); definition_cp=new CodeCompletionWidget(definition_txt, true); comment_edt->setVisible(false); comment_lbl->setVisible(false); - sqlcode_grp->layout()->setContentsMargins(4,4,4,4); + preview_txt = PgModelerUiNs::createNumberedTextEditor(attribs_tbw->widget(2), false); + preview_txt->setReadOnly(true); + preview_hl = new SyntaxHighlighter(preview_txt); + preview_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); + + attribs_tbw->widget(0)->layout()->setContentsMargins(4,4,4,4); + attribs_tbw->widget(0)->layout()->addWidget(definition_txt); + + attribs_tbw->widget(2)->layout()->setContentsMargins(4,4,4,4); + attribs_tbw->widget(2)->layout()->addWidget(preview_txt); + + // Configuring the object types accepted by object references + types = BaseObject::getObjectTypes(false, { ObjectType::Database, ObjectType::GenericSql, + ObjectType::Permission, ObjectType::Relationship, + ObjectType::Tag, ObjectType::Textbox }); + types.push_back(ObjectType::Column); + + object_sel = new ObjectSelectorWidget(types, true, this); + + objects_refs_tab = new ObjectsTableWidget(ObjectsTableWidget::AllButtons, true, this); + references_grid->addWidget(object_sel, 0, 1, 1, 1); + references_grid->addWidget(objects_refs_tab, 2, 0, 1, 2); + + objects_refs_tab->setColumnCount(5); + objects_refs_tab->setHeaderLabel(trUtf8("Ref. name"), 0); + objects_refs_tab->setHeaderIcon(QIcon(PgModelerUiNs::getIconPath("uid")), 0); + + objects_refs_tab->setHeaderLabel(trUtf8("Object"), 1); + objects_refs_tab->setHeaderIcon(QIcon(PgModelerUiNs::getIconPath(BaseObject::getSchemaName(ObjectType::Table))), 1); + + objects_refs_tab->setHeaderLabel(trUtf8("Type"), 2); + objects_refs_tab->setHeaderIcon(QIcon(PgModelerUiNs::getIconPath(BaseObject::getSchemaName(ObjectType::Type))), 2); + + objects_refs_tab->setHeaderLabel(trUtf8("Signature"), 3); + objects_refs_tab->setHeaderLabel(trUtf8("Format name"), 4); + setMinimumSize(700, 500); + + connect(object_sel, &ObjectSelectorWidget::s_selectorChanged, [&](bool selected){ + sel_obj_icon_lbl->setPixmap(selected ? PgModelerUiNs::getIconPath(object_sel->getSelectedObject()->getSchemaName()) : QPixmap()); + sel_obj_icon_lbl->setToolTip(selected ? object_sel->getSelectedObject()->getTypeName() : QString()); + }); + + connect(objects_refs_tab, SIGNAL(s_rowAdded(int)), this, SLOT(addObjectReference(int))); + connect(objects_refs_tab, SIGNAL(s_rowEdited(int)), this, SLOT(editObjectReference(int))); + connect(objects_refs_tab, SIGNAL(s_rowUpdated(int)), this, SLOT(updateObjectReference(int))); + + connect(objects_refs_tab, &ObjectsTableWidget::s_rowAboutToRemove, [&](int row){ + QString ref_name = objects_refs_tab->getCellText(row, 0); + dummy_gsql.removeObjectReference(ref_name); + }); + + connect(objects_refs_tab, &ObjectsTableWidget::s_rowsRemoved, [&](){ + dummy_gsql.removeObjectReferences(); + }); + + connect(attribs_tbw, &QTabWidget::currentChanged, [&](int idx){ + if(idx == attribs_tbw->count() - 1) + updateCodePreview(); + }); } void GenericSQLWidget::setAttributes(DatabaseModel *model, OperationList *op_list, GenericSQL *genericsql) { + BaseObjectWidget::setAttributes(model, op_list, genericsql); + if(genericsql) + { + dummy_gsql = *genericsql; definition_txt->setPlainText(genericsql->getDefinition()); + objects_refs_tab->blockSignals(true); - BaseObjectWidget::setAttributes(model, op_list, genericsql); + for(auto &ref : genericsql->getObjectsReferences()) + { + objects_refs_tab->addRow(); + showObjectReferenceData(objects_refs_tab->getRowCount() - 1, + ref.object, ref.ref_name, ref.use_signature, ref.format_name); + } - definition_cp->configureCompletion(this->model, definition_hl); + objects_refs_tab->blockSignals(false); + } + + object_sel->setModel(model); + definition_cp->configureCompletion(model, definition_hl); +} + +void GenericSQLWidget::addObjectReference(int row) +{ + try + { + QString ref_name = ref_name_edt->text().remove(AttrDelimRegexp); + BaseObject *object = object_sel->getSelectedObject(); + bool use_signature = use_signature_chk->isChecked(), + format_name = format_name_chk->isChecked(); + + dummy_gsql.addObjectReference(object, ref_name, use_signature, format_name); + showObjectReferenceData(row, object, ref_name, use_signature, format_name); + clearObjectReferenceForm(); + } + catch(Exception &e) + { + objects_refs_tab->blockSignals(true); + objects_refs_tab->removeRow(row); + objects_refs_tab->blockSignals(false); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +void GenericSQLWidget::editObjectReference(int row) +{ + ref_name_edt->setText(objects_refs_tab->getCellText(row, 0)); + use_signature_chk->setChecked(objects_refs_tab->getCellText(row, 3) == trUtf8("Yes")); + format_name_chk->setChecked(objects_refs_tab->getCellText(row, 4) == trUtf8("Yes")); + object_sel->setSelectedObject(reinterpret_cast(objects_refs_tab->getRowData(row).value())); +} + +void GenericSQLWidget::updateObjectReference(int row) +{ + QString ref_name = objects_refs_tab->getCellText(row, 0), + new_ref_name = ref_name_edt->text().remove(AttrDelimRegexp); + BaseObject *object = object_sel->getSelectedObject(); + bool use_signature = use_signature_chk->isChecked(), + format_name = format_name_chk->isChecked(); + + try + { + dummy_gsql.updateObjectReference(ref_name, object, new_ref_name, use_signature, format_name); + showObjectReferenceData(row, object, new_ref_name, use_signature, format_name); + clearObjectReferenceForm(); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + } +} + +void GenericSQLWidget::clearObjectReferenceForm(void) +{ + object_sel->clearSelector(); + ref_name_edt->clear(); + use_signature_chk->setChecked(false); + format_name_chk->setChecked(false); + objects_refs_tab->clearSelection(); +} + +void GenericSQLWidget::updateCodePreview(void) +{ + try + { + if(!name_edt->text().isEmpty() && !definition_txt->toPlainText().isEmpty()) + { + if(!name_edt->text().isEmpty()) + dummy_gsql.setName(name_edt->text()); + + dummy_gsql.setDefinition(definition_txt->toPlainText()); + dummy_gsql.setCodeInvalidated(true); + preview_txt->setPlainText(dummy_gsql.getCodeDefinition(SchemaParser::SqlDefinition)); + } + else + preview_txt->setPlainText(QString("-- %1 --").arg(trUtf8("No object name, SQL code or references defined! Preview unavailable."))); + } + catch(Exception &e) + { + preview_txt->setPlainText(QString("/* %1 */").arg(e.getExceptionsText())); + } +} + +void GenericSQLWidget::showObjectReferenceData(int row, BaseObject *object, const QString &ref_name, bool use_signature, bool format_name) +{ + objects_refs_tab->setCellText(ref_name, row, 0); + objects_refs_tab->setCellText(use_signature ? object->getSignature(format_name) : object->getName(format_name), row, 1); + objects_refs_tab->setCellText(object->getTypeName(), row, 2); + objects_refs_tab->setCellText(use_signature ? trUtf8("Yes") : trUtf8("No"), row, 3); + objects_refs_tab->setCellText(format_name ? trUtf8("Yes") : trUtf8("No"), row, 4); + objects_refs_tab->setRowData(QVariant::fromValue(reinterpret_cast(object)), row); } void GenericSQLWidget::applyConfiguration(void) @@ -54,7 +231,8 @@ void GenericSQLWidget::applyConfiguration(void) startConfiguration(); genericsql=dynamic_cast(this->object); - genericsql->setDefinition(definition_txt->toPlainText()); + dummy_gsql.setDefinition(definition_txt->toPlainText()); + *genericsql = dummy_gsql; BaseObjectWidget::applyConfiguration(); finishConfiguration(); @@ -62,7 +240,6 @@ void GenericSQLWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } - diff --git a/libpgmodeler_ui/src/genericsqlwidget.h b/libpgmodeler_ui/src/genericsqlwidget.h index 41586fdcf8..0c1ec99d06 100644 --- a/libpgmodeler_ui/src/genericsqlwidget.h +++ b/libpgmodeler_ui/src/genericsqlwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -28,24 +28,48 @@ #include "ui_genericsqlwidget.h" #include "baseobjectwidget.h" #include "codecompletionwidget.h" +#include "objectstablewidget.h" +#include "objectselectorwidget.h" +#include "hinttextwidget.h" class GenericSQLWidget: public BaseObjectWidget, public Ui::GenericSQLWidget { private: Q_OBJECT - NumberedTextEditor *definition_txt; + HintTextWidget *ref_name_ht, *use_signature_ht, *format_name_ht; - SyntaxHighlighter *definition_hl; + NumberedTextEditor *definition_txt, *preview_txt; + + SyntaxHighlighter *definition_hl, *preview_hl; CodeCompletionWidget *definition_cp; - public: - GenericSQLWidget(QWidget * parent = 0); + ObjectsTableWidget *objects_refs_tab; + + ObjectSelectorWidget *object_sel; + + /*! \brief This dummy object is used to generated the code preview while the user changes the fields + * in form. Once the dummy is configure it is copied to the real object being handled by the form (this->object) */ + GenericSQL dummy_gsql; + //! \brief A regular expression used to remove attribute/reference delimiters {} from the names of configured references + static const QRegExp AttrDelimRegexp; + + void showObjectReferenceData(int row, BaseObject *object, const QString &ref_name, bool use_signature, bool format_name); + + public: + GenericSQLWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, GenericSQL *genericsql=nullptr); public slots: void applyConfiguration(void); + + private slots: + void updateCodePreview(void); + void addObjectReference(int row); + void editObjectReference(int row); + void updateObjectReference(int row); + void clearObjectReferenceForm(void); }; #endif diff --git a/libpgmodeler_ui/src/hinttextwidget.cpp b/libpgmodeler_ui/src/hinttextwidget.cpp index 2ff0e363ba..c41f5b95ef 100644 --- a/libpgmodeler_ui/src/hinttextwidget.cpp +++ b/libpgmodeler_ui/src/hinttextwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -24,7 +24,7 @@ HintTextWidget::HintTextWidget(QWidget *btn_parent, QWidget *parent): QWidget(parent) { if(!btn_parent) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); QHBoxLayout *layout=new QHBoxLayout(btn_parent); QGraphicsDropShadowEffect *shadow=nullptr; @@ -36,7 +36,7 @@ HintTextWidget::HintTextWidget(QWidget *btn_parent, QWidget *parent): QWidget(pa hint_tb=new QToolButton(this); hint_tb->setCheckable(true); hint_tb->setToolButtonStyle(Qt::ToolButtonIconOnly); - hint_tb->setIcon(QPixmap(PgModelerUiNS::getIconPath("help"))); + hint_tb->setIcon(QPixmap(PgModelerUiNs::getIconPath("help"))); shadow=new QGraphicsDropShadowEffect(this); shadow->setOffset(5,5); @@ -49,11 +49,11 @@ HintTextWidget::HintTextWidget(QWidget *btn_parent, QWidget *parent): QWidget(pa this->setVisible(false); text_lbl->installEventFilter(this); - PgModelerUiNS::configureWidgetFont(text_lbl, PgModelerUiNS::MEDIUM_FONT_FACTOR); + PgModelerUiNs::configureWidgetFont(text_lbl, PgModelerUiNs::MediumFontFactor); parent->installEventFilter(this); - setIconSize(SMALL_ICON); + setIconSize(SmallIcon); connect(hint_tb, SIGNAL(toggled(bool)), this, SLOT(setVisible(bool))); } @@ -95,17 +95,20 @@ void HintTextWidget::setText(const QString &text) QFontMetrics f=text_lbl->fontMetrics(); QString txt=text; QRect ret; - QSize txt_size; + QSize txt_size, max_size; txt.replace(QRegExp(QString("(<)(br)(/)?(>)")), QString("\n")); txt.remove(QRegExp(QString("(<)(/)?([a-z]|[A-Z])+(>)"))); ret=f.boundingRect(0,0, this->maximumWidth(), this->maximumHeight(), Qt::TextWordWrap | Qt::AlignLeft | Qt::AlignTop , txt); txt_size=QSize(ret.size().width() + 15, ret.size().height() + 15); + max_size=txt_size; + max_size.setWidth(max_size.width() * 1.025); + max_size.setHeight(max_size.height() * 1.05); text_lbl->setMargin(5); text_lbl->setText(text); - text_lbl->setMaximumSize(txt_size); - text_lbl->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); + text_lbl->setMaximumSize(max_size); + text_lbl->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Preferred); this->setMinimumSize(txt_size); this->adjustSize(); } @@ -113,9 +116,9 @@ void HintTextWidget::setText(const QString &text) void HintTextWidget::setIconSize(unsigned icon_sz) { if(icon_sz==0) - icon_sz=SMALL_ICON; - else if(icon_sz > LARGE_ICON) - icon_sz=LARGE_ICON; + icon_sz=SmallIcon; + else if(icon_sz > LargeIcon) + icon_sz=LargeIcon; hint_tb->setMaximumSize(icon_sz + 8, icon_sz + 8); hint_tb->setIconSize(QSize(icon_sz, icon_sz)); @@ -129,7 +132,7 @@ QString HintTextWidget::getText(void) bool HintTextWidget::eventFilter(QObject *object, QEvent *event) { //Close the hint when it text lost its focus - if(object==text_lbl && (event->type()==QEvent::MouseButtonPress || event->type()==QEvent::FocusOut)) + if(object==text_lbl && (event->type()==QEvent::MouseButtonDblClick || event->type()==QEvent::FocusOut)) { hint_tb->setChecked(false); return(true); @@ -140,3 +143,9 @@ bool HintTextWidget::eventFilter(QObject *object, QEvent *event) return(QWidget::eventFilter(object, event)); } + +void HintTextWidget::showEvent(QShowEvent *) +{ + this->activateWindow(); + this->raise(); +} diff --git a/libpgmodeler_ui/src/hinttextwidget.h b/libpgmodeler_ui/src/hinttextwidget.h index d49c5bf8b8..bc5c345391 100644 --- a/libpgmodeler_ui/src/hinttextwidget.h +++ b/libpgmodeler_ui/src/hinttextwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -41,10 +41,12 @@ class HintTextWidget: public QWidget, public Ui::HintTextWidget { bool eventFilter(QObject *object, QEvent *event); + void showEvent(QShowEvent *); + public: - const static unsigned SMALL_ICON=16, - MEDIUM_ICON=24, - LARGE_ICON=32; + static constexpr unsigned SmallIcon=16, + MediumIcon=24, + LargeIcon=32; HintTextWidget(QWidget *btn_parent, QWidget *parent); diff --git a/libpgmodeler_ui/src/htmlitemdelegate.cpp b/libpgmodeler_ui/src/htmlitemdelegate.cpp index 7374ab0063..f30a5bec25 100644 --- a/libpgmodeler_ui/src/htmlitemdelegate.cpp +++ b/libpgmodeler_ui/src/htmlitemdelegate.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -45,7 +45,7 @@ void HtmlItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opti text.replace(QString("\n"), QString("
")); rect=QRect(QPoint(option.rect.left() + option.decorationSize.width() + 5, - option.rect.top()), option.rect.size()); + option.rect.top()), option.rect.size()); //Painting the correct background color according to the item state if((option.state & QStyle::State_Selected) == QStyle::State_Selected) @@ -63,7 +63,8 @@ void HtmlItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opti //Set the text to a html document instance and draw it to the painter doc.setHtml(text); - painter->translate(rect.topLeft()); + int dy = abs(option.rect.height() - option.decorationSize.height()) / 2; + painter->translate(rect.topLeft() - QPoint(0, dy)); doc.drawContents(painter); } diff --git a/libpgmodeler_ui/src/htmlitemdelegate.h b/libpgmodeler_ui/src/htmlitemdelegate.h index 902e9d2ee4..8bf17eeb0e 100644 --- a/libpgmodeler_ui/src/htmlitemdelegate.h +++ b/libpgmodeler_ui/src/htmlitemdelegate.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -34,7 +34,7 @@ class HtmlItemDelegate : public PlainTextItemDelegate { Q_OBJECT public: - HtmlItemDelegate(QObject * parent = 0); + HtmlItemDelegate(QObject * parent = nullptr); ~HtmlItemDelegate(void); protected: diff --git a/libpgmodeler_ui/src/indexwidget.cpp b/libpgmodeler_ui/src/indexwidget.cpp index fe8fb3a1c2..6bd9e240c2 100644 --- a/libpgmodeler_ui/src/indexwidget.cpp +++ b/libpgmodeler_ui/src/indexwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "indexwidget.h" -IndexWidget::IndexWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_INDEX) +IndexWidget::IndexWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Index) { try { @@ -31,23 +31,23 @@ IndexWidget::IndexWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_INDEX) Ui_IndexWidget::setupUi(this); predicate_hl=new SyntaxHighlighter(predicate_txt, false, true); - predicate_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + predicate_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); - elements_wgt = new ElementsWidget(this); + elements_tab = new ElementsTableWidget(this); grid=new QGridLayout; grid->setContentsMargins(4,4,4,4); - grid->addWidget(elements_wgt,0,0); + grid->addWidget(elements_tab,0,0); tabWidget->widget(1)->setLayout(grid); - configureFormLayout(index_grid, OBJ_INDEX); + configureFormLayout(index_grid, ObjectType::Index); IndexingType::getTypes(list); indexing_cmb->addItems(list); - fields_map[BaseObjectWidget::generateVersionsInterval(BaseObjectWidget::AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_92)].push_back(buffering_chk); - fields_map[BaseObjectWidget::generateVersionsInterval(BaseObjectWidget::AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_95)].push_back(indexing_lbl); - values_map[indexing_lbl].push_back(~IndexingType(IndexingType::brin)); + fields_map[BaseObjectWidget::generateVersionsInterval(BaseObjectWidget::AfterVersion, PgSqlVersions::PgSqlVersion92)].push_back(buffering_chk); + fields_map[BaseObjectWidget::generateVersionsInterval(BaseObjectWidget::AfterVersion, PgSqlVersions::PgSqlVersion95)].push_back(indexing_lbl); + values_map[indexing_lbl].push_back(~IndexingType(IndexingType::Brin)); frame=BaseObjectWidget::generateVersionWarningFrame(fields_map, &values_map); frame->setParent(this); @@ -56,7 +56,7 @@ IndexWidget::IndexWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_INDEX) connect(indexing_cmb, SIGNAL(currentIndexChanged(int)), this, SLOT(selectIndexingType(void))); connect(fill_factor_chk, SIGNAL(toggled(bool)), fill_factor_sb, SLOT(setEnabled(bool))); - connect(elements_wgt, SIGNAL(s_elementHandled(int)), this, SLOT(enableSortingOptions())); + //connect(elements_tab, SIGNAL(s_elementHandled(int)), this, SLOT(enableSortingOptions())); configureTabOrder(); selectIndexingType(); @@ -65,38 +65,37 @@ IndexWidget::IndexWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_INDEX) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void IndexWidget::selectIndexingType(void) { - fast_update_chk->setEnabled(IndexingType(indexing_cmb->currentText())==IndexingType::gin); - buffering_chk->setEnabled(IndexingType(indexing_cmb->currentText())==IndexingType::gist); + fast_update_chk->setEnabled(IndexingType(indexing_cmb->currentText())==IndexingType::Gin); + buffering_chk->setEnabled(IndexingType(indexing_cmb->currentText())==IndexingType::Gist); fill_factor_sb->setEnabled(fill_factor_chk->isChecked() && fill_factor_chk->isEnabled()); - enableSortingOptions(); } -void IndexWidget::enableSortingOptions(void) +/*void IndexWidget::enableSortingOptions(void) { - elements_wgt->sorting_chk->setEnabled(IndexingType(indexing_cmb->currentText())==IndexingType::btree); - elements_wgt->ascending_rb->setEnabled(elements_wgt->sorting_chk->isEnabled()); - elements_wgt->descending_rb->setEnabled(elements_wgt->sorting_chk->isEnabled()); - elements_wgt->nulls_first_chk->setEnabled(elements_wgt->sorting_chk->isEnabled()); + elements_tab->sorting_chk->setEnabled(IndexingType(indexing_cmb->currentText())==IndexingType::btree); + elements_tab->ascending_rb->setEnabled(elements_tab->sorting_chk->isEnabled()); + elements_tab->descending_rb->setEnabled(elements_tab->sorting_chk->isEnabled()); + elements_tab->nulls_first_chk->setEnabled(elements_tab->sorting_chk->isEnabled()); - if(!elements_wgt->sorting_chk->isEnabled()) + if(!elements_tab->sorting_chk->isEnabled()) { - elements_wgt->sorting_chk->setChecked(false); - elements_wgt->nulls_first_chk->setChecked(false); + elements_tab->sorting_chk->setChecked(false); + elements_tab->nulls_first_chk->setChecked(false); } -} +}*/ void IndexWidget::setAttributes(DatabaseModel *model, OperationList *op_list, BaseTable *parent_obj, Index *index) { vector idx_elems; if(!parent_obj) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); BaseObjectWidget::setAttributes(model, op_list, index, parent_obj); @@ -113,16 +112,17 @@ void IndexWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Ba else fill_factor_sb->setValue(90); - concurrent_chk->setChecked(index->getIndexAttribute(Index::CONCURRENT)); - fast_update_chk->setChecked(index->getIndexAttribute(Index::FAST_UPDATE)); - unique_chk->setChecked(index->getIndexAttribute(Index::UNIQUE)); - buffering_chk->setChecked(index->getIndexAttribute(Index::BUFFERING)); + concurrent_chk->setChecked(index->getIndexAttribute(Index::Concurrent)); + fast_update_chk->setChecked(index->getIndexAttribute(Index::FastUpdate)); + unique_chk->setChecked(index->getIndexAttribute(Index::Unique)); + buffering_chk->setChecked(index->getIndexAttribute(Index::Buffering)); predicate_txt->setPlainText(index->getPredicate()); selectIndexingType(); } - elements_wgt->setAttributes(model, parent_obj, idx_elems); + elements_tab->setAttributes(model, parent_obj); + elements_tab->setElements(idx_elems); } void IndexWidget::applyConfiguration(void) @@ -138,10 +138,10 @@ void IndexWidget::applyConfiguration(void) BaseObjectWidget::applyConfiguration(); - index->setIndexAttribute(Index::FAST_UPDATE, fast_update_chk->isChecked()); - index->setIndexAttribute(Index::CONCURRENT, concurrent_chk->isChecked()); - index->setIndexAttribute(Index::UNIQUE, unique_chk->isChecked()); - index->setIndexAttribute(Index::BUFFERING, buffering_chk->isChecked()); + index->setIndexAttribute(Index::FastUpdate, fast_update_chk->isChecked()); + index->setIndexAttribute(Index::Concurrent, concurrent_chk->isChecked()); + index->setIndexAttribute(Index::Unique, unique_chk->isChecked()); + index->setIndexAttribute(Index::Buffering, buffering_chk->isChecked()); index->setPredicate(predicate_txt->toPlainText().toUtf8()); index->setIndexingType(IndexingType(indexing_cmb->currentText())); @@ -150,7 +150,7 @@ void IndexWidget::applyConfiguration(void) else index->setFillFactor(0); - elements_wgt->getElements(idx_elems); + elements_tab->getElements(idx_elems); index->addIndexElements(idx_elems); finishConfiguration(); @@ -158,7 +158,7 @@ void IndexWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/indexwidget.h b/libpgmodeler_ui/src/indexwidget.h index 2a52493e33..ec2edfc063 100644 --- a/libpgmodeler_ui/src/indexwidget.h +++ b/libpgmodeler_ui/src/indexwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -27,8 +27,8 @@ #include "baseobjectwidget.h" #include "ui_indexwidget.h" -#include "objectstablewidget.h" -#include "elementswidget.h" +//#include "objectstablewidget.h" +#include "elementstablewidget.h" class IndexWidget: public BaseObjectWidget, public Ui::IndexWidget { private: @@ -37,15 +37,16 @@ class IndexWidget: public BaseObjectWidget, public Ui::IndexWidget { //! \brief Syntax highlighter for predicate SyntaxHighlighter *predicate_hl; - ElementsWidget *elements_wgt; + //ElementWidget *elements_wgt; + ElementsTableWidget *elements_tab; public: - IndexWidget(QWidget * parent = 0); + IndexWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, BaseTable *parent_obj, Index *index); private slots: void selectIndexingType(void); - void enableSortingOptions(void); + //void enableSortingOptions(void); public slots: void applyConfiguration(void); diff --git a/libpgmodeler_ui/src/languagewidget.cpp b/libpgmodeler_ui/src/languagewidget.cpp index 146fa04c13..e50bd20f2e 100644 --- a/libpgmodeler_ui/src/languagewidget.cpp +++ b/libpgmodeler_ui/src/languagewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "languagewidget.h" -LanguageWidget::LanguageWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_LANGUAGE) +LanguageWidget::LanguageWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Language) { try { @@ -29,15 +29,15 @@ LanguageWidget::LanguageWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_LA func_validator_sel=nullptr; func_inline_sel=nullptr; - func_handler_sel=new ObjectSelectorWidget(OBJ_FUNCTION, true, this); - func_validator_sel=new ObjectSelectorWidget(OBJ_FUNCTION, true, this); - func_inline_sel=new ObjectSelectorWidget(OBJ_FUNCTION, true, this); + func_handler_sel=new ObjectSelectorWidget(ObjectType::Function, true, this); + func_validator_sel=new ObjectSelectorWidget(ObjectType::Function, true, this); + func_inline_sel=new ObjectSelectorWidget(ObjectType::Function, true, this); language_grid->addWidget(func_handler_sel,1,1,1,2); language_grid->addWidget(func_validator_sel,2,1,1,2); language_grid->addWidget(func_inline_sel,3,1,1,2); - configureFormLayout(language_grid, OBJ_LANGUAGE); + configureFormLayout(language_grid, ObjectType::Language); frame=generateInformationFrame(trUtf8("The functions to be assigned to the language should have, respectively, the following signatures:

Handler Function: language_handler function()
Validator Function: void function(oid)
Inline Function: void function(internal)")); @@ -51,7 +51,7 @@ LanguageWidget::LanguageWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_LA } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -66,9 +66,9 @@ void LanguageWidget::setAttributes(DatabaseModel *model, OperationList *op_list, if(language) { trusted_chk->setChecked(language->isTrusted()); - func_handler_sel->setSelectedObject(language->getFunction(Language::HANDLER_FUNC)); - func_validator_sel->setSelectedObject(language->getFunction(Language::VALIDATOR_FUNC)); - func_inline_sel->setSelectedObject(language->getFunction(Language::INLINE_FUNC)); + func_handler_sel->setSelectedObject(language->getFunction(Language::HandlerFunc)); + func_validator_sel->setSelectedObject(language->getFunction(Language::ValidatorFunc)); + func_inline_sel->setSelectedObject(language->getFunction(Language::InlineFunc)); } } @@ -83,9 +83,9 @@ void LanguageWidget::applyConfiguration(void) language=dynamic_cast(this->object); language->setTrusted(trusted_chk->isChecked()); - language->setFunction(dynamic_cast(func_handler_sel->getSelectedObject()), Language::HANDLER_FUNC); - language->setFunction(dynamic_cast(func_validator_sel->getSelectedObject()), Language::VALIDATOR_FUNC); - language->setFunction(dynamic_cast(func_inline_sel->getSelectedObject()), Language::INLINE_FUNC); + language->setFunction(dynamic_cast(func_handler_sel->getSelectedObject()), Language::HandlerFunc); + language->setFunction(dynamic_cast(func_validator_sel->getSelectedObject()), Language::ValidatorFunc); + language->setFunction(dynamic_cast(func_inline_sel->getSelectedObject()), Language::InlineFunc); BaseObjectWidget::applyConfiguration(); finishConfiguration(); @@ -93,7 +93,7 @@ void LanguageWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/languagewidget.h b/libpgmodeler_ui/src/languagewidget.h index dad3985938..3d915076c9 100644 --- a/libpgmodeler_ui/src/languagewidget.h +++ b/libpgmodeler_ui/src/languagewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -37,7 +37,7 @@ class LanguageWidget: public BaseObjectWidget, public Ui::LanguageWidget { *func_inline_sel; public: - LanguageWidget(QWidget * parent = 0); + LanguageWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Language *language); diff --git a/libpgmodeler_ui/src/layerswidget.cpp b/libpgmodeler_ui/src/layerswidget.cpp new file mode 100644 index 0000000000..32269b33ca --- /dev/null +++ b/libpgmodeler_ui/src/layerswidget.cpp @@ -0,0 +1,201 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "layerswidget.h" + +LayersWidget::LayersWidget(QWidget *parent) : QWidget(parent) +{ + setupUi(this); + setModel(nullptr); + curr_item = nullptr; + curr_row = -1; + layers_lst->installEventFilter(this); + + connect(hide_tb, SIGNAL(clicked(bool)), this, SIGNAL(s_visibilityChanged(bool))); + connect(layers_lst, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(startLayerRenaming(QListWidgetItem*))); + connect(layers_lst, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(updateActiveLayers())); + connect(layers_lst, SIGNAL(itemSelectionChanged()), this, SLOT(finishLayerRenaming())); + connect(layers_lst, SIGNAL(itemSelectionChanged()), this, SLOT(enableButtons())); + connect(add_tb, SIGNAL(clicked(bool)), this, SLOT(addLayer())); + connect(remove_tb, SIGNAL(clicked(bool)), this, SLOT(removeLayer(bool))); + connect(remove_all_tb, &QToolButton::clicked, [&](){ + removeLayer(true); + }); +} + +void LayersWidget::updateLayers(void) +{ + QListWidgetItem *item = nullptr; + + for(auto &layer : model->scene->getLayers()) + { + item = new QListWidgetItem(layer); + item->setFlags(item->flags() | Qt::ItemIsUserCheckable); + item->setCheckState(model->scene->isLayerActive(layer) ? Qt::Checked : Qt::Unchecked); + layers_lst->addItem(item); + } +} + +bool LayersWidget::eventFilter(QObject *watched, QEvent *event) +{ + if(watched == layers_lst && event->type() == QEvent::KeyPress) + { + QKeyEvent *k_event = dynamic_cast(event); + + if(curr_item && (k_event->key() == Qt::Key_Enter || k_event->key() == Qt::Key_Return)) + finishLayerRenaming(); + else if(!curr_item && k_event->key() == Qt::Key_F2 && layers_lst->currentRow() > 0) + startLayerRenaming(layers_lst->currentItem()); + } + + return(false); +} + +void LayersWidget::updateActiveLayers(void) +{ + QStringList active_layers; + QListWidgetItem *item = nullptr; + + for(int row = 0; row < layers_lst->count(); row++) + { + item = layers_lst->item(row); + + if(item->checkState() == Qt::Checked) + active_layers.push_back(item->text()); + } + + model->scene->setActiveLayers(active_layers); + emit s_activeLayersChanged(); +} + +void LayersWidget::removeLayer(bool clear) +{ + QListWidgetItem *item = nullptr; + Messagebox msg_box; + + if(clear) + msg_box.show(trUtf8("This action will delete all layers (except the default one) and the objects in them will be moved to the default layer. Do you want to proceed?"), + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); + else + msg_box.show(trUtf8("Delete the selected layer will cause objects in it to be moved to the default layer. Do you want to proceed?"), + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); + + if(msg_box.result() == QDialog::Accepted) + { + if(clear) + { + model->scene->removeLayers(); + + while(layers_lst->count() > 1) + { + item = layers_lst->takeItem(layers_lst->count() - 1); + delete(item); + } + } + else if(layers_lst->currentRow() > 0) + { + item = layers_lst->currentItem(); + model->scene->removeLayer(item->text()); + layers_lst->takeItem(layers_lst->currentRow()); + delete(item); + } + + layers_lst->setCurrentRow(-1); + enableButtons(); + } +} + +void LayersWidget::enableButtons(void) +{ + remove_tb->setEnabled(layers_lst->currentRow() > 0); + remove_all_tb->setEnabled(layers_lst->count() > 1); +} + +void LayersWidget::setVisible(bool value) +{ + QWidget::setVisible(value); + emit s_visibilityChanged(value); +} + +void LayersWidget::setModel(ModelWidget *model) +{ + bool enable = model != nullptr; + + this->model = model; + layers_lst->clear(); + add_tb->setEnabled(enable); + + if(model) + updateLayers(); +} + +QListWidgetItem *LayersWidget::addLayer(const QString &name) +{ + QListWidgetItem *item = nullptr; + QString aux_name = name.isEmpty() ? trUtf8("New layer") : name; + + aux_name = model->scene->addLayer(aux_name); + item = new QListWidgetItem(aux_name); + item->setFlags((item->flags() | Qt::ItemIsUserCheckable) ^ Qt::ItemIsEditable); + item->setCheckState(Qt::Unchecked); + + layers_lst->addItem(item); + + /* Reconfigure the model's menu if we have selected items so the new layer can + * appear in the "Move to layer" quick action */ + if(!model->scene->selectedItems().isEmpty()) + model->configureObjectSelection(); + + enableButtons(); + + return(item); +} + +void LayersWidget::startLayerRenaming(QListWidgetItem *item) +{ + if(layers_lst->item(0) != item) + { + curr_item = item; + curr_text = item->text(); + curr_row = layers_lst->currentRow(); + layers_lst->openPersistentEditor(item); + } +} + +void LayersWidget::finishLayerRenaming(void) +{ + if(curr_item) + { + layers_lst->closePersistentEditor(curr_item); + + if(curr_item->text().isEmpty()) + curr_item->setText(curr_text); + else + curr_item->setText(model->scene->renameLayer(curr_row, curr_item->text())); + + curr_item = nullptr; + curr_text.clear(); + curr_row = -1; + + /* Reconfigure the model's menu if we have selected items so the renamed layer can + * appear in the "Move to layer" quick action */ + if(!model->scene->selectedItems().isEmpty()) + model->configureObjectSelection(); + } +} + diff --git a/libpgmodeler_ui/src/layerswidget.h b/libpgmodeler_ui/src/layerswidget.h new file mode 100644 index 0000000000..7e461c5e0a --- /dev/null +++ b/libpgmodeler_ui/src/layerswidget.h @@ -0,0 +1,90 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +/** +\ingroup libpgmodeler_ui +\class LayersWidget +\brief Implements the widget that allows the user to handle scene layers +*/ + +#ifndef LAYERS_WIDGET_H +#define LAYERS_WIDGET_H + +#include +#include "ui_layerswidget.h" +#include "modelwidget.h" + +class LayersWidget : public QWidget, Ui::LayersWidget { + private: + Q_OBJECT + + //! \brief Model in which the layer widget will operate on + ModelWidget *model; + + /*! \brief The current selected item in the layers list. We need to store it in a separated attribute + * for renaming purposes */ + QListWidgetItem *curr_item; + + //! \brief Stores the current's item text (layer name) to revert the renaming if the user aborts it + QString curr_text; + + //! \brief Stores the current's item row + int curr_row; + + //! \brief Configures the layers listing + void updateLayers(void); + + bool eventFilter(QObject *watched, QEvent *event); + + public: + explicit LayersWidget(QWidget *parent = nullptr); + + //! \brief Defines the model in which the widget will work + void setModel(ModelWidget *model); + + private slots: + //! \brief Add a new item (layer) to the listing. If the provided name is empty a default name is assigned + QListWidgetItem *addLayer(const QString &name = QString()); + + //! \brief Triggers the renaming operation over a item + void startLayerRenaming(QListWidgetItem *item); + + //! \brief Finishes the renaming operation over a item + void finishLayerRenaming(void); + + //! \brief Updates the active layeres on the scene causing a redraw of the items + void updateActiveLayers(void); + + //! \brief Remove a layer from the listing. If 'clear' is true them all layers (except the default) are removed + void removeLayer(bool clear = false); + + //! \brief Enables the control buttons according to the selection on the list + void enableButtons(void); + + public slots: + void setVisible(bool value); + + signals: + //! \brief Signal emitted whenever the widget changes its visibility + void s_visibilityChanged(bool); + + //! \brief Signal emitted whenever the current active layers change + void s_activeLayersChanged(void); +}; + +#endif diff --git a/libpgmodeler_ui/src/linenumberswidget.cpp b/libpgmodeler_ui/src/linenumberswidget.cpp index 11db826fd8..10fe35be3c 100644 --- a/libpgmodeler_ui/src/linenumberswidget.cpp +++ b/libpgmodeler_ui/src/linenumberswidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -19,14 +19,23 @@ #include "linenumberswidget.h" #include #include +#include "exception.h" QColor LineNumbersWidget::font_color=Qt::lightGray; QColor LineNumbersWidget::bg_color=Qt::black; LineNumbersWidget::LineNumbersWidget(QPlainTextEdit * parent) : QWidget(parent) { - first_line=line_count=0; + if(!parent) + throw Exception(ErrorCode::AsgNotAllocattedObject ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + parent_edt = qobject_cast(parent); + first_line=line_count=start_sel_pos=0; dy=0; + has_selection = false; + start_sel_line = -1; + + connect(parent_edt, SIGNAL(selectionChanged()), this, SLOT(update())); } void LineNumbersWidget::drawLineNumbers(unsigned first_line, unsigned line_count, int dy) @@ -51,8 +60,20 @@ void LineNumbersWidget::setColors(const QColor &font_color, const QColor &bg_col void LineNumbersWidget::paintEvent(QPaintEvent *event) { QPainter painter(this); - int y=dy, height=fontMetrics().height(); + int y = dy, height = 0; unsigned last_line=first_line + line_count; + QFont font = painter.font(); + unsigned fs_line = 0, ls_line = 0; + QTextCursor cursor = parent_edt->textCursor(); + + if(cursor.hasSelection()) + { + QTextCursor start = cursor, end = cursor; + start.setPosition(cursor.selectionStart(), QTextCursor::MoveAnchor); + fs_line = start.blockNumber(); + end.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor); + ls_line = end.blockNumber(); + } //Repaint the widget to clear previous drawn numbers painter.fillRect(event->rect(), bg_color); @@ -61,15 +82,77 @@ void LineNumbersWidget::paintEvent(QPaintEvent *event) //Draw line numbers for(unsigned lin=first_line; lin < last_line; lin++) { - painter.drawText(0, y, this->width(), fontMetrics().height(), - Qt::AlignHCenter, QString::number(lin)); + font.setBold(cursor.hasSelection() && lin-1 >= fs_line && lin-1 <= ls_line); + height = QFontMetrics(font).height(); + painter.setFont(font); + + if(font.bold()) + { + painter.setBrush(bg_color.dark(150)); + painter.setPen(Qt::transparent); + painter.drawRect(QRect(-1, y, this->width() + 1, height)); + painter.setPen(font_color.light(180)); + } + else + painter.setPen(font_color); + + painter.drawText(0, y, this->width(), height, Qt::AlignHCenter, QString::number(lin)); y+=height; } } -QColor LineNumbersWidget::getBackgroundColor(void) +void LineNumbersWidget::mousePressEvent(QMouseEvent *event) { - return(LineNumbersWidget::bg_color); + if(event->buttons() == Qt::LeftButton && !has_selection) + { + QTextCursor cursor = parent_edt->cursorForPosition(QPoint(0, event->pos().y())); + + has_selection = true; + cursor.select(QTextCursor::LineUnderCursor); + parent_edt->setTextCursor(cursor); + start_sel_line = cursor.blockNumber(); + start_sel_pos = cursor.position(); + } +} + +void LineNumbersWidget::mouseMoveEvent(QMouseEvent *event) +{ + if(event->buttons() == Qt::LeftButton && has_selection) + { + QTextCursor cursor = parent_edt->cursorForPosition(QPoint(0, event->pos().y())), + curr_cursor = parent_edt->textCursor(); + + //If the user wants selects lines below the first + if(start_sel_line < cursor.blockNumber()) + { + cursor.movePosition(QTextCursor::EndOfLine); + curr_cursor.setPosition(cursor.position(), QTextCursor::KeepAnchor); + parent_edt->setTextCursor(curr_cursor); + } + //If the user wants selects lines above the first + else if(start_sel_line > cursor.blockNumber()) + { + curr_cursor.setPosition(start_sel_pos); + curr_cursor.movePosition(QTextCursor::EndOfLine); + curr_cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, curr_cursor.position() - cursor.position()); + parent_edt->setTextCursor(curr_cursor); + } + else + { + cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor); + parent_edt->setTextCursor(cursor); + } + + this->update(); + } } +void LineNumbersWidget::mouseReleaseEvent(QMouseEvent *) +{ + has_selection = false; +} +QColor LineNumbersWidget::getBackgroundColor(void) +{ + return(LineNumbersWidget::bg_color); +} diff --git a/libpgmodeler_ui/src/linenumberswidget.h b/libpgmodeler_ui/src/linenumberswidget.h index ac83e76c25..8df8932b9c 100644 --- a/libpgmodeler_ui/src/linenumberswidget.h +++ b/libpgmodeler_ui/src/linenumberswidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -32,6 +32,10 @@ class LineNumbersWidget : public QWidget { private: Q_OBJECT + QPlainTextEdit *parent_edt; + + bool has_selection; + //! \brief The first line number that must be drawn unsigned first_line, @@ -41,6 +45,8 @@ class LineNumbersWidget : public QWidget { //! \brief The y axis increment to start drawn the line number int dy; + int start_sel_line, start_sel_pos; + //! \brief Font color for drawn line numbers static QColor font_color, @@ -49,9 +55,12 @@ class LineNumbersWidget : public QWidget { protected: void paintEvent(QPaintEvent *event); + void mousePressEvent(QMouseEvent *event); + void mouseMoveEvent(QMouseEvent *event); + void mouseReleaseEvent(QMouseEvent *); public: - explicit LineNumbersWidget(QPlainTextEdit *parent = 0); + explicit LineNumbersWidget(QPlainTextEdit *parent); /*! \brief Draw the lines starting from 'first_line' and stoping at fisrt_line + line_count -1. The dy param. defines an initial Y translation before drawn lines */ diff --git a/libpgmodeler_ui/src/mainwindow.cpp b/libpgmodeler_ui/src/mainwindow.cpp index d7ce6e8b05..df2ec6f820 100644 --- a/libpgmodeler_ui/src/mainwindow.cpp +++ b/libpgmodeler_ui/src/mainwindow.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -34,14 +34,17 @@ MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(par PluginsConfigWidget *plugins_conf_wgt=nullptr; QGridLayout *grid=nullptr; - pending_op=NO_PENDING_OPER; + pending_op=NoPendingOp; central_wgt=nullptr; - canvas_info_wgt = new SceneInfoWidget(this); - QHBoxLayout *hbox = new QHBoxLayout(canvas_info_parent); - hbox->addWidget(canvas_info_wgt); + layers_wgt = new LayersWidget(this); + layers_wgt->setVisible(false); + + scene_info_wgt = new SceneInfoWidget(this); + QHBoxLayout *hbox = new QHBoxLayout(scene_info_parent); + hbox->addWidget(scene_info_wgt); hbox->setContentsMargins(4,4,4,4); - canvas_info_parent->setLayout(hbox); + scene_info_parent->setLayout(hbox); QToolButton *tool_btn = qobject_cast(control_tb->widgetForAction(action_arrange_objects)); tool_btn->setMenu(&arrange_menu); @@ -60,29 +63,31 @@ MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(par grid->setContentsMargins(0,0,0,0); grid->setSpacing(0); grid->addWidget(central_wgt, 0, 0); - views_stw->widget(WELCOME_VIEW)->setLayout(grid); + views_stw->widget(WelcomeView)->setLayout(grid); - action_welcome->setData(WELCOME_VIEW); - action_design->setData(DESIGN_VIEW); - action_manage->setData(MANAGE_VIEW); + action_welcome->setData(WelcomeView); + action_design->setData(DesignView); + action_manage->setData(ManageView); sql_tool_wgt=new SQLToolWidget; grid=new QGridLayout; grid->setContentsMargins(0,0,0,0); grid->setSpacing(0); grid->addWidget(sql_tool_wgt, 0, 0); - views_stw->widget(MANAGE_VIEW)->setLayout(grid); + views_stw->widget(ManageView)->setLayout(grid); - configuration_form=new ConfigurationForm(nullptr, Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint); - PgModelerUiNS::resizeDialog(configuration_form); + configuration_form=new ConfigurationForm(nullptr, Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint); + PgModelerUiNs::resizeDialog(configuration_form); configuration_form->loadConfiguration(); - plugins_conf_wgt=dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::PLUGINS_CONF_WGT)); - plugins_conf_wgt->installPluginsActions(nullptr, plugins_menu, this, SLOT(executePlugin(void))); + plugins_conf_wgt=dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::PluginsConfWgt)); + plugins_conf_wgt->installPluginsActions(nullptr, plugins_menu, this, SLOT(executePlugin(void)), this); plugins_menu->setEnabled(!plugins_menu->isEmpty()); action_plugins->setEnabled(!plugins_menu->isEmpty()); action_plugins->setMenu(plugins_menu); + action_other_actions->setMenu(&more_actions_menu); + confs=GeneralConfigWidget::getConfigurationParams(); itr=confs.begin(); itr_end=confs.end(); @@ -91,19 +96,19 @@ MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(par while(itr!=itr_end) { attribs=itr->second; - if(attribs.count(ParsersAttributes::PATH)!=0) + if(attribs.count(Attributes::Path)!=0) { try { //Storing the file of a previous session - if(itr->first.contains(ParsersAttributes::_FILE_) && - !attribs[ParsersAttributes::PATH].isEmpty()) - prev_session_files.push_back(attribs[ParsersAttributes::PATH]); + if(itr->first.contains(Attributes::File) && + !attribs[Attributes::Path].isEmpty()) + prev_session_files.push_back(attribs[Attributes::Path]); //Creating the recent models menu - else if(itr->first.contains(ParsersAttributes::RECENT) && - !attribs[ParsersAttributes::PATH].isEmpty()) - recent_models.push_back(attribs[ParsersAttributes::PATH]); + else if(itr->first.contains(Attributes::Recent) && + !attribs[Attributes::Path].isEmpty()) + recent_models.push_back(attribs[Attributes::Path]); } catch(Exception &e) { @@ -118,6 +123,8 @@ MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(par //Enables the action to restore session when there are registered session files action_restore_session->setEnabled(!prev_session_files.isEmpty()); central_wgt->last_session_tb->setEnabled(action_restore_session->isEnabled()); + + } catch(Exception &e) { @@ -138,6 +145,7 @@ MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(par control_tb->addAction(action_bug_report); control_tb->addAction(action_donate); + control_tb->addAction(action_support); control_tb->addAction(action_about); control_tb->addAction(action_update_found); @@ -160,12 +168,13 @@ MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(par } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } connect(central_wgt->new_tb, SIGNAL(clicked()), this, SLOT(addModel())); connect(central_wgt->open_tb, SIGNAL(clicked()), this, SLOT(loadModel())); connect(central_wgt->last_session_tb, SIGNAL(clicked()), this, SLOT(restoreLastSession())); + connect(central_wgt->support_tb, SIGNAL(clicked()), this, SLOT(openSupport())); #ifndef NO_UPDATE_CHECK connect(update_notifier_wgt, SIGNAL(s_updateAvailable(bool)), action_update_found, SLOT(setVisible(bool))); @@ -203,12 +212,19 @@ MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(par connect(action_redo,SIGNAL(triggered(bool)),oper_list_wgt,SLOT(redoOperation(void))); connect(model_nav_wgt, SIGNAL(s_modelCloseRequested(int)), this, SLOT(closeModel(int))); - connect(model_nav_wgt, SIGNAL(s_currentModelChanged(int)), this, SLOT(setCurrentModel())); + connect(model_nav_wgt, SIGNAL(s_currentModelChanged(int)), this, SLOT(setCurrentModel())); connect(action_print, SIGNAL(triggered(bool)), this, SLOT(printModel(void))); - connect(action_configuration, SIGNAL(triggered(bool)), configuration_form, SLOT(show())); + + connect(action_configuration, &QAction::triggered, [&](){ + GeneralConfigWidget::restoreWidgetGeometry(configuration_form); + configuration_form->exec(); + GeneralConfigWidget::saveWidgetGeometry(configuration_form); + }); connect(oper_list_wgt, SIGNAL(s_operationExecuted(void)), overview_wgt, SLOT(updateOverview(void))); + connect(layers_wgt, SIGNAL(s_activeLayersChanged(void)), overview_wgt, SLOT(updateOverview(void))); + connect(configuration_form, SIGNAL(finished(int)), this, SLOT(applyConfigurations(void))); connect(configuration_form, SIGNAL(rejected()), this, SLOT(updateConnections())); connect(&model_save_timer, SIGNAL(timeout(void)), this, SLOT(saveAllModels(void))); @@ -227,7 +243,9 @@ MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(par connect(model_valid_wgt, &ModelValidationWidget::s_connectionsUpdateRequest, [&](){ updateConnections(true); }); connect(sql_tool_wgt, &SQLToolWidget::s_connectionsUpdateRequest, [&](){ updateConnections(true); }); - window_title=this->windowTitle() + QString(" ") + GlobalAttributes::PGMODELER_VERSION; + connect(action_compact_view, SIGNAL(toggled(bool)), this, SLOT(toggleCompactView())); + + window_title=this->windowTitle() + QString(" ") + GlobalAttributes::PgModelerVersion; #ifdef DEMO_VERSION window_title+=trUtf8(" (Demo)"); @@ -303,15 +321,18 @@ MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(par connect(model_valid_wgt, SIGNAL(s_validationInProgress(bool)), obj_finder_wgt, SLOT(setDisabled(bool))); connect(model_valid_wgt, SIGNAL(s_validationInProgress(bool)), models_tbw, SLOT(setDisabled(bool))); connect(model_valid_wgt, SIGNAL(s_validationInProgress(bool)), this, SLOT(stopTimers(bool))); + connect(model_valid_wgt, SIGNAL(s_validationInProgress(bool)), layers_btn, SLOT(setDisabled(bool))); + connect(model_valid_wgt, SIGNAL(s_validationInProgress(bool)), layers_wgt, SLOT(close())); - connect(model_valid_wgt, &ModelValidationWidget::s_validationCanceled, [&](){ pending_op=NO_PENDING_OPER; }); + connect(model_valid_wgt, &ModelValidationWidget::s_validationCanceled, [&](){ pending_op=NoPendingOp; }); connect(model_valid_wgt, SIGNAL(s_validationFinished(bool)), this, SLOT(executePendingOperation(bool))); connect(model_valid_wgt, SIGNAL(s_fixApplied()), this, SLOT(removeOperations()), Qt::QueuedConnection); connect(model_valid_wgt, SIGNAL(s_graphicalObjectsUpdated()), model_objs_wgt, SLOT(updateObjectsView()), Qt::QueuedConnection); - connect(&tmpmodel_save_timer, SIGNAL(timeout()), &tmpmodel_thread, SLOT(start())); - connect(&tmpmodel_thread, SIGNAL(started()), this, SLOT(saveTemporaryModels())); - connect(&tmpmodel_thread, &QThread::started, [&](){ tmpmodel_thread.setPriority(QThread::HighPriority); }); + connect(layers_btn, SIGNAL(toggled(bool)), this, SLOT(toggleLayersWidget(bool))); + connect(layers_wgt, SIGNAL(s_visibilityChanged(bool)), layers_btn, SLOT(setChecked(bool))); + + connect(&tmpmodel_save_timer, SIGNAL(timeout()), this, SLOT(saveTemporaryModels())); models_tbw_parent->resize(QSize(models_tbw_parent->maximumWidth(), models_tbw_parent->height())); @@ -321,7 +342,7 @@ MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(par showRightWidgetsBar(); showBottomWidgetsBar(); - GeneralConfigWidget *conf_wgt=dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::GENERAL_CONF_WGT)); + GeneralConfigWidget *conf_wgt=dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::GeneralConfWgt)); confs=conf_wgt->getConfigurationParams(); //If a previous session was restored save the temp models @@ -330,11 +351,9 @@ MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(par configureSamplesMenu(); applyConfigurations(); - //Temporary models are saved every two minutes - tmpmodel_save_timer.setInterval(120000); - QList actions=general_tb->actions(); QToolButton *btn=nullptr; + QFont font; for(auto &act : actions) { @@ -342,8 +361,11 @@ MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(par if(btn) { - PgModelerUiNS::configureWidgetFont(btn, PgModelerUiNS::SMALL_FONT_FACTOR); - btn->setGraphicsEffect(createDropShadow(btn)); + PgModelerUiNs::configureWidgetFont(btn, static_cast(PgModelerUiNs::MediumFontFactor)); + font = btn->font(); + font.setBold(true); + btn->setFont(font); + PgModelerUiNs::createDropShadow(btn); } } @@ -383,16 +405,17 @@ MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(par #ifndef Q_OS_MAC //Restoring the canvas grid options - action_show_grid->setChecked(confs[ParsersAttributes::CONFIGURATION][ParsersAttributes::SHOW_CANVAS_GRID]==ParsersAttributes::_TRUE_); - action_alin_objs_grade->setChecked(confs[ParsersAttributes::CONFIGURATION][ParsersAttributes::ALIGN_OBJS_TO_GRID]==ParsersAttributes::_TRUE_); - action_show_delimiters->setChecked(confs[ParsersAttributes::CONFIGURATION][ParsersAttributes::SHOW_PAGE_DELIMITERS]==ParsersAttributes::_TRUE_); + action_show_grid->setChecked(confs[Attributes::Configuration][Attributes::ShowCanvasGrid]==Attributes::True); + action_alin_objs_grade->setChecked(confs[Attributes::Configuration][Attributes::AlignObjsToGrid]==Attributes::True); + action_show_delimiters->setChecked(confs[Attributes::Configuration][Attributes::ShowPageDelimiters]==Attributes::True); + action_compact_view->setChecked(confs[Attributes::Configuration][Attributes::CompactView]==Attributes::True); ObjectsScene::setGridOptions(action_show_grid->isChecked(), action_alin_objs_grade->isChecked(), action_show_delimiters->isChecked()); //Hiding/showing the main menu bar depending on the retrieved conf - main_menu_mb->setVisible(confs[ParsersAttributes::CONFIGURATION][ParsersAttributes::SHOW_MAIN_MENU]==ParsersAttributes::_TRUE_); + main_menu_mb->setVisible(confs[Attributes::Configuration][Attributes::ShowMainMenu]==Attributes::True); if(main_menu_mb->isVisible()) file_menu->addAction(action_hide_main_menu); @@ -407,11 +430,15 @@ MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(par action_update_found->setVisible(false); QTimer::singleShot(1000, this, SLOT(restoreTemporaryModels())); + //If there's no previuos geometry registered for the mainwindow display it maximized + if(!GeneralConfigWidget::restoreWidgetGeometry(this)) + this->setWindowState(Qt::WindowMaximized); + #ifdef NO_UPDATE_CHECK #warning "NO UPDATE CHECK: Update checking is disabled." #else //Enabling update check at startup - if(confs[ParsersAttributes::CONFIGURATION][ParsersAttributes::CHECK_UPDATE]==ParsersAttributes::_TRUE_) + if(confs[Attributes::Configuration][Attributes::CheckUpdate]==Attributes::True) QTimer::singleShot(10000, update_notifier_wgt, SLOT(checkForUpdate())); #endif @@ -423,6 +450,19 @@ MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(par MainWindow::~MainWindow(void) { + ModelWidget *model = nullptr; + int idx = 0; + + /* Destroying models from the last to the first in order + * to destroy other objects inside the models in the proper order */ + while(models_tbw->count() > 0) + { + idx = models_tbw->count() - 1; + model = dynamic_cast(models_tbw->widget(idx)); + models_tbw->removeTab(idx); + delete(model); + } + //This fix the crash on exit at Mac OSX system (but not sure why) (???) file_menu->clear(); delete(restoration_form); @@ -432,7 +472,7 @@ MainWindow::~MainWindow(void) void MainWindow::restoreTemporaryModels(void) { - PgModelerUiNS::resizeDialog(restoration_form); + PgModelerUiNs::resizeDialog(restoration_form); //Restore temporary models (if exists) if(restoration_form->hasTemporaryModels()) @@ -495,6 +535,8 @@ void MainWindow::restoreLastSession(void) { try { + qApp->setOverrideCursor(Qt::WaitCursor); + while(!prev_session_files.isEmpty()) { this->addModel(prev_session_files.front()); @@ -503,9 +545,11 @@ void MainWindow::restoreLastSession(void) action_restore_session->setEnabled(false); central_wgt->last_session_tb->setEnabled(false); + qApp->restoreOverrideCursor(); } catch(Exception &e) { + qApp->restoreOverrideCursor(); Messagebox msg_box; msg_box.show(e); } @@ -518,12 +562,13 @@ void MainWindow::stopTimers(bool value) { tmpmodel_save_timer.stop(); model_save_timer.stop(); - tmpmodel_thread.quit(); } else { - tmpmodel_save_timer.start(); - model_save_timer.start(); + tmpmodel_save_timer.start(); + + if(model_save_timer.interval() < InfinityInterval) + model_save_timer.start(); } } @@ -537,11 +582,14 @@ void MainWindow::fixModel(const QString &filename) { QFileInfo fi(filename); model_fix_form.input_file_edt->setText(fi.absoluteFilePath()); - model_fix_form.output_file_edt->setText(fi.absolutePath() + GlobalAttributes::DIR_SEPARATOR + fi.baseName() + QString("_fixed.") + fi.suffix()); + model_fix_form.output_file_edt->setText(fi.absolutePath() + GlobalAttributes::DirSeparator + fi.baseName() + QString("_fixed.") + fi.suffix()); } - PgModelerUiNS::resizeDialog(&model_fix_form); + PgModelerUiNs::resizeDialog(&model_fix_form); + GeneralConfigWidget::restoreWidgetGeometry(&model_fix_form); model_fix_form.exec(); + GeneralConfigWidget::saveWidgetGeometry(&model_fix_form); + disconnect(&model_fix_form, nullptr, this, nullptr); } @@ -556,6 +604,8 @@ void MainWindow::resizeEvent(QResizeEvent *) action_about->setChecked(false); action_donate->setChecked(false); action_update_found->setChecked(false); + + toggleLayersWidget(layers_wgt->isVisible()); } void MainWindow::closeEvent(QCloseEvent *event) @@ -568,10 +618,11 @@ void MainWindow::closeEvent(QCloseEvent *event) GeneralConfigWidget *conf_wgt=nullptr; map confs; + GeneralConfigWidget::saveWidgetGeometry(this); + //Stops the saving timers as well the temp. model saving thread before close pgmodeler model_save_timer.stop(); tmpmodel_save_timer.stop(); - tmpmodel_thread.quit(); plugins_menu->clear(); //If not in demo version there is no confirmation before close the software @@ -598,7 +649,7 @@ void MainWindow::closeEvent(QCloseEvent *event) msg_box.show(trUtf8("Save modified model(s)"), trUtf8("The following models were modified but not saved: %1. Do you really want to quit pgModeler?").arg(model_names.join(", ")), - Messagebox::CONFIRM_ICON,Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon,Messagebox::YesNoButtons); /* If the user rejects the message box the close event will be aborted causing pgModeler not to be finished */ @@ -616,17 +667,19 @@ void MainWindow::closeEvent(QCloseEvent *event) attribs_map attribs; this->overview_wgt->close(); - conf_wgt=dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::GENERAL_CONF_WGT)); + conf_wgt=dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::GeneralConfWgt)); confs=conf_wgt->getConfigurationParams(); - attribs[ParsersAttributes::SHOW_MAIN_MENU]=main_menu_mb->isVisible() ? ParsersAttributes::_TRUE_ : QString(); - conf_wgt->addConfigurationParam(ParsersAttributes::CONFIGURATION, attribs); + attribs[Attributes::CompactView]=action_compact_view->isChecked() ? Attributes::True : QString(); + attribs[Attributes::ShowMainMenu]=main_menu_mb->isVisible() ? Attributes::True : QString(); + + conf_wgt->addConfigurationParam(Attributes::Configuration, attribs); attribs.clear(); count=models_tbw->count(); //Remove the references to old session - conf_wgt->removeConfigurationParam(QRegExp(QString("(%1)([0-9])+").arg(ParsersAttributes::_FILE_))); + conf_wgt->removeConfigurationParam(QRegExp(QString("(%1)([0-9])+").arg(Attributes::File))); //Saving the session for(i=0; i < count; i++) @@ -635,9 +688,9 @@ void MainWindow::closeEvent(QCloseEvent *event) if(!model->getFilename().isEmpty()) { - param_id=QString("%1%2").arg(ParsersAttributes::_FILE_).arg(i); - attribs[ParsersAttributes::ID]=param_id; - attribs[ParsersAttributes::PATH]=model->getFilename(); + param_id=QString("%1%2").arg(Attributes::File).arg(i); + attribs[Attributes::Id]=param_id; + attribs[Attributes::Path]=model->getFilename(); conf_wgt->addConfigurationParam(param_id, attribs); attribs.clear(); } @@ -652,9 +705,9 @@ void MainWindow::closeEvent(QCloseEvent *event) while(!recent_models.isEmpty()) { - param_id=QString("%1%2").arg(ParsersAttributes::RECENT).arg(i++); - attribs[ParsersAttributes::ID]=param_id; - attribs[ParsersAttributes::PATH]=recent_models.front(); + param_id=QString("%1%2").arg(Attributes::Recent).arg(QString::number(i++).rightJustified(2, '0')); + attribs[Attributes::Id]=param_id; + attribs[Attributes::Path]=recent_models.front(); conf_wgt->addConfigurationParam(param_id, attribs); attribs.clear(); recent_models.pop_front(); @@ -667,20 +720,7 @@ void MainWindow::closeEvent(QCloseEvent *event) storeDockWidgetsSettings(); conf_wgt->saveConfiguration(); - restoration_form->removeTemporaryModels(); - - //Remove import log files - QDir dir(GlobalAttributes::TEMPORARY_DIR); - QStringList log_files; - - dir.setNameFilters({QString("*.log")}); - log_files=dir.entryList(QDir::Files); - - while(!log_files.isEmpty()) - { - dir.remove(log_files.front()); - log_files.pop_front(); - } + restoration_form->removeTemporaryFiles(); SQLExecutionWidget::saveSQLHistory(); qApp->quit(); @@ -691,7 +731,7 @@ void MainWindow::closeEvent(QCloseEvent *event) void MainWindow::updateConnections(bool force) { ConnectionsConfigWidget *conn_cfg_wgt= - dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::CONNECTIONS_CONF_WGT)); + dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::ConnectionsConfWgt)); if(force || (!force && (conn_cfg_wgt->isConfigurationChanged() || model_valid_wgt->connections_cmb->count()==0 || @@ -704,7 +744,7 @@ void MainWindow::updateConnections(bool force) } if(sender()!=model_valid_wgt) - ConnectionsConfigWidget::fillConnectionsComboBox(model_valid_wgt->connections_cmb, true, Connection::OP_VALIDATION); + ConnectionsConfigWidget::fillConnectionsComboBox(model_valid_wgt->connections_cmb, true, Connection::OpValidation); } } @@ -720,7 +760,8 @@ void MainWindow::saveTemporaryModels(void) if(count > 0) { - canvas_info_parent->setVisible(false); + QApplication::setOverrideCursor(Qt::WaitCursor); + scene_info_parent->setVisible(false); bg_saving_wgt->setVisible(true); bg_saving_pb->setValue(0); bg_saving_wgt->repaint(); @@ -728,27 +769,26 @@ void MainWindow::saveTemporaryModels(void) for(int i=0; i < count; i++) { model=dynamic_cast(models_tbw->widget(i)); - bg_saving_pb->setValue(((i+1)/static_cast(count)) * 100); - - if(model->isModified() || !QFileInfo(model->getTempFilename()).exists()) - model->getDatabaseModel()->saveModel(model->getTempFilename(), SchemaParser::XML_DEFINITION); + bg_saving_pb->setValue(((i+1)/static_cast(count)) * 100); - QThread::msleep(200); + if(model->isModified()) + model->getDatabaseModel()->saveModel(model->getTempFilename(), SchemaParser::XmlDefinition); } bg_saving_pb->setValue(100); bg_saving_wgt->setVisible(false); - canvas_info_parent->setVisible(true); + scene_info_parent->setVisible(true); + QApplication::restoreOverrideCursor(); } - tmpmodel_thread.quit(); + tmpmodel_save_timer.start(); } catch(Exception &e) { + QApplication::restoreOverrideCursor(); Messagebox msg_box; - - tmpmodel_thread.quit(); msg_box.show(e); + tmpmodel_save_timer.start(); } #endif } @@ -759,7 +799,7 @@ void MainWindow::updateRecentModelsMenu(void) recent_mdls_menu.clear(); recent_models.removeDuplicates(); - for(int i=0; i < recent_models.size() && i < MAX_RECENT_MODELS; i++) + for(int i=0; i < recent_models.size() && i < GeneralConfigWidget::MaxRecentModels; i++) { act=recent_mdls_menu.addAction(QFileInfo(recent_models[i]).fileName(),this,SLOT(loadModelFromAction(void))); act->setToolTip(recent_models[i]); @@ -789,16 +829,19 @@ void MainWindow::loadModelFromAction(void) try { + qApp->setOverrideCursor(Qt::WaitCursor); addModel(filename); recent_models.push_back(act->data().toString()); updateRecentModelsMenu(); + qApp->restoreOverrideCursor(); } catch(Exception &e) { + qApp->restoreOverrideCursor(); if(QFileInfo(filename).exists()) showFixMessage(e, filename); else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } } @@ -815,7 +858,7 @@ void MainWindow::addModel(const QString &filename) #warning "DEMO VERSION: database model creation limit." if(models_tbw->count()==1) throw Exception(trUtf8("The demonstration version can create only `one' instance of database model!"), - ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); #endif try @@ -838,7 +881,7 @@ void MainWindow::addModel(const QString &filename) obj_name=model_tab->db_model->getName(); models_tbw->blockSignals(true); - models_tbw->setUpdatesEnabled(false); + models_tbw->setUpdatesEnabled(false); models_tbw->addTab(model_tab, obj_name); models_tbw->setCurrentIndex(models_tbw->count()-1); models_tbw->blockSignals(false); @@ -846,7 +889,6 @@ void MainWindow::addModel(const QString &filename) //Creating the system objects (public schema and languages C, SQL and pgpgsql) model_tab->db_model->createSystemObjects(filename.isEmpty()); - model_tab->db_model->setInvalidated(false); if(!filename.isEmpty()) { @@ -854,12 +896,16 @@ void MainWindow::addModel(const QString &filename) { model_tab->loadModel(filename); models_tbw->setTabToolTip(models_tbw->currentIndex(), filename); + //Get the "public" schema and set as system object - public_sch=dynamic_cast(model_tab->db_model->getObject(QString("public"), OBJ_SCHEMA)); + public_sch=dynamic_cast(model_tab->db_model->getObject(QString("public"), ObjectType::Schema)); if(public_sch) public_sch->setSystemObject(true); - models_tbw->setVisible(true); + model_tab->db_model->setInvalidated(false); model_tab->restoreLastCanvasPosition(); + + //Making a copy of the loaded database model file as the first version of the temp. model + QFile::copy(filename, model_tab->getTempFilename()); } catch(Exception &e) { @@ -874,32 +920,32 @@ void MainWindow::addModel(const QString &filename) //delete(model_tab); updateToolsState(true); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } model_nav_wgt->addModel(model_tab); - models_tbw->setUpdatesEnabled(true); + models_tbw->setUpdatesEnabled(true); + models_tbw->setVisible(true); setCurrentModel(); - if(start_timers) + if(start_timers) { - if(model_save_timer.interval() > 0) + if(model_save_timer.interval() > 0) model_save_timer.start(); tmpmodel_save_timer.start(); - } + } model_tab->setModified(false); + action_save_model->setEnabled(false); if(action_alin_objs_grade->isChecked()) current_model->scene->alignObjectsToGrid(); - - models_tbw->update(); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -908,9 +954,9 @@ void MainWindow::addModel(ModelWidget *model_wgt) try { if(!model_wgt) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(model_wgt->parent()) - throw Exception(ERR_ASG_WGT_ALREADY_HAS_PARENT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgWidgetAlreadyHasParent,__PRETTY_FUNCTION__,__FILE__,__LINE__); model_nav_wgt->addModel(model_wgt); @@ -926,7 +972,7 @@ void MainWindow::addModel(ModelWidget *model_wgt) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -938,7 +984,7 @@ int MainWindow::getModelCount(void) ModelWidget *MainWindow::getModel(int idx) { if(idx < 0 || idx > models_tbw->count()) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(dynamic_cast(models_tbw->widget(idx))); } @@ -956,6 +1002,7 @@ void MainWindow::showMainMenu(void) void MainWindow::setCurrentModel(void) { + layers_wgt->setVisible(false); models_tbw->setVisible(models_tbw->count() > 0); action_design->setEnabled(models_tbw->count() > 0); @@ -966,10 +1013,10 @@ void MainWindow::setCurrentModel(void) removeModelActions(); - edit_menu->clear(); - edit_menu->addAction(action_undo); - edit_menu->addAction(action_redo); - edit_menu->addSeparator(); + edit_menu->clear(); + edit_menu->addAction(action_undo); + edit_menu->addAction(action_redo); + edit_menu->addSeparator(); //Avoids the tree state saving in order to restore the current model tree state model_objs_wgt->saveTreeState(false); @@ -978,7 +1025,7 @@ void MainWindow::setCurrentModel(void) if(current_model) model_objs_wgt->saveTreeState(model_tree_states[current_model]); - models_tbw->setCurrentIndex(model_nav_wgt->getCurrentIndex()); + models_tbw->setCurrentIndex(model_nav_wgt->getCurrentIndex()); current_model=dynamic_cast(models_tbw->currentWidget()); action_arrange_objects->setEnabled(current_model != nullptr); @@ -986,11 +1033,14 @@ void MainWindow::setCurrentModel(void) { QToolButton *tool_btn=nullptr; QList btns; + QFont font; + layers_wgt->setModel(current_model); current_model->setFocus(Qt::OtherFocusReason); current_model->cancelObjectAddition(); + general_tb->addSeparator(); - general_tb->addAction(current_model->action_new_object); + general_tb->addAction(current_model->action_new_object); tool_btn=qobject_cast(general_tb->widgetForAction(current_model->action_new_object)); tool_btn->setPopupMode(QToolButton::InstantPopup); btns.push_back(tool_btn); @@ -1008,39 +1058,39 @@ void MainWindow::setCurrentModel(void) tool_btn=qobject_cast(general_tb->widgetForAction(current_model->action_source_code)); btns.push_back(tool_btn); - general_tb->addAction(current_model->action_select_all); - tool_btn=qobject_cast(general_tb->widgetForAction(current_model->action_select_all)); + more_actions_menu.clear(); + more_actions_menu.addAction(current_model->action_select_all); + more_actions_menu.addAction(current_model->action_fade); + more_actions_menu.addAction(current_model->action_collapse_mode); + more_actions_menu.addAction(current_model->action_edit_creation_order); + general_tb->addAction(action_other_actions); + tool_btn = qobject_cast(general_tb->widgetForAction(action_other_actions)); tool_btn->setPopupMode(QToolButton::InstantPopup); btns.push_back(tool_btn); - general_tb->addAction(current_model->action_fade); - tool_btn=qobject_cast(general_tb->widgetForAction(current_model->action_fade)); - tool_btn->setPopupMode(QToolButton::InstantPopup); - btns.push_back(tool_btn); - - general_tb->addAction(current_model->action_edit_creation_order); - tool_btn=qobject_cast(general_tb->widgetForAction(current_model->action_edit_creation_order)); - btns.push_back(tool_btn); - for(QToolButton *btn : btns) { - PgModelerUiNS::configureWidgetFont(btn, PgModelerUiNS::SMALL_FONT_FACTOR); - btn->setGraphicsEffect(createDropShadow(tool_btn)); - } + PgModelerUiNs::configureWidgetFont(btn, static_cast(PgModelerUiNs::MediumFontFactor)); + font = btn->font(); + font.setBold(true); + btn->setFont(font); + PgModelerUiNs::createDropShadow(btn); + } - edit_menu->addAction(current_model->action_copy); - edit_menu->addAction(current_model->action_cut); - edit_menu->addAction(current_model->action_duplicate); - edit_menu->addAction(current_model->action_paste); - edit_menu->addAction(current_model->action_remove); - edit_menu->addAction(current_model->action_cascade_del); + edit_menu->addAction(current_model->action_copy); + edit_menu->addAction(current_model->action_cut); + edit_menu->addAction(current_model->action_duplicate); + edit_menu->addAction(current_model->action_paste); + edit_menu->addAction(current_model->action_remove); + edit_menu->addAction(current_model->action_cascade_del); if(current_model->getFilename().isEmpty()) this->setWindowTitle(window_title); else this->setWindowTitle(window_title + QString(" - ") + QDir::toNativeSeparators(current_model->getFilename())); - connect(current_model, SIGNAL(s_manipulationCanceled(void)),this, SLOT(updateDockWidgets(void)), Qt::UniqueConnection); + //connect(current_model, SIGNAL(s_manipulationCanceled(void)),this, SLOT(updateDockWidgets(void)), Qt::UniqueConnection); + connect(current_model, SIGNAL(s_manipulationCanceled(void)),oper_list_wgt, SLOT(updateOperationList(void)), Qt::UniqueConnection); connect(current_model, SIGNAL(s_objectsMoved(void)),oper_list_wgt, SLOT(updateOperationList(void)), Qt::UniqueConnection); connect(current_model, SIGNAL(s_objectModified(void)),this, SLOT(updateDockWidgets(void)), Qt::UniqueConnection); connect(current_model, SIGNAL(s_objectCreated(void)),this, SLOT(updateDockWidgets(void)), Qt::UniqueConnection); @@ -1050,10 +1100,10 @@ void MainWindow::setCurrentModel(void) connect(current_model, SIGNAL(s_zoomModified(double)), this, SLOT(updateToolsState(void)), Qt::UniqueConnection); connect(current_model, SIGNAL(s_objectModified(void)), this, SLOT(updateModelTabName(void)), Qt::UniqueConnection); - connect(current_model, SIGNAL(s_sceneInteracted(BaseObjectView*)), canvas_info_wgt, SLOT(updateSelectedObject(BaseObjectView*)), Qt::UniqueConnection); - connect(current_model, SIGNAL(s_sceneInteracted(int,QRectF)), canvas_info_wgt, SLOT(updateSelectedObjects(int,QRectF)), Qt::UniqueConnection); - connect(current_model, SIGNAL(s_sceneInteracted(QPointF)), canvas_info_wgt, SLOT(updateMousePosition(QPointF)), Qt::UniqueConnection); - connect(current_model, SIGNAL(s_zoomModified(double)), canvas_info_wgt, SLOT(updateSceneZoom(double)), Qt::UniqueConnection); + connect(current_model, SIGNAL(s_sceneInteracted(BaseObjectView*)), scene_info_wgt, SLOT(updateSelectedObject(BaseObjectView*)), Qt::UniqueConnection); + connect(current_model, SIGNAL(s_sceneInteracted(int,QRectF)), scene_info_wgt, SLOT(updateSelectedObjects(int,QRectF)), Qt::UniqueConnection); + connect(current_model, SIGNAL(s_sceneInteracted(QPointF)), scene_info_wgt, SLOT(updateMousePosition(QPointF)), Qt::UniqueConnection); + connect(current_model, SIGNAL(s_zoomModified(double)), scene_info_wgt, SLOT(updateSceneZoom(double)), Qt::UniqueConnection); connect(action_alin_objs_grade, SIGNAL(triggered(bool)), this, SLOT(setGridOptions(void)), Qt::UniqueConnection); connect(action_show_grid, SIGNAL(triggered(bool)), this, SLOT(setGridOptions(void)), Qt::UniqueConnection); @@ -1065,8 +1115,8 @@ void MainWindow::setCurrentModel(void) if(action_overview->isChecked()) overview_wgt->show(current_model); - canvas_info_wgt->updateMousePosition(QPointF(0,0)); - canvas_info_wgt->updateSceneZoom(current_model->getCurrentZoom()); + scene_info_wgt->updateMousePosition(QPointF(0,0)); + scene_info_wgt->updateSceneZoom(current_model->getCurrentZoom()); current_model->emitSceneInteracted(); } else @@ -1090,7 +1140,7 @@ void MainWindow::setCurrentModel(void) void MainWindow::setGridOptions(void) { - GeneralConfigWidget *conf_wgt = dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::GENERAL_CONF_WGT)); + GeneralConfigWidget *conf_wgt = dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::GeneralConfWgt)); map attribs = conf_wgt->getConfigurationParams(); //Configures the global settings for the scene grid @@ -1098,9 +1148,9 @@ void MainWindow::setGridOptions(void) action_alin_objs_grade->isChecked(), action_show_delimiters->isChecked()); - attribs[ParsersAttributes::CONFIGURATION][ParsersAttributes::ALIGN_OBJS_TO_GRID] = (action_alin_objs_grade->isChecked() ? ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_); - attribs[ParsersAttributes::CONFIGURATION][ParsersAttributes::SHOW_CANVAS_GRID] = (action_show_grid->isChecked() ? ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_); - attribs[ParsersAttributes::CONFIGURATION][ParsersAttributes::SHOW_PAGE_DELIMITERS] = (action_show_delimiters->isChecked() ? ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_); + attribs[Attributes::Configuration][Attributes::AlignObjsToGrid] = (action_alin_objs_grade->isChecked() ? Attributes::True : Attributes::False); + attribs[Attributes::Configuration][Attributes::ShowCanvasGrid] = (action_show_grid->isChecked() ? Attributes::True : Attributes::False); + attribs[Attributes::Configuration][Attributes::ShowPageDelimiters] = (action_show_delimiters->isChecked() ? Attributes::True : Attributes::False); if(current_model) { @@ -1110,14 +1160,14 @@ void MainWindow::setGridOptions(void) current_model->scene->alignObjectsToGrid(); //Forcing the relationship updating to fit the new position of the tables - current_model->getDatabaseModel()->setObjectsModified({ OBJ_RELATIONSHIP, BASE_RELATIONSHIP }); + current_model->getDatabaseModel()->setObjectsModified({ ObjectType::Relationship, ObjectType::BaseRelationship }); } //Redraw the scene to apply the new grid options current_model->scene->update(); } - conf_wgt->addConfigurationParam(ParsersAttributes::CONFIGURATION, attribs[ParsersAttributes::CONFIGURATION]); + conf_wgt->addConfigurationParam(Attributes::Configuration, attribs[Attributes::Configuration]); } void MainWindow::applyZoom(void) @@ -1128,10 +1178,10 @@ void MainWindow::applyZoom(void) if(sender()==action_normal_zoom) zoom=1; - else if(sender()==action_inc_zoom && zoom < ModelWidget::MAXIMUM_ZOOM) - zoom+=ModelWidget::ZOOM_INCREMENT; - else if(sender()==action_dec_zoom && zoom > ModelWidget::MINIMUM_ZOOM) - zoom-=ModelWidget::ZOOM_INCREMENT; + else if(sender()==action_inc_zoom && zoom < ModelWidget::MaximumZoom) + zoom+=ModelWidget::ZoomIncrement; + else if(sender()==action_dec_zoom && zoom > ModelWidget::MinimumZoom) + zoom-=ModelWidget::ZoomIncrement; current_model->applyZoom(zoom); } @@ -1142,7 +1192,7 @@ void MainWindow::removeModelActions(void) QList act_list; act_list=general_tb->actions(); - while(act_list.size() > GENERAL_ACTIONS_COUNT) + while(act_list.size() > GeneralActionsCount) { general_tb->removeAction(act_list.back()); act_list.pop_back(); @@ -1173,7 +1223,7 @@ void MainWindow::closeModel(int model_id) { msg_box.show(trUtf8("Save model"), trUtf8("The model %1 was modified! Do you really want to close without save it?").arg(model->getDatabaseModel()->getName()), - Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); } #endif @@ -1230,21 +1280,21 @@ void MainWindow::updateModelTabName(void) void MainWindow::applyConfigurations(void) { - if(!sender() || + if(!sender() || (sender()==configuration_form && configuration_form->result()==QDialog::Accepted)) { GeneralConfigWidget *conf_wgt=nullptr; int count, i; ModelWidget *model=nullptr; - conf_wgt=dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::GENERAL_CONF_WGT)); + conf_wgt=dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::GeneralConfWgt)); //Disable the auto save if the option is not checked if(!conf_wgt->autosave_interv_chk->isChecked()) { //Stop the save timer - model_save_timer.stop(); - model_save_timer.setInterval(0); + model_save_timer.setInterval(InfinityInterval); + model_save_timer.stop(); } else { @@ -1252,6 +1302,12 @@ void MainWindow::applyConfigurations(void) model_save_timer.start(); } + //Temporary models are saved every five minutes + tmpmodel_save_timer.setInterval(model_save_timer.interval() < InfinityInterval ? model_save_timer.interval()/2 : 300000); + tmpmodel_save_timer.start(); + + QApplication::setOverrideCursor(Qt::WaitCursor); + //Force the update of all opened models count=models_tbw->count(); for(i=0; i < count; i++) @@ -1259,11 +1315,15 @@ void MainWindow::applyConfigurations(void) model=dynamic_cast(models_tbw->widget(i)); model->updateObjectsOpacity(); model->db_model->setObjectsModified(); - model->update(); } + if(current_model) + current_model->update(); + updateConnections(); - sql_tool_wgt->configureSnippets(); + sql_tool_wgt->configureSnippets(); + + QApplication::restoreOverrideCursor(); } sql_tool_wgt->updateTabs(); @@ -1292,7 +1352,7 @@ void MainWindow::saveModel(ModelWidget *model) Messagebox msg_box; msg_box.show(trUtf8("Warning"), trUtf8("You're running a demonstration version! The model saving feature is available only in the full version!"), - Messagebox::ALERT_ICON, Messagebox::OK_BUTTON); + Messagebox::AlertIcon, Messagebox::OkButton); #else try { @@ -1307,9 +1367,9 @@ void MainWindow::saveModel(ModelWidget *model) { msg_box.show(trUtf8("Confirmation"), trUtf8(" WARNING: The model %1 is invalidated! It's recommended to validate it before save in order to create a consistent model otherwise the generated file will be broken demanding manual fixes to be loadable again!").arg(db_model->getName()), - Messagebox::ALERT_ICON, Messagebox::ALL_BUTTONS, + Messagebox::AlertIcon, Messagebox::AllButtons, trUtf8("Validate"), trUtf8("Save anyway"), QString(), - PgModelerUiNS::getIconPath("validation"), PgModelerUiNS::getIconPath("salvar")); + PgModelerUiNs::getIconPath("validation"), PgModelerUiNs::getIconPath("salvar")); //If the user cancel the saving force the stopping of autosave timer to give user the chance to validate the model if(msg_box.isCancelled()) @@ -1322,7 +1382,7 @@ void MainWindow::saveModel(ModelWidget *model) else if(msg_box.result()==QDialog::Accepted) { validation_btn->setChecked(true); - this->pending_op=(sender()==action_save_as ? PENDING_SAVE_AS_OPER : PENDING_SAVE_OPER); + this->pending_op=(sender()==action_save_as ? PendingSaveAsOp : PendingSaveOp); action_design->setChecked(true); model_valid_wgt->validateModel(); } @@ -1336,7 +1396,7 @@ void MainWindow::saveModel(ModelWidget *model) && (model->isModified() || sender()==action_save_as)) { //If the action that calls the slot were the 'save as' or the model filename isn't set - if(sender()==action_save_as || model->filename.isEmpty() || pending_op==PENDING_SAVE_AS_OPER) + if(sender()==action_save_as || model->filename.isEmpty() || pending_op==PendingSaveAsOp) { QFileDialog file_dlg; @@ -1363,12 +1423,13 @@ void MainWindow::saveModel(ModelWidget *model) } stopTimers(false); + action_save_model->setEnabled(false); } } catch(Exception &e) { stopTimers(false); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } #endif } @@ -1385,14 +1446,14 @@ void MainWindow::exportModel(void) { msg_box.show(trUtf8("Confirmation"), trUtf8(" WARNING: The model %1 is invalidated! Before run the export process it's recommended to validate in order to correctly create the objects on database server!").arg(db_model->getName()), - Messagebox::ALERT_ICON, Messagebox::ALL_BUTTONS, + Messagebox::AlertIcon, Messagebox::AllButtons, trUtf8("Validate"), trUtf8("Export anyway"), QString(), - PgModelerUiNS::getIconPath("validation"), PgModelerUiNS::getIconPath("exportar")); + PgModelerUiNs::getIconPath("validation"), PgModelerUiNs::getIconPath("exportar")); if(msg_box.result()==QDialog::Accepted) { validation_btn->setChecked(true); - this->pending_op=PENDING_EXPORT_OPER; + this->pending_op=PendingExportOp; model_valid_wgt->validateModel(); } } @@ -1402,8 +1463,12 @@ void MainWindow::exportModel(void) { stopTimers(true); connect(&model_export_form, &ModelExportForm::s_connectionsUpdateRequest, [&](){ updateConnections(true); }); - PgModelerUiNS::resizeDialog(&model_export_form); + + PgModelerUiNs::resizeDialog(&model_export_form); + GeneralConfigWidget::restoreWidgetGeometry(&model_export_form); model_export_form.exec(current_model); + GeneralConfigWidget::saveWidgetGeometry(&model_export_form); + stopTimers(false); } } @@ -1416,8 +1481,10 @@ void MainWindow::importDatabase(void) connect(&db_import_form, &DatabaseImportForm::s_connectionsUpdateRequest, [&](){ updateConnections(true); }); db_import_form.setModelWidget(current_model); - PgModelerUiNS::resizeDialog(&db_import_form); + PgModelerUiNs::resizeDialog(&db_import_form); + GeneralConfigWidget::restoreWidgetGeometry(&db_import_form); db_import_form.exec(); + GeneralConfigWidget::saveWidgetGeometry(&db_import_form); stopTimers(false); if(db_import_form.result()==QDialog::Accepted && db_import_form.getModelWidget()) @@ -1439,14 +1506,14 @@ void MainWindow::diffModelDatabase(void) { msg_box.show(trUtf8("Confirmation"), trUtf8(" WARNING: The model %1 is invalidated! Before run the diff process it's recommended to validate in order to correctly analyze and generate the difference between the model and a database!").arg(db_model->getName()), - Messagebox::ALERT_ICON, Messagebox::ALL_BUTTONS, + Messagebox::AlertIcon, Messagebox::AllButtons, trUtf8("Validate"), trUtf8("Diff anyway"), QString(), - PgModelerUiNS::getIconPath("validation"), PgModelerUiNS::getIconPath("diff")); + PgModelerUiNs::getIconPath("validation"), PgModelerUiNs::getIconPath("diff")); if(msg_box.result()==QDialog::Accepted) { validation_btn->setChecked(true); - this->pending_op=PENDING_DIFF_OPER; + this->pending_op=PendingDiffOp; model_valid_wgt->validateModel(); } } @@ -1458,8 +1525,15 @@ void MainWindow::diffModelDatabase(void) stopTimers(true); connect(&modeldb_diff_frm, &ModelDatabaseDiffForm::s_connectionsUpdateRequest, [&](){ updateConnections(true); }); - PgModelerUiNS::resizeDialog(&modeldb_diff_frm); + connect(&modeldb_diff_frm, &ModelDatabaseDiffForm::s_loadDiffInSQLTool, [&](QString conn_id, QString database, QString filename){ + action_manage->toggle(); + sql_tool_wgt->addSQLExecutionTab(conn_id, database, filename); + }); + + PgModelerUiNs::resizeDialog(&modeldb_diff_frm); + GeneralConfigWidget::restoreWidgetGeometry(&modeldb_diff_frm); modeldb_diff_frm.exec(); + GeneralConfigWidget::saveWidgetGeometry(&modeldb_diff_frm); stopTimers(false); } } @@ -1475,7 +1549,7 @@ void MainWindow::printModel(void) QRectF margins; QSizeF custom_size; qreal ml,mt,mr,mb, ml1, mt1, mr1, mb1; - GeneralConfigWidget *conf_wgt=dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::GENERAL_CONF_WGT)); + GeneralConfigWidget *conf_wgt=dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::GeneralConfWgt)); print_dlg.setOption(QAbstractPrintDialog::PrintCurrentPage, false); print_dlg.setWindowTitle(trUtf8("Database model printing")); @@ -1507,7 +1581,7 @@ void MainWindow::printModel(void) orientation!=curr_orientation || curr_paper_size!=paper_size) { msg_box.show(trUtf8("Changes were detected in the definitions of paper/margin of the model which may cause the incorrect print of the objects. Do you want to continue printing using the new settings? To use the default settings click 'No' or 'Cancel' to abort printing."), - Messagebox::ALERT_ICON, Messagebox::ALL_BUTTONS); + Messagebox::AlertIcon, Messagebox::AllButtons); } if(!msg_box.isCancelled()) @@ -1528,7 +1602,7 @@ void MainWindow::loadModel(void) try { file_dlg.setNameFilter(trUtf8("Database model (*.dbm);;All files (*.*)")); - file_dlg.setWindowIcon(QPixmap(PgModelerUiNS::getIconPath("pgsqlModeler48x48"))); + file_dlg.setWindowIcon(QPixmap(PgModelerUiNs::getIconPath("pgsqlModeler48x48"))); file_dlg.setWindowTitle(trUtf8("Load model")); file_dlg.setFileMode(QFileDialog::ExistingFiles); file_dlg.setAcceptMode(QFileDialog::AcceptOpen); @@ -1554,16 +1628,20 @@ void MainWindow::loadModels(const QStringList &list) try { + qApp->setOverrideCursor(Qt::WaitCursor); + for(i=0; i < list.count(); i++) { addModel(list[i]); recent_models.push_front(list[i]); } - updateRecentModelsMenu(); + updateRecentModelsMenu(); + qApp->restoreOverrideCursor(); } catch(Exception &e) { + qApp->restoreOverrideCursor(); showFixMessage(e, list[i]); } } @@ -1572,12 +1650,12 @@ void MainWindow::showFixMessage(Exception &e, const QString &filename) { Messagebox msg_box; - msg_box.show(Exception(Exception::getErrorMessage(ERR_MODEL_FILE_NOT_LOADED).arg(filename), - ERR_MODEL_FILE_NOT_LOADED ,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e), - trUtf8("Could not load the database model file `%1'. Check the error stack to see details. You can try to fix it in order to make it loadable again.").arg(filename), - Messagebox::ERROR_ICON, Messagebox::YES_NO_BUTTONS, - trUtf8("Fix model"), trUtf8("Cancel"), QString(), - PgModelerUiNS::getIconPath("fixobject"), PgModelerUiNS::getIconPath("msgbox_erro")); + msg_box.show(Exception(Exception::getErrorMessage(ErrorCode::ModelFileNotLoaded).arg(filename), + ErrorCode::ModelFileNotLoaded ,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e), + trUtf8("Could not load the database model file `%1'. Check the error stack to see details. You can try to fix it in order to make it loadable again.").arg(filename), + Messagebox::ErrorIcon, Messagebox::YesNoButtons, + trUtf8("Fix model"), trUtf8("Cancel"), QString(), + PgModelerUiNs::getIconPath("fixobject"), PgModelerUiNs::getIconPath("msgbox_erro")); if(msg_box.result()==QDialog::Accepted) fixModel(filename); @@ -1599,10 +1677,9 @@ void MainWindow::updateToolsState(bool model_closed) action_print->setEnabled(enabled); action_save_as->setEnabled(enabled); - action_save_model->setEnabled(enabled); + action_save_model->setEnabled(!model_closed && current_model && current_model->isModified()); action_save_all->setEnabled(enabled); action_export->setEnabled(enabled); - //action_diff->setEnabled(enabled); action_close_model->setEnabled(enabled); action_show_grid->setEnabled(enabled); action_show_delimiters->setEnabled(enabled); @@ -1614,6 +1691,7 @@ void MainWindow::updateToolsState(bool model_closed) action_alin_objs_grade->setEnabled(enabled); action_undo->setEnabled(enabled); action_redo->setEnabled(enabled); + action_compact_view->setEnabled(enabled); action_handle_metadata->setEnabled(enabled); @@ -1622,9 +1700,9 @@ void MainWindow::updateToolsState(bool model_closed) action_undo->setEnabled(current_model->op_list->isUndoAvailable()); action_redo->setEnabled(current_model->op_list->isRedoAvailable()); - action_inc_zoom->setEnabled(current_model->getCurrentZoom() <= (ModelWidget::MAXIMUM_ZOOM - ModelWidget::ZOOM_INCREMENT)); + action_inc_zoom->setEnabled(current_model->getCurrentZoom() <= (ModelWidget::MaximumZoom - ModelWidget::ZoomIncrement)); action_normal_zoom->setEnabled(current_model->getCurrentZoom()!=0); - action_dec_zoom->setEnabled(current_model->getCurrentZoom() >= ModelWidget::MINIMUM_ZOOM); + action_dec_zoom->setEnabled(current_model->getCurrentZoom() >= ModelWidget::MinimumZoom); } } @@ -1638,7 +1716,7 @@ void MainWindow::updateDockWidgets(void) model_valid_wgt->setModel(current_model); if(current_model && obj_finder_wgt->result_tbw->rowCount() > 0) - obj_finder_wgt->findObjects(); + obj_finder_wgt->findObjects(); } void MainWindow::executePlugin(void) @@ -1664,14 +1742,7 @@ void MainWindow::showOverview(bool show) void MainWindow::openSupport(void) { - Messagebox msg_box; - - msg_box.show(trUtf8("Access support page"), - trUtf8("This action will open a web browser window! Want to proceed?"), - Messagebox::CONFIRM_ICON,Messagebox::YES_NO_BUTTONS); - - if(msg_box.result()==QDialog::Accepted) - QDesktopServices::openUrl(QUrl(GlobalAttributes::PGMODELER_SUPPORT)); + QDesktopServices::openUrl(QUrl(GlobalAttributes::PgModelerSupport)); } void MainWindow::toggleUpdateNotifier(bool show) @@ -1730,22 +1801,9 @@ void MainWindow::setFloatingWidgetPos(QWidget *widget, QAction *act, QToolBar *t } } -QGraphicsDropShadowEffect *MainWindow::createDropShadow(QToolButton *btn) -{ - QGraphicsDropShadowEffect *shadow=nullptr; - - shadow=new QGraphicsDropShadowEffect(btn); - shadow->setXOffset(2); - shadow->setYOffset(2); - shadow->setBlurRadius(5); - shadow->setColor(QColor(0,0,0, 100)); - - return(shadow); -} - void MainWindow::configureSamplesMenu(void) { - QDir dir(GlobalAttributes::SAMPLES_DIR); + QDir dir(GlobalAttributes::SamplesDir); QStringList files=dir.entryList({QString("*.dbm")}); QAction *act=nullptr; QString path; @@ -1753,7 +1811,7 @@ void MainWindow::configureSamplesMenu(void) while(!files.isEmpty()) { act=sample_mdls_menu.addAction(files.front(),this,SLOT(loadModelFromAction(void))); - path=QFileInfo(GlobalAttributes::SAMPLES_DIR + GlobalAttributes::DIR_SEPARATOR + files.front()).absoluteFilePath(); + path=QFileInfo(GlobalAttributes::SamplesDir + GlobalAttributes::DirSeparator + files.front()).absoluteFilePath(); act->setToolTip(path); act->setData(path); files.pop_front(); @@ -1770,57 +1828,57 @@ void MainWindow::configureSamplesMenu(void) void MainWindow::storeDockWidgetsSettings(void) { - GeneralConfigWidget *conf_wgt=dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::GENERAL_CONF_WGT)); + GeneralConfigWidget *conf_wgt=dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::GeneralConfWgt)); attribs_map params; - params[ParsersAttributes::VALIDATOR]=ParsersAttributes::_TRUE_; - params[ParsersAttributes::SQL_VALIDATION]=(model_valid_wgt->sql_validation_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - params[ParsersAttributes::USE_UNIQUE_NAMES]=(model_valid_wgt->use_tmp_names_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - params[ParsersAttributes::PGSQL_VERSION]=model_valid_wgt->version_cmb->currentText(); - conf_wgt->addConfigurationParam(ParsersAttributes::VALIDATOR, params); + params[Attributes::Validator]=Attributes::True; + params[Attributes::SqlValidation]=(model_valid_wgt->sql_validation_chk->isChecked() ? Attributes::True : QString()); + params[Attributes::UseUniqueNames]=(model_valid_wgt->use_tmp_names_chk->isChecked() ? Attributes::True : QString()); + params[Attributes::PgSqlVersion]=model_valid_wgt->version_cmb->currentText(); + conf_wgt->addConfigurationParam(Attributes::Validator, params); params.clear(); - params[ParsersAttributes::OBJECT_FINDER]=ParsersAttributes::_TRUE_; - params[ParsersAttributes::SELECT_OBJECTS]=(obj_finder_wgt->select_btn->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - params[ParsersAttributes::FADEIN_OBJECTS]=(obj_finder_wgt->fade_btn->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - params[ParsersAttributes::REGULAR_EXP]=(obj_finder_wgt->regexp_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - params[ParsersAttributes::CASE_SENSITIVE]=(obj_finder_wgt->case_sensitive_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - params[ParsersAttributes::EXACT_MATCH]=(obj_finder_wgt->exact_match_chk->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - conf_wgt->addConfigurationParam(ParsersAttributes::OBJECT_FINDER, params); + params[Attributes::ObjectFinder]=Attributes::True; + params[Attributes::SelectObjects]=(obj_finder_wgt->select_btn->isChecked() ? Attributes::True : QString()); + params[Attributes::FadeInObjects]=(obj_finder_wgt->fade_btn->isChecked() ? Attributes::True : QString()); + params[Attributes::RegularExp]=(obj_finder_wgt->regexp_chk->isChecked() ? Attributes::True : QString()); + params[Attributes::CaseSensitive]=(obj_finder_wgt->case_sensitive_chk->isChecked() ? Attributes::True : QString()); + params[Attributes::ExactMatch]=(obj_finder_wgt->exact_match_chk->isChecked() ? Attributes::True : QString()); + conf_wgt->addConfigurationParam(Attributes::ObjectFinder, params); params.clear(); - params[ParsersAttributes::SQL_TOOL]=ParsersAttributes::_TRUE_; - params[ParsersAttributes::SHOW_ATTRIBUTES_GRID]=(sql_tool_wgt->attributes_tb->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - params[ParsersAttributes::SHOW_SOURCE_PANE]=(sql_tool_wgt->source_pane_tb->isChecked() ? ParsersAttributes::_TRUE_ : QString()); - conf_wgt->addConfigurationParam(ParsersAttributes::SQL_TOOL, params); + params[Attributes::SqlTool]=Attributes::True; + params[Attributes::ShowAttributesGrid]=(sql_tool_wgt->attributes_tb->isChecked() ? Attributes::True : QString()); + params[Attributes::ShowSourcePane]=(sql_tool_wgt->source_pane_tb->isChecked() ? Attributes::True : QString()); + conf_wgt->addConfigurationParam(Attributes::SqlTool, params); params.clear(); } void MainWindow::restoreDockWidgetsSettings(void) { - GeneralConfigWidget *conf_wgt=dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::GENERAL_CONF_WGT)); + GeneralConfigWidget *conf_wgt=dynamic_cast(configuration_form->getConfigurationWidget(ConfigurationForm::GeneralConfWgt)); map confs=conf_wgt->getConfigurationParams(); - if(confs.count(ParsersAttributes::VALIDATOR)) + if(confs.count(Attributes::Validator)) { - model_valid_wgt->sql_validation_chk->setChecked(confs[ParsersAttributes::VALIDATOR][ParsersAttributes::SQL_VALIDATION]==ParsersAttributes::_TRUE_); - model_valid_wgt->use_tmp_names_chk->setChecked(confs[ParsersAttributes::VALIDATOR][ParsersAttributes::USE_UNIQUE_NAMES]==ParsersAttributes::_TRUE_); - model_valid_wgt->version_cmb->setCurrentText(confs[ParsersAttributes::VALIDATOR][ParsersAttributes::PGSQL_VERSION]); + model_valid_wgt->sql_validation_chk->setChecked(confs[Attributes::Validator][Attributes::SqlValidation]==Attributes::True); + model_valid_wgt->use_tmp_names_chk->setChecked(confs[Attributes::Validator][Attributes::UseUniqueNames]==Attributes::True); + model_valid_wgt->version_cmb->setCurrentText(confs[Attributes::Validator][Attributes::PgSqlVersion]); } - if(confs.count(ParsersAttributes::OBJECT_FINDER)) + if(confs.count(Attributes::ObjectFinder)) { - obj_finder_wgt->select_btn->setChecked(confs[ParsersAttributes::OBJECT_FINDER][ParsersAttributes::SELECT_OBJECTS]==ParsersAttributes::_TRUE_); - obj_finder_wgt->fade_btn->setChecked(confs[ParsersAttributes::OBJECT_FINDER][ParsersAttributes::FADEIN_OBJECTS]==ParsersAttributes::_TRUE_); - obj_finder_wgt->regexp_chk->setChecked(confs[ParsersAttributes::OBJECT_FINDER][ParsersAttributes::REGULAR_EXP]==ParsersAttributes::_TRUE_); - obj_finder_wgt->case_sensitive_chk->setChecked(confs[ParsersAttributes::OBJECT_FINDER][ParsersAttributes::CASE_SENSITIVE]==ParsersAttributes::_TRUE_); - obj_finder_wgt->exact_match_chk->setChecked(confs[ParsersAttributes::OBJECT_FINDER][ParsersAttributes::EXACT_MATCH]==ParsersAttributes::_TRUE_); + obj_finder_wgt->select_btn->setChecked(confs[Attributes::ObjectFinder][Attributes::SelectObjects]==Attributes::True); + obj_finder_wgt->fade_btn->setChecked(confs[Attributes::ObjectFinder][Attributes::FadeInObjects]==Attributes::True); + obj_finder_wgt->regexp_chk->setChecked(confs[Attributes::ObjectFinder][Attributes::RegularExp]==Attributes::True); + obj_finder_wgt->case_sensitive_chk->setChecked(confs[Attributes::ObjectFinder][Attributes::CaseSensitive]==Attributes::True); + obj_finder_wgt->exact_match_chk->setChecked(confs[Attributes::ObjectFinder][Attributes::ExactMatch]==Attributes::True); } - if(confs.count(ParsersAttributes::SQL_TOOL)) + if(confs.count(Attributes::SqlTool)) { - sql_tool_wgt->attributes_tb->setChecked(confs[ParsersAttributes::SQL_TOOL][ParsersAttributes::SHOW_ATTRIBUTES_GRID]==ParsersAttributes::_TRUE_); - sql_tool_wgt->source_pane_tb->setChecked(confs[ParsersAttributes::SQL_TOOL][ParsersAttributes::SHOW_SOURCE_PANE]==ParsersAttributes::_TRUE_); + sql_tool_wgt->attributes_tb->setChecked(confs[Attributes::SqlTool][Attributes::ShowAttributesGrid]==Attributes::True); + sql_tool_wgt->source_pane_tb->setChecked(confs[Attributes::SqlTool][Attributes::ShowSourcePane]==Attributes::True); } } @@ -1830,31 +1888,31 @@ void MainWindow::showDemoVersionWarning(void) Messagebox msg_box; msg_box.show(trUtf8("Warning"), trUtf8("You're running a demonstration version! Note that you'll be able to create only %1 instances \ - of each type of object and some key features will be disabled or limited!

You can purchase a full binary copy or get the source code at pgmodeler.com.br.\ - NOTE: pgModeler is an open source software, but purchasing binary copies or providing some donations will support the project and cover all development costs.

\ - HINT: in order to test all features it's recommended to use the demo.dbm model located in Sample models at Welcome view.



").arg(GlobalAttributes::MAX_OBJECT_COUNT), - Messagebox::ALERT_ICON, Messagebox::OK_BUTTON); + of each type of object and some key features will be disabled or limited!

You can purchase a full binary copy or get the source code at https://pgmodeler.io.\ + NOTE: pgModeler is an open source software, but purchasing binary copies or providing some donations will support the project and keep the development alive and at full speed!

\ + HINT: in order to test all features it's recommended to use the demo.dbm model located in Sample models at Welcome view.



").arg(GlobalAttributes::MaxObjectCount), + Messagebox::AlertIcon, Messagebox::OkButton); #endif } void MainWindow::executePendingOperation(bool valid_error) { - if(!valid_error && pending_op!=NO_PENDING_OPER) + if(!valid_error && pending_op!=NoPendingOp) { static const QString op_names[]={ QString(), QT_TR_NOOP("save"), QT_TR_NOOP("save"), - QT_TR_NOOP("export"), QT_TR_NOOP("diff") }; + QT_TR_NOOP("export"), QT_TR_NOOP("diff") }; - PgModelerUiNS::createOutputTreeItem(model_valid_wgt->output_trw, + PgModelerUiNs::createOutputTreeItem(model_valid_wgt->output_trw, trUtf8("Executing pending %1 operation...").arg(op_names[pending_op])); - if(pending_op==PENDING_SAVE_OPER || pending_op==PENDING_SAVE_AS_OPER) + if(pending_op==PendingSaveOp || pending_op==PendingSaveAsOp) saveModel(); - else if(pending_op==PENDING_EXPORT_OPER) + else if(pending_op==PendingExportOp) exportModel(); - else if(pending_op==PENDING_DIFF_OPER) + else if(pending_op==PendingDiffOp) diffModelDatabase(); - pending_op=NO_PENDING_OPER; + pending_op=NoPendingOp; } } @@ -1862,6 +1920,8 @@ void MainWindow::changeCurrentView(bool checked) { QAction *curr_act=qobject_cast(sender()); + layers_wgt->setVisible(false); + if(checked) { bool enable=(curr_act==action_design); @@ -1883,7 +1943,7 @@ void MainWindow::changeCurrentView(bool checked) action_design->blockSignals(false); actions=general_tb->actions(); - for(int i=GENERAL_ACTIONS_COUNT; i < actions.count(); i++) + for(int i=GeneralActionsCount; i < actions.count(); i++) { actions[i]->setEnabled(enable); @@ -1921,8 +1981,10 @@ void MainWindow::changeCurrentView(bool checked) void MainWindow::reportBug(void) { BugReportForm bugrep_frm; - PgModelerUiNS::resizeDialog(&bugrep_frm); + PgModelerUiNs::resizeDialog(&bugrep_frm); + GeneralConfigWidget::restoreWidgetGeometry(&bugrep_frm); bugrep_frm.exec(); + GeneralConfigWidget::saveWidgetGeometry(&bugrep_frm); } void MainWindow::removeOperations(void) @@ -1941,7 +2003,11 @@ void MainWindow::handleObjectsMetadata(void) objs_meta_frm.setModelWidget(current_model); objs_meta_frm.setModelWidgets(model_nav_wgt->getModelWidgets()); connect(&objs_meta_frm, SIGNAL(s_metadataHandled()), model_objs_wgt, SLOT(updateObjectsView())); + + PgModelerUiNs::resizeDialog(&objs_meta_frm); + GeneralConfigWidget::restoreWidgetGeometry(&objs_meta_frm); objs_meta_frm.exec(); + GeneralConfigWidget::saveWidgetGeometry(&objs_meta_frm); } void MainWindow::arrangeObjects(void) @@ -1950,7 +2016,7 @@ void MainWindow::arrangeObjects(void) return; Messagebox msgbox; - msgbox.show(trUtf8("Rearrange objects over the canvas is an irreversible operation! Would like to proceed?"), Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + msgbox.show(trUtf8("Rearrange objects over the canvas is an irreversible operation! Would like to proceed?"), Messagebox::ConfirmIcon, Messagebox::YesNoButtons); if(msgbox.result() == QDialog::Accepted) { @@ -1966,3 +2032,40 @@ void MainWindow::arrangeObjects(void) QApplication::restoreOverrideCursor(); } } + +void MainWindow::toggleCompactView(void) +{ + ModelWidget *model_wgt = nullptr; + + BaseObjectView::setCompactViewEnabled(action_compact_view->isChecked()); + QApplication::setOverrideCursor(Qt::WaitCursor); + + for(int idx = 0; idx < models_tbw->count(); idx++) + { + model_wgt = dynamic_cast(models_tbw->widget(idx)); + + if(action_compact_view->isChecked()) + model_wgt->setAllCollapseMode(CollapseMode::ExtAttribsCollapsed); + else + model_wgt->setAllCollapseMode(CollapseMode::NotCollapsed); + + model_wgt->getDatabaseModel()->setObjectsModified({ ObjectType::Table, ObjectType::View, ObjectType::Relationship, + ObjectType::BaseRelationship, ObjectType::Schema}); + } + + if(current_model) + current_model->update(); + + QApplication::restoreOverrideCursor(); +} + +void MainWindow::toggleLayersWidget(bool show) +{ + QPoint tb_pos = mapTo(this, tool_btns_bar_wgt->pos()), + btn_pos = mapTo(this, layers_btn->pos()); + + layers_wgt->move(btn_pos.x() + general_tb->width(), + tb_pos.y() - layers_wgt->height() * 0.80); + layers_wgt->setVisible(show); +} + diff --git a/libpgmodeler_ui/src/mainwindow.h b/libpgmodeler_ui/src/mainwindow.h index 6acf2f6ded..311715c4d4 100644 --- a/libpgmodeler_ui/src/mainwindow.h +++ b/libpgmodeler_ui/src/mainwindow.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -50,28 +50,27 @@ #include "configurationform.h" #include "donatewidget.h" #include "sceneinfowidget.h" +#include "layerswidget.h" class MainWindow: public QMainWindow, public Ui::MainWindow { private: Q_OBJECT - //! \brief Maximum number of files listed on recent models menu - const static int MAX_RECENT_MODELS=15; + static constexpr int GeneralActionsCount=8; - const static int GENERAL_ACTIONS_COUNT=8; - - const static int WELCOME_VIEW=0, - DESIGN_VIEW=1, - MANAGE_VIEW=2; + static constexpr int WelcomeView=0, + DesignView=1, + ManageView=2, + InfinityInterval = INT_MAX; static bool confirm_validation; //! \brief Constants used to mark a pending operation to be executed after validate model - const static unsigned NO_PENDING_OPER=0, - PENDING_SAVE_OPER=1, - PENDING_SAVE_AS_OPER=2, - PENDING_EXPORT_OPER=3, - PENDING_DIFF_OPER=4; + static constexpr unsigned NoPendingOp=0, + PendingSaveOp=1, + PendingSaveAsOp=2, + PendingExportOp=3, + PendingDiffOp=4; unsigned pending_op; @@ -79,7 +78,9 @@ class MainWindow: public QMainWindow, public Ui::MainWindow { DonateWidget *donate_wgt; - SceneInfoWidget *canvas_info_wgt; + SceneInfoWidget *scene_info_wgt; + + LayersWidget *layers_wgt; /*! \brief Widget positioned on the center of main window that contains some basic operations like create new model, open a file, restore session */ @@ -88,9 +89,6 @@ class MainWindow: public QMainWindow, public Ui::MainWindow { //! \brief Widget used to navigate through the opened models. ModelNavigationWidget *model_nav_wgt; - //! \brief Thread that controls temporary model file savings - QThread tmpmodel_thread; - //! \brief Timer used for auto saving the model and temporary model. QTimer model_save_timer, tmpmodel_save_timer; @@ -143,7 +141,9 @@ class MainWindow: public QMainWindow, public Ui::MainWindow { sample_mdls_menu, - arrange_menu; + arrange_menu, + + more_actions_menu; //! \brief QMainWindow::closeEvent() overload: Saves the configurations before close the application void closeEvent(QCloseEvent *event); @@ -153,9 +153,6 @@ class MainWindow: public QMainWindow, public Ui::MainWindow { //! \brief Set the postion of a floating widget based upon an action at a tool bar void setFloatingWidgetPos(QWidget *widget, QAction *act, QToolBar *toolbar, bool map_to_window); - //! \brief Creates drop shadown on a tool button that represents an QAction - QGraphicsDropShadowEffect *createDropShadow(QToolButton *btn); - void configureSamplesMenu(void); /*! \brief Stores the current checkboxes states of the main dock widgets on the set of configuration params @@ -169,7 +166,7 @@ class MainWindow: public QMainWindow, public Ui::MainWindow { void showFixMessage(Exception &e, const QString &filename); public: - MainWindow(QWidget *parent = 0, Qt::WindowFlags flags = 0); + MainWindow(QWidget *parent = nullptr, Qt::WindowFlags flags = 0); ~MainWindow(void); //! \brief Loads a set of models from string list @@ -291,6 +288,8 @@ class MainWindow: public QMainWindow, public Ui::MainWindow { void handleObjectsMetadata(void); void restoreTemporaryModels(void); void arrangeObjects(void); + void toggleCompactView(void); + void toggleLayersWidget(bool show); }; #endif diff --git a/libpgmodeler_ui/src/messagebox.cpp b/libpgmodeler_ui/src/messagebox.cpp index efa66df897..7f3c1d6c37 100644 --- a/libpgmodeler_ui/src/messagebox.cpp +++ b/libpgmodeler_ui/src/messagebox.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -31,8 +31,10 @@ Messagebox::Messagebox(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f) connect(show_errors_tb,SIGNAL(clicked()),this,SLOT(showExceptionList())); connect(show_errors_tb,SIGNAL(toggled(bool)),show_raw_info_tb,SLOT(setVisible(bool))); connect(show_raw_info_tb,SIGNAL(toggled(bool)),this,SLOT(showExceptionList(void))); - show_errors_tb->setVisible(false); + show_raw_info_tb->setVisible(false); + error_show_btns_wgt->setVisible(false); + custom_option_chk->setVisible(false); } void Messagebox::handleYesOkClick(void) @@ -62,11 +64,22 @@ bool Messagebox::isCancelled(void) return(cancelled); } +void Messagebox::setCustomOptionText(const QString &text) +{ + custom_option_chk->setVisible(!text.isEmpty()); + custom_option_chk->setText(text); +} + +bool Messagebox::isCustomOptionChecked(void) +{ + return(custom_option_chk->isChecked()); +} + void Messagebox::showExceptionList(void) { if(show_errors_tb->isChecked()) { - show_errors_tb->setIcon(QPixmap(PgModelerUiNS::getIconPath("desfazer"))); + show_errors_tb->setIcon(QPixmap(PgModelerUiNs::getIconPath("desfazer"))); if(show_raw_info_tb->isChecked()) objs_group_wgt->setCurrentIndex(2); @@ -79,7 +92,7 @@ void Messagebox::showExceptionList(void) } else { - show_errors_tb->setIcon(QPixmap(PgModelerUiNS::getIconPath("refazer"))); + show_errors_tb->setIcon(QPixmap(PgModelerUiNs::getIconPath("refazer"))); objs_group_wgt->setCurrentIndex(0); } } @@ -94,14 +107,14 @@ void Messagebox::show(Exception e, const QString &msg, unsigned icon_type, unsig show_raw_info_tb->blockSignals(false); raw_info_txt->setPlainText(e.getExceptionsText()); - PgModelerUiNS::createExceptionsTree(exceptions_trw, e, nullptr); + PgModelerUiNs::createExceptionsTree(exceptions_trw, e, nullptr); exceptions_trw->expandAll(); exceptions_trw->scrollToTop(); if(msg.isEmpty()) - str_aux=PgModelerUiNS::formatMessage(e.getErrorMessage()); + str_aux=PgModelerUiNs::formatMessage(e.getErrorMessage()); else - str_aux=PgModelerUiNS::formatMessage(msg); + str_aux=PgModelerUiNs::formatMessage(msg); this->show(title, str_aux, icon_type, buttons, yes_lbl, no_lbl, cancel_lbl, yes_ico, no_ico, cancel_ico); } @@ -119,36 +132,36 @@ void Messagebox::show(const QString &title, const QString &msg, unsigned icon_ty if(!yes_lbl.isEmpty()) yes_ok_btn->setText(yes_lbl); else - yes_ok_btn->setText(buttons==OK_BUTTON ? trUtf8("&Ok") : trUtf8("&Yes")); + yes_ok_btn->setText(buttons==OkButton ? trUtf8("&Ok") : trUtf8("&Yes")); - yes_ok_btn->setIcon(!yes_ico.isEmpty() ? QIcon(yes_ico) : QPixmap(PgModelerUiNS::getIconPath("confirmar"))); + yes_ok_btn->setIcon(!yes_ico.isEmpty() ? QIcon(yes_ico) : QPixmap(PgModelerUiNs::getIconPath("confirmar"))); no_btn->setText(!no_lbl.isEmpty() ? no_lbl : trUtf8("&No")); - no_btn->setIcon(!no_ico.isEmpty() ? QIcon(no_ico) : QPixmap(PgModelerUiNS::getIconPath("fechar1"))); + no_btn->setIcon(!no_ico.isEmpty() ? QIcon(no_ico) : QPixmap(PgModelerUiNs::getIconPath("fechar1"))); cancel_btn->setText(!cancel_lbl.isEmpty() ? cancel_lbl : trUtf8("&Cancel")); - cancel_btn->setIcon(!cancel_ico.isEmpty() ? QIcon(cancel_ico) : QPixmap(PgModelerUiNS::getIconPath("cancelar"))); + cancel_btn->setIcon(!cancel_ico.isEmpty() ? QIcon(cancel_ico) : QPixmap(PgModelerUiNs::getIconPath("cancelar"))); - no_btn->setVisible(buttons==YES_NO_BUTTONS || buttons==ALL_BUTTONS); - cancel_btn->setVisible(buttons==OK_CANCEL_BUTTONS || buttons==ALL_BUTTONS); + no_btn->setVisible(buttons==YesNoButtons || buttons==AllButtons); + cancel_btn->setVisible(buttons==OkCancelButtons || buttons==AllButtons); if(title.isEmpty()) { switch(icon_type) { - case ERROR_ICON: + case ErrorIcon: aux_title=trUtf8("Error"); break; - case ALERT_ICON: + case AlertIcon: aux_title=trUtf8("Alert"); break; - case INFO_ICON: + case InfoIcon: aux_title=trUtf8("Information"); break; - case CONFIRM_ICON: + case ConfirmIcon: aux_title=trUtf8("Confirmation"); break; } @@ -156,19 +169,19 @@ void Messagebox::show(const QString &title, const QString &msg, unsigned icon_ty switch(icon_type) { - case ERROR_ICON: + case ErrorIcon: icon_name=QString("msgbox_erro"); break; - case INFO_ICON: + case InfoIcon: icon_name=QString("msgbox_info"); break; - case ALERT_ICON: + case AlertIcon: icon_name=QString("msgbox_alerta"); break; - case CONFIRM_ICON: + case ConfirmIcon: icon_name=QString("msgbox_quest"); break; @@ -181,14 +194,14 @@ void Messagebox::show(const QString &title, const QString &msg, unsigned icon_ty icon_lbl->setVisible(!icon_name.isEmpty()); if(!icon_name.isEmpty()) - icon_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath(icon_name))); + icon_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath(icon_name))); msg_lbl->setText(msg); this->setWindowTitle(aux_title); this->objs_group_wgt->setCurrentIndex(0); this->show_errors_tb->setChecked(false); - this->show_errors_tb->setVisible((exceptions_trw->topLevelItemCount() > 0)); + error_show_btns_wgt->setVisible((exceptions_trw->topLevelItemCount() > 0)); showExceptionList(); this->resize(this->minimumWidth(), this->minimumHeight()); @@ -205,7 +218,7 @@ void Messagebox::show(const QString &title, const QString &msg, unsigned icon_ty else if(size.height() >= max_h) this->setMinimumHeight(max_h); - float factor = BaseObjectView::getScreenDpiFactor(); + double factor = BaseObjectView::getScreenDpiFactor(); this->resize(this->minimumWidth() * factor, this->minimumHeight() * factor); QDialog::exec(); diff --git a/libpgmodeler_ui/src/messagebox.h b/libpgmodeler_ui/src/messagebox.h index d549e1fb15..89dd923b5d 100644 --- a/libpgmodeler_ui/src/messagebox.h +++ b/libpgmodeler_ui/src/messagebox.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -36,37 +36,40 @@ class Messagebox: public QDialog, public Ui::Messagebox { public: //! \brief Constants used to define the message icon - static const unsigned NO_ICON=10, - ERROR_ICON=11, - INFO_ICON=12, - ALERT_ICON=13, - CONFIRM_ICON=14; + static constexpr unsigned NoIcon=10, + ErrorIcon=11, + InfoIcon=12, + AlertIcon=13, + ConfirmIcon=14; //! \brief Constants used to configure the visible buttons - static const unsigned YES_NO_BUTTONS=0, - OK_CANCEL_BUTTONS=1, - OK_BUTTON=2, - ALL_BUTTONS=3; + static constexpr unsigned YesNoButtons=0, + OkCancelButtons=1, + OkButton=2, + AllButtons=3; - Messagebox(QWidget * parent = 0, Qt::WindowFlags f = 0); + Messagebox(QWidget * parent = nullptr, Qt::WindowFlags f = Qt::Widget); /*! \brief Shows the message box defining the icons and available buttons. User can specify custom button labels as well custom icons. The icons can be a path to a local file or a Qt resource icon ':/path/icon' and will be enabled only specifing custom labels for the respective button. */ - void show(const QString &title, const QString &msg, unsigned icon_type=NO_ICON, unsigned buttons=OK_BUTTON, + void show(const QString &title, const QString &msg, unsigned icon_type=NoIcon, unsigned buttons=OkButton, const QString &yes_lbl=QString(), const QString &no_lbl=QString(), const QString &cancel_lbl=QString(), const QString &yes_ico=QString(), const QString &no_ico=QString(), const QString &cancel_ico=QString()); //! \brief Shows the message box using an excpetion as message - void show(Exception e, const QString &msg=QString(), unsigned icon_type=ERROR_ICON, unsigned buttons=OK_BUTTON, + void show(Exception e, const QString &msg=QString(), unsigned icon_type=ErrorIcon, unsigned buttons=OkButton, const QString &yes_lbl=QString(), const QString &no_lbl=QString(), const QString &cancel_lbl=QString(), const QString &yes_ico=QString(), const QString &no_ico=QString(), const QString &cancel_ico=QString()); //! \brief Shows a simple message box with the title automatically defined by the icon type - void show(const QString &msg, unsigned icon_type=NO_ICON, unsigned buttons=OK_BUTTON); + void show(const QString &msg, unsigned icon_type=NoIcon, unsigned buttons=OkButton); bool isCancelled(void); + void setCustomOptionText(const QString &text); + bool isCustomOptionChecked(void); + private slots: void handleYesOkClick(void); void handleNoCancelClick(void); diff --git a/libpgmodeler_ui/src/metadatahandlingform.cpp b/libpgmodeler_ui/src/metadatahandlingform.cpp index 2bb8f8f70c..db918eb8b9 100644 --- a/libpgmodeler_ui/src/metadatahandlingform.cpp +++ b/libpgmodeler_ui/src/metadatahandlingform.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -43,8 +43,8 @@ MetadataHandlingForm::MetadataHandlingForm(QWidget *parent, Qt::WindowFlags f) : objs_fadedout_ht=new HintTextWidget(objs_fadedout_hint, this); objs_fadedout_ht->setText(objs_fadedout_chk->statusTip()); - objs_extattribs_ht=new HintTextWidget(objs_extattribs_hint, this); - objs_extattribs_ht->setText(objs_extattribs_chk->statusTip()); + objs_collapse_mode_ht=new HintTextWidget(objs_collapse_mode_hint, this); + objs_collapse_mode_ht->setText(objs_collapse_mode_chk->statusTip()); custom_sql_ht=new HintTextWidget(custom_sql_hint, this); custom_sql_ht->setText(custom_sql_chk->statusTip()); @@ -70,6 +70,9 @@ MetadataHandlingForm::MetadataHandlingForm(QWidget *parent, Qt::WindowFlags f) : generic_sql_objs_ht=new HintTextWidget(generic_sql_objs_hint, this); generic_sql_objs_ht->setText(generic_sql_objs_chk->statusTip()); + objs_aliases_ht=new HintTextWidget(objs_aliases_hint, this); + objs_aliases_ht->setText(objs_aliases_chk->statusTip()); + htmlitem_deleg=new HtmlItemDelegate(this); output_trw->setItemDelegateForColumn(0, htmlitem_deleg); @@ -88,6 +91,8 @@ MetadataHandlingForm::MetadataHandlingForm(QWidget *parent, Qt::WindowFlags f) : connect(restore_rb, SIGNAL(toggled(bool)), this, SLOT(enableMetadataHandling())); connect(extract_restore_rb, SIGNAL(toggled(bool)), this, SLOT(enableMetadataHandling())); connect(extract_only_rb, SIGNAL(toggled(bool)), this, SLOT(enableMetadataHandling())); + connect(select_all_btn, SIGNAL(clicked(bool)), this, SLOT(selectAllOptions())); + connect(clear_all_btn, SIGNAL(clicked(bool)), this, SLOT(selectAllOptions())); } void MetadataHandlingForm::enableMetadataHandling(void) @@ -103,6 +108,20 @@ void MetadataHandlingForm::enableMetadataHandling(void) (restore_rb->isChecked() && !backup_file_edt->text().isEmpty())))); } +void MetadataHandlingForm::selectAllOptions(void) +{ + bool check = sender() == select_all_btn; + QCheckBox *checkbox = nullptr; + + for(auto &obj : options_grp->children()) + { + checkbox = dynamic_cast(obj); + + if(checkbox) + checkbox->setChecked(check); + } +} + void MetadataHandlingForm::setModelWidget(ModelWidget *model_wgt) { this->model_wgt=model_wgt; @@ -133,7 +152,7 @@ void MetadataHandlingForm::handleObjectsMetada(void) if(!backup_file_edt->text().isEmpty() && backup_file_edt->text() == model_wgt->getFilename()) throw Exception(trUtf8("The backup file cannot be the same as the input model!"), - ERR_CUSTOM, __PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::Custom, __PRETTY_FUNCTION__,__FILE__,__LINE__); QTemporaryFile tmp_file; QString metadata_file; @@ -147,19 +166,20 @@ void MetadataHandlingForm::handleObjectsMetada(void) settings_tbw->setTabEnabled(1, true); settings_tbw->setCurrentIndex(1); - options+=(db_metadata_chk->isChecked() ? DatabaseModel::META_DB_ATTRIBUTES : 0); - options+=(custom_colors_chk->isChecked() ? DatabaseModel::META_OBJS_CUSTOMCOLORS : 0); - options+=(custom_sql_chk->isChecked() ? DatabaseModel::META_OBJS_CUSTOMSQL : 0); - options+=(objs_positioning_chk->isChecked() ? DatabaseModel::META_OBJS_POSITIONING : 0); - options+=(objs_protection_chk->isChecked() ? DatabaseModel::META_OBJS_PROTECTION : 0); - options+=(objs_sql_disabled_chk->isChecked() ? DatabaseModel::META_OBJS_SQLDISABLED : 0); - options+=(tag_objs_chk->isChecked() ? DatabaseModel::META_TAG_OBJS : 0); - options+=(textbox_objs_chk->isChecked() ? DatabaseModel::META_TEXTBOX_OBJS : 0); - options+=(objs_fadedout_chk->isChecked() ? DatabaseModel::META_OBJS_FADEDOUT : 0); - options+=(objs_extattribs_chk->isChecked() ? DatabaseModel::META_OBJS_EXTATTRIBS : 0); - options+=(generic_sql_objs_chk->isChecked() ? DatabaseModel::META_GENERIC_SQL_OBJS : 0); - - connect(model_wgt->getDatabaseModel(), SIGNAL(s_objectLoaded(int,QString,unsigned)), this, SLOT(updateProgress(int,QString,unsigned))); + options+=(db_metadata_chk->isChecked() ? DatabaseModel::MetaDbAttributes : 0); + options+=(custom_colors_chk->isChecked() ? DatabaseModel::MetaObjsCustomColors : 0); + options+=(custom_sql_chk->isChecked() ? DatabaseModel::MetaObjsCustomSql : 0); + options+=(objs_positioning_chk->isChecked() ? DatabaseModel::MetaObjsPositioning : 0); + options+=(objs_protection_chk->isChecked() ? DatabaseModel::MetaObjsProtection : 0); + options+=(objs_sql_disabled_chk->isChecked() ? DatabaseModel::MetaObjsSqlDisabled : 0); + options+=(tag_objs_chk->isChecked() ? DatabaseModel::MetaTagObjs : 0); + options+=(textbox_objs_chk->isChecked() ? DatabaseModel::MetaTextboxObjs : 0); + options+=(objs_fadedout_chk->isChecked() ? DatabaseModel::MetaObjsFadeOut : 0); + options+=(objs_collapse_mode_chk->isChecked() ? DatabaseModel::MetaObjsCollapseMode : 0); + options+=(generic_sql_objs_chk->isChecked() ? DatabaseModel::MetaGenericSqlObjs : 0); + options+=(objs_aliases_chk->isChecked() ? DatabaseModel::MetaObjsAliases : 0); + + connect(model_wgt->getDatabaseModel(), SIGNAL(s_objectLoaded(int,QString,unsigned)), this, SLOT(updateProgress(int,QString,unsigned)), Qt::UniqueConnection); if(extract_restore_rb->isChecked() || extract_only_rb->isChecked()) { @@ -170,8 +190,8 @@ void MetadataHandlingForm::handleObjectsMetada(void) else { //Configuring the temporary metadata file - tmp_file.setFileTemplate(GlobalAttributes::TEMPORARY_DIR + - GlobalAttributes::DIR_SEPARATOR + + tmp_file.setFileTemplate(GlobalAttributes::TemporaryDir + + GlobalAttributes::DirSeparator + QString("%1_metadata_XXXXXX.%2").arg(extract_model->getName()).arg(QString("omf"))); tmp_file.open(); @@ -179,20 +199,20 @@ void MetadataHandlingForm::handleObjectsMetada(void) tmp_file.close(); } - connect(extract_model, SIGNAL(s_objectLoaded(int,QString,unsigned)), this, SLOT(updateProgress(int,QString,unsigned))); + connect(extract_model, SIGNAL(s_objectLoaded(int,QString,unsigned)), this, SLOT(updateProgress(int,QString,unsigned)), Qt::UniqueConnection); - root_item=PgModelerUiNS::createOutputTreeItem(output_trw, - PgModelerUiNS::formatMessage(trUtf8("Extracting metadata to file `%1'").arg(metadata_file)), - QPixmap(PgModelerUiNS::getIconPath("msgbox_info")), nullptr); + root_item=PgModelerUiNs::createOutputTreeItem(output_trw, + PgModelerUiNs::formatMessage(trUtf8("Extracting metadata to file `%1'").arg(metadata_file)), + QPixmap(PgModelerUiNs::getIconPath("msgbox_info")), nullptr); extract_model->saveObjectsMetadata(metadata_file, options); if(extract_restore_rb->isChecked() && !backup_file_edt->text().isEmpty()) { root_item->setExpanded(false); - root_item=PgModelerUiNS::createOutputTreeItem(output_trw, - PgModelerUiNS::formatMessage(trUtf8("Saving backup metadata to file `%1'").arg(backup_file_edt->text())), - QPixmap(PgModelerUiNS::getIconPath("msgbox_info")), nullptr); + root_item=PgModelerUiNs::createOutputTreeItem(output_trw, + PgModelerUiNs::formatMessage(trUtf8("Saving backup metadata to file `%1'").arg(backup_file_edt->text())), + QPixmap(PgModelerUiNs::getIconPath("msgbox_info")), nullptr); model_wgt->getDatabaseModel()->saveObjectsMetadata(backup_file_edt->text()); } @@ -207,9 +227,9 @@ void MetadataHandlingForm::handleObjectsMetada(void) if(!extract_only_rb->isChecked()) { - root_item=PgModelerUiNS::createOutputTreeItem(output_trw, - PgModelerUiNS::formatMessage(trUtf8("Applying metadata from file `%1'").arg(metadata_file)), - QPixmap(PgModelerUiNS::getIconPath("msgbox_info")), nullptr); + root_item=PgModelerUiNs::createOutputTreeItem(output_trw, + PgModelerUiNs::formatMessage(trUtf8("Applying metadata from file `%1'").arg(metadata_file)), + QPixmap(PgModelerUiNs::getIconPath("msgbox_info")), nullptr); model_wgt->setUpdatesEnabled(false); model_wgt->getDatabaseModel()->loadObjectsMetadata(metadata_file, options); @@ -229,21 +249,21 @@ void MetadataHandlingForm::handleObjectsMetada(void) } catch(Exception &e) { - QPixmap icon=QPixmap(PgModelerUiNS::getIconPath("msgbox_erro")); + QPixmap icon=QPixmap(PgModelerUiNs::getIconPath("msgbox_erro")); disconnect(model_wgt->getDatabaseModel(), nullptr, this, nullptr); if(extract_model) disconnect(extract_model, nullptr, this, nullptr); - PgModelerUiNS::createOutputTreeItem(output_trw, - PgModelerUiNS::formatMessage(e.getErrorMessage()), + PgModelerUiNs::createOutputTreeItem(output_trw, + PgModelerUiNs::formatMessage(e.getErrorMessage()), icon, nullptr); ico_lbl->setPixmap(icon); progress_lbl->setText(trUtf8("Metadata processing aborted!")); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -284,20 +304,20 @@ void MetadataHandlingForm::selectFile(bool is_output) void MetadataHandlingForm::updateProgress(int progress, QString msg, unsigned int type_id) { ObjectType obj_type=static_cast(type_id); - QString fmt_msg=PgModelerUiNS::formatMessage(msg); + QString fmt_msg=PgModelerUiNs::formatMessage(msg); QPixmap icon; - if(obj_type==BASE_OBJECT) + if(obj_type==ObjectType::BaseObject) { if(progress==100) - icon=QPixmap(PgModelerUiNS::getIconPath("msgbox_info")); + icon=QPixmap(PgModelerUiNs::getIconPath("msgbox_info")); else - icon=QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta")); + icon=QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta")); } else - icon=QPixmap(PgModelerUiNS::getIconPath(obj_type)); + icon=QPixmap(PgModelerUiNs::getIconPath(obj_type)); - PgModelerUiNS::createOutputTreeItem(output_trw, fmt_msg, icon, root_item); + PgModelerUiNs::createOutputTreeItem(output_trw, fmt_msg, icon, root_item); progress_lbl->setText(fmt_msg); ico_lbl->setPixmap(icon); progress_pb->setValue(progress); diff --git a/libpgmodeler_ui/src/metadatahandlingform.h b/libpgmodeler_ui/src/metadatahandlingform.h index 32a6e17f64..587c8b0509 100644 --- a/libpgmodeler_ui/src/metadatahandlingform.h +++ b/libpgmodeler_ui/src/metadatahandlingform.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -41,21 +41,22 @@ class MetadataHandlingForm: public QDialog, public Ui::MetadataHandlingForm { HintTextWidget *db_metadata_ht, *objs_positioning_ht, *objs_protection_ht, *objs_sql_disabled_ht, *custom_sql_ht, *textbox_objs_ht, *tag_objs_ht, - *custom_colors_ht, *extract_restore_ht, *restore_ht, *objs_fadedout_ht, *objs_extattribs_ht, - *generic_sql_objs_ht, *extract_only_ht; + *custom_colors_ht, *extract_restore_ht, *restore_ht, *objs_fadedout_ht, + *objs_collapse_mode_ht, *generic_sql_objs_ht, *extract_only_ht, *objs_aliases_ht; void showEvent(QShowEvent *); void selectFile(bool is_output); public: - MetadataHandlingForm(QWidget * parent = 0, Qt::WindowFlags f = 0); + MetadataHandlingForm(QWidget * parent = nullptr, Qt::WindowFlags f = Qt::Widget); void setModelWidget(ModelWidget *model_wgt); void setModelWidgets(QList models); private slots: void updateProgress(int progress, QString msg, unsigned type_id); - void handleObjectsMetada(void); + void handleObjectsMetada(void); void enableMetadataHandling(void); + void selectAllOptions(void); signals: void s_metadataHandled(void); diff --git a/libpgmodeler_ui/src/modeldatabasediffform.cpp b/libpgmodeler_ui/src/modeldatabasediffform.cpp index fa395531a9..6d6b2c261e 100644 --- a/libpgmodeler_ui/src/modeldatabasediffform.cpp +++ b/libpgmodeler_ui/src/modeldatabasediffform.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,13 +20,16 @@ #include "configurationform.h" #include "databaseimportform.h" #include "pgmodeleruins.h" +#include + +bool ModelDatabaseDiffForm::low_verbosity = false; ModelDatabaseDiffForm::ModelDatabaseDiffForm(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f) { try { setupUi(this); - sqlcode_txt=PgModelerUiNS::createNumberedTextEditor(sqlcode_wgt); + sqlcode_txt=PgModelerUiNs::createNumberedTextEditor(sqlcode_wgt); sqlcode_txt->setReadOnly(true); htmlitem_del=new HtmlItemDelegate(this); @@ -98,11 +101,11 @@ ModelDatabaseDiffForm::ModelDatabaseDiffForm(QWidget *parent, Qt::WindowFlags f) ignore_error_codes_ht->setText(ignore_error_codes_chk->statusTip()); sqlcode_hl=new SyntaxHighlighter(sqlcode_txt); - sqlcode_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + sqlcode_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); - pgsql_ver_cmb->addItems(PgSQLVersions::ALL_VERSIONS); + pgsql_ver_cmb->addItems(PgSqlVersions::AllVersions); - PgModelerUiNS::configureWidgetFont(message_lbl, PgModelerUiNS::MEDIUM_FONT_FACTOR); + PgModelerUiNs::configureWidgetFont(message_lbl, PgModelerUiNs::MediumFontFactor); connect(cancel_btn, &QToolButton::clicked, [&](){ cancelOperation(true); }); connect(pgsql_ver_chk, SIGNAL(toggled(bool)), pgsql_ver_cmb, SLOT(setEnabled(bool))); @@ -129,6 +132,7 @@ ModelDatabaseDiffForm::ModelDatabaseDiffForm(QWidget *parent, Qt::WindowFlags f) connect(src_database_cmb, SIGNAL(currentIndexChanged(int)), this, SLOT(enableDiffMode())); connect(src_model_rb, SIGNAL(toggled(bool)), this, SLOT(enableDiffMode())); connect(src_database_rb, SIGNAL(toggled(bool)), this, SLOT(enableDiffMode())); + connect(open_in_sql_tool_btn, SIGNAL(clicked(bool)), this, SLOT(loadDiffInSQLTool())); #ifdef DEMO_VERSION #warning "DEMO VERSION: forcing ignore errors in diff due to the object count limit." @@ -144,15 +148,15 @@ ModelDatabaseDiffForm::ModelDatabaseDiffForm(QWidget *parent, Qt::WindowFlags f) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } ModelDatabaseDiffForm::~ModelDatabaseDiffForm(void) { - destroyThread(IMPORT_THREAD); - destroyThread(DIFF_THREAD); - destroyThread(EXPORT_THREAD); + destroyThread(ImportThread); + destroyThread(DiffThread); + destroyThread(ExportThread); destroyModel(); } @@ -173,13 +177,18 @@ void ModelDatabaseDiffForm::setModelWidget(ModelWidget *model_wgt) } } +void ModelDatabaseDiffForm::setLowVerbosity(bool value) +{ + low_verbosity = value; +} + void ModelDatabaseDiffForm::resetForm(void) { ConnectionsConfigWidget::fillConnectionsComboBox(src_connections_cmb, true); src_connections_cmb->setEnabled(src_connections_cmb->count() > 0); src_connection_lbl->setEnabled(src_connections_cmb->isEnabled()); - ConnectionsConfigWidget::fillConnectionsComboBox(connections_cmb, true, Connection::OP_DIFF); + ConnectionsConfigWidget::fillConnectionsComboBox(connections_cmb, true, Connection::OpDiff); connections_cmb->setEnabled(connections_cmb->count() > 0); connection_lbl->setEnabled(connections_cmb->isEnabled()); @@ -191,11 +200,12 @@ void ModelDatabaseDiffForm::resetForm(void) void ModelDatabaseDiffForm::closeEvent(QCloseEvent *event) { //Ignore the close event when the thread is running - if(process_paused || - (import_thread && import_thread->isRunning()) || + if((import_thread && import_thread->isRunning()) || (diff_thread && diff_thread->isRunning()) || - (export_thread && export_thread->isRunning())) + (export_thread && export_thread->isRunning())) event->ignore(); + else if(process_paused) + cancelOperation(true); } void ModelDatabaseDiffForm::showEvent(QShowEvent *) @@ -208,7 +218,7 @@ void ModelDatabaseDiffForm::showEvent(QShowEvent *) void ModelDatabaseDiffForm::createThread(unsigned thread_id) { - if(thread_id==SRC_IMPORT_THREAD) + if(thread_id==SrcImportThread) { src_import_thread=new QThread; src_import_helper=new DatabaseImportHelper; @@ -221,7 +231,7 @@ void ModelDatabaseDiffForm::createThread(unsigned thread_id) connect(src_import_helper, SIGNAL(s_importFinished(Exception)), this, SLOT(handleImportFinished(Exception))); connect(src_import_helper, SIGNAL(s_importAborted(Exception)), this, SLOT(captureThreadError(Exception))); } - else if(thread_id==IMPORT_THREAD) + else if(thread_id==ImportThread) { import_thread=new QThread; import_helper=new DatabaseImportHelper; @@ -234,7 +244,7 @@ void ModelDatabaseDiffForm::createThread(unsigned thread_id) connect(import_helper, SIGNAL(s_importFinished(Exception)), this, SLOT(handleImportFinished(Exception))); connect(import_helper, SIGNAL(s_importAborted(Exception)), this, SLOT(captureThreadError(Exception))); } - else if(thread_id==DIFF_THREAD) + else if(thread_id==DiffThread) { diff_thread=new QThread; diff_helper=new ModelsDiffHelper; @@ -275,21 +285,21 @@ void ModelDatabaseDiffForm::createThread(unsigned thread_id) void ModelDatabaseDiffForm::destroyThread(unsigned thread_id) { - if(thread_id==SRC_IMPORT_THREAD && src_import_thread) + if(thread_id==SrcImportThread && src_import_thread) { delete(src_import_thread); delete(src_import_helper); src_import_thread=nullptr; src_import_helper=nullptr; } - else if(thread_id==IMPORT_THREAD && import_thread) + else if(thread_id==ImportThread && import_thread) { delete(import_thread); delete(import_helper); import_thread=nullptr; import_helper=nullptr; } - else if(thread_id==DIFF_THREAD && diff_thread) + else if(thread_id==DiffThread && diff_thread) { diff_thread=nullptr; diff_helper=nullptr; @@ -378,7 +388,7 @@ void ModelDatabaseDiffForm::listDatabases(void) db_cmb->clear(); db_cmb->setEnabled(false); db_lbl->setEnabled(false); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -397,14 +407,18 @@ void ModelDatabaseDiffForm::generateDiff(void) { //Destroy previously allocated threads and helper before start over. destroyModel(); - destroyThread(SRC_IMPORT_THREAD); - destroyThread(IMPORT_THREAD); - destroyThread(DIFF_THREAD); - destroyThread(EXPORT_THREAD); + destroyThread(SrcImportThread); + destroyThread(ImportThread); + destroyThread(DiffThread); + destroyThread(ExportThread); clearOutput(); curr_step = 1; + if(low_verbosity) + PgModelerUiNs::createOutputTreeItem(output_trw, trUtf8("Low verbosity is set: only key informations and errors will be displayed."), + QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta")), nullptr, false); + if(src_model_rb->isChecked()) { source_model = loaded_model; @@ -413,11 +427,12 @@ void ModelDatabaseDiffForm::generateDiff(void) else total_steps=4; - importDatabase(src_database_rb->isChecked() ? SRC_IMPORT_THREAD : IMPORT_THREAD); + importDatabase(src_database_rb->isChecked() ? SrcImportThread : ImportThread); buttons_wgt->setEnabled(false); cancel_btn->setEnabled(true); generate_btn->setEnabled(false); + close_btn->setEnabled(false); settings_tbw->setTabEnabled(0, false); settings_tbw->setTabEnabled(1, true); @@ -429,15 +444,15 @@ void ModelDatabaseDiffForm::importDatabase(unsigned thread_id) { try { - if(thread_id != SRC_IMPORT_THREAD && thread_id != IMPORT_THREAD) - throw Exception(ERR_ALOC_OBJECT_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(thread_id != SrcImportThread && thread_id != ImportThread) + throw Exception(ErrorCode::AllocationObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); createThread(thread_id); - QThread *thread = (thread_id == SRC_IMPORT_THREAD ? src_import_thread : import_thread); - DatabaseImportHelper *import_hlp = (thread_id == SRC_IMPORT_THREAD ? src_import_helper : import_helper); - QComboBox *conn_cmb = (thread_id == SRC_IMPORT_THREAD ? src_connections_cmb : connections_cmb), - *db_cmb = (thread_id == SRC_IMPORT_THREAD ? src_database_cmb : database_cmb); + QThread *thread = (thread_id == SrcImportThread ? src_import_thread : import_thread); + DatabaseImportHelper *import_hlp = (thread_id == SrcImportThread ? src_import_helper : import_helper); + QComboBox *conn_cmb = (thread_id == SrcImportThread ? src_connections_cmb : connections_cmb), + *db_cmb = (thread_id == SrcImportThread ? src_database_cmb : database_cmb); Connection conn=(*reinterpret_cast(conn_cmb->itemData(conn_cmb->currentIndex()).value())), conn1; map> obj_oids; map> col_oids; @@ -445,30 +460,30 @@ void ModelDatabaseDiffForm::importDatabase(unsigned thread_id) DatabaseModel *db_model = nullptr; conn1=conn; + step_ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("import"))); + + conn.switchToDatabase(db_cmb->currentText()); + step_lbl->setText(trUtf8("Step %1/%2: Importing database %3...") .arg(curr_step) .arg(total_steps) - .arg(db_cmb->currentText())); + .arg(conn.getConnectionId(true, true))); - step_ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("import"))); - - if(thread_id == SRC_IMPORT_THREAD) - src_import_item=PgModelerUiNS::createOutputTreeItem(output_trw, step_lbl->text(), *step_ico_lbl->pixmap(), nullptr); + if(thread_id == SrcImportThread) + src_import_item=PgModelerUiNs::createOutputTreeItem(output_trw, step_lbl->text(), *step_ico_lbl->pixmap(), nullptr); else - import_item=PgModelerUiNS::createOutputTreeItem(output_trw, step_lbl->text(), *step_ico_lbl->pixmap(), nullptr); + import_item=PgModelerUiNs::createOutputTreeItem(output_trw, step_lbl->text(), *step_ico_lbl->pixmap(), nullptr); - conn.switchToDatabase(db_cmb->currentText()); pgsql_ver=conn.getPgSQLVersion(true); - catalog.setConnection(conn); //The import process will exclude built-in array array types, system and extension objects - catalog.setFilter(Catalog::LIST_ALL_OBJS | Catalog::EXCL_BUILTIN_ARRAY_TYPES | - Catalog::EXCL_EXTENSION_OBJS | Catalog::EXCL_SYSTEM_OBJS); - catalog.getObjectsOIDs(obj_oids, col_oids, {{ParsersAttributes::FILTER_TABLE_TYPES, ParsersAttributes::_TRUE_}}); - obj_oids[OBJ_DATABASE].push_back(db_cmb->currentData().value()); + catalog.setFilter(Catalog::ListAllObjects | Catalog::ExclBuiltinArrayTypes | + Catalog::ExclExtensionObjs | Catalog::ExclSystemObjs); + catalog.getObjectsOIDs(obj_oids, col_oids, {{Attributes::FilterTableTypes, Attributes::True}}); + obj_oids[ObjectType::Database].push_back(db_cmb->currentData().value()); - if(thread_id == SRC_IMPORT_THREAD) + if(thread_id == SrcImportThread) { source_model=new DatabaseModel; source_model->createSystemObjects(true); @@ -485,41 +500,44 @@ void ModelDatabaseDiffForm::importDatabase(unsigned thread_id) import_hlp->setSelectedOIDs(db_model, obj_oids, col_oids); import_hlp->setCurrentDatabase(db_cmb->currentText()); import_hlp->setImportOptions(import_sys_objs_chk->isChecked(), import_ext_objs_chk->isChecked(), true, - ignore_errors_chk->isChecked(), false, false, false); + ignore_errors_chk->isChecked(), false, false, false); thread->start(); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void ModelDatabaseDiffForm::diffModels(void) { - createThread(DIFF_THREAD); + createThread(DiffThread); step_lbl->setText(trUtf8("Step %1/%2: Comparing %3 and %4...") .arg(curr_step) .arg(total_steps) .arg(source_model->getName()) .arg(imported_model->getName())); - step_ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("diff"))); + step_ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("diff"))); + + if(src_import_item) + output_trw->collapseItem(src_import_item); output_trw->collapseItem(import_item); diff_progress=step_pb->value(); - diff_item=PgModelerUiNS::createOutputTreeItem(output_trw, step_lbl->text(), *step_ico_lbl->pixmap(), nullptr); + diff_item=PgModelerUiNs::createOutputTreeItem(output_trw, step_lbl->text(), *step_ico_lbl->pixmap(), nullptr); - diff_helper->setDiffOption(ModelsDiffHelper::OPT_KEEP_CLUSTER_OBJS, keep_cluster_objs_chk->isChecked()); - diff_helper->setDiffOption(ModelsDiffHelper::OPT_CASCADE_MODE, cascade_mode_chk->isChecked()); - diff_helper->setDiffOption(ModelsDiffHelper::OPT_TRUCANTE_TABLES, trunc_tables_chk->isChecked()); - diff_helper->setDiffOption(ModelsDiffHelper::OPT_FORCE_RECREATION, force_recreation_chk->isChecked()); - diff_helper->setDiffOption(ModelsDiffHelper::OPT_RECREATE_UNCHANGEBLE, recreate_unmod_chk->isChecked()); - diff_helper->setDiffOption(ModelsDiffHelper::OPT_KEEP_OBJ_PERMS, keep_obj_perms_chk->isChecked()); - diff_helper->setDiffOption(ModelsDiffHelper::OPT_REUSE_SEQUENCES, reuse_sequences_chk->isChecked()); - diff_helper->setDiffOption(ModelsDiffHelper::OPT_PRESERVE_DB_NAME, preserve_db_name_chk->isChecked()); - diff_helper->setDiffOption(ModelsDiffHelper::OPT_DONT_DROP_MISSING_OBJS, dont_drop_missing_objs_chk->isChecked()); - diff_helper->setDiffOption(ModelsDiffHelper::OPT_DROP_MISSING_COLS_CONSTR, drop_missing_cols_constr_chk->isChecked()); + diff_helper->setDiffOption(ModelsDiffHelper::OptKeepClusterObjs, keep_cluster_objs_chk->isChecked()); + diff_helper->setDiffOption(ModelsDiffHelper::OptCascadeMode, cascade_mode_chk->isChecked()); + diff_helper->setDiffOption(ModelsDiffHelper::OptTruncateTables, trunc_tables_chk->isChecked()); + diff_helper->setDiffOption(ModelsDiffHelper::OptForceRecreation, force_recreation_chk->isChecked()); + diff_helper->setDiffOption(ModelsDiffHelper::OptRecreateUnchangeble, recreate_unmod_chk->isChecked()); + diff_helper->setDiffOption(ModelsDiffHelper::OptKeepObjectPerms, keep_obj_perms_chk->isChecked()); + diff_helper->setDiffOption(ModelsDiffHelper::OptReuseSequences, reuse_sequences_chk->isChecked()); + diff_helper->setDiffOption(ModelsDiffHelper::OptPreserveDbName, preserve_db_name_chk->isChecked()); + diff_helper->setDiffOption(ModelsDiffHelper::OptDontDropMissingObjs, dont_drop_missing_objs_chk->isChecked()); + diff_helper->setDiffOption(ModelsDiffHelper::OptDropMissingColsConstr, drop_missing_cols_constr_chk->isChecked()); diff_helper->setModels(source_model, imported_model); @@ -533,62 +551,66 @@ void ModelDatabaseDiffForm::diffModels(void) void ModelDatabaseDiffForm::exportDiff(bool confirm) { - createThread(EXPORT_THREAD); + createThread(ExportThread); Messagebox msg_box; if(confirm) msg_box.show(trUtf8("Confirmation"), trUtf8(" WARNING: The generated diff is ready to be exported! Once started this process will cause irreversible changes on the database. Do you really want to proceed?"), - Messagebox::ALERT_ICON, Messagebox::ALL_BUTTONS, + Messagebox::AlertIcon, Messagebox::AllButtons, trUtf8("Apply diff"), trUtf8("Preview diff"), QString(), - PgModelerUiNS::getIconPath("diff"), PgModelerUiNS::getIconPath("codigosql")); + PgModelerUiNs::getIconPath("diff"), PgModelerUiNs::getIconPath("codigosql")); if(!confirm || msg_box.result()==QDialog::Accepted) { + export_conn=new Connection; + *export_conn=*reinterpret_cast(connections_cmb->itemData(connections_cmb->currentIndex()).value()); + settings_tbw->setCurrentIndex(1); apply_on_server_btn->setEnabled(true); - step_lbl->setText(trUtf8("Step %1/%2: Exporting diff to database %3...") + step_lbl->setText(trUtf8("Step %1/%2: Exporting diff to database %3@%4...") .arg(curr_step) .arg(total_steps) - .arg(imported_model->getName())); - step_ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("exportar"))); + .arg(imported_model->getName()) + .arg(export_conn->getConnectionId(true))); + step_ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("exportar"))); output_trw->collapseItem(diff_item); diff_progress=step_pb->value(); - export_item=PgModelerUiNS::createOutputTreeItem(output_trw, step_lbl->text(), *step_ico_lbl->pixmap(), nullptr); + export_item=PgModelerUiNs::createOutputTreeItem(output_trw, step_lbl->text(), *step_ico_lbl->pixmap(), nullptr); - export_conn=new Connection; - *export_conn=*reinterpret_cast(connections_cmb->itemData(connections_cmb->currentIndex()).value()); export_helper->setExportToDBMSParams(sqlcode_txt->toPlainText(), export_conn, database_cmb->currentText(), ignore_duplic_chk->isChecked()); if(ignore_error_codes_chk->isChecked()) export_helper->setIgnoredErrors(error_codes_edt->text().simplified().split(' ')); export_thread->start(); + close_btn->setEnabled(false); } else if(msg_box.isCancelled()) cancelOperation(true); else { process_paused=true; + close_btn->setEnabled(true); settings_tbw->setCurrentIndex(2); apply_on_server_btn->setVisible(true); output_trw->collapseItem(diff_item); - PgModelerUiNS::createOutputTreeItem(output_trw, + PgModelerUiNs::createOutputTreeItem(output_trw, trUtf8("Diff process paused. Waiting user action..."), - QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta")), nullptr); + QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta")), nullptr); } } void ModelDatabaseDiffForm::filterDiffInfos(void) { QToolButton *btn=dynamic_cast(sender()); - map diff_types={ {create_tb, ObjectsDiffInfo::CREATE_OBJECT}, - {drop_tb, ObjectsDiffInfo::DROP_OBJECT}, - {alter_tb, ObjectsDiffInfo::ALTER_OBJECT}, - {ignore_tb, ObjectsDiffInfo::IGNORE_OBJECT}}; + map diff_types={ {create_tb, ObjectsDiffInfo::CreateObject}, + {drop_tb, ObjectsDiffInfo::DropObject}, + {alter_tb, ObjectsDiffInfo::AlterObject}, + {ignore_tb, ObjectsDiffInfo::IgnoreObject}}; for(int i=0; i < diff_item->childCount(); i++) { @@ -597,6 +619,44 @@ void ModelDatabaseDiffForm::filterDiffInfos(void) } } +void ModelDatabaseDiffForm::loadDiffInSQLTool(void) +{ + QString database = database_cmb->currentText(), filename; + QFile out_tmp_file; + Connection conn=(*reinterpret_cast(connections_cmb->itemData(connections_cmb->currentIndex()).value())); + QByteArray buffer; + QTemporaryFile tmp_sql_file; + + cancelOperation(true); + + if(store_in_file_rb->isChecked()) + filename = file_edt->text(); + else + { + tmp_sql_file.setFileTemplate(GlobalAttributes::TemporaryDir + + GlobalAttributes::DirSeparator + + QString("diff_%1_XXXXXX.sql").arg(database)); + + tmp_sql_file.open(); + filename = tmp_sql_file.fileName(); + tmp_sql_file.close(); + + out_tmp_file.setFileName(filename); + out_tmp_file.open(QFile::WriteOnly); + + if(!out_tmp_file.isOpen()) + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotWritten).arg(out_tmp_file.fileName()), + ErrorCode::FileDirectoryNotWritten,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + buffer.append(sqlcode_txt->toPlainText()); + out_tmp_file.write(buffer); + out_tmp_file.close(); + } + + emit s_loadDiffInSQLTool(conn.getConnectionId(), database, filename); + close(); +} + void ModelDatabaseDiffForm::resetButtons(void) { buttons_wgt->setEnabled(true); @@ -613,16 +673,16 @@ void ModelDatabaseDiffForm::saveDiffToFile(void) QFile output; step_lbl->setText(trUtf8("Saving diff to file %1").arg(file_edt->text())); - step_ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("salvar"))); - import_item=PgModelerUiNS::createOutputTreeItem(output_trw, step_lbl->text(), *step_ico_lbl->pixmap(), nullptr); + step_ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("salvar"))); + import_item=PgModelerUiNs::createOutputTreeItem(output_trw, step_lbl->text(), *step_ico_lbl->pixmap(), nullptr); step_pb->setValue(90); progress_pb->setValue(100); output.setFileName(file_edt->text()); if(!output.open(QFile::WriteOnly)) - captureThreadError(Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(file_edt->text()), - ERR_FILE_DIR_NOT_WRITTEN, __PRETTY_FUNCTION__,__FILE__,__LINE__)); + captureThreadError(Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotWritten).arg(file_edt->text()), + ErrorCode::FileDirectoryNotWritten, __PRETTY_FUNCTION__,__FILE__,__LINE__)); output.write(sqlcode_txt->toPlainText().toUtf8()); output.close(); @@ -638,10 +698,10 @@ void ModelDatabaseDiffForm::finishDiff(void) step_lbl->setText(trUtf8("Diff process sucessfully ended!")); progress_lbl->setText(trUtf8("No operations left.")); - step_ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("msgbox_info"))); - progress_ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("msgbox_info"))); + step_ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("msgbox_info"))); + progress_ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("msgbox_info"))); - import_item=PgModelerUiNS::createOutputTreeItem(output_trw, step_lbl->text(), *step_ico_lbl->pixmap(), nullptr); + import_item=PgModelerUiNs::createOutputTreeItem(output_trw, step_lbl->text(), *step_ico_lbl->pixmap(), nullptr); step_pb->setValue(100); progress_pb->setValue(100); } @@ -653,10 +713,10 @@ void ModelDatabaseDiffForm::cancelOperation(bool cancel_by_user) step_lbl->setText(trUtf8("Operation cancelled by the user.")); progress_lbl->setText(trUtf8("No operations left.")); - step_ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta"))); - progress_ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta"))); + step_ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta"))); + progress_ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta"))); - PgModelerUiNS::createOutputTreeItem(output_trw, step_lbl->text(), *step_ico_lbl->pixmap(), nullptr); + PgModelerUiNs::createOutputTreeItem(output_trw, step_lbl->text(), *step_ico_lbl->pixmap(), nullptr); } if(src_import_helper && src_import_thread->isRunning()) @@ -685,6 +745,7 @@ void ModelDatabaseDiffForm::cancelOperation(bool cancel_by_user) resetButtons(); process_paused=false; + close_btn->setEnabled(true); } void ModelDatabaseDiffForm::captureThreadError(Exception e) @@ -693,12 +754,12 @@ void ModelDatabaseDiffForm::captureThreadError(Exception e) cancelOperation(false); progress_lbl->setText(trUtf8("Process aborted due to errors!")); - progress_ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("msgbox_erro"))); + progress_ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("msgbox_erro"))); - item=PgModelerUiNS::createOutputTreeItem(output_trw, PgModelerUiNS::formatMessage(e.getErrorMessage()), *progress_ico_lbl->pixmap(), nullptr, false, true); - PgModelerUiNS::createExceptionsTree(output_trw, e, item); + item=PgModelerUiNs::createOutputTreeItem(output_trw, PgModelerUiNs::formatMessage(e.getErrorMessage()), *progress_ico_lbl->pixmap(), nullptr, false, true); + PgModelerUiNs::createExceptionsTree(output_trw, e, item); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } void ModelDatabaseDiffForm::handleImportFinished(Exception e) @@ -706,7 +767,7 @@ void ModelDatabaseDiffForm::handleImportFinished(Exception e) if(!e.getErrorMessage().isEmpty()) { Messagebox msgbox; - msgbox.show(e, e.getErrorMessage(), Messagebox::ALERT_ICON); + msgbox.show(e, e.getErrorMessage(), Messagebox::AlertIcon); } curr_step++; @@ -715,7 +776,7 @@ void ModelDatabaseDiffForm::handleImportFinished(Exception e) { src_import_thread->quit(); src_import_item->setExpanded(false); - importDatabase(IMPORT_THREAD); + importDatabase(ImportThread); } else { @@ -766,15 +827,15 @@ void ModelDatabaseDiffForm::handleErrorIgnored(QString err_code, QString err_msg { QTreeWidgetItem *item=nullptr; - item=PgModelerUiNS::createOutputTreeItem(output_trw, trUtf8("Error code %1 found and ignored. Proceeding with export.").arg(err_code), - QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta")), + item=PgModelerUiNs::createOutputTreeItem(output_trw, trUtf8("Error code %1 found and ignored. Proceeding with export.").arg(err_code), + QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta")), export_item, false); - PgModelerUiNS::createOutputTreeItem(output_trw, PgModelerUiNS::formatMessage(err_msg), + PgModelerUiNs::createOutputTreeItem(output_trw, PgModelerUiNs::formatMessage(err_msg), QPixmap(QString("msgbox_alerta")), item, false); - PgModelerUiNS::createOutputTreeItem(output_trw, cmd, + PgModelerUiNs::createOutputTreeItem(output_trw, cmd, QPixmap(), item, false); } @@ -783,16 +844,18 @@ void ModelDatabaseDiffForm::updateProgress(int progress, QString msg, ObjectType { int progress_aux = 0; - msg=PgModelerUiNS::formatMessage(msg); - + msg=PgModelerUiNs::formatMessage(msg); if(src_import_thread && src_import_thread->isRunning()) { progress_aux = progress/5; - PgModelerUiNS::createOutputTreeItem(output_trw, msg, - QPixmap(PgModelerUiNS::getIconPath(obj_type)), - src_import_item); + if(!low_verbosity) + { + PgModelerUiNs::createOutputTreeItem(output_trw, msg, + QPixmap(PgModelerUiNs::getIconPath(obj_type)), + src_import_item); + } } else if(import_thread && import_thread->isRunning()) { @@ -801,16 +864,19 @@ void ModelDatabaseDiffForm::updateProgress(int progress, QString msg, ObjectType else progress_aux = 20 + (progress/5); - PgModelerUiNS::createOutputTreeItem(output_trw, msg, - QPixmap(PgModelerUiNS::getIconPath(obj_type)), - import_item); + if(!low_verbosity) + { + PgModelerUiNs::createOutputTreeItem(output_trw, msg, + QPixmap(PgModelerUiNs::getIconPath(obj_type)), + import_item); + } } else if(diff_thread && diff_thread->isRunning()) { - if((progress == 0 || progress == 100) && obj_type==BASE_OBJECT) + if((progress == 0 || progress == 100) && obj_type==ObjectType::BaseObject) { - PgModelerUiNS::createOutputTreeItem(output_trw, msg, - QPixmap(PgModelerUiNS::getIconPath("msgbox_info")), + PgModelerUiNs::createOutputTreeItem(output_trw, msg, + QPixmap(PgModelerUiNs::getIconPath("msgbox_info")), diff_item); } @@ -823,15 +889,18 @@ void ModelDatabaseDiffForm::updateProgress(int progress, QString msg, ObjectType progress_aux = diff_progress + (progress/3); - if(obj_type==BASE_OBJECT) - ico=QPixmap(PgModelerUiNS::getIconPath("codigosql")); - else - ico=QPixmap(PgModelerUiNS::getIconPath(obj_type)); + if(!low_verbosity) + { + if(obj_type==ObjectType::BaseObject) + ico=QPixmap(PgModelerUiNs::getIconPath("codigosql")); + else + ico=QPixmap(PgModelerUiNs::getIconPath(obj_type)); - item=PgModelerUiNS::createOutputTreeItem(output_trw, msg, ico, export_item, false); + item=PgModelerUiNs::createOutputTreeItem(output_trw, msg, ico, export_item, false); - if(!cmd.isEmpty()) - PgModelerUiNS::createOutputTreeItem(output_trw, cmd, QPixmap(), item, false); + if(!cmd.isEmpty()) + PgModelerUiNs::createOutputTreeItem(output_trw, cmd, QPixmap(), item, false); + } } if(progress_aux > step_pb->value()) @@ -840,34 +909,38 @@ void ModelDatabaseDiffForm::updateProgress(int progress, QString msg, ObjectType progress_lbl->setText(msg); progress_pb->setValue(progress); - if(obj_type!=BASE_OBJECT) - progress_ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath(obj_type))); + if(obj_type!=ObjectType::BaseObject) + progress_ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath(obj_type))); else - progress_ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("msgbox_info"))); + progress_ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("msgbox_info"))); - this->repaint(); + //this->repaint(); } void ModelDatabaseDiffForm::updateDiffInfo(ObjectsDiffInfo diff_info) { - map buttons={ {ObjectsDiffInfo::CREATE_OBJECT, create_tb}, - {ObjectsDiffInfo::DROP_OBJECT, drop_tb}, - {ObjectsDiffInfo::ALTER_OBJECT, alter_tb}, - {ObjectsDiffInfo::IGNORE_OBJECT, ignore_tb} }; + map buttons={ {ObjectsDiffInfo::CreateObject, create_tb}, + {ObjectsDiffInfo::DropObject, drop_tb}, + {ObjectsDiffInfo::AlterObject, alter_tb}, + {ObjectsDiffInfo::IgnoreObject, ignore_tb} }; unsigned diff_type=diff_info.getDiffType(); QToolButton *btn=buttons[diff_type]; QTreeWidgetItem *item=nullptr; - item=PgModelerUiNS::createOutputTreeItem(output_trw, - PgModelerUiNS::formatMessage(diff_info.getInfoMessage()), - QPixmap(PgModelerUiNS::getIconPath(diff_info.getObject()->getSchemaName())), diff_item); - item->setData(0, Qt::UserRole, diff_info.getDiffType()); + if(!low_verbosity) + { + item=PgModelerUiNs::createOutputTreeItem(output_trw, + PgModelerUiNs::formatMessage(diff_info.getInfoMessage()), + QPixmap(PgModelerUiNs::getIconPath(diff_info.getObject()->getSchemaName())), diff_item); + item->setData(0, Qt::UserRole, diff_info.getDiffType()); + } if(diff_helper) btn->setText(QString::number(diff_helper->getDiffTypeCount(diff_type))); - output_trw->setItemHidden(item, !btn->isChecked()); + if(item) + output_trw->setItemHidden(item, !btn->isChecked()); } void ModelDatabaseDiffForm::selectOutputFile(void) diff --git a/libpgmodeler_ui/src/modeldatabasediffform.h b/libpgmodeler_ui/src/modeldatabasediffform.h index 0094bad297..9c899508ae 100644 --- a/libpgmodeler_ui/src/modeldatabasediffform.h +++ b/libpgmodeler_ui/src/modeldatabasediffform.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -39,6 +39,10 @@ class ModelDatabaseDiffForm: public QDialog, public Ui::ModelDatabaseDiffForm { private: Q_OBJECT + /*! \brief Indicates if the full output generated during the process should be displayed + * When this attribute is true, only errors and some key info messages are displayed. */ + static bool low_verbosity; + NumberedTextEditor *sqlcode_txt; //! \brief Custom delegate used to paint html texts in output tree @@ -110,17 +114,20 @@ class ModelDatabaseDiffForm: public QDialog, public Ui::ModelDatabaseDiffForm { void finishDiff(void); //! \brief Constants used to reference the thread/helper to be handled in createThread() and destroyThread() - static const unsigned SRC_IMPORT_THREAD=0, - IMPORT_THREAD=1, - DIFF_THREAD=2, - EXPORT_THREAD=3; + static constexpr unsigned SrcImportThread=0, + ImportThread=1, + DiffThread=2, + ExportThread=3; public: - ModelDatabaseDiffForm(QWidget * parent = 0, Qt::WindowFlags f = 0); + ModelDatabaseDiffForm(QWidget * parent = nullptr, Qt::WindowFlags f = Qt::Widget); ~ModelDatabaseDiffForm(void); void setModelWidget(ModelWidget *model_wgt); + //! \brief Defines if all the output generated during the import process should be displayed + static void setLowVerbosity(bool value); + private slots: void listDatabases(void); void enableDiffMode(void); @@ -138,11 +145,17 @@ class ModelDatabaseDiffForm: public QDialog, public Ui::ModelDatabaseDiffForm { void diffModels(void); void exportDiff(bool confirm=true); void filterDiffInfos(void); + void loadDiffInSQLTool(void); signals: /*! \brief This signal is emitted whenever the user changes the connections settings within this widget without use the main configurations dialog */ void s_connectionsUpdateRequest(void); + + /*! \brief This signal is emitted whenever the user wants to load the generated diff in the sql tool + * The signal contains the connection id, the database name and the temp filename that is generated containing + * the commands to be loaded */ + void s_loadDiffInSQLTool(QString conn_id, QString database, QString sql_file); }; #endif diff --git a/libpgmodeler_ui/src/modelexportform.cpp b/libpgmodeler_ui/src/modelexportform.cpp index 1442cc6b0f..cc947d3531 100644 --- a/libpgmodeler_ui/src/modelexportform.cpp +++ b/libpgmodeler_ui/src/modelexportform.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -21,6 +21,8 @@ #include "configurationform.h" #include "pgmodeleruins.h" +bool ModelExportForm::low_verbosity = false; + ModelExportForm::ModelExportForm(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f) { model=nullptr; @@ -93,11 +95,11 @@ ModelExportForm::ModelExportForm(QWidget *parent, Qt::WindowFlags f) : QDialog(p connect(svg_rb, SIGNAL(toggled(bool)), page_by_page_chk, SLOT(setDisabled(bool))); connect(ignore_error_codes_chk, SIGNAL(toggled(bool)), error_codes_edt, SLOT(setEnabled(bool))); - pgsqlvers_cmb->addItems(PgSQLVersions::ALL_VERSIONS); - pgsqlvers1_cmb->addItems(PgSQLVersions::ALL_VERSIONS); + pgsqlvers_cmb->addItems(PgSqlVersions::AllVersions); + pgsqlvers1_cmb->addItems(PgSqlVersions::AllVersions); - double values[]={ ModelWidget::MINIMUM_ZOOM, 0.10f, 0.25f, 0.5f, 0.75f, 1, 1.25f, 1.50f, 1.75f, 2, - 2.25, 2.50, 2.75, 3, 3.25, 3.50, 3.75, ModelWidget::MAXIMUM_ZOOM }; + double values[]={ ModelWidget::MinimumZoom, 0.10, 0.25, 0.5, 0.75, 1, 1.25, 1.50, 1.75, 2, + 2.25, 2.50, 2.75, 3, 3.25, 3.50, 3.75, ModelWidget::MaximumZoom }; unsigned cnt=sizeof(values)/sizeof(double); for(unsigned i=0; i < cnt; i++) @@ -108,12 +110,17 @@ ModelExportForm::ModelExportForm(QWidget *parent, Qt::WindowFlags f) : QDialog(p settings_tbw->setTabEnabled(1, false); } +void ModelExportForm::setLowVerbosity(bool value) +{ + low_verbosity = value; +} + void ModelExportForm::exec(ModelWidget *model) { if(model) { this->model=model; - ConnectionsConfigWidget::fillConnectionsComboBox(connections_cmb, true, Connection::OP_EXPORT); + ConnectionsConfigWidget::fillConnectionsComboBox(connections_cmb, true, Connection::OpExport); selectExportMode(); QDialog::exec(); } @@ -123,39 +130,40 @@ void ModelExportForm::handleErrorIgnored(QString err_code, QString err_msg, QStr { QTreeWidgetItem *item=nullptr; - item=PgModelerUiNS::createOutputTreeItem(output_trw, trUtf8("Error code %1 found and ignored. Proceeding with export.").arg(err_code), - QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta")), nullptr, false); + item=PgModelerUiNs::createOutputTreeItem(output_trw, trUtf8("Error code %1 found and ignored. Proceeding with export.").arg(err_code), + QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta")), nullptr, false); - PgModelerUiNS::createOutputTreeItem(output_trw, PgModelerUiNS::formatMessage(err_msg), - QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta")), item, false); + PgModelerUiNs::createOutputTreeItem(output_trw, PgModelerUiNs::formatMessage(err_msg), + QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta")), item, false); - PgModelerUiNS::createOutputTreeItem(output_trw, cmd, QPixmap(), item, false); + PgModelerUiNs::createOutputTreeItem(output_trw, cmd, QPixmap(), item, false); } void ModelExportForm::updateProgress(int progress, QString msg, ObjectType obj_type, QString cmd, bool is_code_gen) { QTreeWidgetItem *item=nullptr; - QString text=PgModelerUiNS::formatMessage(msg); + QString text=PgModelerUiNs::formatMessage(msg); QPixmap ico; progress_lbl->setText(text); progress_pb->setValue(progress); - if(obj_type!=BASE_OBJECT) - ico=QPixmap(PgModelerUiNS::getIconPath(obj_type)); + if(obj_type!=ObjectType::BaseObject) + ico=QPixmap(PgModelerUiNs::getIconPath(obj_type)); else if(!cmd.isEmpty()) - ico=QPixmap(PgModelerUiNS::getIconPath("codigosql")); + ico=QPixmap(PgModelerUiNs::getIconPath("codigosql")); else - ico=QPixmap(PgModelerUiNS::getIconPath("msgbox_info")); + ico=QPixmap(PgModelerUiNs::getIconPath("msgbox_info")); ico_lbl->setPixmap(ico); - if(!is_code_gen) + // If low_verbosity is set only messages hinted by obj_type == BaseObject are show because they hold key info messages + if(!is_code_gen && (!low_verbosity || (low_verbosity && obj_type == ObjectType::BaseObject && cmd.isEmpty()))) { - item=PgModelerUiNS::createOutputTreeItem(output_trw, text, ico, nullptr, false); + item=PgModelerUiNs::createOutputTreeItem(output_trw, text, ico, nullptr, false); if(!cmd.isEmpty()) - PgModelerUiNS::createOutputTreeItem(output_trw, cmd, QPixmap(), item, false); + PgModelerUiNs::createOutputTreeItem(output_trw, cmd, QPixmap(), item, false); } } @@ -203,6 +211,10 @@ void ModelExportForm::exportModel(void) QString version; Connection *conn=reinterpret_cast(connections_cmb->itemData(connections_cmb->currentIndex()).value()); + if(low_verbosity) + PgModelerUiNs::createOutputTreeItem(output_trw, trUtf8("Low verbosity is set: only key informations and errors will be displayed."), + QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta")), nullptr, false); + //If the user chose a specific version if(pgsqlvers1_cmb->isEnabled()) version=pgsqlvers1_cmb->currentText(); @@ -294,15 +306,15 @@ void ModelExportForm::selectOutputFile(void) void ModelExportForm::captureThreadError(Exception e) { - QTreeWidgetItem *item=PgModelerUiNS::createOutputTreeItem(output_trw, PgModelerUiNS::formatMessage(e.getErrorMessage()), - QPixmap(PgModelerUiNS::getIconPath("msgbox_erro")), nullptr, false, true); + QTreeWidgetItem *item=PgModelerUiNs::createOutputTreeItem(output_trw, PgModelerUiNs::formatMessage(e.getErrorMessage()), + QPixmap(PgModelerUiNs::getIconPath("msgbox_erro")), nullptr, false, true); - PgModelerUiNS::createExceptionsTree(output_trw, e, item); + PgModelerUiNs::createExceptionsTree(output_trw, e, item); - ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("msgbox_erro"))); + ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("msgbox_erro"))); finishExport(trUtf8("Exporting process aborted!")); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } void ModelExportForm::cancelExport(void) @@ -313,22 +325,22 @@ void ModelExportForm::cancelExport(void) void ModelExportForm::handleExportCanceled(void) { - QPixmap ico=QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta")); + QPixmap ico=QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta")); QString msg=trUtf8("Exporting process canceled by user!"); finishExport(msg); ico_lbl->setPixmap(ico); - PgModelerUiNS::createOutputTreeItem(output_trw, msg, ico); + PgModelerUiNs::createOutputTreeItem(output_trw, msg, ico); } void ModelExportForm::handleExportFinished(void) { - QPixmap ico=QPixmap(PgModelerUiNS::getIconPath("msgbox_info")); + QPixmap ico=QPixmap(PgModelerUiNs::getIconPath("msgbox_info")); QString msg=trUtf8("Exporting process sucessfuly ended!"); finishExport(msg); ico_lbl->setPixmap(ico); - PgModelerUiNS::createOutputTreeItem(output_trw, msg, ico); + PgModelerUiNs::createOutputTreeItem(output_trw, msg, ico); } void ModelExportForm::finishExport(const QString &msg) diff --git a/libpgmodeler_ui/src/modelexportform.h b/libpgmodeler_ui/src/modelexportform.h index ecc520605f..8688f2a919 100644 --- a/libpgmodeler_ui/src/modelexportform.h +++ b/libpgmodeler_ui/src/modelexportform.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -36,6 +36,10 @@ class ModelExportForm: public QDialog, public Ui::ModelExportForm { private: Q_OBJECT + /*! \brief Indicates if the full output generated during the process should be displayed + * When this attribute is true, only errors and some key info messages are displayed. */ + static bool low_verbosity; + //! \brief Custom delegate used to paint html texts in output tree HtmlItemDelegate *htmlitem_del; @@ -59,7 +63,10 @@ class ModelExportForm: public QDialog, public Ui::ModelExportForm { int exec(void){ return(QDialog::Rejected); } public: - ModelExportForm(QWidget * parent = 0, Qt::WindowFlags f = 0); + ModelExportForm(QWidget * parent = nullptr, Qt::WindowFlags f = Qt::Widget); + + //! \brief Defines if all the output generated during the import process should be displayed + static void setLowVerbosity(bool value); public slots: void exec(ModelWidget *model); diff --git a/libpgmodeler_ui/src/modelexporthelper.cpp b/libpgmodeler_ui/src/modelexporthelper.cpp index 6953a39dbb..f2ba043b58 100644 --- a/libpgmodeler_ui/src/modelexporthelper.cpp +++ b/libpgmodeler_ui/src/modelexporthelper.cpp @@ -11,7 +11,7 @@ void ModelExportHelper::resetExportParams(void) sql_gen_progress=progress=0; db_created=ignore_dup=drop_db=drop_objs=export_canceled=false; simulate=use_tmp_names=db_sql_reenabled=false; - created_objs[OBJ_ROLE]=created_objs[OBJ_TABLESPACE]=-1; + created_objs[ObjectType::Role]=created_objs[ObjectType::Tablespace]=-1; db_model=nullptr; connection=nullptr; scene=nullptr; @@ -26,9 +26,9 @@ void ModelExportHelper::abortExport(Exception &e) //When running in a separated thread (other than the main application thread) redirects the error in form of signal if(this->thread() && this->thread()!=qApp->thread()) - emit s_exportAborted(Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e)); + emit s_exportAborted(Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e)); else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } void ModelExportHelper::handleSQLError(Exception &e, const QString &sql_cmd, bool ignore_dup) @@ -39,7 +39,7 @@ void ModelExportHelper::handleSQLError(Exception &e, const QString &sql_cmd, boo emit s_errorIgnored(e.getExtraInfo(), e.getErrorMessage(), sql_cmd); //Raises an excpetion if the error returned by the database is not listed in the ignored list of errors else if(ignored_errors.indexOf(e.getExtraInfo()) < 0) - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e, sql_cmd); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e, sql_cmd); else errors.push_back(e); } @@ -62,7 +62,7 @@ void ModelExportHelper::setIgnoredErrors(const QStringList &err_codes) void ModelExportHelper::exportToSQL(DatabaseModel *db_model, const QString &filename, const QString &pgsql_ver) { if(!db_model) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); connect(db_model, SIGNAL(s_objectLoaded(int,QString,uint)), this, SLOT(updateProgress(int,QString,uint))); @@ -72,17 +72,17 @@ void ModelExportHelper::exportToSQL(DatabaseModel *db_model, const QString &file BaseObject::setPgSQLVersion(pgsql_ver); emit s_progressUpdated(progress, trUtf8("Generating SQL code for PostgreSQL `%1'").arg(BaseObject::getPgSQLVersion()), - BASE_OBJECT); + ObjectType::BaseObject); progress=1; - db_model->saveModel(filename, SchemaParser::SQL_DEFINITION); + db_model->saveModel(filename, SchemaParser::SqlDefinition); - emit s_progressUpdated(100, trUtf8("Output SQL file `%1' successfully written.").arg(filename), BASE_OBJECT); + emit s_progressUpdated(100, trUtf8("Output SQL file `%1' successfully written.").arg(filename), ObjectType::BaseObject); emit s_exportFinished(); } catch(Exception &e) { disconnect(db_model, nullptr, this, nullptr); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } disconnect(db_model, nullptr, this, nullptr); @@ -91,7 +91,7 @@ void ModelExportHelper::exportToSQL(DatabaseModel *db_model, const QString &file void ModelExportHelper::exportToPNG(ObjectsScene *scene, const QString &filename, double zoom, bool show_grid, bool show_delim, bool page_by_page, QGraphicsView *viewp) { if(!scene) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { @@ -117,7 +117,9 @@ void ModelExportHelper::exportToPNG(ObjectsScene *scene, const QString &filename scene->clearSelection(); //Make a backup of the current scene options - ObjectsScene::getGridOptions(shw_grd, align_objs, shw_dlm); + shw_grd = ObjectsScene::isShowGrid(); + align_objs = ObjectsScene::isAlignObjectsToGrid(); + shw_dlm = ObjectsScene::isShowPageDelimiters(); //Sets the options passed by the user ObjectsScene::setGridOptions(show_grid, false, show_delim); @@ -146,14 +148,14 @@ void ModelExportHelper::exportToPNG(ObjectsScene *scene, const QString &filename pages=scene->getPagesForPrinting(page_sz, margins.size(), h_cnt, v_cnt); //Configures the template filename for pages pixmaps - tmpl_filename=fi.absolutePath() + GlobalAttributes::DIR_SEPARATOR + fi.baseName() + QString("_p%1.") + fi.completeSuffix(); + tmpl_filename=fi.absolutePath() + GlobalAttributes::DirSeparator + fi.baseName() + QString("_p%1.") + fi.completeSuffix(); } else { QRectF rect=scene->itemsBoundingRect(true); //Give some margin to the resulting image - QSizeF margin=QSizeF(5 * BaseObjectView::HORIZ_SPACING, 5 * BaseObjectView::VERT_SPACING); + QSizeF margin=QSizeF(5 * BaseObjectView::HorizSpacing, 5 * BaseObjectView::VertSpacing); rect.setTopLeft(rect.topLeft() - QPointF(margin.width(), margin.height())); rect.setSize(rect.size() + margin); @@ -197,8 +199,8 @@ void ModelExportHelper::exportToPNG(ObjectsScene *scene, const QString &filename painter.setRenderHint(QPainter::TextAntialiasing, true); painter.setRenderHint(QPainter::SmoothPixmapTransform, true); - emit s_progressUpdated((page_idx/static_cast(pages.size())) * 90, - trUtf8("Rendering objects to page %1/%2.").arg(page_idx).arg(pages.size()), BASE_OBJECT); + emit s_progressUpdated((page_idx/static_cast(pages.size())) * 90, + trUtf8("Rendering objects to page %1/%2.").arg(page_idx).arg(pages.size()), ObjectType::BaseObject); //Render the entire viewport onto the pixmap view->render(&painter, QRectF(QPointF(0,0), pix.size()), retv); @@ -214,8 +216,8 @@ void ModelExportHelper::exportToPNG(ObjectsScene *scene, const QString &filename ObjectsScene::setGridOptions(shw_grd, align_objs, shw_dlm); scene->update(); - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(file), - ERR_FILE_DIR_NOT_WRITTEN,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotWritten).arg(file), + ErrorCode::FileDirectoryNotWritten,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } @@ -225,7 +227,7 @@ void ModelExportHelper::exportToPNG(ObjectsScene *scene, const QString &filename if(!export_canceled) { - emit s_progressUpdated(100, trUtf8("Output image `%1' successfully written.").arg(filename), BASE_OBJECT); + emit s_progressUpdated(100, trUtf8("Output image `%1' successfully written.").arg(filename), ObjectType::BaseObject); emit s_exportFinished(); } else @@ -236,14 +238,14 @@ void ModelExportHelper::exportToPNG(ObjectsScene *scene, const QString &filename } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void ModelExportHelper::exportToSVG(ObjectsScene *scene, const QString &filename, bool show_grid, bool show_delim) { if(!scene) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); bool shw_dlm=false, shw_grd=false, align_objs=false; QSvgGenerator svg_gen; @@ -251,7 +253,9 @@ void ModelExportHelper::exportToSVG(ObjectsScene *scene, const QString &filename QFileInfo fi(filename); //Making a backup of the current scene options - ObjectsScene::getGridOptions(shw_grd, align_objs, shw_dlm); + shw_grd = ObjectsScene::isShowGrid(); + shw_dlm = ObjectsScene::isShowPageDelimiters(); + align_objs = ObjectsScene::isAlignObjectsToGrid(); scene->setBackgroundBrush(Qt::NoBrush); //Disabling grid and delimiters @@ -273,8 +277,8 @@ void ModelExportHelper::exportToSVG(ObjectsScene *scene, const QString &filename scene->update(); if(!fi.exists() || !fi.isWritable() || !fi.isReadable()) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(filename), - ERR_FILE_DIR_NOT_WRITTEN,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotWritten).arg(filename), + ErrorCode::FileDirectoryNotWritten,__PRETTY_FUNCTION__,__FILE__,__LINE__); QFile svg_file; svg_file.setFileName(filename); @@ -290,7 +294,7 @@ void ModelExportHelper::exportToSVG(ObjectsScene *scene, const QString &filename //Forcing the usage of the font settings defined for BaseObjectView and its subclasses svg_def.replace(font_attr.arg(scene->font().family()), - font_attr.arg(BaseObjectView::getFontStyle(ParsersAttributes::GLOBAL).font().family())); + font_attr.arg(BaseObjectView::getFontStyle(Attributes::Global).font().family())); /* Removing the empty (transparent) backgound object in order to save some space in the file if the grid or delimiter is displayed */ @@ -304,7 +308,7 @@ void ModelExportHelper::exportToSVG(ObjectsScene *scene, const QString &filename svg_file.close(); } - emit s_progressUpdated(100, trUtf8("Output file `%1' successfully written.").arg(filename), BASE_OBJECT); + emit s_progressUpdated(100, trUtf8("Output file `%1' successfully written.").arg(filename), ObjectType::BaseObject); emit s_exportFinished(); } @@ -314,30 +318,30 @@ void ModelExportHelper::exportToDBMS(DatabaseModel *db_model, Connection conn, c QString version, sql_cmd, buf, sql_cmd_comment; Connection new_db_conn; unsigned i, count; - ObjectType types[]={OBJ_ROLE, OBJ_TABLESPACE}; + ObjectType types[]={ObjectType::Role, ObjectType::Tablespace}; BaseObject *object=nullptr; - QString tmpl_comm_regexp = QString("(COMMENT)( )+(ON)( )+(%1)(.)+(\n)(") + ParsersAttributes::DDL_END_TOKEN + QString(")"); + QString tmpl_comm_regexp = QString("(COMMENT)( )+(ON)( )+(%1)(.)+(\n)(") + Attributes::DdlEndToken + QString(")"); QRegExp comm_regexp; try { if(!db_model) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); /* If the export is called using ignore duplications or drop database and simulation mode at same time an error is raised because the simulate mode (mainly used as SQL validation) cannot undo column addition (this can be changed in the future) */ if(simulate && (ignore_dup || drop_db || drop_objs)) - throw Exception(ERR_MIX_INCOMP_EXPORT_OPTS,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::MixingIncompExportOptions,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(drop_db && drop_objs) - throw Exception(ERR_MIX_INCOMP_DROP_OPTS,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::MixingIncompDropOptions,__PRETTY_FUNCTION__,__FILE__,__LINE__); connect(db_model, SIGNAL(s_objectLoaded(int,QString,uint)), this, SLOT(updateProgress(int,QString,uint)), Qt::DirectConnection); export_canceled=false; db_created=false; progress=sql_gen_progress=0; - created_objs[OBJ_ROLE]=created_objs[OBJ_TABLESPACE]=-1; + created_objs[ObjectType::Role]=created_objs[ObjectType::Tablespace]=-1; errors.clear(); //Retrive the DBMS version in order to generate the correct code @@ -364,7 +368,7 @@ void ModelExportHelper::exportToDBMS(DatabaseModel *db_model, Connection conn, c generateTempObjectNames(db_model); } else if(use_tmp_names) - throw Exception(ERR_INV_USE_TMPNAMES_EXPORT_OPT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InvUsageTempNamesExportOption,__PRETTY_FUNCTION__,__FILE__,__LINE__); if(simulate && db_model->isSQLDisabled()) @@ -414,7 +418,7 @@ void ModelExportHelper::exportToDBMS(DatabaseModel *db_model, Connection conn, c for(i=0; i < count && !export_canceled; i++) { object=db_model->getObject(i, types[type_id]); - progress=((10 * (type_id+1)) + ((i/static_cast(count)) * 10)); + progress=((10 * (type_id+1)) + ((i/static_cast(count)) * 10)); try { @@ -427,9 +431,9 @@ void ModelExportHelper::exportToDBMS(DatabaseModel *db_model, Connection conn, c .arg(object->getTypeName()), object->getObjectType()); - sql_cmd=object->getCodeDefinition(SchemaParser::SQL_DEFINITION); + sql_cmd=object->getCodeDefinition(SchemaParser::SqlDefinition); - if(types[type_id] == OBJ_TABLESPACE) + if(types[type_id] == ObjectType::Tablespace) { comm_regexp = QRegExp(tmpl_comm_regexp.arg(object->getSQLName())); pos = comm_regexp.indexIn(sql_cmd); @@ -469,9 +473,9 @@ void ModelExportHelper::exportToDBMS(DatabaseModel *db_model, Connection conn, c emit s_progressUpdated(progress, trUtf8("Creating database `%1'") .arg(db_model->getName()), - OBJ_DATABASE); + ObjectType::Database); - sql_cmd=db_model->__getCodeDefinition(SchemaParser::SQL_DEFINITION); + sql_cmd=db_model->__getCodeDefinition(SchemaParser::SqlDefinition); pos = comm_regexp.indexIn(sql_cmd); /* If we find a comment on statment we should strip it from the DB definition in @@ -499,7 +503,7 @@ void ModelExportHelper::exportToDBMS(DatabaseModel *db_model, Connection conn, c //Connects to the new created database to create the other objects progress=20; new_db_conn=conn; - new_db_conn.setConnectionParam(Connection::PARAM_DB_NAME, db_model->getName()); + new_db_conn.setConnectionParam(Connection::ParamDbName, db_model->getName()); emit s_progressUpdated(progress, trUtf8("Connecting to database `%1'") .arg(db_model->getName())); @@ -511,7 +515,7 @@ void ModelExportHelper::exportToDBMS(DatabaseModel *db_model, Connection conn, c emit s_progressUpdated(progress, trUtf8("Generating SQL for `%1' objects...").arg(db_model->getObjectCount())); //Exporting the database model definition using the opened connection - buf=db_model->getCodeDefinition(SchemaParser::SQL_DEFINITION, false); + buf=db_model->getCodeDefinition(SchemaParser::SqlDefinition, false); progress=40; exportBufferToDBMS(buf, new_db_conn, drop_objs); } @@ -560,13 +564,13 @@ void ModelExportHelper::exportToDBMS(DatabaseModel *db_model, Connection conn, c if(this->thread() && this->thread()!=qApp->thread()) { errors.push_back(e); - emit s_exportAborted(Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, errors)); + emit s_exportAborted(Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, errors)); } else { //Redirects any error to terrorsr if(errors.empty()) - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); else { errors.push_back(e); @@ -582,12 +586,12 @@ void ModelExportHelper::saveGenAtlerCmdsStatus(DatabaseModel *db_model) Table *tab=nullptr; Relationship *rel=nullptr; - objects.insert(objects.end(), db_model->getObjectList(OBJ_TABLE)->begin(), - db_model->getObjectList(OBJ_TABLE)->end()); + objects.insert(objects.end(), db_model->getObjectList(ObjectType::Table)->begin(), + db_model->getObjectList(ObjectType::Table)->end()); //Store the relationship on the auxiliary vector but only many-to-many are considered - objects.insert(objects.end(), db_model->getObjectList(OBJ_RELATIONSHIP)->begin(), - db_model->getObjectList(OBJ_RELATIONSHIP)->end()); + objects.insert(objects.end(), db_model->getObjectList(ObjectType::Relationship)->begin(), + db_model->getObjectList(ObjectType::Relationship)->end()); alter_cmds_status.clear(); @@ -630,12 +634,12 @@ void ModelExportHelper::restoreGenAtlerCmdsStatus(void) void ModelExportHelper::undoDBMSExport(DatabaseModel *db_model, Connection &conn, bool use_tmp_names) { QString drop_cmd=QString("DROP %1 %2;"); - ObjectType types[]={OBJ_ROLE, OBJ_TABLESPACE}; + ObjectType types[]={ObjectType::Role, ObjectType::Tablespace}; int type_id; BaseObject *object=nullptr; //In case of error during the export all created object are removed - if(db_created || created_objs[OBJ_ROLE] >= 0 || created_objs[OBJ_TABLESPACE] >= 0) + if(db_created || created_objs[ObjectType::Role] >= 0 || created_objs[ObjectType::Tablespace] >= 0) { emit s_progressUpdated(99, trUtf8("Destroying objects created on the server.")); @@ -681,20 +685,20 @@ void ModelExportHelper::generateTempObjectNames(DatabaseModel *db_model) QTextStream stream(&tmp_name); QDateTime dt=QDateTime::currentDateTime(); QCryptographicHash hash(QCryptographicHash::Md5); - map obj_suffixes={ { OBJ_DATABASE, QString("db_") }, - { OBJ_ROLE, QString("rl_")}, - { OBJ_TABLESPACE, QString("tb_")} }; + map obj_suffixes={ { ObjectType::Database, QString("db_") }, + { ObjectType::Role, QString("rl_")}, + { ObjectType::Tablespace, QString("tb_")} }; orig_obj_names.clear(); orig_obj_names[db_model]=db_model->getName(); - for(auto &role : *db_model->getObjectList(OBJ_ROLE)) + for(auto &role : *db_model->getObjectList(ObjectType::Role)) { if(!role->isSystemObject()) orig_obj_names[role]=role->getName(); } - for(auto &tabspc : *db_model->getObjectList(OBJ_TABLESPACE)) + for(auto &tabspc : *db_model->getObjectList(ObjectType::Tablespace)) { if(!tabspc->isSystemObject()) orig_obj_names[tabspc]=tabspc->getName(); @@ -763,7 +767,7 @@ void ModelExportHelper::exportBufferToDBMS(const QString &buffer, Connection &co alter_tab=QString("ALTER TABLE"); vector db_sql_cmds; QTextStream ts; - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; bool ddl_tk_found=false, is_create=false, is_drop=false; unsigned aux_prog=0, curr_size=0, buf_size=sql_buf.size(), factor=(db_name.isEmpty() ? 70 : 90); @@ -776,14 +780,14 @@ void ModelExportHelper::exportBufferToDBMS(const QString &buffer, Connection &co drop_tab_obj_reg(QString("^((\\-\\-)+( )*)+(%1)(.)+(DROP)(.)+").arg(alter_tab)), reg_aux; - vector obj_types={ OBJ_ROLE, OBJ_FUNCTION, OBJ_TRIGGER, OBJ_INDEX, OBJ_POLICY, - OBJ_RULE, OBJ_TABLE, OBJ_VIEW, OBJ_DOMAIN, - OBJ_SCHEMA, OBJ_AGGREGATE, OBJ_OPFAMILY, - OBJ_OPCLASS, OBJ_OPERATOR, OBJ_SEQUENCE, - OBJ_CONVERSION, OBJ_CAST, OBJ_LANGUAGE, - OBJ_COLLATION, OBJ_EXTENSION, OBJ_TYPE, - OBJ_EVENT_TRIGGER, OBJ_DATABASE }; - + vector obj_types={ ObjectType::Role, ObjectType::Function, ObjectType::Trigger, ObjectType::Index, + ObjectType::Policy, ObjectType::Rule, ObjectType::Table, ObjectType::View, ObjectType::Domain, + ObjectType::Schema, ObjectType::Aggregate, ObjectType::OpFamily, + ObjectType::OpClass, ObjectType::Operator, ObjectType::Sequence, + ObjectType::Conversion, ObjectType::Cast, ObjectType::Language, + ObjectType::Collation, ObjectType::Extension, ObjectType::Type, + ObjectType::EventTrigger, ObjectType::ForeignDataWrapper, ObjectType::ForeignServer, + ObjectType::UserMapping, ObjectType::Database, ObjectType::BaseObject }; /* Extract each SQL command from the buffer and execute them separately. This is done to permit the user, in case of error, identify what object is wrongly configured. */ @@ -791,10 +795,10 @@ void ModelExportHelper::exportBufferToDBMS(const QString &buffer, Connection &co if(!conn.isStablished()) { - orig_conn_db_name = conn.getConnectionParam(Connection::PARAM_DB_NAME); + orig_conn_db_name = conn.getConnectionParam(Connection::ParamDbName); if(!db_name.isEmpty()) - conn.setConnectionParam(Connection::PARAM_DB_NAME, db_name); + conn.setConnectionParam(Connection::ParamDbName, db_name); conn.connect(); } @@ -806,7 +810,7 @@ void ModelExportHelper::exportBufferToDBMS(const QString &buffer, Connection &co //Cleanup single line comments lin=ts.readLine(); curr_size+=lin.size(); - aux_prog=progress + ((curr_size/static_cast(buf_size)) * factor); + aux_prog=progress + ((curr_size/static_cast(buf_size)) * factor); /* If the simulation mode is off and the drop objects option is checked, check if the current line matches one of the accepted drop commands @@ -826,7 +830,7 @@ void ModelExportHelper::exportBufferToDBMS(const QString &buffer, Connection &co } else { - ddl_tk_found=(lin.indexOf(ParsersAttributes::DDL_END_TOKEN) >= 0); + ddl_tk_found=(lin.indexOf(Attributes::DdlEndToken) >= 0); lin.remove(QRegExp(QString("^(--)+(.)+$"))); //If the line isn't empty after cleanup it will be included on sql command @@ -845,7 +849,7 @@ void ModelExportHelper::exportBufferToDBMS(const QString &buffer, Connection &co { aux_cmd.remove('"'); aux_cmd.remove(QString("IF EXISTS ")); - obj_type=(aux_cmd.contains(QString("COLUMN")) ? OBJ_COLUMN : OBJ_CONSTRAINT); + obj_type=(aux_cmd.contains(QString("COLUMN")) ? ObjectType::Column : ObjectType::Constraint); reg_aux=QRegExp(QString("(COLUMN|CONSTRAINT)( )+")); //Extracting the table name @@ -890,24 +894,23 @@ void ModelExportHelper::exportBufferToDBMS(const QString &buffer, Connection &co obj_type=obj_tp; - //Appeding special tokens when the object is an index or view if(lin.startsWith(QString("CREATE")) || lin.startsWith(QString("ALTER"))) { - if(obj_tp==OBJ_INDEX) + if(obj_tp==ObjectType::Index) { lin.remove(QString("UNIQUE")); lin.remove(QString("CONCURRENTLY")); } - else if(obj_tp==OBJ_VIEW) + else if(obj_tp==ObjectType::View) { lin.remove(QString("MATERIALIZED")); lin.remove(QString("RECURSIVE")); } - else if(obj_tp==OBJ_TABLE) + else if(obj_tp==ObjectType::Table) { lin.remove(QString("UNLOGGED")); } - else if(obj_tp==OBJ_FUNCTION) + else if(obj_tp==ObjectType::Function) { lin.remove(QString("OR REPLACE")); } @@ -933,32 +936,53 @@ void ModelExportHelper::exportBufferToDBMS(const QString &buffer, Connection &co lin=lin.mid(reg_aux.matchedLength(), sql_cmd.indexOf('\n')).simplified(); lin.remove('"'); - if(obj_tp!=OBJ_CAST) + if(obj_tp != ObjectType::BaseObject) { - int spc_idx=lin.indexOf(' '); - obj_name=lin.mid(0, (spc_idx >= 0 ? spc_idx + 1 : lin.size())); - - if(obj_tp!=OBJ_FUNCTION) + if(obj_tp!=ObjectType::Cast && obj_tp != ObjectType::UserMapping) + { + int spc_idx=lin.indexOf(' '); + obj_name=lin.mid(0, (spc_idx >= 0 ? spc_idx + 1 : lin.size())); + + if(obj_tp!=ObjectType::Function) + { + obj_name=obj_name.remove('(').simplified(); + obj_name=obj_name.remove(')').simplified(); + } + } + else if(obj_tp == ObjectType::UserMapping) + { + obj_name.prepend(lin.remove(QString("FOR")).trimmed() + QChar('@')); + } + else { - obj_name=obj_name.remove('(').simplified(); - obj_name=obj_name.remove(')').simplified(); + obj_name=QString("cast") + lin.replace(QString(" AS "),QString(",")); } + + //Stores the object type name + obj_tp_name=BaseObject::getTypeName(obj_tp); + obj_name.remove(';'); + + if(is_create) + msg=trUtf8("Creating object `%1' (%2)").arg(obj_name).arg(obj_tp_name); + else if(is_drop) + msg=trUtf8("Dropping object `%1' (%2)").arg(obj_name).arg(obj_tp_name); + else + msg=trUtf8("Changing object `%1' (%2)").arg(obj_name).arg(obj_tp_name); } + // If the type of the object being create can't be identified else { - obj_name=QString("cast") + lin.replace(QString(" AS "),QString(",")); - } + QString aux_cmd_type; - //Stores the object type name - obj_tp_name=BaseObject::getTypeName(obj_tp); - obj_name.remove(';'); + if(is_create) + aux_cmd_type = QString("CREATE"); + else if(is_drop) + aux_cmd_type = QString("DROP"); + else + aux_cmd_type = QString("ALTER"); - if(is_create) - msg=trUtf8("Creating object `%1' (%2)").arg(obj_name).arg(obj_tp_name); - else if(is_drop) - msg=trUtf8("Dropping object `%1' (%2)").arg(obj_name).arg(obj_tp_name); - else - msg=trUtf8("Changing object `%1' (%2)").arg(obj_name).arg(obj_tp_name); + msg=trUtf8("Running auxiliary `%1' command...").arg(aux_cmd_type); + } break; } @@ -971,13 +995,13 @@ void ModelExportHelper::exportBufferToDBMS(const QString &buffer, Connection &co else if(!sql_cmd.trimmed().isEmpty()) { //General commands like grant, revoke or set aren't explicitly shown - emit s_progressUpdated(aux_prog, trUtf8("Running auxiliary command."), BASE_OBJECT, sql_cmd); + emit s_progressUpdated(aux_prog, trUtf8("Running auxiliary command."), ObjectType::BaseObject, sql_cmd); } //Executes the extracted SQL command if(!sql_cmd.isEmpty()) { - if(obj_type!=OBJ_DATABASE) + if(obj_type != ObjectType::Database) conn.executeDDLCommand(sql_cmd); else db_sql_cmds.push_back(sql_cmd); @@ -991,7 +1015,7 @@ void ModelExportHelper::exportBufferToDBMS(const QString &buffer, Connection &co { conn.close(); aux_conn=conn; - aux_conn.setConnectionParam(Connection::PARAM_DB_NAME, orig_conn_db_name); + aux_conn.setConnectionParam(Connection::ParamDbName, orig_conn_db_name); aux_conn.connect(); for(QString cmd : db_sql_cmds) aux_conn.executeDDLCommand(cmd); diff --git a/libpgmodeler_ui/src/modelexporthelper.h b/libpgmodeler_ui/src/modelexporthelper.h index 2ad9382f0c..1031a6fade 100644 --- a/libpgmodeler_ui/src/modelexporthelper.h +++ b/libpgmodeler_ui/src/modelexporthelper.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -189,7 +189,7 @@ class ModelExportHelper: public QObject { signals: //! \brief This singal is emitted whenever the export progress changes - void s_progressUpdated(int progress, QString msg, ObjectType obj_type=BASE_OBJECT, QString cmd=QString(), bool is_code_gen=false); + void s_progressUpdated(int progress, QString msg, ObjectType obj_type=ObjectType::BaseObject, QString cmd=QString(), bool is_code_gen=false); //! \brief This signal is emited when the export has finished void s_exportFinished(void); diff --git a/libpgmodeler_ui/src/modelfixform.cpp b/libpgmodeler_ui/src/modelfixform.cpp index 227188a84b..0cf13e1308 100644 --- a/libpgmodeler_ui/src/modelfixform.cpp +++ b/libpgmodeler_ui/src/modelfixform.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -21,7 +21,7 @@ #include #include "pgmodeleruins.h" -const QString ModelFixForm::PGMODELER_CLI=QString("pgmodeler-cli"); +const QString ModelFixForm::PgModelerCli=QString("pgmodeler-cli"); ModelFixForm::ModelFixForm(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f) { @@ -30,17 +30,17 @@ ModelFixForm::ModelFixForm(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, setupUi(this); hideEvent(nullptr); - PgModelerUiNS::configureWidgetFont(invalid_cli_lbl, PgModelerUiNS::MEDIUM_FONT_FACTOR); - PgModelerUiNS::configureWidgetFont(message_lbl, PgModelerUiNS::MEDIUM_FONT_FACTOR); - PgModelerUiNS::configureWidgetFont(not_found_lbl, PgModelerUiNS::MEDIUM_FONT_FACTOR); + PgModelerUiNs::configureWidgetFont(invalid_cli_lbl, PgModelerUiNs::MediumFontFactor); + PgModelerUiNs::configureWidgetFont(message_lbl, PgModelerUiNs::MediumFontFactor); + PgModelerUiNs::configureWidgetFont(not_found_lbl, PgModelerUiNs::MediumFontFactor); //Configuring font style for output widget - if(!confs[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_FONT].isEmpty()) + if(!confs[Attributes::Configuration][Attributes::CodeFont].isEmpty()) { - double size=confs[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_FONT_SIZE].toDouble(); - if(size < 5.0f) size=5.0f; + double size=confs[Attributes::Configuration][Attributes::CodeFontSize].toDouble(); + if(size < 5.0) size=5.0; - output_txt->setFontFamily(confs[ParsersAttributes::CONFIGURATION][ParsersAttributes::CODE_FONT]); + output_txt->setFontFamily(confs[Attributes::Configuration][Attributes::CodeFont]); output_txt->setFontPointSize(size); } @@ -72,20 +72,20 @@ void ModelFixForm::hideEvent(QHideEvent *) int ModelFixForm::exec(void) { - QFileInfo fi(GlobalAttributes::PGMODELER_CLI_PATH); + QFileInfo fi(GlobalAttributes::PgModelerCLIPath); //Show an warning if the cli command doesn't exists if(!fi.exists()) { not_found_lbl->setText(trUtf8("Could not locate %1 tool on %2. The fix process can't continue! Please check pgModeler installation or try to manually specify the command below.") - .arg(PGMODELER_CLI).arg(fi.absoluteDir().absolutePath())); + .arg(PgModelerCli).arg(fi.absoluteDir().absolutePath())); message_frm->setVisible(true); pgmodeler_cli_lbl->setVisible(true); pgmodeler_cli_edt->setVisible(true); sel_cli_exe_tb->setVisible(true); } else - pgmodeler_cli_edt->setText(GlobalAttributes::PGMODELER_CLI_PATH); + pgmodeler_cli_edt->setText(GlobalAttributes::PgModelerCLIPath); return(QDialog::exec()); } @@ -95,7 +95,7 @@ void ModelFixForm::enableFix(void) if(!pgmodeler_cli_edt->text().isEmpty()) { QFileInfo fi(pgmodeler_cli_edt->text()); - bool visible=!fi.exists() || fi.baseName()!=PGMODELER_CLI; + bool visible=!fi.exists() || fi.baseName()!=PgModelerCli; invalid_cli_lbl->setVisible(visible); message_frm->setVisible(visible); @@ -139,7 +139,7 @@ void ModelFixForm::selectFile(void) if(sender_obj==sel_cli_exe_tb) { - QString cli_cmd=PGMODELER_CLI; + QString cli_cmd=PgModelerCli; txt=pgmodeler_cli_edt; #ifdef Q_OS_WIN diff --git a/libpgmodeler_ui/src/modelfixform.h b/libpgmodeler_ui/src/modelfixform.h index fe008ac2c6..1a5842835a 100644 --- a/libpgmodeler_ui/src/modelfixform.h +++ b/libpgmodeler_ui/src/modelfixform.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -33,7 +33,7 @@ class ModelFixForm: public QDialog, public Ui::ModelFixForm { private: Q_OBJECT - const static QString PGMODELER_CLI; + static const QString PgModelerCli; //! \brief Process used to execute pgmodeler-cli QProcess pgmodeler_cli_proc; @@ -41,7 +41,7 @@ class ModelFixForm: public QDialog, public Ui::ModelFixForm { void hideEvent(QHideEvent *); public: - ModelFixForm(QWidget * parent = 0, Qt::WindowFlags f = 0); + ModelFixForm(QWidget * parent = nullptr, Qt::WindowFlags f = Qt::Widget); public slots: int exec(void); diff --git a/libpgmodeler_ui/src/modelnavigationwidget.cpp b/libpgmodeler_ui/src/modelnavigationwidget.cpp index 7dd94f1403..49edffd2b2 100644 --- a/libpgmodeler_ui/src/modelnavigationwidget.cpp +++ b/libpgmodeler_ui/src/modelnavigationwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libpgmodeler_ui/src/modelnavigationwidget.h b/libpgmodeler_ui/src/modelnavigationwidget.h index 900573849b..37950de4cf 100644 --- a/libpgmodeler_ui/src/modelnavigationwidget.h +++ b/libpgmodeler_ui/src/modelnavigationwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -38,7 +38,7 @@ class ModelNavigationWidget: public QWidget, public Ui::ModelNavigationWidget { void enableNavigationButtons(void); public: - ModelNavigationWidget(QWidget * parent = 0); + ModelNavigationWidget(QWidget * parent = nullptr); //! \brief Returns the combo's current index int getCurrentIndex(void); diff --git a/libpgmodeler_ui/src/modelobjectswidget.cpp b/libpgmodeler_ui/src/modelobjectswidget.cpp index b7aa3839f4..10a602916b 100644 --- a/libpgmodeler_ui/src/modelobjectswidget.cpp +++ b/libpgmodeler_ui/src/modelobjectswidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -120,8 +120,8 @@ void ModelObjectsWidget::editObject(void) { //If the user double-clicked the item "Permission (n)" on tree view if(sender()==objectstree_tw && objectstree_tw->currentItem() && - objectstree_tw->currentItem()->data(1, Qt::UserRole).toUInt()==OBJ_PERMISSION) - model_wgt->showObjectForm(OBJ_PERMISSION, reinterpret_cast(objectstree_tw->currentItem()->data(0, Qt::UserRole).value())); + objectstree_tw->currentItem()->data(1, Qt::UserRole).toUInt() == enum_cast(ObjectType::Permission)) + model_wgt->showObjectForm(ObjectType::Permission, reinterpret_cast(objectstree_tw->currentItem()->data(0, Qt::UserRole).value())); //If the user double-clicked a permission on list view else if(sender()==objectslist_tbw && objectslist_tbw->currentRow() >= 0) { @@ -129,7 +129,9 @@ void ModelObjectsWidget::editObject(void) Permission *perm=dynamic_cast(obj); if(perm) - model_wgt->showObjectForm(OBJ_PERMISSION,perm->getObject()); + model_wgt->showObjectForm(ObjectType::Permission, perm->getObject()); + else + model_wgt->editObject(); } else model_wgt->editObject(); @@ -138,7 +140,7 @@ void ModelObjectsWidget::editObject(void) void ModelObjectsWidget::selectObject(void) { - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; ModelWidget *model_wgt=nullptr; if(!simplified_view && this->model_wgt) @@ -159,17 +161,17 @@ void ModelObjectsWidget::selectObject(void) //If user select a group item popups a "New [OBJECT]" menu if((!simplified_view || (simplified_view && enable_obj_creation)) && !selected_object && QApplication::mouseButtons()==Qt::RightButton && - obj_type!=OBJ_COLUMN && obj_type!=OBJ_CONSTRAINT && obj_type!=OBJ_RULE && - obj_type!=OBJ_INDEX && obj_type!=OBJ_TRIGGER && obj_type!=OBJ_PERMISSION) + obj_type!=ObjectType::Column && obj_type!=ObjectType::Constraint && obj_type!=ObjectType::Rule && + obj_type!=ObjectType::Index && obj_type!=ObjectType::Trigger && obj_type!=ObjectType::Permission) { - QAction act(QPixmap(PgModelerUiNS::getIconPath(obj_type)), + QAction act(QPixmap(PgModelerUiNs::getIconPath(obj_type)), trUtf8("New") + QString(" ") + BaseObject::getTypeName(obj_type), nullptr); QMenu popup; //If not a relationship, connect the action to the addNewObject method of the model wiget - if(obj_type!=OBJ_RELATIONSHIP) + if(obj_type!=ObjectType::Relationship) { - act.setData(QVariant(obj_type)); + act.setData(QVariant(enum_cast(obj_type))); connect(&act, SIGNAL(triggered()), model_wgt, SLOT(addNewObject())); } //Case is a relationship, insert the relationship menu of the model wiget into the action @@ -196,7 +198,7 @@ void ModelObjectsWidget::selectObject(void) } } - if(obj_type!=OBJ_PERMISSION && selected_object && !simplified_view) + if(obj_type!=ObjectType::Permission && selected_object && !simplified_view) { model_wgt->scene->clearSelection(); model_wgt->configureObjectMenu(selected_object); @@ -221,13 +223,13 @@ QTreeWidgetItem *ModelObjectsWidget::createItemForObject(BaseObject *object, QTr QString obj_name; if(!object) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject ,__PRETTY_FUNCTION__,__FILE__,__LINE__); obj_type=object->getObjectType(); tab_obj=dynamic_cast(object); item=new QTreeWidgetItem(root); - if(obj_type==OBJ_FUNCTION) + if(obj_type==ObjectType::Function) { Function *func=dynamic_cast(object); func->createSignature(false); @@ -235,13 +237,13 @@ QTreeWidgetItem *ModelObjectsWidget::createItemForObject(BaseObject *object, QTr obj_name=func->getSignature(); func->createSignature(true); } - else if(obj_type==OBJ_OPERATOR) + else if(obj_type==ObjectType::Operator) { Operator *oper=dynamic_cast(object); item->setText(0, oper->getSignature(false)); obj_name=oper->getSignature(false); } - else if(obj_type==OBJ_OPCLASS || obj_type == OBJ_OPFAMILY) + else if(obj_type==ObjectType::OpClass || obj_type == ObjectType::OpFamily) { obj_name=object->getSignature(false); obj_name.replace(QRegExp("( )+(USING)( )+"), QString(" [")); @@ -267,74 +269,74 @@ QTreeWidgetItem *ModelObjectsWidget::createItemForObject(BaseObject *object, QTr if(tab_obj && tab_obj->isAddedByRelationship()) { font.setItalic(true); - item->setForeground(0,BaseObjectView::getFontStyle(ParsersAttributes::INH_COLUMN).foreground()); + item->setForeground(0,BaseObjectView::getFontStyle(Attributes::InhColumn).foreground()); } else if(object->isProtected() || object->isSystemObject()) { font.setItalic(true); - item->setForeground(0,BaseObjectView::getFontStyle(ParsersAttributes::PROT_COLUMN).foreground()); + item->setForeground(0,BaseObjectView::getFontStyle(Attributes::ProtColumn).foreground()); } item->setFont(0,font); - if(obj_type==BASE_RELATIONSHIP || obj_type==OBJ_RELATIONSHIP) + if(obj_type==ObjectType::BaseRelationship || obj_type==ObjectType::Relationship) { rel_type=dynamic_cast(object)->getRelationshipType(); - if(obj_type==BASE_RELATIONSHIP) + if(obj_type==ObjectType::BaseRelationship) { - if(rel_type==BaseRelationship::RELATIONSHIP_FK) + if(rel_type==BaseRelationship::RelationshipFk) str_aux=QString("fk"); else str_aux=QString("tv"); } - else if(rel_type==BaseRelationship::RELATIONSHIP_11) + else if(rel_type==BaseRelationship::Relationship11) str_aux=QString("11"); - else if(rel_type==BaseRelationship::RELATIONSHIP_1N) + else if(rel_type==BaseRelationship::Relationship1n) str_aux=QString("1n"); - else if(rel_type==BaseRelationship::RELATIONSHIP_NN) + else if(rel_type==BaseRelationship::RelationshipNn) str_aux=QString("nn"); - else if(rel_type==BaseRelationship::RELATIONSHIP_DEP) + else if(rel_type==BaseRelationship::RelationshipDep) str_aux=QString("dep"); - else if(rel_type==BaseRelationship::RELATIONSHIP_GEN) + else if(rel_type==BaseRelationship::RelationshipGen) str_aux=QString("gen"); } - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) { constr_type=dynamic_cast(object)->getConstraintType(); - if(constr_type==ConstraintType::primary_key) - str_aux=QString("_%1").arg(TableObjectView::TXT_PRIMARY_KEY); - else if(constr_type==ConstraintType::foreign_key) - str_aux=QString("_%1").arg(TableObjectView::TXT_FOREIGN_KEY); - else if(constr_type==ConstraintType::check) - str_aux=QString("_%1").arg(TableObjectView::TXT_CHECK); - else if(constr_type==ConstraintType::unique) - str_aux=QString("_%1").arg(TableObjectView::TXT_UNIQUE); - else if(constr_type==ConstraintType::exclude) - str_aux=QString("_%1").arg(TableObjectView::TXT_EXCLUDE); + if(constr_type==ConstraintType::PrimaryKey) + str_aux=QString("_%1").arg(TableObjectView::TextPrimaryKey); + else if(constr_type==ConstraintType::ForeignKey) + str_aux=QString("_%1").arg(TableObjectView::TextForeignKey); + else if(constr_type==ConstraintType::Check) + str_aux=QString("_%1").arg(TableObjectView::TextCheck); + else if(constr_type==ConstraintType::Unique) + str_aux=QString("_%1").arg(TableObjectView::TextUnique); + else if(constr_type==ConstraintType::Exclude) + str_aux=QString("_%1").arg(TableObjectView::TextExclude); } - item->setIcon(0, QPixmap(PgModelerUiNS::getIconPath(BaseObject::getSchemaName(obj_type) + str_aux))); + item->setIcon(0, QPixmap(PgModelerUiNs::getIconPath(BaseObject::getSchemaName(obj_type) + str_aux))); return(item); } void ModelObjectsWidget::setObjectVisible(ObjectType obj_type, bool visible) { - if(obj_type!=BASE_OBJECT && obj_type!=BASE_TABLE) + if(obj_type!=ObjectType::BaseObject && obj_type!=ObjectType::BaseTable) visible_objs_map[obj_type]=visible; if(visible && simplified_view) { - if(obj_type!=OBJ_DATABASE) - visible_objs_map[OBJ_DATABASE]=true; + if(obj_type!=ObjectType::Database) + visible_objs_map[ObjectType::Database]=true; if(TableObject::isTableObject(obj_type)) - visible_objs_map[OBJ_TABLE]=visible_objs_map[OBJ_SCHEMA]=true; + visible_objs_map[ObjectType::Table]=visible_objs_map[ObjectType::Schema]=true; if(BaseObject::acceptsSchema(obj_type)) - visible_objs_map[OBJ_SCHEMA]=true; + visible_objs_map[ObjectType::Schema]=true; } } @@ -429,11 +431,11 @@ void ModelObjectsWidget::filterObjects(void) void ModelObjectsWidget::updateObjectsView(void) { - updateDatabaseTree(); - updateObjectsList(); + updateDatabaseTree(); + updateObjectsList(); - if(!filter_edt->text().isEmpty()) - filterObjects(); + if(!filter_edt->text().isEmpty()) + filterObjects(); } void ModelObjectsWidget::updateObjectsList(void) @@ -450,8 +452,7 @@ void ModelObjectsWidget::updateObjectsList(void) visible_types.push_back(tp.first); } - objects=db_model->findObjects(QString(), visible_types,true, false, false, false); - + objects=db_model->findObjects(QString(), visible_types, false, false, false); } ObjectFinderWidget::updateObjectTable(objectslist_tbw, objects); @@ -459,28 +460,28 @@ void ModelObjectsWidget::updateObjectsList(void) void ModelObjectsWidget::updateSchemaTree(QTreeWidgetItem *root) { - if(db_model && visible_objs_map[OBJ_SCHEMA]) + if(db_model && visible_objs_map[ObjectType::Schema]) { BaseObject *schema=nullptr; vector obj_list; QFont font; QTreeWidgetItem *item=nullptr, *item1=nullptr, *item2=nullptr, *item3=nullptr; - vector types = BaseObject::getChildObjectTypes(OBJ_SCHEMA); - int count, count2, i; - QPixmap group_icon=QPixmap(PgModelerUiNS::getIconPath(QString(BaseObject::getSchemaName(OBJ_SCHEMA)) + QString("_grp"))); + vector types = BaseObject::getChildObjectTypes(ObjectType::Schema); + int count = 0, count2 = 0, i = 0; + QPixmap group_icon=QPixmap(PgModelerUiNs::getIconPath(QString(BaseObject::getSchemaName(ObjectType::Schema)) + QString("_grp"))); - //Removing the OBJ_TABLE and OBJ_VIEW types since they are handled separetedly - types.erase(std::find(types.begin(), types.end(), OBJ_TABLE)); - types.erase(std::find(types.begin(), types.end(), OBJ_VIEW)); + //Removing the ObjectType::Table and ObjectType::View types since they are handled separetedly + types.erase(std::find(types.begin(), types.end(), ObjectType::Table)); + types.erase(std::find(types.begin(), types.end(), ObjectType::View)); //Get the current schema count on database - count=(db_model->getObjectCount(OBJ_SCHEMA)); + count=(db_model->getObjectCount(ObjectType::Schema)); item=new QTreeWidgetItem(root); item->setIcon(0,group_icon); - item->setData(1, Qt::UserRole, QVariant::fromValue(OBJ_SCHEMA)); + item->setData(1, Qt::UserRole, QVariant(enum_cast(ObjectType::Schema))); //Create the schema group item - item->setText(0, QString("%1 (%2)").arg(BaseObject::getTypeName(OBJ_SCHEMA)).arg(count)); + item->setText(0, QString("%1 (%2)").arg(BaseObject::getTypeName(ObjectType::Schema)).arg(count)); font=item->font(0); font.setItalic(true); item->setFont(0, font); @@ -498,7 +499,7 @@ void ModelObjectsWidget::updateSchemaTree(QTreeWidgetItem *root) } else { - schema=db_model->getObject(i, OBJ_SCHEMA); + schema=db_model->getObject(i, ObjectType::Schema); item2=createItemForObject(schema, item); } @@ -514,14 +515,14 @@ void ModelObjectsWidget::updateSchemaTree(QTreeWidgetItem *root) if(visible_objs_map[type]) { item3=new QTreeWidgetItem(item2); - item3->setIcon(0,QPixmap(PgModelerUiNS::getIconPath(BaseObject::getSchemaName(type) + QString("_grp")))); + item3->setIcon(0,QPixmap(PgModelerUiNs::getIconPath(BaseObject::getSchemaName(type) + QString("_grp")))); //Get the objects that belongs to the current schema obj_list=db_model->getObjects(type, schema); count2=obj_list.size(); item3->setText(0, QString("%1 (%2)").arg(BaseObject::getTypeName(type)).arg(count2)); - item3->setData(1, Qt::UserRole, QVariant::fromValue(type)); + item3->setData(1, Qt::UserRole, QVariant(enum_cast(type))); font=item3->font(0); font.setItalic(true); @@ -535,33 +536,33 @@ void ModelObjectsWidget::updateSchemaTree(QTreeWidgetItem *root) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } } void ModelObjectsWidget::updateTableTree(QTreeWidgetItem *root, BaseObject *schema) { - if(db_model && visible_objs_map[OBJ_TABLE]) + if(db_model && visible_objs_map[ObjectType::Table]) { vector obj_list; Table *table=nullptr; QTreeWidgetItem *item=nullptr, *item1=nullptr, *item2=nullptr; QFont font; - vector types = BaseObject::getChildObjectTypes(OBJ_TABLE); - QPixmap group_icon=QPixmap(PgModelerUiNS::getIconPath(BaseObject::getSchemaName(OBJ_TABLE) + QString("_grp"))); + vector types = BaseObject::getChildObjectTypes(ObjectType::Table); + QPixmap group_icon=QPixmap(PgModelerUiNs::getIconPath(BaseObject::getSchemaName(ObjectType::Table) + QString("_grp"))); try { //Get all tables that belongs to the specified schema - obj_list=db_model->getObjects(OBJ_TABLE, schema); + obj_list=db_model->getObjects(ObjectType::Table, schema); //Create a table group item item=new QTreeWidgetItem(root); item->setIcon(0,group_icon); - item->setText(0,BaseObject::getTypeName(OBJ_TABLE) + + item->setText(0,BaseObject::getTypeName(ObjectType::Table) + QString(" (%1)").arg(obj_list.size())); - item->setData(1, Qt::UserRole, QVariant::fromValue(OBJ_TABLE)); + item->setData(1, Qt::UserRole, QVariant(enum_cast(ObjectType::Table))); font=item->font(0); font.setItalic(true); @@ -578,7 +579,7 @@ void ModelObjectsWidget::updateTableTree(QTreeWidgetItem *root, BaseObject *sche if(visible_objs_map[type]) { item2=new QTreeWidgetItem(item1); - item2->setIcon(0,QPixmap(PgModelerUiNS::getIconPath(BaseObject::getSchemaName(type) + QString("_grp")))); + item2->setIcon(0,QPixmap(PgModelerUiNs::getIconPath(BaseObject::getSchemaName(type) + QString("_grp")))); font=item2->font(0); font.setItalic(true); item2->setFont(0, font); @@ -593,64 +594,63 @@ void ModelObjectsWidget::updateTableTree(QTreeWidgetItem *root, BaseObject *sche } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } } void ModelObjectsWidget::updateViewTree(QTreeWidgetItem *root, BaseObject *schema) { - if(db_model && visible_objs_map[OBJ_VIEW]) + if(db_model && visible_objs_map[ObjectType::View]) { BaseObject *object=nullptr; vector obj_list; View *view=nullptr; QTreeWidgetItem *item=nullptr, *item1=nullptr, *item2=nullptr; QFont font; - ObjectType types[]={ OBJ_RULE, OBJ_TRIGGER, OBJ_INDEX }; - int count, count1, type_cnt=sizeof(types)/sizeof(ObjectType), i, i1, i2; - QPixmap group_icon=QPixmap(PgModelerUiNS::getIconPath(QString(BaseObject::getSchemaName(OBJ_VIEW)) + QString("_grp"))); + vector types = BaseObject::getChildObjectTypes(ObjectType::View); + int count = 0, count1 = 0, i = 0, i2 = 0; + QPixmap group_icon=QPixmap(PgModelerUiNs::getIconPath(QString(BaseObject::getSchemaName(ObjectType::View)) + QString("_grp"))); try { //Get all views that belongs to the specified schema - obj_list=db_model->getObjects(OBJ_VIEW, schema); + obj_list=db_model->getObjects(ObjectType::View, schema); //Create a table group item item=new QTreeWidgetItem(root); item->setIcon(0,group_icon); - item->setText(0,BaseObject::getTypeName(OBJ_VIEW) + - QString(" (%1)").arg(obj_list.size())); - item->setData(1, Qt::UserRole, QVariant::fromValue(OBJ_VIEW)); + item->setText(0,BaseObject::getTypeName(ObjectType::View) + QString(" (%1)").arg(obj_list.size())); + item->setData(1, Qt::UserRole, QVariant(enum_cast(ObjectType::View))); font=item->font(0); font.setItalic(true); item->setFont(0, font); count=obj_list.size(); + for(i=0; i < count; i++) { view=dynamic_cast(obj_list[i]); item1=createItemForObject(view, item); //Creating the group for the child objects (rules, triggers) - for(i1=0; i1 < type_cnt; i1++) + for(auto &type : types) { - if(visible_objs_map[types[i1]]) + if(visible_objs_map[type]) { item2=new QTreeWidgetItem(item1); - item2->setIcon(0,QPixmap(PgModelerUiNS::getIconPath(BaseObject::getSchemaName(types[i1]) + QString("_grp")))); + item2->setIcon(0,QPixmap(PgModelerUiNs::getIconPath(BaseObject::getSchemaName(type) + QString("_grp")))); font=item2->font(0); font.setItalic(true); item2->setFont(0, font); - count1=view->getObjectCount(types[i1]); - item2->setText(0,BaseObject::getTypeName(types[i1]) + - QString(" (%1)").arg(count1)); + count1 = view->getObjectCount(type); + item2->setText(0,BaseObject::getTypeName(type) + QString(" (%1)").arg(count1)); for(i2=0; i2 < count1; i2++) { - object=view->getObject(i2,types[i1]); + object=view->getObject(i2, type); createItemForObject(object, item2); } } @@ -659,7 +659,7 @@ void ModelObjectsWidget::updateViewTree(QTreeWidgetItem *root, BaseObject *schem } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } } @@ -668,29 +668,29 @@ void ModelObjectsWidget::updatePermissionTree(QTreeWidgetItem *root, BaseObject { try { - if(db_model && visible_objs_map[OBJ_PERMISSION] && - Permission::objectAcceptsPermission(object->getObjectType())) + if(db_model && visible_objs_map[ObjectType::Permission] && + Permission::acceptsPermission(object->getObjectType())) { vector perms; QTreeWidgetItem *item=new QTreeWidgetItem(root); QFont font=item->font(0); db_model->getPermissions(object, perms); - item->setIcon(0,QPixmap(PgModelerUiNS::getIconPath("permission_grp"))); + item->setIcon(0,QPixmap(PgModelerUiNs::getIconPath("permission_grp"))); font.setItalic(true); item->setFont(0, font); item->setText(0, QString("%1 (%2)") - .arg(BaseObject::getTypeName(OBJ_PERMISSION)) + .arg(BaseObject::getTypeName(ObjectType::Permission)) .arg(perms.size())); item->setData(0, Qt::UserRole, generateItemValue(object)); - item->setData(1, Qt::UserRole, static_cast(OBJ_PERMISSION)); + item->setData(1, Qt::UserRole, static_cast(ObjectType::Permission)); } } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -705,49 +705,52 @@ void ModelObjectsWidget::updateDatabaseTree(void) QTreeWidgetItem *root=nullptr,*item1=nullptr, *item2=nullptr; QFont font; vector ref_list, tree_state, obj_list; - ObjectType types[]={ OBJ_ROLE, OBJ_TABLESPACE, - OBJ_LANGUAGE, OBJ_CAST, OBJ_TEXTBOX, - OBJ_RELATIONSHIP, OBJ_EVENT_TRIGGER, - OBJ_TAG, OBJ_GENERIC_SQL, OBJ_EXTENSION }; - unsigned count, i, i1, type_cnt=sizeof(types)/sizeof(ObjectType); + vector types = BaseObject::getChildObjectTypes(ObjectType::Database); + unsigned count = 0, i = 0, i1 = 0; + + types.push_back(ObjectType::Tag); + types.push_back(ObjectType::GenericSql); + types.push_back(ObjectType::Textbox); + types.push_back(ObjectType::Relationship); + types.erase(std::find(types.begin(), types.end(), ObjectType::Schema)); try { if(save_tree_state) saveTreeState(tree_state); + objectstree_tw->setUpdatesEnabled(false); objectstree_tw->clear(); - if(visible_objs_map[OBJ_DATABASE]) + if(visible_objs_map[ObjectType::Database]) { root=createItemForObject(db_model); objectstree_tw->insertTopLevelItem(0,root); updateSchemaTree(root); - for(i=0; i < type_cnt; i++) + for(auto &type : types) { - if(visible_objs_map[types[i]]) + if(visible_objs_map[type]) { item1=new QTreeWidgetItem(root); - str_aux=QString(BaseObject::getSchemaName(types[i])); + str_aux=QString(BaseObject::getSchemaName(type)); - item1->setIcon(0,QPixmap(PgModelerUiNS::getIconPath(str_aux + QString("_grp")))); - item1->setData(1, Qt::UserRole, QVariant::fromValue(types[i])); + item1->setIcon(0,QPixmap(PgModelerUiNs::getIconPath(str_aux + QString("_grp")))); + item1->setData(1, Qt::UserRole, QVariant(enum_cast(type))); - obj_list=(*db_model->getObjectList(types[i])); + obj_list=(*db_model->getObjectList(type)); //Special case for relationship, merging the base relationship list to the relationship list - if(types[i]==OBJ_RELATIONSHIP) + if(type==ObjectType::Relationship) { vector obj_list_aux; - obj_list_aux=(*db_model->getObjectList(BASE_RELATIONSHIP)); + obj_list_aux=(*db_model->getObjectList(ObjectType::BaseRelationship)); obj_list.insert(obj_list.end(), obj_list_aux.begin(), obj_list_aux.end()); } count=obj_list.size(); - item1->setText(0,BaseObject::getTypeName(types[i]) + - QString(" (%1)").arg(count)); + item1->setText(0,BaseObject::getTypeName(type) + QString(" (%1)").arg(count)); font=item1->font(0); font.setItalic(true); item1->setFont(0, font); @@ -757,7 +760,7 @@ void ModelObjectsWidget::updateDatabaseTree(void) object=obj_list.at(i1); item2=createItemForObject(object, item1); - if(types[i]==OBJ_TAG) + if(types[i]==ObjectType::Tag) { db_model->getObjectReferences(object, ref_list); @@ -768,6 +771,7 @@ void ModelObjectsWidget::updateDatabaseTree(void) } } + objectstree_tw->setUpdatesEnabled(true); objectstree_tw->expandItem(root); if(save_tree_state) @@ -776,7 +780,7 @@ void ModelObjectsWidget::updateDatabaseTree(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } objectstree_tw->sortByColumn(0, Qt::AscendingOrder); @@ -790,7 +794,7 @@ BaseObject *ModelObjectsWidget::getSelectedObject(void) void ModelObjectsWidget::enableObjectCreation(bool value) { - enable_obj_creation=value; + enable_obj_creation=value; } void ModelObjectsWidget::close(void) @@ -952,6 +956,8 @@ void ModelObjectsWidget::restoreTreeState(vector &tree_items) { QTreeWidgetItem *item=nullptr, *parent_item=nullptr; + objectslist_tbw->setUpdatesEnabled(false); + while(!tree_items.empty()) { item=getTreeItem(tree_items.back()); @@ -969,6 +975,8 @@ void ModelObjectsWidget::restoreTreeState(vector &tree_items) tree_items.pop_back(); } + + objectslist_tbw->setUpdatesEnabled(true); } QTreeWidgetItem *ModelObjectsWidget::getTreeItem(BaseObject *object) diff --git a/libpgmodeler_ui/src/modelobjectswidget.h b/libpgmodeler_ui/src/modelobjectswidget.h index 2c71b20ca7..21f2b5cc7a 100644 --- a/libpgmodeler_ui/src/modelobjectswidget.h +++ b/libpgmodeler_ui/src/modelobjectswidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -38,7 +38,7 @@ class ModelObjectsWidget: public QWidget, public Ui::ModelObjectsWidget { /*! \brief Indicates if the widget must be used as a simplified view (without the most interactions). The purpose to use it as simplified view is to be serve as a object pick commonly used on the object selectors. See ObjectSelectorWidget for details. */ - bool simplified_view, + bool simplified_view, /*! \brief Indicates if the object tree state must be saved, this means, that the current item expansion is memorized and can be restored at any moment via restoreTreeState() method */ @@ -98,7 +98,7 @@ class ModelObjectsWidget: public QWidget, public Ui::ModelObjectsWidget { bool eventFilter(QObject *object, QEvent *event); public: - ModelObjectsWidget(bool simplified_view=false, QWidget * parent = 0); + ModelObjectsWidget(bool simplified_view=false, QWidget * parent = nullptr); BaseObject *getSelectedObject(void); diff --git a/libpgmodeler_ui/src/modeloverviewwidget.cpp b/libpgmodeler_ui/src/modeloverviewwidget.cpp index a63ebf8a0d..b65a8e93a3 100644 --- a/libpgmodeler_ui/src/modeloverviewwidget.cpp +++ b/libpgmodeler_ui/src/modeloverviewwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -22,10 +22,23 @@ ModelOverviewWidget::ModelOverviewWidget(QWidget *parent) : QWidget(parent, Qt::WindowCloseButtonHint | Qt::Tool) { setupUi(this); + + scrollarea = nullptr; this->model=nullptr; zoom_factor=1; - curr_resize_factor=RESIZE_FACTOR; + curr_resize_factor=ResizeFactor; this->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + + QVBoxLayout *vbox = new QVBoxLayout; + scrollarea=new QScrollArea(frame); + scrollarea->setWidgetResizable(true); + scrollarea->setFrameStyle(QFrame::Box); + scrollarea->setFrameShadow(QFrame::Plain); + scrollarea->setVisible(false); + vbox->addWidget(scrollarea); + vbox->setContentsMargins(0,0,0,0); + frame->setLayout(vbox); + label->setStyleSheet("QLabel#label{ border: 0px; }"); } void ModelOverviewWidget::show(ModelWidget *model) @@ -93,9 +106,9 @@ bool ModelOverviewWidget::eventFilter(QObject *object, QEvent *event) QPoint dt_angle = w_event->angleDelta(); if(dt_angle.y() < 0) - model->applyZoom(model->getCurrentZoom() - ModelWidget::ZOOM_INCREMENT); + model->applyZoom(model->getCurrentZoom() - ModelWidget::ZoomIncrement); else - model->applyZoom(model->getCurrentZoom() + ModelWidget::ZOOM_INCREMENT); + model->applyZoom(model->getCurrentZoom() + ModelWidget::ZoomIncrement); return(false); } @@ -114,6 +127,8 @@ void ModelOverviewWidget::updateOverview(bool force_update) { QPixmap pix; + QApplication::setOverrideCursor(Qt::WaitCursor); + //Creates a pixmap with the size of the scene pix=QPixmap(pixmap_size); @@ -130,6 +145,9 @@ void ModelOverviewWidget::updateOverview(bool force_update) else { frame->setEnabled(true); + + p.setRenderHints(QPainter::Antialiasing, false); + p.setRenderHints(QPainter::TextAntialiasing, false); this->model->scene->render(&p, pix.rect(), scene_rect.toRect()); //Resizes the pixmap to the previous configured QSize @@ -137,6 +155,7 @@ void ModelOverviewWidget::updateOverview(bool force_update) } label->resize(curr_size.toSize()); + QApplication::restoreOverrideCursor(); } } @@ -151,13 +170,26 @@ void ModelOverviewWidget::resizeWindowFrame(void) //Resizes the window frame based upon the model's viewport dimensions size=this->model->viewport->geometry().size(); - size.setWidth((size.width() * factor)); - size.setHeight((size.height() * factor)); + size.setWidth(size.width() * factor); + size.setHeight(size.height() * factor); window_frm->resize(size.toSize()); //Set the frame position based upon the viewport scroll bar values - window_frm->move(QPoint(h_scroll->value() * factor, v_scroll->value() * factor)); + window_frm->move(QPoint(h_scroll->value() * factor - (scrollarea->isVisible() ? scrollarea->horizontalScrollBar()->value() : 0), + v_scroll->value() * factor - (scrollarea->isVisible() ? scrollarea->verticalScrollBar()->value() : 0))); + if(scrollarea->isVisible()) + { + if(window_frm->geometry().bottom() > frame->geometry().bottom()) + scrollarea->verticalScrollBar()->setValue(scrollarea->verticalScrollBar()->value() + (scrollarea->verticalScrollBar()->maximum() * 0.30)); + else if(window_frm->geometry().top() < 0) + scrollarea->verticalScrollBar()->setValue(scrollarea->verticalScrollBar()->value() - (scrollarea->verticalScrollBar()->maximum() * 0.30)); + + if(window_frm->geometry().right() > frame->geometry().right()) + scrollarea->horizontalScrollBar()->setValue(scrollarea->horizontalScrollBar()->value() + (scrollarea->horizontalScrollBar()->maximum() * 0.30)); + else if(window_frm->geometry().left() < 0) + scrollarea->horizontalScrollBar()->setValue(scrollarea->horizontalScrollBar()->value() - (scrollarea->horizontalScrollBar()->maximum() * 0.30)); + } } } @@ -171,12 +203,12 @@ void ModelOverviewWidget::resizeOverview(void) //Make an initial calculation of the overview window size scene_rect=this->model->scene->sceneRect(); curr_size=scene_rect.size(); - curr_size.setWidth(curr_size.width() * RESIZE_FACTOR); - curr_size.setHeight(curr_size.height() * RESIZE_FACTOR); + curr_size.setWidth(curr_size.width() * ResizeFactor); + curr_size.setHeight(curr_size.height() * ResizeFactor); - //If the size exceeds the screen half width or height - if(curr_size.width() > screen_rect.width() * 0.80f || - curr_size.height() > screen_rect.height() * 0.80f) + //If the size exceeds the screen's width or height in 90% + if(curr_size.width() > screen_rect.width() * 0.90 || + curr_size.height() > screen_rect.height() * 0.90) { int max_val = std::max(scene_rect.width(), scene_rect.height()); @@ -189,7 +221,7 @@ void ModelOverviewWidget::resizeOverview(void) } else { - curr_resize_factor=RESIZE_FACTOR/2; + curr_resize_factor=ResizeFactor/2; pixmap_size=scene_rect.size().toSize(); } @@ -199,13 +231,48 @@ void ModelOverviewWidget::resizeOverview(void) } else { - curr_resize_factor=RESIZE_FACTOR; + curr_resize_factor=ResizeFactor; pixmap_size=scene_rect.size().toSize(); } - this->resize(curr_size.toSize()); - this->setMaximumSize(curr_size.toSize()); - this->setMinimumSize(curr_size.toSize()); + QSize size = curr_size.toSize(); + bool show_scrollarea = false; + + if(curr_size.width() > screen_rect.width() * 0.90 ) + { + size.setWidth(screen_rect.width() * 0.90); + show_scrollarea = true; + } + + if(curr_size.height() > screen_rect.height() * 0.90) + { + size.setHeight(screen_rect.height() * 0.90); + show_scrollarea = true; + } + + if(show_scrollarea && !scrollarea->isVisible()) + { + frame->setStyleSheet("QFrame#frame{ border: 0px; }"); + frame->layout()->removeWidget(label); + frame->layout()->addWidget(scrollarea); + scrollarea->setVisible(true); + scrollarea->setWidget(label); + window_frm->setParent(scrollarea); + } + else if(!show_scrollarea) + { + frame->setStyleSheet(""); + scrollarea->setVisible(false); + scrollarea->takeWidget(); + frame->layout()->removeWidget(scrollarea); + frame->layout()->addWidget(label); + window_frm->setParent(frame); + } + + window_frm->setVisible(true); + this->resize(size); + this->setMaximumSize(size); + this->setMinimumSize(size); } } @@ -228,7 +295,7 @@ void ModelOverviewWidget::mouseMoveEvent(QMouseEvent *event) if(event->buttons()==Qt::LeftButton) { QRect rect=window_frm->geometry(), rect1; - int width, height, x=event->x(), y=event->y(); + int width = 0, height = 0, x=event->x(), y=event->y() + scrollarea->verticalScrollBar()->value(); width=rect.width()/2; height=rect.height()/2; @@ -239,23 +306,9 @@ void ModelOverviewWidget::mouseMoveEvent(QMouseEvent *event) rect.setRight(x + width); rect.setBottom(y + height); - rect1=frame->geometry(); - - if(rect.left() < 0) - rect.translate(abs(rect.left()),0); - - if(rect.top() < 0) - rect.translate(0, abs(rect.top())); - - if(rect.right() >= rect1.right()) - rect.translate((rect1.right() - rect.right())-rect1.left(),0); - - if(rect.bottom() >= rect1.bottom()) - rect.translate(0,(rect1.bottom() - rect.bottom())-rect1.top()); - - window_frm->setGeometry(rect); - this->model->viewport->horizontalScrollBar()->setValue(ceilf(zoom_factor * scene_rect.width() * (rect.x()/static_cast(rect1.width())))); - this->model->viewport->verticalScrollBar()->setValue(ceilf(zoom_factor * scene_rect.height() * (rect.y()/static_cast(rect1.height())))); + rect1=label->geometry(); + this->model->viewport->horizontalScrollBar()->setValue(ceil(zoom_factor * scene_rect.width() * (rect.x()/static_cast(rect1.width())))); + this->model->viewport->verticalScrollBar()->setValue(ceil(zoom_factor * scene_rect.height() * (rect.y()/static_cast(rect1.height())))); } } diff --git a/libpgmodeler_ui/src/modeloverviewwidget.h b/libpgmodeler_ui/src/modeloverviewwidget.h index d5e950a27b..6557f29f0e 100644 --- a/libpgmodeler_ui/src/modeloverviewwidget.h +++ b/libpgmodeler_ui/src/modeloverviewwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -34,6 +34,8 @@ class ModelOverviewWidget: public QWidget, public Ui::ModelOverviewWidget { private: Q_OBJECT + QScrollArea *scrollarea; + //! \brief Model which object are drawn on the overview widget ModelWidget *model; @@ -52,7 +54,7 @@ class ModelOverviewWidget: public QWidget, public Ui::ModelOverviewWidget { QSize pixmap_size; //! \brief Resize factor applied to overview widgets (default: 20% of the scene original size) - static constexpr double RESIZE_FACTOR=0.20f; + static constexpr double ResizeFactor=0.20; void mouseDoubleClickEvent(QMouseEvent *); void mousePressEvent(QMouseEvent *event); @@ -67,7 +69,7 @@ class ModelOverviewWidget: public QWidget, public Ui::ModelOverviewWidget { void updateOverview(bool force_update); public: - ModelOverviewWidget(QWidget *parent = 0); + ModelOverviewWidget(QWidget *parent = nullptr); public slots: //! \brief Updates the overview (only if the widget is visible) diff --git a/libpgmodeler_ui/src/modelrestorationform.cpp b/libpgmodeler_ui/src/modelrestorationform.cpp index 2e434fe72e..d8c97370c1 100644 --- a/libpgmodeler_ui/src/modelrestorationform.cpp +++ b/libpgmodeler_ui/src/modelrestorationform.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -23,7 +23,7 @@ ModelRestorationForm::ModelRestorationForm(QWidget *parent, Qt::WindowFlags f) : { setupUi(this); - PgModelerUiNS::configureWidgetFont(message_lbl, PgModelerUiNS::MEDIUM_FONT_FACTOR); + PgModelerUiNs::configureWidgetFont(message_lbl, PgModelerUiNs::MediumFontFactor); keep_models_ht=new HintTextWidget(keep_models_hint, this); keep_models_ht->setText(keep_models_chk->statusTip()); @@ -35,7 +35,7 @@ ModelRestorationForm::ModelRestorationForm(QWidget *parent, Qt::WindowFlags f) : QStringList ModelRestorationForm::getTemporaryModels(void) { //Returns if there is some .dbm file on the tmp dir - return(QDir(GlobalAttributes::TEMPORARY_DIR, QString("*.dbm"), QDir::Name, QDir::Files | QDir::NoDotAndDotDot).entryList()); + return(QDir(GlobalAttributes::TemporaryDir, QString("*.dbm"), QDir::Name, QDir::Files | QDir::NoDotAndDotDot).entryList()); } int ModelRestorationForm::exec(void) @@ -48,11 +48,10 @@ int ModelRestorationForm::exec(void) QRegExp regexp=QRegExp("(\\getTemporaryModels().isEmpty()); } +void ModelRestorationForm::removeTemporaryFiles(void) +{ + QDir tmp_file; + QStringList tmp_files = QDir(GlobalAttributes::TemporaryDir, QString("*.dbm;*.dbk;*.omf;*.sql;*.log"), + QDir::Name, QDir::Files | QDir::NoDotAndDotDot).entryList(); + + for(auto &file : tmp_files) + tmp_file.remove(GlobalAttributes::TemporaryDir + GlobalAttributes::DirSeparator + file); +} + void ModelRestorationForm::removeTemporaryModels(void) { QStringList file_list=this->getTemporaryModels(); QDir tmp_file; - while(!file_list.isEmpty()) - { - tmp_file.remove(GlobalAttributes::TEMPORARY_DIR + GlobalAttributes::DIR_SEPARATOR + file_list.front()); - file_list.pop_front(); - } + for(auto &file : file_list) + tmp_file.remove(GlobalAttributes::TemporaryDir + GlobalAttributes::DirSeparator + file); } void ModelRestorationForm::removeTemporaryModel(const QString &tmp_model) { QDir tmp_file; QString file=QFileInfo(tmp_model).fileName(); - tmp_file.remove(GlobalAttributes::TEMPORARY_DIR + GlobalAttributes::DIR_SEPARATOR + file); + tmp_file.remove(GlobalAttributes::TemporaryDir + GlobalAttributes::DirSeparator + file); } void ModelRestorationForm::enableRestoration(void) diff --git a/libpgmodeler_ui/src/modelrestorationform.h b/libpgmodeler_ui/src/modelrestorationform.h index f859f004e3..3baa89e9f1 100644 --- a/libpgmodeler_ui/src/modelrestorationform.h +++ b/libpgmodeler_ui/src/modelrestorationform.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -37,7 +37,7 @@ class ModelRestorationForm: public QDialog, public Ui::ModelRestorationForm { HintTextWidget * keep_models_ht; public: - ModelRestorationForm(QWidget * parent = 0, Qt::WindowFlags f = 0); + ModelRestorationForm(QWidget * parent = nullptr, Qt::WindowFlags f = Qt::Widget); //! \brief Returns the list of temporary files existant on tmp/ dir QStringList getTemporaryModels(void); @@ -48,7 +48,10 @@ class ModelRestorationForm: public QDialog, public Ui::ModelRestorationForm { public slots: int exec(void); - //! \brief Clears the tmp/ dir removing all temporary files + //! \brief Clears the tmp/ dir by removing all temporary files (*.dbm, *.dbk, *.omf, *.sql. *.log) + void removeTemporaryFiles(void); + + //! \brief Clears the tmp/ dir removing all temporary models (*.dbm) void removeTemporaryModels(void); //! \brief Remove only the specified temp model diff --git a/libpgmodeler_ui/src/modelsdiffhelper.cpp b/libpgmodeler_ui/src/modelsdiffhelper.cpp index fb2f6fe164..a496bd0010 100644 --- a/libpgmodeler_ui/src/modelsdiffhelper.cpp +++ b/libpgmodeler_ui/src/modelsdiffhelper.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,23 +20,35 @@ #include #include "pgmodelerns.h" +const vector ModelsDiffHelper::TableObjsIgnoredAttribs = { Attributes::Alias }; + +const vector ModelsDiffHelper::ObjectsIgnoredAttribs = { + Attributes::MaxObjCount, Attributes::Protected, Attributes::SqlDisabled, + Attributes::RectVisible, Attributes::FillColor, Attributes::FadedOut, + Attributes::CollapseMode, Attributes::AttribsPage, Attributes::ExtAttribsPage, + Attributes::Pagination, Attributes::Alias }; + +const vector ModelsDiffHelper::ObjectsIgnoredTags = { + Attributes::Role, Attributes::Tablespace, Attributes::Collation, + Attributes::Position, Attributes::AppendedSql, Attributes::PrependedSql }; + ModelsDiffHelper::ModelsDiffHelper(void) { diff_canceled=false; - pgsql_version=PgSQLVersions::DEFAULT_VERSION; + pgsql_version=PgSqlVersions::DefaulVersion; source_model=imported_model=nullptr; resetDiffCounter(); - diff_opts[OPT_KEEP_CLUSTER_OBJS]=true; - diff_opts[OPT_CASCADE_MODE]=true; - diff_opts[OPT_TRUCANTE_TABLES]=false; - diff_opts[OPT_FORCE_RECREATION]=true; - diff_opts[OPT_RECREATE_UNCHANGEBLE]=true; - diff_opts[OPT_KEEP_OBJ_PERMS]=true; - diff_opts[OPT_REUSE_SEQUENCES]=true; - diff_opts[OPT_PRESERVE_DB_NAME]=true; - diff_opts[OPT_DONT_DROP_MISSING_OBJS]=false; - diff_opts[OPT_DROP_MISSING_COLS_CONSTR]=false; + diff_opts[OptKeepClusterObjs]=true; + diff_opts[OptCascadeMode]=true; + diff_opts[OptTruncateTables]=false; + diff_opts[OptForceRecreation]=true; + diff_opts[OptRecreateUnchangeble]=true; + diff_opts[OptKeepObjectPerms]=true; + diff_opts[OptReuseSequences]=true; + diff_opts[OptPreserveDbName]=true; + diff_opts[OptDontDropMissingObjs]=false; + diff_opts[OptDropMissingColsConstr]=false; } ModelsDiffHelper::~ModelsDiffHelper(void) @@ -46,11 +58,11 @@ ModelsDiffHelper::~ModelsDiffHelper(void) void ModelsDiffHelper::setDiffOption(unsigned opt_id, bool value) { - if(opt_id > OPT_DROP_MISSING_COLS_CONSTR) - throw Exception(ERR_REF_ELEM_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(opt_id > OptDropMissingColsConstr) + throw Exception(ErrorCode::RefElementInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(opt_id == OPT_DROP_MISSING_COLS_CONSTR) - diff_opts[opt_id]=value & !diff_opts[OPT_DROP_MISSING_COLS_CONSTR]; + if(opt_id == OptDropMissingColsConstr) + diff_opts[opt_id]=value & !diff_opts[OptDropMissingColsConstr]; else diff_opts[opt_id]=value; } @@ -62,10 +74,10 @@ void ModelsDiffHelper::setPgSQLVersion(const QString pgsql_ver) void ModelsDiffHelper::resetDiffCounter(void) { - diffs_counter[ObjectsDiffInfo::ALTER_OBJECT]=0; - diffs_counter[ObjectsDiffInfo::DROP_OBJECT]=0; - diffs_counter[ObjectsDiffInfo::CREATE_OBJECT]=0; - diffs_counter[ObjectsDiffInfo::IGNORE_OBJECT]=0; + diffs_counter[ObjectsDiffInfo::AlterObject]=0; + diffs_counter[ObjectsDiffInfo::DropObject]=0; + diffs_counter[ObjectsDiffInfo::CreateObject]=0; + diffs_counter[ObjectsDiffInfo::IgnoreObject]=0; } QString ModelsDiffHelper::getDiffDefinition(void) @@ -81,8 +93,8 @@ void ModelsDiffHelper::setModels(DatabaseModel *src_model, DatabaseModel *imp_mo unsigned ModelsDiffHelper::getDiffTypeCount(unsigned diff_type) { - if(diff_type >= ObjectsDiffInfo::NO_DIFFERENCE) - throw Exception(ERR_REF_ELEM_INV_INDEX ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(diff_type >= ObjectsDiffInfo::NoDifference) + throw Exception(ErrorCode::RefElementInvalidIndex ,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(diffs_counter[diff_type]); } @@ -92,12 +104,12 @@ void ModelsDiffHelper::diffModels(void) try { if(!source_model || !imported_model) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject ,__PRETTY_FUNCTION__,__FILE__,__LINE__); //First, we need to detect the objects to be dropped - diffModels(ObjectsDiffInfo::DROP_OBJECT); + diffModels(ObjectsDiffInfo::DropObject); //Second, we will check the objects to be created or modified - diffModels(ObjectsDiffInfo::CREATE_OBJECT); + diffModels(ObjectsDiffInfo::CreateObject); if(diff_canceled) emit s_diffCanceled(); @@ -109,7 +121,7 @@ void ModelsDiffHelper::diffModels(void) } catch(Exception &e) { - emit s_diffAborted(Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo())); + emit s_diffAborted(Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo())); } destroyTempObjects(); @@ -123,21 +135,21 @@ void ModelsDiffHelper::cancelDiff(void) void ModelsDiffHelper::diffTables(Table *src_table, Table *imp_table, unsigned diff_type) { - ObjectType types[2]={ OBJ_COLUMN, OBJ_CONSTRAINT }; + ObjectType types[2]={ ObjectType::Column, ObjectType::Constraint }; vector *tab_objs=nullptr; Constraint *constr=nullptr; Table *ref_tab=nullptr, *comp_tab=nullptr; BaseObject *aux_obj=nullptr; - if(diff_type==ObjectsDiffInfo::DROP_OBJECT) + if(diff_type==ObjectsDiffInfo::DropObject) { /* In case of DROP, the reference table is the one from the database and the compared table is the one from model */ ref_tab=imp_table; comp_tab=src_table; } - else if(diff_type==ObjectsDiffInfo::CREATE_OBJECT || - diff_type==ObjectsDiffInfo::ALTER_OBJECT) + else if(diff_type==ObjectsDiffInfo::CreateObject || + diff_type==ObjectsDiffInfo::AlterObject) { ref_tab=src_table; comp_tab=imp_table; @@ -156,9 +168,9 @@ void ModelsDiffHelper::diffTables(Table *src_table, Table *imp_table, unsigned d //Ignoring object with sql disabled or check constraints added by generalizations if(tab_obj->isSQLDisabled() || (constr && constr->isAddedByGeneralization() && - constr->getConstraintType()==ConstraintType::check)) + constr->getConstraintType()==ConstraintType::Check)) { - generateDiffInfo(ObjectsDiffInfo::IGNORE_OBJECT, tab_obj); + generateDiffInfo(ObjectsDiffInfo::IgnoreObject, tab_obj); } else { @@ -166,26 +178,26 @@ void ModelsDiffHelper::diffTables(Table *src_table, Table *imp_table, unsigned d columns created by common relationships will be considered on the comparison. Also, foreign keys are discarded here, since they will be compared on the main comparison at diffModels() */ - if(aux_obj && diff_type!=ObjectsDiffInfo::DROP_OBJECT && + if(aux_obj && diff_type!=ObjectsDiffInfo::DropObject && ((tab_obj->isAddedByGeneralization() || !tab_obj->isAddedByLinking() || - (aux_obj->getObjectType()==OBJ_COLUMN && tab_obj->isAddedByLinking())) || - (constr && constr->getConstraintType()!=ConstraintType::foreign_key))) + (aux_obj->getObjectType()==ObjectType::Column && tab_obj->isAddedByLinking())) || + (constr && constr->getConstraintType()!=ConstraintType::ForeignKey))) { //If there are some differences on the XML code of the objects - if(tab_obj->isCodeDiffersFrom(aux_obj)) - generateDiffInfo(ObjectsDiffInfo::ALTER_OBJECT, tab_obj, aux_obj); + if(tab_obj->isCodeDiffersFrom(aux_obj, TableObjsIgnoredAttribs)) + generateDiffInfo(ObjectsDiffInfo::AlterObject, tab_obj, aux_obj); } /* If the object does not exists it will generate a drop info and the original - one (tab_obj) was not included by generalization (to avoid drop inherited columns) */ - else if(!aux_obj && !tab_obj->isAddedByGeneralization()) + one (tab_obj) was not included by generalization or partitioning (to avoid drop inherited/copied columns) */ + else if(!aux_obj && !tab_obj->isAddedByGeneralization() && !tab_obj->isAddedByCopy()) { - if(diff_type!=ObjectsDiffInfo::DROP_OBJECT || - (diff_type==ObjectsDiffInfo::DROP_OBJECT && !diff_opts[OPT_DONT_DROP_MISSING_OBJS]) || - (diff_type==ObjectsDiffInfo::DROP_OBJECT && diff_opts[OPT_DROP_MISSING_COLS_CONSTR])) + if(diff_type!=ObjectsDiffInfo::DropObject || + (diff_type==ObjectsDiffInfo::DropObject && !diff_opts[OptDontDropMissingObjs]) || + (diff_type==ObjectsDiffInfo::DropObject && diff_opts[OptDropMissingColsConstr])) generateDiffInfo(diff_type, tab_obj); else - generateDiffInfo(ObjectsDiffInfo::IGNORE_OBJECT, tab_obj); + generateDiffInfo(ObjectsDiffInfo::IgnoreObject, tab_obj); } } @@ -210,21 +222,20 @@ void ModelsDiffHelper::diffModels(unsigned diff_type) DatabaseModel *aux_model=nullptr; bool objs_differs=false, xml_differs=false; - if(diff_type==ObjectsDiffInfo::DROP_OBJECT) + if(diff_type==ObjectsDiffInfo::DropObject) { /* For DROP detection, we must gather the objects from the database in order to check if they exists on the model. The object drop order here is the inverse of the creation order on the database */ - obj_order=imported_model->getCreationOrder(SchemaParser::SQL_DEFINITION, true); + obj_order=imported_model->getCreationOrder(SchemaParser::SqlDefinition, true); aux_model=source_model; factor=25; } - else if(diff_type==ObjectsDiffInfo::CREATE_OBJECT || - diff_type==ObjectsDiffInfo::ALTER_OBJECT) + else if(diff_type==ObjectsDiffInfo::CreateObject || diff_type==ObjectsDiffInfo::AlterObject) { /* For creation or modification of objects the order followed is the same as the creation order on the source model */ - obj_order=source_model->getCreationOrder(SchemaParser::SQL_DEFINITION, true, true); + obj_order=source_model->getCreationOrder(SchemaParser::SqlDefinition, true, true); aux_model=imported_model; factor=50; prog=50; @@ -237,96 +248,100 @@ void ModelsDiffHelper::diffModels(unsigned diff_type) idx++; /* If this checking the following objects are discarded: - 1) BASE_RELATIONSHIP objects + 1) ObjectType::ObjBaseRelationship objects 2) Objects which SQL code is disabled or system objects 3) Cluster objects such as roles and tablespaces (when the operatoin is DROP and keep_cluster_objs is true) */ - if(obj_type!=BASE_RELATIONSHIP && + if(obj_type!=ObjectType::BaseRelationship && !object->isSystemObject() && !object->isSQLDisabled() && - ((diff_type==ObjectsDiffInfo::DROP_OBJECT && (!diff_opts[OPT_KEEP_CLUSTER_OBJS] || (diff_opts[OPT_KEEP_CLUSTER_OBJS] && obj_type!=OBJ_ROLE && obj_type!=OBJ_TABLESPACE))) || - (diff_type!=ObjectsDiffInfo::DROP_OBJECT))) + ((diff_type==ObjectsDiffInfo::DropObject && (!diff_opts[OptKeepClusterObjs] || (diff_opts[OptKeepClusterObjs] && obj_type!=ObjectType::Role && obj_type!=ObjectType::Tablespace))) || + (diff_type!=ObjectsDiffInfo::DropObject))) { - emit s_progressUpdated(prog + ((idx/static_cast(obj_order.size())) * factor), - trUtf8("Processing object `%1' (%2)...").arg(object->getSignature()).arg(object->getTypeName()), - object->getObjectType()); + emit s_progressUpdated(prog + ((idx/static_cast(obj_order.size())) * factor), + trUtf8("Processing object `%1' (%2)...").arg(object->getSignature()).arg(object->getTypeName()), + object->getObjectType()); //Processing objects that are not database, table child object (they are processed further) - if(obj_type!=OBJ_DATABASE && !TableObject::isTableObject(obj_type)) + if(obj_type!=ObjectType::Database && !TableObject::isTableObject(obj_type)) { /* Processing permissions. If the operation is DROP and keep_obj_perms is true the - the permission is ignored */ - if(obj_type==OBJ_PERMISSION && + * the permission is ignored */ + if(obj_type==ObjectType::Permission && - ((diff_type==ObjectsDiffInfo::DROP_OBJECT && - !diff_opts[OPT_KEEP_OBJ_PERMS]) || + ((diff_type==ObjectsDiffInfo::DropObject && + !diff_opts[OptKeepObjectPerms]) || - (diff_type==ObjectsDiffInfo::CREATE_OBJECT && - (aux_model->getPermissionIndex(dynamic_cast(object), true) < 0 || - !diff_opts[OPT_KEEP_OBJ_PERMS])))) + (diff_type==ObjectsDiffInfo::CreateObject && + (aux_model->getPermissionIndex(dynamic_cast(object), true) < 0 || + !diff_opts[OptKeepObjectPerms])))) generateDiffInfo(diff_type, object); - //Processing relationship (in this case only generalization ones are considered) - else if(obj_type==OBJ_RELATIONSHIP) + //Processing relationship (in this case only generalization and patitioning ones are considered) + else if(obj_type==ObjectType::Relationship) { Table *ref_tab=nullptr, *rec_tab=nullptr; Relationship *rel=dynamic_cast(object); rec_tab=aux_model->getTable(rel->getReceiverTable()->getName(true)); - if(rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_GEN) + if(rel->getRelationshipType()==BaseRelationship::RelationshipGen || + rel->getRelationshipType()==BaseRelationship::RelationshipPart) { - ref_tab=aux_model->getTable(rel->getReferenceTable()->getName(true)); + Relationship *aux_rel = nullptr; + + ref_tab = aux_model->getTable(rel->getReferenceTable()->getName(true)); + aux_rel = dynamic_cast(aux_model->getRelationship(ref_tab, rec_tab)); /* If the receiver table exists on the model generates a info for the relationship, otherwise, the generalization will be created automatically when the table is created (see table's code defintion) */ - if(rec_tab && !aux_model->getRelationship(ref_tab, rec_tab)) + if(rec_tab && !aux_rel) generateDiffInfo(diff_type, rel); + /* Special case for partitioning: we detach (drop) and reattach (create) the partition + * if the partition bound expression differs from a model to another. This is done only + * if the receiver table (partition) exists in the imported model. */ + else if(rel->getRelationshipType()==BaseRelationship::RelationshipPart && + rec_tab && + aux_model == imported_model && + aux_rel && rel->getPartitionBoundingExpr().simplified() != + aux_rel->getPartitionBoundingExpr().simplified()) + { + generateDiffInfo(ObjectsDiffInfo::DropObject, rel); + generateDiffInfo(ObjectsDiffInfo::CreateObject, rel); + } } } - else if(obj_type!=OBJ_PERMISSION) + else if(obj_type!=ObjectType::Permission) { //Get the object from the database obj_name=object->getSignature(); aux_object=aux_model->getObject(obj_name, obj_type); //Special case for many-to-many relationships - if(obj_type==OBJ_TABLE && !aux_object) + if(obj_type==ObjectType::Table && !aux_object) aux_object=getRelNNTable(obj_name, aux_model); - if(diff_type != ObjectsDiffInfo::DROP_OBJECT && aux_object) + if(diff_type != ObjectsDiffInfo::DropObject && aux_object) { /* Try to get a diff from the retrieve object and the current object, - comparing only basic attributes like schema, tablespace and owner - this is why the BaseObject::getAlterDefinition is called */ + * comparing only basic attributes like schema, tablespace and owner + * this is why the BaseObject::getAlterDefinition is called */ objs_differs=!aux_object->BaseObject::getAlterDefinition(object).isEmpty(); //If the objects does not differ, try to compare their XML definition if(!objs_differs) - xml_differs=object->isCodeDiffersFrom(aux_object, - { ParsersAttributes::PROTECTED, - ParsersAttributes::SQL_DISABLED, - ParsersAttributes::RECT_VISIBLE, - ParsersAttributes::FILL_COLOR, - ParsersAttributes::FADED_OUT, - ParsersAttributes::HIDE_EXT_ATTRIBS}, - { ParsersAttributes::ROLE, - ParsersAttributes::TABLESPACE, - ParsersAttributes::COLLATION, - ParsersAttributes::POSITION, - ParsersAttributes::APPENDED_SQL, - ParsersAttributes::PREPENDED_SQL }); + xml_differs=object->isCodeDiffersFrom(aux_object, ObjectsIgnoredAttribs, ObjectsIgnoredTags); //If a difference was detected between the objects if(objs_differs || xml_differs) { - generateDiffInfo(ObjectsDiffInfo::ALTER_OBJECT, object, aux_object); + generateDiffInfo(ObjectsDiffInfo::AlterObject, object, aux_object); //If the object is a table, do additional comparision between their child objects - if((!diff_opts[OPT_FORCE_RECREATION] || diff_opts[OPT_RECREATE_UNCHANGEBLE]) && object->getObjectType()==OBJ_TABLE) + if((!diff_opts[OptForceRecreation] || diff_opts[OptRecreateUnchangeble]) && object->getObjectType()==ObjectType::Table) { Table *tab=dynamic_cast
(object), *aux_tab=dynamic_cast
(aux_object); - diffTables(tab, aux_tab, ObjectsDiffInfo::DROP_OBJECT); - diffTables(tab, aux_tab, ObjectsDiffInfo::CREATE_OBJECT); + diffTables(tab, aux_tab, ObjectsDiffInfo::DropObject); + diffTables(tab, aux_tab, ObjectsDiffInfo::CreateObject); } objs_differs=xml_differs=false; @@ -334,11 +349,11 @@ void ModelsDiffHelper::diffModels(unsigned diff_type) } else if(!aux_object) { - if(diff_type != ObjectsDiffInfo::DROP_OBJECT || - (diff_type == ObjectsDiffInfo::DROP_OBJECT && !diff_opts[OPT_DONT_DROP_MISSING_OBJS])) + if(diff_type != ObjectsDiffInfo::DropObject || + (diff_type == ObjectsDiffInfo::DropObject && !diff_opts[OptDontDropMissingObjs])) generateDiffInfo(diff_type, object); else - generateDiffInfo(ObjectsDiffInfo::IGNORE_OBJECT, object); + generateDiffInfo(ObjectsDiffInfo::IgnoreObject, object); } } } @@ -346,10 +361,10 @@ void ModelsDiffHelper::diffModels(unsigned diff_type) else if(TableObject::isTableObject(obj_type)) diffTableObject(dynamic_cast(object), diff_type); //Comparison between model db and the imported db - else if(diff_type==ObjectsDiffInfo::CREATE_OBJECT) + else if(diff_type==ObjectsDiffInfo::CreateObject) { if(!source_model->getAlterDefinition(imported_model).isEmpty()) - generateDiffInfo(ObjectsDiffInfo::ALTER_OBJECT, source_model, imported_model); + generateDiffInfo(ObjectsDiffInfo::AlterObject, source_model, imported_model); } if(diff_canceled) @@ -357,8 +372,8 @@ void ModelsDiffHelper::diffModels(unsigned diff_type) } else { - generateDiffInfo(ObjectsDiffInfo::IGNORE_OBJECT, object); - emit s_progressUpdated(prog + ((idx/static_cast(obj_order.size())) * factor), + generateDiffInfo(ObjectsDiffInfo::IgnoreObject, object); + emit s_progressUpdated(prog + ((idx/static_cast(obj_order.size())) * factor), trUtf8("Skipping object `%1' (%2)...").arg(object->getSignature()).arg(object->getTypeName()), object->getObjectType()); @@ -369,7 +384,7 @@ void ModelsDiffHelper::diffModels(unsigned diff_type) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -385,7 +400,7 @@ void ModelsDiffHelper::diffTableObject(TableObject *tab_obj, unsigned diff_type) tab_name=base_tab->getSignature(); //If the operation is a DROP, try to get the table from the source mode - if(diff_type==ObjectsDiffInfo::DROP_OBJECT) + if(diff_type==ObjectsDiffInfo::DropObject) { aux_base_tab=dynamic_cast(source_model->getObject(tab_name, base_tab->getObjectType())); @@ -393,7 +408,7 @@ void ModelsDiffHelper::diffTableObject(TableObject *tab_obj, unsigned diff_type) if(!aux_base_tab) aux_base_tab=dynamic_cast(getRelNNTable(tab_name, source_model)); } - else if(diff_type==ObjectsDiffInfo::CREATE_OBJECT || diff_type==ObjectsDiffInfo::ALTER_OBJECT) + else if(diff_type==ObjectsDiffInfo::CreateObject || diff_type==ObjectsDiffInfo::AlterObject) { aux_base_tab=dynamic_cast(imported_model->getObject(tab_name, base_tab->getObjectType())); @@ -404,7 +419,7 @@ void ModelsDiffHelper::diffTableObject(TableObject *tab_obj, unsigned diff_type) if(aux_base_tab) { - if(obj_type==OBJ_CONSTRAINT) + if(obj_type==ObjectType::Constraint) { Table *aux_table=dynamic_cast
(aux_base_tab); aux_tab_obj=aux_table->getObject(obj_name, obj_type); @@ -415,26 +430,26 @@ void ModelsDiffHelper::diffTableObject(TableObject *tab_obj, unsigned diff_type) if(!aux_tab_obj) { - if(diff_type!=ObjectsDiffInfo::DROP_OBJECT || - (diff_type==ObjectsDiffInfo::DROP_OBJECT && !diff_opts[OPT_DONT_DROP_MISSING_OBJS])) + if(diff_type!=ObjectsDiffInfo::DropObject || + (diff_type==ObjectsDiffInfo::DropObject && !diff_opts[OptDontDropMissingObjs])) generateDiffInfo(diff_type, tab_obj); else - generateDiffInfo(ObjectsDiffInfo::IGNORE_OBJECT, tab_obj); + generateDiffInfo(ObjectsDiffInfo::IgnoreObject, tab_obj); } - else if(diff_type!=ObjectsDiffInfo::DROP_OBJECT && tab_obj->isCodeDiffersFrom(aux_tab_obj)) - generateDiffInfo(ObjectsDiffInfo::ALTER_OBJECT, tab_obj, aux_tab_obj); + else if(diff_type!=ObjectsDiffInfo::DropObject && tab_obj->isCodeDiffersFrom(aux_tab_obj, TableObjsIgnoredAttribs)) + generateDiffInfo(ObjectsDiffInfo::AlterObject, tab_obj, aux_tab_obj); } BaseObject *ModelsDiffHelper::getRelNNTable(const QString &obj_name, DatabaseModel *model) { - vector *rels=model->getObjectList(OBJ_RELATIONSHIP); + vector *rels=model->getObjectList(ObjectType::Relationship); Relationship *rel=nullptr; BaseObject *tab=nullptr; for(auto &obj : *rels) { rel=dynamic_cast(obj); - if(rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_NN && + if(rel->getRelationshipType()==BaseRelationship::RelationshipNn && rel->getGeneratedTable() && rel->getGeneratedTable()->getSignature()==obj_name) { tab=rel->getGeneratedTable(); @@ -454,15 +469,15 @@ void ModelsDiffHelper::generateDiffInfo(unsigned diff_type, BaseObject *object, ObjectsDiffInfo diff_info; /* If the info is for ALTER and there is a DROP info on the list, - the object will be recreated instead of modified */ - if((!diff_opts[OPT_FORCE_RECREATION] || diff_opts[OPT_RECREATE_UNCHANGEBLE]) && - diff_type==ObjectsDiffInfo::ALTER_OBJECT && - isDiffInfoExists(ObjectsDiffInfo::DROP_OBJECT, old_object, nullptr) && - !isDiffInfoExists(ObjectsDiffInfo::CREATE_OBJECT, object, nullptr)) + * the object will be recreated instead of modified */ + if((!diff_opts[OptForceRecreation] || diff_opts[OptRecreateUnchangeble]) && + diff_type==ObjectsDiffInfo::AlterObject && + isDiffInfoExists(ObjectsDiffInfo::DropObject, old_object, nullptr) && + !isDiffInfoExists(ObjectsDiffInfo::CreateObject, object, nullptr)) { - diff_info=ObjectsDiffInfo(ObjectsDiffInfo::CREATE_OBJECT, object, nullptr); + diff_info=ObjectsDiffInfo(ObjectsDiffInfo::CreateObject, object, nullptr); diff_infos.push_back(diff_info); - diffs_counter[ObjectsDiffInfo::CREATE_OBJECT]++; + diffs_counter[ObjectsDiffInfo::CreateObject]++; emit s_objectsDiffInfoGenerated(diff_info); } else if(!isDiffInfoExists(diff_type, object, old_object)) @@ -471,10 +486,10 @@ void ModelsDiffHelper::generateDiffInfo(unsigned diff_type, BaseObject *object, *old_col=dynamic_cast(old_object); /* Special case for columns marked with ALTER. - If the type of them is "serial" or similar then a sequence will be created and the - type of the column changed to "integer" or similar, this because the ALTER command - for columns don't accept the type "serial" */ - if(diff_type==ObjectsDiffInfo::ALTER_OBJECT && col && old_col && + * If the type of them is "serial" or similar then a sequence will be created and the + * type of the column changed to "integer" or similar, this because the ALTER command + * for columns don't accept the type "serial" */ + if(diff_type==ObjectsDiffInfo::AlterObject && col && old_col && (col->getType()!=old_col->getType() && col->getType().isSerialType())) { Column *aux_col=new Column; @@ -482,8 +497,8 @@ void ModelsDiffHelper::generateDiffInfo(unsigned diff_type, BaseObject *object, BaseTable *tab=col->getParentTable(); QString seq_name=QString("%1_%2_seq").arg(tab->getName()).arg(col->getName()); - if(seq_name.length() > BaseObject::OBJECT_NAME_MAX_LENGTH) - seq_name.chop(seq_name.length() - BaseObject::OBJECT_NAME_MAX_LENGTH); + if(seq_name.length() > BaseObject::ObjectNameMaxLength) + seq_name.chop(seq_name.length() - BaseObject::ObjectNameMaxLength); seq->setName(seq_name); seq->setOwner(tab->getOwner()); @@ -497,21 +512,29 @@ void ModelsDiffHelper::generateDiffInfo(unsigned diff_type, BaseObject *object, //Assigns the sequence to the column in order to configure the default value correctly aux_col->setSequence(seq); - //Creates a new ALTER info with the created column - diff_info=ObjectsDiffInfo(ObjectsDiffInfo::ALTER_OBJECT, aux_col, col); - diff_infos.push_back(diff_info); - diffs_counter[ObjectsDiffInfo::ALTER_OBJECT]++; - emit s_objectsDiffInfoGenerated(diff_info); + /* Creates a new ALTER info with the created column onlly if we don't need to reuse sequences + * or if the sequence reusing is enabled but the type of the columns aren't equivalent or even + * the types are equivalent but the sequences used by each columns aren't the same */ + if(!diff_opts[OptReuseSequences] || + (diff_opts[OptReuseSequences] && + (!col->getType().getAliasType().isEquivalentTo(old_col->getType()) || + (old_col->getSequence() && old_col->getSequence()->getSignature() != seq->getSignature())))) + { + diff_info=ObjectsDiffInfo(ObjectsDiffInfo::AlterObject, aux_col, col); + diff_infos.push_back(diff_info); + diffs_counter[ObjectsDiffInfo::AlterObject]++; + emit s_objectsDiffInfoGenerated(diff_info); + } - if(!diff_opts[OPT_REUSE_SEQUENCES] || imported_model->getObjectIndex(seq->getSignature(), OBJ_SEQUENCE) < 0) + if(!diff_opts[OptReuseSequences] || imported_model->getObjectIndex(seq->getSignature(), ObjectType::Sequence) < 0) { //Creates a CREATE info with the sequence - diff_info=ObjectsDiffInfo(ObjectsDiffInfo::CREATE_OBJECT, seq, nullptr); + diff_info=ObjectsDiffInfo(ObjectsDiffInfo::CreateObject, seq, nullptr); diff_infos.push_back(diff_info); - diffs_counter[ObjectsDiffInfo::CREATE_OBJECT]++; + diffs_counter[ObjectsDiffInfo::CreateObject]++; emit s_objectsDiffInfoGenerated(diff_info); } - else if(diff_opts[OPT_REUSE_SEQUENCES]) + else if(diff_opts[OptReuseSequences]) { //Removing DROP infos related to the sequence that will be reused vector::iterator itr=diff_infos.begin(), @@ -519,8 +542,8 @@ void ModelsDiffHelper::generateDiffInfo(unsigned diff_type, BaseObject *object, while(itr!=itr_end) { - if(itr->getDiffType()==ObjectsDiffInfo::DROP_OBJECT && - itr->getObject()->getObjectType()==OBJ_SEQUENCE && + if(itr->getDiffType()==ObjectsDiffInfo::DropObject && + itr->getObject()->getObjectType()==ObjectType::Sequence && itr->getObject()->getSignature()==seq->getSignature()) { diff_infos.erase(itr); @@ -531,8 +554,8 @@ void ModelsDiffHelper::generateDiffInfo(unsigned diff_type, BaseObject *object, } } - /* Stores the created objects in the temp list in order to be destroyed at the - end of the process. */ + /* Stores the created objects in the temp list in order to be destroyed + * at the end of the process. */ tmp_objects.push_back(aux_col); tmp_objects.push_back(seq); } @@ -546,8 +569,8 @@ void ModelsDiffHelper::generateDiffInfo(unsigned diff_type, BaseObject *object, /* If the info is for DROP, generate the drop for referer objects of the one marked to be dropped */ - if((!diff_opts[OPT_FORCE_RECREATION] || diff_opts[OPT_RECREATE_UNCHANGEBLE]) && - diff_type==ObjectsDiffInfo::DROP_OBJECT) + if((!diff_opts[OptForceRecreation] || diff_opts[OptRecreateUnchangeble]) && + diff_type==ObjectsDiffInfo::DropObject) { vector ref_objs; ObjectType obj_type=object->getObjectType(); @@ -559,8 +582,8 @@ void ModelsDiffHelper::generateDiffInfo(unsigned diff_type, BaseObject *object, /* Avoiding columns to be dropped when a sequence linked to them is dropped too. This because a column can be a reference to a sequence so to avoid drop and recreate that column this one will not be erased, unless the column does not exists in the model anymore */ - if((obj_type==OBJ_SEQUENCE && obj->getObjectType()!=OBJ_COLUMN) && - (obj_type!=OBJ_SEQUENCE && obj->getObjectType()!=BASE_RELATIONSHIP)) + if((obj_type==ObjectType::Sequence && obj->getObjectType()!=ObjectType::Column) && + (obj_type!=ObjectType::Sequence && obj->getObjectType()!=ObjectType::BaseRelationship)) generateDiffInfo(diff_type, obj); if(diff_canceled) @@ -572,7 +595,7 @@ void ModelsDiffHelper::generateDiffInfo(unsigned diff_type, BaseObject *object, } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -626,7 +649,7 @@ void ModelsDiffHelper::processDiffInfos(void) emit s_progressUpdated(0, trUtf8("Processing diff infos...")); //Reuniting the schema names to inject a SET search_path command - for(auto &schema : *imported_model->getObjectList(OBJ_SCHEMA)) + for(auto &schema : *imported_model->getObjectList(ObjectType::Schema)) sch_names.push_back(schema->getName(true)); //Separating the base types @@ -634,7 +657,7 @@ void ModelsDiffHelper::processDiffInfos(void) { type=dynamic_cast(diff.getObject()); - if(type && type->getConfiguration()==Type::BASE_TYPE) + if(type && type->getConfiguration()==Type::BaseType) { type->convertFunctionParameters(); types.push_back(type); @@ -650,7 +673,7 @@ void ModelsDiffHelper::processDiffInfos(void) constr=dynamic_cast(object); col=dynamic_cast(object); - emit s_progressUpdated((idx++/static_cast(diff_infos.size())) * 100, + emit s_progressUpdated((idx++/static_cast(diff_infos.size())) * 100, trUtf8("Processing `%1' info for object `%2' (%3)...") .arg(diff.getDiffTypeString()).arg(object->getSignature()).arg(object->getTypeName()), obj_type); @@ -659,7 +682,7 @@ void ModelsDiffHelper::processDiffInfos(void) check if the constraint is added by generalization or if this is not the case if it already exists in a ancestor table of its parent, this avoid the generation of commands to create or drop an inherited constraint raising errors when export the diff */ - if(constr && constr->getConstraintType()==ConstraintType::check) + if(constr && constr->getConstraintType()==ConstraintType::Check) { parent_tab=dynamic_cast
(constr->getParentTable()); skip_obj=constr->isAddedByGeneralization(); @@ -685,20 +708,21 @@ void ModelsDiffHelper::processDiffInfos(void) } //Generating the DROP commands - if(diff_type==ObjectsDiffInfo::DROP_OBJECT) + if(diff_type==ObjectsDiffInfo::DropObject) { - if(rel && rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_GEN) + if(rel && (rel->getRelationshipType()==BaseRelationship::RelationshipGen || + rel->getRelationshipType()==BaseRelationship::RelationshipPart)) { //Undoing inheritances - no_inherit_def+=rel->getInheritDefinition(true); + no_inherit_def+=rel->getAlterRelationshipDefinition(true); } - else if(obj_type==OBJ_PERMISSION) + else if(obj_type==ObjectType::Permission) //Unsetting permissions - unset_perms+=object->getDropDefinition(diff_opts[OPT_CASCADE_MODE]); + unset_perms+=object->getDropDefinition(diff_opts[OptCascadeMode]); else { //Ordinary drop commands for any object except columns - if(obj_type!=OBJ_COLUMN) + if(obj_type!=ObjectType::Column) drop_objs[object->getObjectId()]=getCodeDefinition(object, true); else { @@ -711,23 +735,24 @@ void ModelsDiffHelper::processDiffInfos(void) } } //Generating the CREATE commands - else if(diff_type==ObjectsDiffInfo::CREATE_OBJECT) + else if(diff_type==ObjectsDiffInfo::CreateObject) { - if(rel && rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_GEN) + if(rel && (rel->getRelationshipType()==BaseRelationship::RelationshipGen || + rel->getRelationshipType()==BaseRelationship::RelationshipPart)) { //Creating inheritances - inherit_def+=rel->getInheritDefinition(false); + inherit_def+=rel->getAlterRelationshipDefinition(false); } - else if(obj_type==OBJ_PERMISSION) + else if(obj_type==ObjectType::Permission) //Setting permissions - set_perms+=object->getCodeDefinition(SchemaParser::SQL_DEFINITION); + set_perms+=object->getCodeDefinition(SchemaParser::SqlDefinition); else { /* Special case for constaints: the creation commands for these objects are appended at the very end of create commands secion. Primary keys, unique keys, check constraints and exclude constraints are created after foreign keys */ - if(object->getObjectType()==OBJ_CONSTRAINT) + if(object->getObjectType()==ObjectType::Constraint) { - if(dynamic_cast(object)->getConstraintType()==ConstraintType::foreign_key) + if(dynamic_cast(object)->getConstraintType()==ConstraintType::ForeignKey) create_fks[object->getObjectId()]=getCodeDefinition(object, false); else create_constrs[object->getObjectId()]=getCodeDefinition(object, false); @@ -736,20 +761,20 @@ void ModelsDiffHelper::processDiffInfos(void) { create_objs[object->getObjectId()]=getCodeDefinition(object, false); - if(obj_type==OBJ_SCHEMA) + if(obj_type==ObjectType::Schema) sch_names.push_back(object->getName(true)); } } } //Generating the ALTER commands - else if(diff_type==ObjectsDiffInfo::ALTER_OBJECT) + else if(diff_type==ObjectsDiffInfo::AlterObject) { //Recreating the object instead of generating an ALTER command for it - if((diff_opts[OPT_FORCE_RECREATION] && obj_type!=OBJ_DATABASE) && - (!diff_opts[OPT_RECREATE_UNCHANGEBLE] || - (diff_opts[OPT_RECREATE_UNCHANGEBLE] && !object->acceptsAlterCommand() && - diff.getObject()->getCodeDefinition(SchemaParser::SQL_DEFINITION).simplified()!= - diff.getOldObject()->getCodeDefinition(SchemaParser::SQL_DEFINITION).simplified()))) + if((diff_opts[OptForceRecreation] && obj_type!=ObjectType::Database) && + (!diff_opts[OptRecreateUnchangeble] || + (diff_opts[OptRecreateUnchangeble] && !object->acceptsAlterCommand() && + diff.getObject()->getCodeDefinition(SchemaParser::SqlDefinition).simplified()!= + diff.getOldObject()->getCodeDefinition(SchemaParser::SqlDefinition).simplified()))) { recreateObject(object, drop_vect, create_vect); @@ -761,13 +786,13 @@ void ModelsDiffHelper::processDiffInfos(void) for(auto &obj : create_vect) { //The there is no ALTER info registered for an object's reference - if(!isDiffInfoExists(ObjectsDiffInfo::ALTER_OBJECT, nullptr, obj, false)) + if(!isDiffInfoExists(ObjectsDiffInfo::AlterObject, nullptr, obj, false)) { /* Special case for constraints, their code will be appeded to a separated variable in order to create them at the end of diff buffer */ - if(obj->getObjectType()==OBJ_CONSTRAINT) + if(obj->getObjectType()==ObjectType::Constraint) { - if(dynamic_cast(obj)->getConstraintType()==ConstraintType::foreign_key) + if(dynamic_cast(obj)->getConstraintType()==ConstraintType::ForeignKey) create_fks[obj->getObjectId()]=getCodeDefinition(obj, false); else create_constrs[obj->getObjectId()]=getCodeDefinition(obj, false); @@ -785,7 +810,7 @@ void ModelsDiffHelper::processDiffInfos(void) if(diff.getOldObject()) alter_def=diff.getOldObject()->getAlterDefinition(object); - if(obj_type == OBJ_DATABASE && diff_opts[OPT_PRESERVE_DB_NAME]) + if(obj_type == ObjectType::Database && diff_opts[OptPreserveDbName]) alter_def.remove(QRegExp(QString("(ALTER)( )+(DATABASE)( )+(%1)( )+(RENAME)( )+(TO)(.)*(\\n)").arg(diff.getOldObject()->getSignature()))); if(!alter_def.isEmpty()) @@ -794,7 +819,7 @@ void ModelsDiffHelper::processDiffInfos(void) /* If the object is a column checks if the types of the columns are differents, generating a TRUNCATE TABLE for the parent table */ - if(obj_type==OBJ_COLUMN && diff_opts[OPT_TRUCANTE_TABLES]) + if(obj_type==ObjectType::Column && diff_opts[OptTruncateTables]) { Column *src_col=dynamic_cast(object), *old_col=dynamic_cast(diff.getOldObject()); @@ -804,7 +829,7 @@ void ModelsDiffHelper::processDiffInfos(void) (!old_col->getType().isSerialType() && !src_col->getType().isEquivalentTo(old_col->getType()))) && truncate_tabs.count(tab->getObjectId())==0) { - truncate_tabs[tab->getObjectId()]=tab->getTruncateDefinition(diff_opts[OPT_CASCADE_MODE]); + truncate_tabs[tab->getObjectId()]=tab->getTruncateDefinition(diff_opts[OptCascadeMode]); } } } @@ -818,9 +843,9 @@ void ModelsDiffHelper::processDiffInfos(void) schema_id=type->getSchema()->getObjectId(); if(create_objs.count(schema_id)!=0) - create_objs[schema_id]+=type->getCodeDefinition(SchemaParser::SQL_DEFINITION, true); + create_objs[schema_id]+=type->getCodeDefinition(SchemaParser::SqlDefinition, true); else - attribs[ParsersAttributes::CREATE_CMDS]+=type->getCodeDefinition(SchemaParser::SQL_DEFINITION, true); + attribs[Attributes::CreateCmds]+=type->getCodeDefinition(SchemaParser::SqlDefinition, true); type->convertFunctionParameters(true); } @@ -842,63 +867,63 @@ void ModelsDiffHelper::processDiffInfos(void) has_diffs=(create_objs_count!=0 || alter_objs.size()!=0 || drop_objs.size()!=0); //Attributes used on the diff schema file - attribs[ParsersAttributes::HAS_CHANGES]=ParsersAttributes::_TRUE_; - attribs[ParsersAttributes::PGMODELER_VERSION]=GlobalAttributes::PGMODELER_VERSION; - attribs[ParsersAttributes::DB_MODEL]=source_model->getName(); - attribs[ParsersAttributes::DATABASE]=imported_model->getName(); - attribs[ParsersAttributes::DATE]=QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"); - attribs[ParsersAttributes::CONNECTION]=imported_model->getName(); - attribs[ParsersAttributes::CHANGE]=QString::number(alter_objs.size()); - attribs[ParsersAttributes::CREATE]=QString::number(create_objs_count); - attribs[ParsersAttributes::DROP]=QString::number(drop_objs.size()); - attribs[ParsersAttributes::TRUNCATE]=QString::number(truncate_tabs.size()); - attribs[ParsersAttributes::ALTER_CMDS]=QString(); - attribs[ParsersAttributes::DROP_CMDS]=QString(); - attribs[ParsersAttributes::CREATE_CMDS]=QString(); - attribs[ParsersAttributes::TRUNCATE_CMDS]=QString(); - attribs[ParsersAttributes::CONSTR_DEFS]=QString(); - attribs[ParsersAttributes::FK_DEFS]=QString(); - attribs[ParsersAttributes::UNSET_PERMS]=unset_perms; - attribs[ParsersAttributes::SET_PERMS]=set_perms; - attribs[ParsersAttributes::FUNCTION]=(has_diffs && source_model->getObjectCount(OBJ_FUNCTION)!=0 ? ParsersAttributes::_TRUE_ : QString()); - attribs[ParsersAttributes::SEARCH_PATH]=(has_diffs ? sch_names.join(',') : QString()); + attribs[Attributes::HasChanges]=Attributes::True; + attribs[Attributes::PgModelerVersion]=GlobalAttributes::PgModelerVersion; + attribs[Attributes::DbModel]=source_model->getName(); + attribs[Attributes::Database]=imported_model->getName(); + attribs[Attributes::Date]=QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"); + attribs[Attributes::Connection]=imported_model->getName(); + attribs[Attributes::Change]=QString::number(alter_objs.size()); + attribs[Attributes::Create]=QString::number(create_objs_count); + attribs[Attributes::Drop]=QString::number(drop_objs.size()); + attribs[Attributes::Truncate]=QString::number(truncate_tabs.size()); + attribs[Attributes::AlterCmds]=QString(); + attribs[Attributes::DropCmds]=QString(); + attribs[Attributes::CreateCmds]=QString(); + attribs[Attributes::TruncateCmds]=QString(); + attribs[Attributes::ConstrDefs]=QString(); + attribs[Attributes::FkDefs]=QString(); + attribs[Attributes::UnsetPerms]=unset_perms; + attribs[Attributes::SetPerms]=set_perms; + attribs[Attributes::Function]=(has_diffs && source_model->getObjectCount(ObjectType::Function)!=0 ? Attributes::True : QString()); + attribs[Attributes::SearchPath]=(has_diffs ? sch_names.join(',') : QString()); ritr=drop_objs.rbegin(); ritr_end=drop_objs.rend(); - attribs[ParsersAttributes::DROP_CMDS]+=no_inherit_def; + attribs[Attributes::DropCmds]+=no_inherit_def; while(ritr!=ritr_end) { - attribs[ParsersAttributes::DROP_CMDS]+=ritr->second; + attribs[Attributes::DropCmds]+=ritr->second; ritr++; } - attribs[ParsersAttributes::DROP_CMDS]+=col_drop_def; + attribs[Attributes::DropCmds]+=col_drop_def; for(auto &itr : create_objs) - attribs[ParsersAttributes::CREATE_CMDS]+=itr.second; + attribs[Attributes::CreateCmds]+=itr.second; - attribs[ParsersAttributes::CREATE_CMDS]+=inherit_def; + attribs[Attributes::CreateCmds]+=inherit_def; for(auto &itr : create_constrs) - attribs[ParsersAttributes::CONSTR_DEFS]+=itr.second; + attribs[Attributes::ConstrDefs]+=itr.second; for(auto &itr : create_fks) - attribs[ParsersAttributes::FK_DEFS]+=itr.second; + attribs[Attributes::FkDefs]+=itr.second; for(auto &itr : truncate_tabs) - attribs[ParsersAttributes::TRUNCATE_CMDS]+=itr.second; + attribs[Attributes::TruncateCmds]+=itr.second; for(auto &itr : alter_objs) - attribs[ParsersAttributes::ALTER_CMDS]+=itr.second; + attribs[Attributes::AlterCmds]+=itr.second; //Generating the whole diff buffer schparser.setPgSQLVersion(pgsql_version); - diff_def=schparser.getCodeDefinition(GlobalAttributes::SCHEMAS_ROOT_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::ALTER_SCHEMA_DIR + GlobalAttributes::DIR_SEPARATOR + - ParsersAttributes::DIFF + GlobalAttributes::SCHEMA_EXT, attribs); + diff_def=schparser.getCodeDefinition(GlobalAttributes::SchemasRootDir + GlobalAttributes::DirSeparator + + GlobalAttributes::AlterSchemaDir + GlobalAttributes::DirSeparator + + Attributes::Diff + GlobalAttributes::SchemaExt, attribs); } if(diff_def.isEmpty()) @@ -916,7 +941,7 @@ void ModelsDiffHelper::processDiffInfos(void) for(Type *type : types) type->convertFunctionParameters(true); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -929,7 +954,7 @@ QString ModelsDiffHelper::getCodeDefinition(BaseObject *object, bool drop_cmd) /* For columns and constraints it is needed to force the generation of ALTER commands on the parent table */ - if(tab_obj && (tab_obj->getObjectType()==OBJ_COLUMN || tab_obj->getObjectType()==OBJ_CONSTRAINT)) + if(tab_obj && (tab_obj->getObjectType()==ObjectType::Column || tab_obj->getObjectType()==ObjectType::Constraint)) { bool gen_alter=false; Table *table=dynamic_cast
(tab_obj->getParentTable()); @@ -938,25 +963,25 @@ QString ModelsDiffHelper::getCodeDefinition(BaseObject *object, bool drop_cmd) table->setGenerateAlterCmds(true); if(drop_cmd) - cmd=tab_obj->getDropDefinition(diff_opts[OPT_CASCADE_MODE]); + cmd=tab_obj->getDropDefinition(diff_opts[OptCascadeMode]); else - cmd=tab_obj->getCodeDefinition(SchemaParser::SQL_DEFINITION); + cmd=tab_obj->getCodeDefinition(SchemaParser::SqlDefinition); table->setGenerateAlterCmds(gen_alter); } else { if(drop_cmd) - cmd=object->getDropDefinition(diff_opts[OPT_CASCADE_MODE]); + cmd=object->getDropDefinition(diff_opts[OptCascadeMode]); else - cmd=object->getCodeDefinition(SchemaParser::SQL_DEFINITION); + cmd=object->getCodeDefinition(SchemaParser::SqlDefinition); } return(cmd); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -977,9 +1002,9 @@ void ModelsDiffHelper::destroyTempObjects(void) void ModelsDiffHelper::recreateObject(BaseObject *object, vector &drop_objs, vector &create_objs) { if(object && - object->getObjectType()!=BASE_RELATIONSHIP && - object->getObjectType()!=OBJ_RELATIONSHIP && - object->getObjectType()!=OBJ_DATABASE) + object->getObjectType()!=ObjectType::BaseRelationship && + object->getObjectType()!=ObjectType::Relationship && + object->getObjectType()!=ObjectType::Database) { vector ref_objs; BaseObject *aux_obj=nullptr; @@ -1007,26 +1032,26 @@ void ModelsDiffHelper::recreateObject(BaseObject *object, vector & /* If the to-be recreate object is a constraint check if it's a pk, if so, the fk's linked to it need to be recreated as well */ - if(aux_obj->getObjectType()==OBJ_CONSTRAINT) + if(aux_obj->getObjectType()==ObjectType::Constraint) { Constraint *constr=dynamic_cast(aux_obj); - if(constr->getConstraintType()==ConstraintType::primary_key) + if(constr->getConstraintType()==ConstraintType::PrimaryKey) { - unsigned i=0, col_cnt=constr->getColumnCount(Constraint::SOURCE_COLS); + unsigned i=0, col_cnt=constr->getColumnCount(Constraint::SourceCols); vector ref_aux; Constraint *aux_constr=nullptr; for(i=0; i < col_cnt; i++) { //Get the objects referencing the source columns of the pk - imported_model->getObjectReferences(constr->getColumn(i, Constraint::SOURCE_COLS), ref_aux, false, true); + imported_model->getObjectReferences(constr->getColumn(i, Constraint::SourceCols), ref_aux, false, true); //Selecting only fks from the references list for(BaseObject *obj : ref_aux) { aux_constr=dynamic_cast(obj); - if(aux_constr && aux_constr->getConstraintType()==ConstraintType::foreign_key) + if(aux_constr && aux_constr->getConstraintType()==ConstraintType::ForeignKey) ref_objs.push_back(aux_constr); } } @@ -1035,13 +1060,13 @@ void ModelsDiffHelper::recreateObject(BaseObject *object, vector & /* Register a drop info for the object only if there is no drop registered previously, avoiding multiple drop statments for the same object */ - if(aux_obj && !isDiffInfoExists(ObjectsDiffInfo::DROP_OBJECT, aux_obj, nullptr)) + if(aux_obj && !isDiffInfoExists(ObjectsDiffInfo::DropObject, aux_obj, nullptr)) drop_objs.push_back(aux_obj); /* Register a create info for the object only if there is no drop or create registered previously, avoiding wrongly recreating the object */ - if(!isDiffInfoExists(ObjectsDiffInfo::DROP_OBJECT, aux_obj, nullptr) && - !isDiffInfoExists(ObjectsDiffInfo::CREATE_OBJECT, aux_obj, nullptr)) + if(!isDiffInfoExists(ObjectsDiffInfo::DropObject, aux_obj, nullptr) && + !isDiffInfoExists(ObjectsDiffInfo::CreateObject, aux_obj, nullptr)) create_objs.push_back(object); //Executing the recreation of the object's references diff --git a/libpgmodeler_ui/src/modelsdiffhelper.h b/libpgmodeler_ui/src/modelsdiffhelper.h index 8a0b2534de..62716eb394 100644 --- a/libpgmodeler_ui/src/modelsdiffhelper.h +++ b/libpgmodeler_ui/src/modelsdiffhelper.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -33,6 +33,15 @@ class ModelsDiffHelper: public QObject { private: Q_OBJECT + //! \brief List of attributes ignored when comparing XML code of table children objects + static const vector TableObjsIgnoredAttribs, + + //! \brief List of attributes ignored when comparing XML code of database objects + ObjectsIgnoredAttribs, + + //! \brief List of tags ignored when comparing XML code of database objects + ObjectsIgnoredTags; + //! \brief Stores the SQL code that represents the diff between model and database QString diff_def, @@ -99,41 +108,41 @@ class ModelsDiffHelper: public QObject { BaseObject *getRelNNTable(const QString &obj_name, DatabaseModel *model); public: - static const unsigned OPT_KEEP_CLUSTER_OBJS=0, + static constexpr unsigned OptKeepClusterObjs=0, //! \brief Indicates if any DROP/TRUNCATE generated must be in cascade mode - OPT_CASCADE_MODE=1, + OptCascadeMode=1, //! \brief Forces the recreation of any object maked as ALTER in the output - OPT_FORCE_RECREATION=2, + OptForceRecreation=2, //! \brief Recreates only objects that can't be modified using ALTER commands - OPT_RECREATE_UNCHANGEBLE=3, + OptRecreateUnchangeble=3, //! \brief Generate a TRUNCATE command for every table which columns was modified in their data types - OPT_TRUCANTE_TABLES=4, + OptTruncateTables=4, //! \brief Indicates if permissions must be preserved on database - OPT_KEEP_OBJ_PERMS=5, + OptKeepObjectPerms=5, /*! \brief Indicates that existing sequences must be reused in serial columns. Since serial columns are converted into integer and a new sequence created and assigned as nextval(sequence) default value for those columns, if reuse is enabled, new sequences will not be created instead the ones which name matches the column's default value will be reused */ - OPT_REUSE_SEQUENCES=6, + OptReuseSequences=6, //! \brief Indicates to not generate and execute commands to rename the destination database - OPT_PRESERVE_DB_NAME=7, + OptPreserveDbName=7, /*! \brief Indicates to not generate and execute commands to drop missing objects. For instance, if user try to diff a partial model against the original database DROP commands will be generated, this option will avoid this situation and preserve the missing (not imported) objects. */ - OPT_DONT_DROP_MISSING_OBJS=8, + OptDontDropMissingObjs=8, /*! \brief Indicates to generate and execute commands to drop missing columns and constraints. For instance, if user try to diff a partial model against the original database and the OPT_DONT_DROP_MISSING_OBJS is set, DROP commands will not be generated, except for columns and constraints. This option is only considered in the process when OPT_DONT_DROP_MISSING_OBJS is enabled. */ - OPT_DROP_MISSING_COLS_CONSTR=9; + OptDropMissingColsConstr=9; ModelsDiffHelper(void); ~ModelsDiffHelper(void); @@ -164,7 +173,7 @@ class ModelsDiffHelper: public QObject { signals: //! \brief This singal is emitted whenever the diff progress changes - void s_progressUpdated(int progress, QString msg, ObjectType obj_type=BASE_OBJECT); + void s_progressUpdated(int progress, QString msg, ObjectType obj_type=ObjectType::BaseObject); //! \brief This signal is emited when the diff has finished void s_diffFinished(void); diff --git a/libpgmodeler_ui/src/modelvalidationhelper.cpp b/libpgmodeler_ui/src/modelvalidationhelper.cpp index f53c0ff65a..24d40cfaee 100644 --- a/libpgmodeler_ui/src/modelvalidationhelper.cpp +++ b/libpgmodeler_ui/src/modelvalidationhelper.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -46,7 +46,8 @@ ModelValidationHelper::~ModelValidationHelper(void) void ModelValidationHelper::generateValidationInfo(unsigned val_type, BaseObject *object, vector refs) { if(!refs.empty() || - (val_type==ValidationInfo::BROKEN_REL_CONFIG && + val_type==ValidationInfo::MissingExtension || + (val_type==ValidationInfo::BrokenRelConfig && std::find(inv_rels.begin(), inv_rels.end(), object)==inv_rels.end())) { //Configures a validation info @@ -54,7 +55,7 @@ void ModelValidationHelper::generateValidationInfo(unsigned val_type, BaseObject error_count++; val_infos.push_back(info); - if(val_type==ValidationInfo::BROKEN_REL_CONFIG) + if(val_type==ValidationInfo::BrokenRelConfig) inv_rels.push_back(object); //Emit the signal containing the info @@ -70,13 +71,13 @@ void ModelValidationHelper::resolveConflict(ValidationInfo &info) BaseObject *obj=nullptr; //Resolving broken references by swaping the object ids - if(info.getValidationType()==ValidationInfo::BROKEN_REFERENCE || - info.getValidationType()==ValidationInfo::SP_OBJ_BROKEN_REFERENCE) + if(info.getValidationType()==ValidationInfo::BrokenReference || + info.getValidationType()==ValidationInfo::SpObjBrokenReference) { BaseObject *info_obj=info.getObject(), *aux_obj=nullptr; unsigned obj_id=info_obj->getObjectId(); - if(info.getValidationType()==ValidationInfo::BROKEN_REFERENCE) + if(info.getValidationType()==ValidationInfo::BrokenReference) { //Search for the object with the minor id while(!refs.empty() && !valid_canceled) @@ -105,7 +106,7 @@ void ModelValidationHelper::resolveConflict(ValidationInfo &info) } } - if(aux_obj && (aux_obj->getObjectType()==OBJ_VIEW || aux_obj->getObjectType()==OBJ_TABLE)) + if(aux_obj && (aux_obj->getObjectType()==ObjectType::View || aux_obj->getObjectType()==ObjectType::Table)) { vector base_rels=db_model->getRelationships(dynamic_cast(aux_obj)); for(auto &rel : base_rels) @@ -131,7 +132,7 @@ void ModelValidationHelper::resolveConflict(ValidationInfo &info) emit s_objectIdChanged(info_obj); } //Resolving no unique name by renaming the constraints/indexes - else if(info.getValidationType()==ValidationInfo::NO_UNIQUE_NAME) + else if(info.getValidationType()==ValidationInfo::NoUniqueName) { unsigned suffix=1; QString new_name; @@ -142,8 +143,8 @@ void ModelValidationHelper::resolveConflict(ValidationInfo &info) /* If the last element of the referrer objects is a table or view the info object itself need to be renamed since tables and views will not be renamed */ - bool rename_obj=(refs.back()->getObjectType()==OBJ_TABLE || - refs.back()->getObjectType()==OBJ_VIEW); + bool rename_obj=(refs.back()->getObjectType()==ObjectType::Table || + refs.back()->getObjectType()==ObjectType::View); if(rename_obj) { @@ -190,10 +191,17 @@ void ModelValidationHelper::resolveConflict(ValidationInfo &info) refs.pop_back(); } } + //Resolving the absence of postgis extension + else if(info.getValidationType()==ValidationInfo::MissingExtension && !db_model->getExtension(QString("postgis"))) + { + Extension *extension = new Extension(); + extension->setName(QString("postgis")); + db_model->addExtension(extension); + } } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -225,7 +233,7 @@ void ModelValidationHelper::redirectExportProgress(int prog, QString msg, Object void ModelValidationHelper::setValidationParams(DatabaseModel *model, Connection *conn, const QString &pgsql_ver, bool use_tmp_names) { if(!model) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); fix_mode=false; valid_canceled=false; @@ -251,15 +259,16 @@ bool ModelValidationHelper::isInFixMode() void ModelValidationHelper::validateModel(void) { if(!db_model) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { - ObjectType types[]={ OBJ_ROLE, OBJ_TABLESPACE, OBJ_SCHEMA, OBJ_LANGUAGE, OBJ_FUNCTION, - OBJ_TYPE, OBJ_DOMAIN, OBJ_SEQUENCE, OBJ_OPERATOR, OBJ_OPFAMILY, - OBJ_OPCLASS, OBJ_COLLATION, OBJ_TABLE, OBJ_EXTENSION, OBJ_VIEW, OBJ_RELATIONSHIP }, - aux_types[]={ OBJ_TABLE, OBJ_VIEW }, - tab_obj_types[]={ OBJ_CONSTRAINT, OBJ_INDEX }, + ObjectType types[]={ ObjectType::Role, ObjectType::Tablespace, ObjectType::Schema, ObjectType::Language, ObjectType::Function, + ObjectType::Type, ObjectType::Domain, ObjectType::Sequence, ObjectType::Operator, ObjectType::OpFamily, + ObjectType::OpClass, ObjectType::Collation, ObjectType::Table, ObjectType::Extension, ObjectType::View, + ObjectType::Relationship, ObjectType::ForeignDataWrapper, ObjectType::ForeignServer, ObjectType::GenericSql }, + aux_types[]={ ObjectType::Table, ObjectType::View }, + tab_obj_types[]={ ObjectType::Constraint, ObjectType::Index }, obj_type; unsigned i, i1, cnt, aux_cnt=sizeof(aux_types)/sizeof(ObjectType), count=sizeof(types)/sizeof(ObjectType), count1=sizeof(tab_obj_types)/sizeof(ObjectType); @@ -274,13 +283,14 @@ void ModelValidationHelper::validateModel(void) map > dup_objects; map >::iterator mitr; QString name, signal_msg=QString("`%1' (%2)"); + bool postgis_exists = db_model->getObjectIndex(QString("postgis"), ObjectType::Extension) >= 0; warn_count=error_count=progress=0; val_infos.clear(); valid_canceled=false; /* Step 1: Validating broken references. This situation happens when a object references another - whose id is smaller than the id of the first one. */ + which id is smaller than the id of the first one. */ for(i=0; i < count && !valid_canceled; i++) { obj_list=db_model->getObjectList(types[i]); @@ -299,12 +309,12 @@ void ModelValidationHelper::validateModel(void) emit s_objectProcessed(signal_msg.arg(object->getName()).arg(object->getTypeName()), object->getObjectType()); /* Special validation case: For generalization and copy relationships validates the ids of participant tables. - * Reference table cannot own an id greater thant receiver table */ - if(obj_type==OBJ_RELATIONSHIP) + Reference table cannot own an id greater thant receiver table */ + if(obj_type==ObjectType::Relationship) { rel=dynamic_cast(object); - if(rel->getRelationshipType()==Relationship::RELATIONSHIP_GEN || - rel->getRelationshipType()==Relationship::RELATIONSHIP_DEP) + if(rel->getRelationshipType()==Relationship::RelationshipGen || + rel->getRelationshipType()==Relationship::RelationshipDep) { recv_tab=rel->getReceiverTable(); ref_tab=rel->getReferenceTable(); @@ -328,14 +338,13 @@ void ModelValidationHelper::validateModel(void) col=dynamic_cast(tab_obj); /* If the current referrer object has an id less than reference object's id - then it will be pushed into the list of invalid references. The only exception is - for foreign keys that are discarded from any validation since they are always created - at end of code defintion being free of any reference breaking. */ + * then it will be pushed into the list of invalid references. The only exception is + * for foreign keys that are discarded from any validation since they are always created + * at end of code defintion being free of any reference breaking. */ if(object != refs.back() && ( - ((col || (constr && constr->getConstraintType()!=ConstraintType::foreign_key)) && - (tab_obj->getParentTable()->getObjectId() <= object->getObjectId())) - || + ((col || (constr && constr->getConstraintType()!=ConstraintType::ForeignKey)) && + (tab_obj->getParentTable()->getObjectId() <= object->getObjectId())) || (!constr && refs.back()->getObjectId() <= object->getObjectId())) ) { @@ -351,26 +360,28 @@ void ModelValidationHelper::validateModel(void) } /* Validating a special object. The validation made here is to check if the special object - (constraint/index/trigger/view) references a column added by a relationship and - that relationship is being created after the creation of the special object */ - if(obj_type==OBJ_TABLE || obj_type==OBJ_VIEW /* || obj_type==OBJ_SEQUENCE */) + * (constraint/index/trigger/view) references a column added by a relationship and + * that relationship is being created after the creation of the special object */ + if(obj_type==ObjectType::Table || obj_type==ObjectType::View || obj_type == ObjectType::GenericSql) { - vector tab_aux_types={ OBJ_CONSTRAINT, OBJ_TRIGGER, OBJ_INDEX }; + vector tab_aux_types={ ObjectType::Constraint, ObjectType::Trigger, ObjectType::Index }; vector *tab_objs; vector ref_cols; vector rels; BaseObject *rel=nullptr; View *view=nullptr; + GenericSQL *gen_sql=nullptr; Constraint *constr=nullptr; table=dynamic_cast
(object); view=dynamic_cast(object); + gen_sql = dynamic_cast(object); if(table) { /* Checking the table children objects if they references some columns added by relationship. - If so, the id of the relationships are swapped with the child object if the first is created - after the latter. */ + * If so, the id of the relationships are swapped with the child object if the first is created + * after the latter. */ for(auto &obj_tp : tab_aux_types) { tab_objs = table->getObjectList(obj_tp); @@ -382,14 +393,14 @@ void ModelValidationHelper::validateModel(void) if(!tab_obj->isAddedByRelationship()) { - if(obj_tp==OBJ_CONSTRAINT) + if(obj_tp==ObjectType::Constraint) { constr=dynamic_cast(tab_obj); - if(constr->getConstraintType()!=ConstraintType::primary_key) + if(constr->getConstraintType()!=ConstraintType::PrimaryKey) ref_cols=constr->getRelationshipAddedColumns(); } - else if(obj_tp==OBJ_TRIGGER) + else if(obj_tp==ObjectType::Trigger) ref_cols=dynamic_cast(tab_obj)->getRelationshipAddedColumns(); else ref_cols=dynamic_cast(tab_obj)->getRelationshipAddedColumns(); @@ -403,11 +414,11 @@ void ModelValidationHelper::validateModel(void) rels.push_back(rel); } - generateValidationInfo(ValidationInfo::SP_OBJ_BROKEN_REFERENCE, tab_obj, rels); + generateValidationInfo(ValidationInfo::SpObjBrokenReference, tab_obj, rels); } } } - else + else if(view) { ref_cols=view->getRelationshipAddedColumns(); @@ -419,24 +430,41 @@ void ModelValidationHelper::validateModel(void) rels.push_back(rel); } - generateValidationInfo(ValidationInfo::SP_OBJ_BROKEN_REFERENCE, object, rels); + generateValidationInfo(ValidationInfo::SpObjBrokenReference, object, rels); + } + else + { + Column *col = nullptr; + + for(auto &ref_obj : gen_sql->getReferencedObjects()) + { + col = dynamic_cast(ref_obj); + if(!col) continue; + + rel = col->getParentRelationship(); + + if(rel->getObjectId() > object->getObjectId() && std::find(rels.begin(), rels.end(), rel) == rels.end()) + rels.push_back(rel); + } + + generateValidationInfo(ValidationInfo::SpObjBrokenReference, object, rels); } } } - generateValidationInfo(ValidationInfo::BROKEN_REFERENCE, object, refs_aux); + generateValidationInfo(ValidationInfo::BrokenReference, object, refs_aux); } } //Emit a signal containing the validation progress - progress=((i+1)/static_cast(count))*20; + progress=((i+1)/static_cast(count))*20; emit s_progressUpdated(progress, QString()); } /* Step 2: Validating name conflitcs between primary keys, unique keys, exclude constraints and indexs of all tables/views. The table and view names are checked too. */ - obj_list=db_model->getObjectList(OBJ_TABLE); + obj_list=db_model->getObjectList(ObjectType::Table); itr=obj_list->begin(); //Searching the model's tables and gathering all the constraints and index @@ -466,9 +494,9 @@ void ModelValidationHelper::validateModel(void) /* If the object is an index or a primary key, unique or exclude constraint, insert the object on duplicated objects map */ if((!constr || - (constr && (constr->getConstraintType()==ConstraintType::primary_key || - constr->getConstraintType()==ConstraintType::unique || - constr->getConstraintType()==ConstraintType::exclude)))) + (constr && (constr->getConstraintType()==ConstraintType::PrimaryKey || + constr->getConstraintType()==ConstraintType::Unique || + constr->getConstraintType()==ConstraintType::Exclude)))) dup_objects[name].push_back(tab_obj); } } @@ -497,39 +525,61 @@ void ModelValidationHelper::validateModel(void) if(mitr->second.size() > 1) { refs.assign(mitr->second.begin() + 1, mitr->second.end()); - generateValidationInfo(ValidationInfo::NO_UNIQUE_NAME, mitr->second.front(), refs); + generateValidationInfo(ValidationInfo::NoUniqueName, mitr->second.front(), refs); refs.clear(); } //Emit a signal containing the validation progress - progress=20 + ((i/static_cast(dup_objects.size()))*20); + progress=20 + ((i/static_cast(dup_objects.size()))*20); emit s_progressUpdated(progress, QString()); i++; mitr++; } + // Step 3: Checking if columns of any table is using GiS data types and the postgis extension is not created. + if(!postgis_exists) + { + obj_list=db_model->getObjectList(ObjectType::Table); + itr=obj_list->begin(); + i=0; + + while(itr!=obj_list->end() && !valid_canceled) + { + table = dynamic_cast
(*itr); + itr++; + + for(auto &obj : *table->getObjectList(ObjectType::Column)) + { + col = dynamic_cast(obj); - /* Step 3: Checking if there are some invalidated relationship. In some cases, specially with identifier and generalization relationships, + if(col->getType().isGiSType()) + generateValidationInfo(ValidationInfo::MissingExtension, col, {}); + } + + progress=30 + ((i/static_cast(obj_list->size()))*20); + } + } + + /* Step 4: Checking if there are some invalidated relationship. In some cases, specially with identifier and generalization relationships, the columns aren't correctly propagated due to creation order and special behavior of those objects. Thus, in order to keep all columns synchonized it is need to make this step and change the relationship creation order if needed. This step is executed only when there is no validation infos generated because for each broken relationship there is the need to do a revalidation of all relationships */ if(val_infos.empty()) { - obj_list=db_model->getObjectList(OBJ_RELATIONSHIP); - itr=db_model->getObjectList(OBJ_RELATIONSHIP)->begin(); + obj_list=db_model->getObjectList(ObjectType::Relationship); + itr=db_model->getObjectList(ObjectType::Relationship)->begin(); while(itr!=obj_list->end() && !valid_canceled) { - progress=30 + ((i/static_cast(obj_list->size()))*20); + progress=40 + ((i/static_cast(obj_list->size()))*20); if(dynamic_cast(*itr)->isInvalidated()) - generateValidationInfo(ValidationInfo::BROKEN_REL_CONFIG, *itr, {}); + generateValidationInfo(ValidationInfo::BrokenRelConfig, *itr, {}); itr++; } } - if(!valid_canceled && !fix_mode) { //Step 3 (optional): Validating the SQL code onto a local DBMS. @@ -559,7 +609,7 @@ void ModelValidationHelper::validateModel(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -574,14 +624,15 @@ void ModelValidationHelper::applyFixes(void) for(unsigned i=0; i < val_infos.size() && !valid_canceled; i++) { if(!validate_rels) - validate_rels=(val_infos[i].getValidationType()==ValidationInfo::BROKEN_REFERENCE || - val_infos[i].getValidationType()==ValidationInfo::SP_OBJ_BROKEN_REFERENCE || - val_infos[i].getValidationType()==ValidationInfo::NO_UNIQUE_NAME); + validate_rels=(val_infos[i].getValidationType()==ValidationInfo::BrokenReference || + val_infos[i].getValidationType()==ValidationInfo::SpObjBrokenReference || + val_infos[i].getValidationType()==ValidationInfo::NoUniqueName || + val_infos[i].getValidationType()==ValidationInfo::MissingExtension); /* Checking if a broken relatinship is found, when this is the case all the pending validation info will not be analyzed until no broken relationship is found */ if(!found_broken_rels) - found_broken_rels=(val_infos[i].getValidationType()==ValidationInfo::BROKEN_REL_CONFIG); + found_broken_rels=(val_infos[i].getValidationType()==ValidationInfo::BrokenRelConfig); if(!valid_canceled) resolveConflict(val_infos[i]); @@ -626,7 +677,7 @@ void ModelValidationHelper::captureThreadError(Exception e) emit s_validationInfoGenerated(val_info); - if(val_info.getValidationType()==ValidationInfo::SQL_VALIDATION_ERR) + if(val_info.getValidationType()==ValidationInfo::SqlValidationError) emit s_validationFinished(); } diff --git a/libpgmodeler_ui/src/modelvalidationhelper.h b/libpgmodeler_ui/src/modelvalidationhelper.h index abde765d10..58bcb66479 100644 --- a/libpgmodeler_ui/src/modelvalidationhelper.h +++ b/libpgmodeler_ui/src/modelvalidationhelper.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -113,7 +113,7 @@ class ModelValidationHelper: public QObject { void s_validationInfoGenerated(ValidationInfo val_info); //! \brief This signal is emitted when the validation progress changes - void s_progressUpdated(int prog, QString msg, ObjectType obj_type=BASE_OBJECT, QString cmd=QString(), bool is_code_gen=false); + void s_progressUpdated(int prog, QString msg, ObjectType obj_type=ObjectType::BaseObject, QString cmd=QString(), bool is_code_gen=false); //! \brief This signal is emitted when the object is processed by the validator void s_objectProcessed(QString obj_name, ObjectType obj_type); diff --git a/libpgmodeler_ui/src/modelvalidationwidget.cpp b/libpgmodeler_ui/src/modelvalidationwidget.cpp index 9319a73cff..2e07067fb6 100644 --- a/libpgmodeler_ui/src/modelvalidationwidget.cpp +++ b/libpgmodeler_ui/src/modelvalidationwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -30,7 +30,7 @@ ModelValidationWidget::ModelValidationWidget(QWidget *parent): QWidget(parent) output_trw->setItemDelegateForColumn(0, htmlitem_del); version_cmb->addItem(trUtf8("Autodetect")); - version_cmb->addItems(PgSQLVersions::ALL_VERSIONS); + version_cmb->addItems(PgSqlVersions::AllVersions); options_frm->setVisible(false); curr_step=0; @@ -61,10 +61,33 @@ ModelValidationWidget::ModelValidationWidget(QWidget *parent): QWidget(parent) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } +bool ModelValidationWidget::eventFilter(QObject *object, QEvent *event) +{ + QMouseEvent *m_event=dynamic_cast(event); + + //Executes the search when user press enter/return on the pattern field + if(m_event && m_event->buttons() == Qt::RightButton) + { + QLabel *label = dynamic_cast(object); + + if(label->hasSelectedText()) + { + label->setContextMenuPolicy(Qt::DefaultContextMenu); + } + else + { + label->setContextMenuPolicy(Qt::NoContextMenu); + selectObject(); + } + } + + return(QWidget::eventFilter(object, event)); +} + void ModelValidationWidget::createThread(void) { if(!validation_thread) @@ -171,6 +194,8 @@ void ModelValidationWidget::clearOutput(void) prog_info_wgt->setVisible(false); fix_btn->setEnabled(false); validation_prog_pb->setValue(0); + warn_lbl->setEnabled(false); + error_lbl->setEnabled(false); warn_count_lbl->setText(QString("%1").arg(0)); error_count_lbl->setText(QString("%1").arg(0)); } @@ -206,7 +231,7 @@ bool ModelValidationWidget::isValidationRunning(void) void ModelValidationWidget::updateValidation(ValidationInfo val_info) { if(validation_thread && - val_info.getValidationType()!=ValidationInfo::VALIDATION_ABORTED && + val_info.getValidationType()!=ValidationInfo::ValidationAborted && !validation_thread->isRunning() && validation_helper->isValidationCanceled()) return; @@ -217,15 +242,18 @@ void ModelValidationWidget::updateValidation(ValidationInfo val_info) BaseTable *table=nullptr; TableObject *tab_obj=nullptr; QString ref_name; + BaseObject *ref_obj=nullptr; + label->installEventFilter(this); label->setTextInteractionFlags(Qt::TextSelectableByMouse); - if(val_info.getValidationType()==ValidationInfo::BROKEN_REFERENCE) + + if(val_info.getValidationType()==ValidationInfo::BrokenReference) label->setText(trUtf8("The object %1 (%2) [id: %3] is being referenced by %4 object(s) before its creation.") .arg(val_info.getObject()->getName(true).remove('"')) .arg(val_info.getObject()->getTypeName()) .arg(val_info.getObject()->getObjectId()) .arg(val_info.getReferences().size())); - else if(val_info.getValidationType()==ValidationInfo::SP_OBJ_BROKEN_REFERENCE) + else if(val_info.getValidationType()==ValidationInfo::SpObjBrokenReference) { QString str_aux; @@ -242,7 +270,7 @@ void ModelValidationWidget::updateValidation(ValidationInfo val_info) .arg(str_aux) .arg(val_info.getReferences().size())); } - else if(val_info.getValidationType()==ValidationInfo::NO_UNIQUE_NAME) + else if(val_info.getValidationType()==ValidationInfo::NoUniqueName) { tab_obj=dynamic_cast(val_info.getObject()); @@ -254,32 +282,44 @@ void ModelValidationWidget::updateValidation(ValidationInfo val_info) else ref_name=val_info.getObject()->getName(true).remove('"'); - label->setText(trUtf8("The object %1 (%2) has a name that conflicts with %3 object's name(s).") + label->setText(trUtf8("The object %1 (%2) has a name that conflicts with %3 object name(s).") .arg(ref_name) .arg(val_info.getObject()->getTypeName()) .arg(val_info.getReferences().size())); } - else if(val_info.getValidationType()==ValidationInfo::BROKEN_REL_CONFIG) + else if(val_info.getValidationType()==ValidationInfo::BrokenRelConfig) label->setText(trUtf8("The relationship %1 [id: %2] is in a permanent invalidation state and needs to be relocated.") .arg(val_info.getObject()->getName(true).remove('"')) .arg(val_info.getObject()->getObjectId())); - else if(val_info.getValidationType()==ValidationInfo::SQL_VALIDATION_ERR) - label->setText(trUtf8("SQL validation failed due to error(s) below. NOTE: These errors does not invalidates the model but may affect operations like export and diff.")); + else if(val_info.getValidationType()==ValidationInfo::SqlValidationError) + label->setText(trUtf8("SQL validation failed due to the error(s) below. NOTE: Errors during SQL validation don't invalidate the model but may affect operations like export and diff.")); + else if(val_info.getValidationType() == ValidationInfo::MissingExtension) + { + Column *col = dynamic_cast(val_info.getObject()); + + label->setText(trUtf8("The column %1 on %2 (%3) is referencing the geospatial data type %4 but the postgis extension is not present in the model!") + .arg(col->getName()) + .arg(col->getParentTable()->getSignature(true)) + .arg(BaseObject::getTypeName(ObjectType::Table)) + .arg(~col->getType())); + } else label->setText(val_info.getErrors().at(0)); + /* Store the reference of the object in order to allow opening the editing form when the user clicks the item on the output + * So the needed fixes can be done manually */ + item->setData(1, Qt::UserRole, QVariant::fromValue(reinterpret_cast(val_info.getObject()))); - if(val_info.getValidationType()==ValidationInfo::SQL_VALIDATION_ERR || - val_info.getValidationType()==ValidationInfo::VALIDATION_ABORTED) + if(val_info.getValidationType()==ValidationInfo::SqlValidationError || + val_info.getValidationType()==ValidationInfo::ValidationAborted) { QStringList errors=val_info.getErrors(); - QFont fnt; - item->setIcon(0, QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta"))); + item->setIcon(0, QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta"))); validation_prog_pb->setValue(validation_prog_pb->maximum()); reenableValidation(); - if(val_info.getValidationType()==ValidationInfo::SQL_VALIDATION_ERR) + if(val_info.getValidationType()==ValidationInfo::SqlValidationError) { //Adding all the sql errors into the output pane while(!errors.isEmpty()) @@ -289,9 +329,6 @@ void ModelValidationWidget::updateValidation(ValidationInfo val_info) label1->setTextInteractionFlags(Qt::TextSelectableByMouse); label1->setText(errors.back()); label1->setTextInteractionFlags(Qt::TextSelectableByMouse); - fnt=label1->font(); - fnt.setPointSizeF(8.0f); - label1->setFont(fnt); output_trw->setItemWidget(item1, 0, label1); errors.pop_back(); } @@ -299,12 +336,17 @@ void ModelValidationWidget::updateValidation(ValidationInfo val_info) } else { - item->setIcon(0, QPixmap(PgModelerUiNS::getIconPath("msgbox_erro"))); + item->setIcon(0, QPixmap(PgModelerUiNs::getIconPath("msgbox_erro"))); - if(val_info.getValidationType()==ValidationInfo::BROKEN_REL_CONFIG) + if(val_info.getValidationType()==ValidationInfo::BrokenRelConfig) { - PgModelerUiNS::createOutputTreeItem(output_trw, trUtf8("HINT: try to swap the relationship by another ones that somehow are linked to it through generated columns or constraints to solve this issue. Note that other objects may be lost in the swap process."), - QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta")), item); + PgModelerUiNs::createOutputTreeItem(output_trw, trUtf8("HINT: try to swap the relationship by another ones that somehow are linked to it through generated columns or constraints to solve this issue. Note that other objects may be lost in the swap process."), + QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta")), item); + } + else if(val_info.getValidationType()==ValidationInfo::MissingExtension) + { + PgModelerUiNs::createOutputTreeItem(output_trw, trUtf8("HINT: Create the extension in the model or let it be created by applying the needed fixes."), + QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta")), item); } else { @@ -312,18 +354,26 @@ void ModelValidationWidget::updateValidation(ValidationInfo val_info) refs=val_info.getReferences(); while(!refs.empty()) { + ref_obj = refs.back(); + item1=new QTreeWidgetItem(item); label1=new QLabel; label1->setTextInteractionFlags(Qt::TextSelectableByMouse); - item1->setIcon(0, QPixmap(PgModelerUiNS::getIconPath(refs.back()->getSchemaName()))); - tab_obj=dynamic_cast(refs.back()); - ref_name=refs.back()->getName(true); + label1->installEventFilter(this); + item1->setIcon(0, QPixmap(PgModelerUiNs::getIconPath(ref_obj->getSchemaName()))); + + /* Store the reference of the referrer object in order to allow opening the editing form when the user clicks the item on the output + * So the needed fixes can be done manually */ + item1->setData(1, Qt::UserRole, QVariant::fromValue(reinterpret_cast(ref_obj))); + + tab_obj=dynamic_cast(ref_obj); + ref_name=ref_obj->getName(true); if(tab_obj) - ref_name=dynamic_cast(refs.back())->getParentTable()->getName(true) + QString(".") + ref_name; + ref_name=dynamic_cast(ref_obj)->getParentTable()->getName(true) + QString(".") + ref_name; - if(val_info.getValidationType()==ValidationInfo::NO_UNIQUE_NAME) + if(val_info.getValidationType()==ValidationInfo::NoUniqueName) { //If the referrer object is a table object, concatenates the parent table name if(tab_obj) @@ -344,20 +394,20 @@ void ModelValidationWidget::updateValidation(ValidationInfo val_info) label1->setText(trUtf8("Conflicting object: %1 (%2).") .arg(ref_name.remove('"')) - .arg(refs.back()->getTypeName())); + .arg(ref_obj->getTypeName())); } else { - if(val_info.getValidationType()==ValidationInfo::SP_OBJ_BROKEN_REFERENCE) + if(val_info.getValidationType()==ValidationInfo::SpObjBrokenReference) label1->setText(trUtf8("Relationship: %1 [id: %2].") .arg(ref_name.remove('"')) - .arg(refs.back()->getObjectId())); + .arg(ref_obj->getObjectId())); else { label1->setText(trUtf8("Referrer object: %1 (%2) [id: %3].") .arg(ref_name.remove('"')) - .arg(refs.back()->getTypeName()) - .arg(refs.back()->getObjectId())); + .arg(ref_obj->getTypeName()) + .arg(ref_obj->getObjectId())); } } @@ -373,12 +423,14 @@ void ModelValidationWidget::updateValidation(ValidationInfo val_info) //Stores the validatin on the current tree item item->setData(0, Qt::UserRole, QVariant::fromValue(val_info)); + warn_lbl->setEnabled(validation_helper->getWarningCount() > 0); + error_lbl->setEnabled(validation_helper->getErrorCount() > 0); warn_count_lbl->setText(QString("%1").arg(validation_helper->getWarningCount())); error_count_lbl->setText(QString("%1").arg(validation_helper->getErrorCount())); output_trw->setItemHidden(item, false); output_trw->scrollToBottom(); - if(val_info.getValidationType()==ValidationInfo::SQL_VALIDATION_ERR) + if(val_info.getValidationType()==ValidationInfo::SqlValidationError) emit s_validationFinished(validation_helper->getErrorCount() != 0); } @@ -414,22 +466,27 @@ void ModelValidationWidget::updateProgress(int prog, QString msg, ObjectType obj validation_helper->getErrorCount()==0 && validation_helper->getWarningCount()==0) { + error_lbl->setEnabled(false); error_count_lbl->setText(QString::number(0)); fix_btn->setEnabled(false); if(sql_validation_chk->isChecked() && connections_cmb->currentIndex() <= 0) { + warn_lbl->setEnabled(true); warn_count_lbl->setText(QString::number(1)); - PgModelerUiNS::createOutputTreeItem(output_trw, + PgModelerUiNs::createOutputTreeItem(output_trw, trUtf8("SQL validation not executed! No connection defined."), - QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta"))); + QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta"))); } else + { + warn_lbl->setEnabled(false); warn_count_lbl->setText(QString::number(0)); + } - PgModelerUiNS::createOutputTreeItem(output_trw, + PgModelerUiNs::createOutputTreeItem(output_trw, trUtf8("Database model successfully validated."), - QPixmap(PgModelerUiNS::getIconPath("msgbox_info"))); + QPixmap(PgModelerUiNs::getIconPath("msgbox_info"))); emit s_validationFinished(validation_helper->getErrorCount() != 0); } @@ -437,14 +494,14 @@ void ModelValidationWidget::updateProgress(int prog, QString msg, ObjectType obj { QPixmap ico; - msg=PgModelerUiNS::formatMessage(msg); + msg=PgModelerUiNs::formatMessage(msg); - if(obj_type!=BASE_OBJECT) - ico=QPixmap(PgModelerUiNS::getIconPath(obj_type)); + if(obj_type!=ObjectType::BaseObject) + ico=QPixmap(PgModelerUiNs::getIconPath(obj_type)); else if(!cmd.isEmpty()) - ico=QPixmap(PgModelerUiNS::getIconPath("sqlcmd")); + ico=QPixmap(PgModelerUiNs::getIconPath("sqlcmd")); else - ico=QPixmap(PgModelerUiNS::getIconPath("msgbox_info")); + ico=QPixmap(PgModelerUiNs::getIconPath("msgbox_info")); if(is_code_gen) { @@ -453,21 +510,21 @@ void ModelValidationWidget::updateProgress(int prog, QString msg, ObjectType obj } else { - ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("codigosql"))); + ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("codigosql"))); object_lbl->setText(trUtf8("Running SQL commands on server...")); - item=PgModelerUiNS::createOutputTreeItem(output_trw, msg, ico, nullptr, false); + item=PgModelerUiNs::createOutputTreeItem(output_trw, msg, ico, nullptr, false); if(!cmd.isEmpty()) - PgModelerUiNS::createOutputTreeItem(output_trw, cmd, QPixmap(), item, false); + PgModelerUiNs::createOutputTreeItem(output_trw, cmd, QPixmap(), item, false); } } } void ModelValidationWidget::updateObjectName(QString obj_name, ObjectType obj_type) { - object_lbl->setText(trUtf8("Processing object: %1").arg(PgModelerUiNS::formatMessage(obj_name))); - ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath(obj_type))); + object_lbl->setText(trUtf8("Processing object: %1").arg(PgModelerUiNs::formatMessage(obj_name))); + ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath(obj_type))); } void ModelValidationWidget::configureValidation(void) @@ -560,5 +617,24 @@ void ModelValidationWidget::swapObjectsIds(void) SwapObjectsIdsWidget *swap_ids_wgt=new SwapObjectsIdsWidget; swap_ids_wgt->setModel(model_wgt->getDatabaseModel()); parent_form.setMainWidget(swap_ids_wgt); + + GeneralConfigWidget::restoreWidgetGeometry(&parent_form, this->metaObject()->className()); parent_form.exec(); + GeneralConfigWidget::saveWidgetGeometry(&parent_form, this->metaObject()->className()); +} + +void ModelValidationWidget::selectObject(void) +{ + QTreeWidgetItem *item = output_trw->currentItem(); + + if(item && !validation_thread->isRunning()) + { + BaseObject *selected_obj=reinterpret_cast(item->data(1, Qt::UserRole).value()); + + if(selected_obj && QApplication::mouseButtons() == Qt::RightButton) + { + model_wgt->configureObjectMenu(selected_obj); + model_wgt->showObjectMenu(); + } + } } diff --git a/libpgmodeler_ui/src/modelvalidationwidget.h b/libpgmodeler_ui/src/modelvalidationwidget.h index aecc877b39..a58d6609e5 100644 --- a/libpgmodeler_ui/src/modelvalidationwidget.h +++ b/libpgmodeler_ui/src/modelvalidationwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -70,11 +70,14 @@ class ModelValidationWidget: public QWidget, public Ui::ModelValidationWidget { void configureValidation(void); + void selectObject(void); + protected: void resizeEvent(QResizeEvent *event); + bool eventFilter(QObject *object, QEvent *event); public: - ModelValidationWidget(QWidget * parent = 0); + ModelValidationWidget(QWidget * parent = nullptr); //! \brief Sets the database model to work on void setModel(ModelWidget *model_wgt); diff --git a/libpgmodeler_ui/src/modelwidget.cpp b/libpgmodeler_ui/src/modelwidget.cpp index 000c455c1d..0e92ef1387 100644 --- a/libpgmodeler_ui/src/modelwidget.cpp +++ b/libpgmodeler_ui/src/modelwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -56,6 +56,11 @@ #include "swapobjectsidswidget.h" #include "genericsqlwidget.h" #include "policywidget.h" +#include "tabledatawidget.h" +#include "generalconfigwidget.h" +#include "foreigndatawrapperwidget.h" +#include "foreignserverwidget.h" +#include "usermappingwidget.h" vector ModelWidget::copied_objects; vector ModelWidget::cutted_objects; @@ -64,12 +69,12 @@ bool ModelWidget::save_restore_pos=true; bool ModelWidget::disable_render_smooth=false; bool ModelWidget::simple_obj_creation=true; ModelWidget *ModelWidget::src_model=nullptr; -float ModelWidget::min_object_opacity=0.10f; +double ModelWidget::min_object_opacity=0.10; -const unsigned ModelWidget::BREAK_VERT_NINETY_DEGREES=0; -const unsigned ModelWidget::BREAK_HORIZ_NINETY_DEGREES=1; -const unsigned ModelWidget::BREAK_VERT_2NINETY_DEGREES=2; -const unsigned ModelWidget::BREAK_HORIZ_2NINETY_DEGREES=3; +constexpr unsigned ModelWidget::BreakVertNinetyDegrees; +constexpr unsigned ModelWidget::BreakHorizNinetyDegrees; +constexpr unsigned ModelWidget::BreakVert2NinetyDegrees; +constexpr unsigned ModelWidget::BreakHoriz2NinetyDegrees; ModelWidget::ModelWidget(QWidget *parent) : QWidget(parent) { @@ -77,49 +82,42 @@ ModelWidget::ModelWidget(QWidget *parent) : QWidget(parent) QLabel *label=nullptr; QGridLayout *grid=nullptr; QAction *action=nullptr; - QString str_ico, str_txt; - QStringList rel_types_cod={QString("11"), QString("1n"), QString("nn"), QString("dep"), QString("gen") }, - rel_labels={ trUtf8("One to One (1-1)"), trUtf8("One to Many (1-n)"), - trUtf8("Many to Many (n-n)"), trUtf8("Copy"), trUtf8("Inheritance") }; - ObjectType types[]={ OBJ_TABLE, OBJ_VIEW, OBJ_TEXTBOX, OBJ_RELATIONSHIP, - OBJ_CAST, OBJ_CONVERSION, OBJ_DOMAIN, - OBJ_FUNCTION, OBJ_AGGREGATE, OBJ_LANGUAGE, - OBJ_OPCLASS, OBJ_OPERATOR, OBJ_OPFAMILY, - OBJ_ROLE, OBJ_SCHEMA, OBJ_SEQUENCE, OBJ_TYPE, - OBJ_COLUMN, OBJ_CONSTRAINT, OBJ_RULE, OBJ_TRIGGER, OBJ_INDEX, OBJ_POLICY, - OBJ_TABLESPACE, OBJ_COLLATION, OBJ_EXTENSION, OBJ_EVENT_TRIGGER, OBJ_TAG, - OBJ_GENERIC_SQL }; - unsigned i, obj_cnt=sizeof(types)/sizeof(ObjectType), - rel_types_id[]={ BaseRelationship::RELATIONSHIP_11, BaseRelationship::RELATIONSHIP_1N, - BaseRelationship::RELATIONSHIP_NN, BaseRelationship::RELATIONSHIP_DEP, - BaseRelationship::RELATIONSHIP_GEN }; + QString str_ico; + QStringList rel_types_cod={QString("11"), QString("1n"), QString("nn"), QString("dep"), QString("gen"), QString("part") }; + unsigned i, + rel_types_id[]={ BaseRelationship::Relationship11, BaseRelationship::Relationship1n, + BaseRelationship::RelationshipNn, BaseRelationship::RelationshipDep, + BaseRelationship::RelationshipGen, BaseRelationship::RelationshipPart}; + + vector types_vect = BaseObject::getObjectTypes(true, { ObjectType::Database, ObjectType::Permission, + ObjectType::BaseRelationship}); current_zoom=1; modified=panning_mode=false; - new_obj_type=BASE_OBJECT; + new_obj_type=ObjectType::BaseObject; //Generating a temporary file name for the model QTemporaryFile tmp_file; //Configuring the template mask which includes the full path to temporary dir - tmp_file.setFileTemplate(GlobalAttributes::TEMPORARY_DIR + GlobalAttributes::DIR_SEPARATOR + QString("model_XXXXXX") + QString(".dbm")); + tmp_file.setFileTemplate(GlobalAttributes::TemporaryDir + GlobalAttributes::DirSeparator + QString("model_XXXXXX") + QString(".dbm")); tmp_file.open(); tmp_filename=tmp_file.fileName(); tmp_file.close(); protected_model_frm=new QFrame(this); - protected_model_frm->setGeometry(QRect(20, 10, 511, 48)); - protected_model_frm->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - protected_model_frm->setMinimumSize(QSize(0, 48)); - protected_model_frm->setMaximumHeight(48); + protected_model_frm->setGeometry(QRect(20, 10, 500, 25)); + protected_model_frm->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + protected_model_frm->setMinimumSize(QSize(0, 25)); protected_model_frm->setFrameShape(QFrame::StyledPanel); protected_model_frm->setFrameShadow(QFrame::Raised); protected_model_frm->setVisible(false); label=new QLabel(protected_model_frm); - label->setMinimumSize(QSize(32, 32)); - label->setMaximumSize(QSize(32, 32)); - label->setPixmap(QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta"))); + label->setMinimumSize(QSize(20, 20)); + label->setMaximumSize(QSize(20, 20)); + label->setScaledContents(true); + label->setPixmap(QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta"))); grid=new QGridLayout; grid->addWidget(label, 0, 0, 1, 1); @@ -135,7 +133,7 @@ ModelWidget::ModelWidget(QWidget *parent) : QWidget(parent) label->setFont(font); label->setWordWrap(true); label->setText(trUtf8("ATTENTION: The database model is protected! Operations that could modify it are disabled!")); - PgModelerUiNS::configureWidgetFont(label, PgModelerUiNS::MEDIUM_FONT_FACTOR); + PgModelerUiNs::configureWidgetFont(label, PgModelerUiNs::MediumFontFactor); grid->addWidget(label, 0, 1, 1, 1); protected_model_frm->setLayout(grid); @@ -150,11 +148,12 @@ ModelWidget::ModelWidget(QWidget *parent) : QWidget(parent) viewport=new QGraphicsView(scene); updateRenderHints(); - viewport->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + viewport->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); //Force the scene to be drawn from the left to right and from top to bottom viewport->setAlignment(Qt::AlignLeft | Qt::AlignTop); viewport->setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate); + viewport->setCacheMode(QGraphicsView::CacheBackground); viewport->centerOn(0,0); viewport->setMouseTracking(true); @@ -174,11 +173,11 @@ ModelWidget::ModelWidget(QWidget *parent) : QWidget(parent) magnifier_frm->setCursor(Qt::CrossCursor); QColor c1, c2; - BaseObjectView::getFillStyle(ParsersAttributes::OBJ_SELECTION, c1, c2); + BaseObjectView::getFillStyle(Attributes::ObjSelection, c1, c2); c1.setAlpha(50); magnifier_frm->setStyleSheet(QString("background-color: %1; border: 1px solid %2;") .arg(c1.name(QColor::HexArgb)) - .arg(BaseObjectView::getBorderStyle(ParsersAttributes::OBJ_SELECTION).color().name(QColor::HexArgb))); + .arg(BaseObjectView::getBorderStyle(Attributes::ObjSelection).color().name(QColor::HexArgb))); magnifier_area_lbl = new QLabel(this); magnifier_area_lbl->raise(); @@ -209,174 +208,211 @@ ModelWidget::ModelWidget(QWidget *parent) : QWidget(parent) zoom_info_lbl->setVisible(false); zoom_info_timer.setInterval(3000); - action_source_code=new QAction(QIcon(PgModelerUiNS::getIconPath("codigosql")), trUtf8("Source"), this); + action_edit_data=new QAction(QIcon(PgModelerUiNs::getIconPath("editdata")), trUtf8("Edit data"), this); + + action_source_code=new QAction(QIcon(PgModelerUiNs::getIconPath("codigosql")), trUtf8("Source"), this); action_source_code->setShortcut(QKeySequence(trUtf8("Alt+S"))); action_source_code->setToolTip(trUtf8("Show object source code")); - action_edit=new QAction(QIcon(PgModelerUiNS::getIconPath("editar")), trUtf8("Properties"), this); + action_edit=new QAction(QIcon(PgModelerUiNs::getIconPath("editar")), trUtf8("Properties"), this); action_edit->setShortcut(QKeySequence(trUtf8("Space"))); action_edit->setToolTip(trUtf8("Edit the object properties")); - action_protect=new QAction(QIcon(PgModelerUiNS::getIconPath("bloqobjeto")), trUtf8("Protect"), this); - action_unprotect=new QAction(QIcon(PgModelerUiNS::getIconPath("desbloqobjeto")), trUtf8("Unprotect"), this); + action_protect=new QAction(QIcon(PgModelerUiNs::getIconPath("bloqobjeto")), trUtf8("Protect"), this); + action_unprotect=new QAction(QIcon(PgModelerUiNs::getIconPath("desbloqobjeto")), trUtf8("Unprotect"), this); action_protect->setToolTip(trUtf8("Protects object(s) from modifications")); - action_remove=new QAction(QIcon(PgModelerUiNS::getIconPath("excluir")), trUtf8("Delete"), this); + action_remove=new QAction(QIcon(PgModelerUiNs::getIconPath("excluir")), trUtf8("Delete"), this); action_remove->setShortcut(QKeySequence(trUtf8("Del"))); - action_remove->setMenuRole(QAction::NoRole); + action_remove->setMenuRole(QAction::NoRole); - action_cascade_del=new QAction(QIcon(PgModelerUiNS::getIconPath("delcascade")), trUtf8("Del. cascade"), this); + action_cascade_del=new QAction(QIcon(PgModelerUiNs::getIconPath("delcascade")), trUtf8("Del. cascade"), this); action_cascade_del->setShortcut(QKeySequence(trUtf8("Shift+Del"))); - action_cascade_del->setMenuRole(QAction::NoRole); + action_cascade_del->setMenuRole(QAction::NoRole); - action_select_all=new QAction(QIcon(PgModelerUiNS::getIconPath("seltodos")), trUtf8("Select all"), this); + action_select_all=new QAction(QIcon(PgModelerUiNs::getIconPath("seltodos")), trUtf8("Select all"), this); action_select_all->setToolTip(trUtf8("Selects all the graphical objects in the model")); action_select_all->setMenu(&select_all_menu); - action_convert_relnn=new QAction(QIcon(PgModelerUiNS::getIconPath("convrelnn")), trUtf8("Convert"), this); + action_convert_relnn=new QAction(QIcon(PgModelerUiNs::getIconPath("convrelnn")), trUtf8("Convert"), this); - action_copy=new QAction(QIcon(PgModelerUiNS::getIconPath("copiar")), trUtf8("Copy"), this); + action_copy=new QAction(QIcon(PgModelerUiNs::getIconPath("copiar")), trUtf8("Copy"), this); action_copy->setShortcut(QKeySequence(trUtf8("Ctrl+C"))); - action_copy->setMenuRole(QAction::NoRole); + action_copy->setMenuRole(QAction::NoRole); - action_paste=new QAction(QIcon(PgModelerUiNS::getIconPath("colar")), trUtf8("Paste"), this); + action_paste=new QAction(QIcon(PgModelerUiNs::getIconPath("colar")), trUtf8("Paste"), this); action_paste->setShortcut(QKeySequence(trUtf8("Ctrl+V"))); - action_paste->setMenuRole(QAction::NoRole); + action_paste->setMenuRole(QAction::NoRole); - action_cut=new QAction(QIcon(PgModelerUiNS::getIconPath("recortar")), trUtf8("Cut"), this); + action_cut=new QAction(QIcon(PgModelerUiNs::getIconPath("recortar")), trUtf8("Cut"), this); action_cut->setShortcut(QKeySequence(trUtf8("Ctrl+X"))); - action_cut->setMenuRole(QAction::NoRole); + action_cut->setMenuRole(QAction::NoRole); - action_deps_refs=new QAction(QIcon(PgModelerUiNS::getIconPath("depsrefs")), trUtf8("Deps && Referrers"), this); + action_deps_refs=new QAction(QIcon(PgModelerUiNs::getIconPath("depsrefs")), trUtf8("Deps && Referrers"), this); - action_new_object=new QAction(QIcon(PgModelerUiNS::getIconPath("novoobjeto")), trUtf8("New"), this); + action_new_object=new QAction(QIcon(PgModelerUiNs::getIconPath("novoobjeto")), trUtf8("New"), this); action_new_object->setToolTip(trUtf8("Add a new object in the model")); - action_quick_actions=new QAction(QIcon(PgModelerUiNS::getIconPath("quickactions")), trUtf8("Quick"), this); + action_quick_actions=new QAction(QIcon(PgModelerUiNs::getIconPath("quickactions")), trUtf8("Quick"), this); action_quick_actions->setToolTip(trUtf8("Quick action for the selected object")); action_quick_actions->setMenu(&quick_actions_menu); - action_rename=new QAction(QIcon(PgModelerUiNS::getIconPath("rename")), trUtf8("Rename"), this); + action_rename=new QAction(QIcon(PgModelerUiNs::getIconPath("rename")), trUtf8("Rename"), this); action_rename->setShortcut(QKeySequence(trUtf8("F2"))); action_rename->setToolTip(trUtf8("Quick rename the object")); - action_moveto_schema=new QAction(QIcon(PgModelerUiNS::getIconPath("movetoschema")), trUtf8("Move to schema"), this); + action_moveto_schema=new QAction(QIcon(PgModelerUiNs::getIconPath("movetoschema")), trUtf8("Move to schema"), this); action_moveto_schema->setMenu(&schemas_menu); - action_set_tag=new QAction(QIcon(PgModelerUiNS::getIconPath("tag")), trUtf8("Set tag"), this); + action_moveto_layer=new QAction(QIcon(PgModelerUiNs::getIconPath("movetolayer")), trUtf8("Move to layer"), this); + action_moveto_layer->setMenu(&layers_menu); + + action_set_tag=new QAction(QIcon(PgModelerUiNs::getIconPath("tag")), trUtf8("Set tag"), this); action_set_tag->setMenu(&tags_menu); - action_edit_perms=new QAction(QIcon(PgModelerUiNS::getIconPath("permission")), trUtf8("Edit permissions"), this); + action_edit_perms=new QAction(QIcon(PgModelerUiNs::getIconPath("permission")), trUtf8("Edit permissions"), this); action_edit_perms->setShortcut(QKeySequence(trUtf8("Ctrl+E"))); - action_change_owner=new QAction(QIcon(PgModelerUiNS::getIconPath("changeowner")), trUtf8("Change owner"), this); + action_change_owner=new QAction(QIcon(PgModelerUiNs::getIconPath("changeowner")), trUtf8("Change owner"), this); action_change_owner->setMenu(&owners_menu); - action_sel_sch_children=new QAction(QIcon(PgModelerUiNS::getIconPath("seltodos")), trUtf8("Select children"), this); - action_sel_tagged_tabs=new QAction(QIcon(PgModelerUiNS::getIconPath("seltodos")), trUtf8("Select tagged"), this); + action_sel_sch_children=new QAction(QIcon(PgModelerUiNs::getIconPath("seltodos")), trUtf8("Select children"), this); + action_sel_tagged_tabs=new QAction(QIcon(PgModelerUiNs::getIconPath("seltodos")), trUtf8("Select tagged"), this); - action_select_object=new QAction(QIcon(PgModelerUiNS::getIconPath("movimentado")), trUtf8("Select"), this); - action_parent_rel=new QAction(QIcon(PgModelerUiNS::getIconPath("relationship")), trUtf8("Open relationship"), this); + action_select_object=new QAction(QIcon(PgModelerUiNs::getIconPath("movimentado")), trUtf8("Select"), this); + action_parent_rel=new QAction(QIcon(PgModelerUiNs::getIconPath("relationship")), trUtf8("Open relationship"), this); - action_append_sql=new QAction(QIcon(PgModelerUiNS::getIconPath("sqlappend")), trUtf8("Custom SQL"), this); + action_append_sql=new QAction(QIcon(PgModelerUiNs::getIconPath("sqlappend")), trUtf8("Custom SQL"), this); action_append_sql->setShortcut(QKeySequence(trUtf8("Alt+Q"))); - action_create_seq_col=new QAction(QIcon(PgModelerUiNS::getIconPath("sequence")), trUtf8("Convert to sequence"), this); - action_conv_int_serial=new QAction(QIcon(PgModelerUiNS::getIconPath("sequence")), trUtf8("Convert to serial"), this); + action_create_seq_col=new QAction(QIcon(PgModelerUiNs::getIconPath("sequence")), trUtf8("Convert to sequence"), this); + action_conv_int_serial=new QAction(QIcon(PgModelerUiNs::getIconPath("sequence")), trUtf8("Convert to serial"), this); - action_break_rel_line=new QAction(QIcon(PgModelerUiNS::getIconPath("breakrelline")), trUtf8("Break line"), this); + action_break_rel_line=new QAction(QIcon(PgModelerUiNs::getIconPath("breakrelline")), trUtf8("Break line"), this); - action_remove_rel_points=new QAction(QIcon(PgModelerUiNS::getIconPath("removepoints")), trUtf8("Remove points"), this); + action_remove_rel_points=new QAction(QIcon(PgModelerUiNs::getIconPath("removepoints")), trUtf8("Remove points"), this); - action_enable_sql=new QAction(QIcon(PgModelerUiNS::getIconPath("codigosql")), trUtf8("Enable SQL"), this); - action_disable_sql=new QAction(QIcon(PgModelerUiNS::getIconPath("disablesql")), trUtf8("Disable SQL"), this); + action_enable_sql=new QAction(QIcon(PgModelerUiNs::getIconPath("codigosql")), trUtf8("Enable SQL"), this); + action_disable_sql=new QAction(QIcon(PgModelerUiNs::getIconPath("disablesql")), trUtf8("Disable SQL"), this); - action_duplicate=new QAction(QIcon(PgModelerUiNS::getIconPath("duplicate")), trUtf8("Duplicate"), this); + action_duplicate=new QAction(QIcon(PgModelerUiNs::getIconPath("duplicate")), trUtf8("Duplicate"), this); action_duplicate->setShortcut(QKeySequence(trUtf8("Ctrl+D"))); - action_duplicate->setMenuRole(QAction::NoRole); + action_duplicate->setMenuRole(QAction::NoRole); + + action_pagination=new QAction(QIcon(PgModelerUiNs::getIconPath("pagination")), trUtf8("Pagination"), this); + action_pagination->setMenu(&pagination_menu); - action_extended_attribs=new QAction(QIcon(PgModelerUiNS::getIconPath("toggleattribs")), trUtf8("Extended attributes"), this); - action_show_ext_attribs=new QAction(trUtf8("Show"), this); - action_hide_ext_attribs=new QAction(trUtf8("Hide"), this); + action = pagination_menu.addAction(trUtf8("Enable")); + action->setData(true); + connect(action, SIGNAL(triggered(bool)), this, SLOT(togglePagination())); - action_jump_to_table=new QAction(QIcon(PgModelerUiNS::getIconPath("jumptotable")), trUtf8("Jump to table"), this); + action = pagination_menu.addAction(trUtf8("Disable")); + action->setData(false); + connect(action, SIGNAL(triggered(bool)), this, SLOT(togglePagination())); + + action_collapse_mode=new QAction(QIcon(PgModelerUiNs::getIconPath("collapse")), trUtf8("Collapse"), this); + action_no_collapse_attribs=new QAction(trUtf8("Not collapsed"), this); + action_no_collapse_attribs->setData(enum_cast(CollapseMode::NotCollapsed)); + action_collapse_ext_attribs=new QAction(trUtf8("Extended attributes"), this); + action_collapse_ext_attribs->setData(enum_cast(CollapseMode::ExtAttribsCollapsed)); + action_collpase_all_attribs=new QAction(trUtf8("All attributes"), this); + action_collpase_all_attribs->setData(enum_cast(CollapseMode::AllAttribsCollapsed)); + + action_jump_to_table=new QAction(QIcon(PgModelerUiNs::getIconPath("jumptotable")), trUtf8("Jump to table"), this); action_jump_to_table->setMenu(&jump_to_tab_menu); - toggle_attrs_menu.addAction(action_show_ext_attribs); - toggle_attrs_menu.addAction(action_hide_ext_attribs); - action_extended_attribs->setMenu(&toggle_attrs_menu); + toggle_attrs_menu.addAction(action_no_collapse_attribs); + toggle_attrs_menu.addAction(action_collapse_ext_attribs); + toggle_attrs_menu.addAction(action_collpase_all_attribs); + action_collapse_mode->setMenu(&toggle_attrs_menu); - action_schemas_rects=new QAction(QIcon(PgModelerUiNS::getIconPath("schemarect")), trUtf8("Schemas rectangles"), this); + action_schemas_rects=new QAction(QIcon(PgModelerUiNs::getIconPath("schemarect")), trUtf8("Schemas rectangles"), this); action_show_schemas_rects=new QAction(trUtf8("Show"), this); action_hide_schemas_rects=new QAction(trUtf8("Hide"), this); toggle_sch_rects_menu.addAction(action_show_schemas_rects); toggle_sch_rects_menu.addAction(action_hide_schemas_rects); action_schemas_rects->setMenu(&toggle_sch_rects_menu); - action_fade=new QAction(QIcon(PgModelerUiNS::getIconPath("fade")), trUtf8("Fade in/out"), this); - action_fade_in=new QAction(QIcon(PgModelerUiNS::getIconPath("fadein")), trUtf8("Fade in"), this); - action_fade_out=new QAction(QIcon(PgModelerUiNS::getIconPath("fadeout")), trUtf8("Fade out"), this); + action_fade=new QAction(QIcon(PgModelerUiNs::getIconPath("fade")), trUtf8("Fade in/out"), this); + action_fade_in=new QAction(QIcon(PgModelerUiNs::getIconPath("fadein")), trUtf8("Fade in"), this); + action_fade_out=new QAction(QIcon(PgModelerUiNs::getIconPath("fadeout")), trUtf8("Fade out"), this); - action_fade_rels_in=new QAction(QIcon(PgModelerUiNS::getIconPath("fadein")), trUtf8("Fade in"), this); - action_fade_rels_out=new QAction(QIcon(PgModelerUiNS::getIconPath("fadeout")), trUtf8("Fade out"), this); + action_fade_rels_in=new QAction(QIcon(PgModelerUiNs::getIconPath("fadein")), trUtf8("Fade in"), this); + action_fade_rels_out=new QAction(QIcon(PgModelerUiNs::getIconPath("fadeout")), trUtf8("Fade out"), this); fade_rels_menu.addAction(action_fade_rels_in); fade_rels_menu.addAction(action_fade_rels_out); - action_fade_rels=new QAction(QIcon(PgModelerUiNS::getIconPath("relationship_grp")), trUtf8("Relationships"), this); + action_fade_rels=new QAction(QIcon(PgModelerUiNs::getIconPath("relationship_grp")), trUtf8("Relationships"), this); action_fade_rels->setMenu(&fade_rels_menu); action_fade->setMenu(&fade_menu); action_fade_in->setMenu(&fade_in_menu); action_fade_out->setMenu(&fade_out_menu); - action_edit_creation_order=new QAction(QIcon(PgModelerUiNS::getIconPath("swapobjs")), trUtf8("Swap ids"), this); + action_edit_creation_order=new QAction(QIcon(PgModelerUiNs::getIconPath("swapobjs")), trUtf8("Swap ids"), this); action_edit_creation_order->setToolTip(trUtf8("Edit the objects creation order by swapping their ids")); connect(action_edit_creation_order, SIGNAL(triggered(bool)), this, SLOT(editCreationOrder())); - action=new QAction(QIcon(PgModelerUiNS::getIconPath("breakline_90dv")), trUtf8("90° (vertical)"), this); + action=new QAction(QIcon(PgModelerUiNs::getIconPath("breakline_90dv")), trUtf8("90° (vertical)"), this); connect(action, SIGNAL(triggered(bool)), this, SLOT(breakRelationshipLine(void))); - action->setData(QVariant::fromValue(BREAK_VERT_NINETY_DEGREES)); + action->setData(QVariant::fromValue(BreakVertNinetyDegrees)); break_rel_menu.addAction(action); - action=new QAction(QIcon(PgModelerUiNS::getIconPath("breakline_90dh")), trUtf8("90° (horizontal)"), this); + action=new QAction(QIcon(PgModelerUiNs::getIconPath("breakline_90dh")), trUtf8("90° (horizontal)"), this); connect(action, SIGNAL(triggered(bool)), this, SLOT(breakRelationshipLine(void))); - action->setData(QVariant::fromValue(BREAK_HORIZ_NINETY_DEGREES)); + action->setData(QVariant::fromValue(BreakHorizNinetyDegrees)); break_rel_menu.addAction(action); - action=new QAction(QIcon(PgModelerUiNS::getIconPath("breakline_290dv")), trUtf8("90° + 90° (vertical)"), this); + action=new QAction(QIcon(PgModelerUiNs::getIconPath("breakline_290dv")), trUtf8("90° + 90° (vertical)"), this); connect(action, SIGNAL(triggered(bool)), this, SLOT(breakRelationshipLine(void))); - action->setData(QVariant::fromValue(BREAK_VERT_2NINETY_DEGREES)); + action->setData(QVariant::fromValue(BreakVert2NinetyDegrees)); break_rel_menu.addAction(action); - action=new QAction(QIcon(PgModelerUiNS::getIconPath("breakline_290dh")), trUtf8("90° + 90° (horizontal)"), this); + action=new QAction(QIcon(PgModelerUiNs::getIconPath("breakline_290dh")), trUtf8("90° + 90° (horizontal)"), this); connect(action, SIGNAL(triggered(bool)), this, SLOT(breakRelationshipLine(void))); - action->setData(QVariant::fromValue(BREAK_HORIZ_2NINETY_DEGREES)); + action->setData(QVariant::fromValue(BreakHoriz2NinetyDegrees)); break_rel_menu.addAction(action); action_break_rel_line->setMenu(&break_rel_menu); //Alocatting the object creation actions - for(i=0; i < obj_cnt; i++) + for(auto &type : types_vect) { - actions_new_objects[types[i]]=new QAction(QIcon(PgModelerUiNS::getIconPath(types[i])), BaseObject::getTypeName(types[i]), this); - actions_new_objects[types[i]]->setData(QVariant(types[i])); - connect(actions_new_objects[types[i]], SIGNAL(triggered(bool)), this, SLOT(addNewObject(void))); + actions_new_objects[type]=new QAction(QIcon(PgModelerUiNs::getIconPath(type)), BaseObject::getTypeName(type), this); + actions_new_objects[type]->setData(QVariant(enum_cast(type))); + connect(actions_new_objects[type], SIGNAL(triggered(bool)), this, SLOT(addNewObject(void))); } + // Configuring the submenu of database level objects + action_database_category = new QAction(QIcon(PgModelerUiNs::getIconPath(ObjectType::Database)), trUtf8("Database object"), this); + action_database_category->setMenu(&database_category_menu); + types_vect = BaseObject::getChildObjectTypes(ObjectType::Database); + + for(auto &type : types_vect) + database_category_menu.addAction(actions_new_objects[type]); + + // Configuring the submenu of schema level objects + action_schema_category = new QAction(QIcon(PgModelerUiNs::getIconPath(ObjectType::Schema)), trUtf8("Schema object"), this); + action_schema_category->setMenu(&schema_category_menu); + types_vect = BaseObject::getChildObjectTypes(ObjectType::Schema); + + for(auto &type : types_vect) + schema_category_menu.addAction(actions_new_objects[type]); + //Creating the relationship submenu rels_menu=new QMenu(this); - actions_new_objects[OBJ_RELATIONSHIP]->setMenu(rels_menu); + actions_new_objects[ObjectType::Relationship]->setMenu(rels_menu); for(int i=0; i < rel_types_cod.size(); i++) { - str_ico=BaseObject::getSchemaName(OBJ_RELATIONSHIP) + rel_types_cod[i]; - str_txt=rel_labels[i]; + str_ico=BaseObject::getSchemaName(ObjectType::Relationship) + rel_types_cod[i]; - action=new QAction(QIcon(PgModelerUiNS::getIconPath(str_ico)), str_txt, this); + action=new QAction(QIcon(PgModelerUiNs::getIconPath(str_ico)), + BaseRelationship::getRelationshipTypeName(rel_types_id[i], false), this); //Storing a unique identifier for the relationship type - action->setData(QVariant(OBJ_RELATIONSHIP + rel_types_id[i])); + action->setData(QVariant(enum_cast(ObjectType::Relationship) + rel_types_id[i])); connect(action, SIGNAL(triggered(bool)), this, SLOT(addNewObject(void))); rels_menu->addAction(action); @@ -386,13 +422,13 @@ ModelWidget::ModelWidget(QWidget *parent) : QWidget(parent) new_obj_overlay_wgt->setObjectName(QString("new_obj_overlay_wgt")); new_obj_overlay_wgt->setVisible(false); - vector graph_types = { BASE_OBJECT, OBJ_SCHEMA, OBJ_TABLE, OBJ_VIEW, OBJ_RELATIONSHIP, OBJ_TEXTBOX }; + vector graph_types = { ObjectType::BaseObject, ObjectType::Schema, ObjectType::Table, ObjectType::View, ObjectType::Relationship, ObjectType::Textbox }; QStringList labels = { trUtf8("All objects"), trUtf8("Schemas"), trUtf8("Tables"), trUtf8("Views"), trUtf8("Relationships"), trUtf8("Textboxes") }; i=0; for(auto &obj_type : graph_types) { - if(obj_type == BASE_OBJECT) + if(obj_type == ObjectType::BaseObject) { action=new QAction(labels[i++], this); action->setShortcut(QKeySequence(trUtf8("Ctrl+A"))); @@ -401,14 +437,15 @@ ModelWidget::ModelWidget(QWidget *parent) : QWidget(parent) } else { - action=new QAction(QIcon(PgModelerUiNS::getIconPath(BaseObject::getSchemaName(obj_type) + QString("_grp"))), labels[i++], this); + action=new QAction(QIcon(PgModelerUiNs::getIconPath(BaseObject::getSchemaName(obj_type) + QString("_grp"))), labels[i++], this); select_all_menu.addAction(action); } - action->setData(QVariant(obj_type)); + action->setData(QVariant(enum_cast(obj_type))); connect(action, SIGNAL(triggered(bool)), this, SLOT(selectAllObjects())); } + connect(action_edit_data, SIGNAL(triggered(bool)), this, SLOT(editTableData())); connect(&zoom_info_timer, SIGNAL(timeout()), zoom_info_lbl, SLOT(hide())); connect(action_source_code, SIGNAL(triggered(bool)), this, SLOT(showSourceCode(void))); connect(action_edit, SIGNAL(triggered(bool)),this,SLOT(editObject(void))); @@ -433,37 +470,37 @@ ModelWidget::ModelWidget(QWidget *parent) : QWidget(parent) connect(action_remove_rel_points, SIGNAL(triggered(bool)), this, SLOT(removeRelationshipPoints(void))); connect(action_enable_sql, SIGNAL(triggered(bool)), this, SLOT(toggleObjectSQL(void))); connect(action_disable_sql, SIGNAL(triggered(bool)), this, SLOT(toggleObjectSQL(void))); - connect(action_remove, &QAction::triggered, [&](){ removeObjects(false); }); connect(action_cascade_del, &QAction::triggered, [&](){ removeObjects(true); }); - connect(action_fade_in, SIGNAL(triggered(bool)), this, SLOT(fadeObjectsIn())); connect(action_fade_out, SIGNAL(triggered(bool)), this, SLOT(fadeObjectsOut())); connect(action_fade_rels_in, SIGNAL(triggered(bool)), this, SLOT(fadeObjectsIn())); connect(action_fade_rels_out, SIGNAL(triggered(bool)), this, SLOT(fadeObjectsOut())); - - connect(action_show_ext_attribs, SIGNAL(triggered(bool)), this, SLOT(toggleExtendedAttributes())); - connect(action_hide_ext_attribs, SIGNAL(triggered(bool)), this, SLOT(toggleExtendedAttributes())); - + connect(action_collapse_ext_attribs, SIGNAL(triggered(bool)), this, SLOT(setCollapseMode())); + connect(action_collpase_all_attribs, SIGNAL(triggered(bool)), this, SLOT(setCollapseMode())); + connect(action_no_collapse_attribs, SIGNAL(triggered(bool)), this, SLOT(setCollapseMode())); connect(action_show_schemas_rects, SIGNAL(triggered(bool)), this, SLOT(toggleSchemasRectangles())); connect(action_hide_schemas_rects, SIGNAL(triggered(bool)), this, SLOT(toggleSchemasRectangles())); - connect(db_model, SIGNAL(s_objectAdded(BaseObject*)), this, SLOT(handleObjectAddition(BaseObject *))); connect(db_model, SIGNAL(s_objectRemoved(BaseObject*)), this, SLOT(handleObjectRemoval(BaseObject *))); - connect(scene, SIGNAL(s_objectsMoved(bool)), this, SLOT(handleObjectsMovement(bool))); connect(scene, SIGNAL(s_objectModified(BaseGraphicObject*)), this, SLOT(handleObjectModification(BaseGraphicObject*))); connect(scene, SIGNAL(s_objectDoubleClicked(BaseGraphicObject*)), this, SLOT(handleObjectDoubleClick(BaseGraphicObject*))); connect(scene, SIGNAL(s_popupMenuRequested(BaseObject*)), this, SLOT(configureObjectMenu(BaseObject *))); connect(scene, SIGNAL(s_popupMenuRequested(void)), this, SLOT(showObjectMenu(void))); connect(scene, SIGNAL(s_objectSelected(BaseGraphicObject*,bool)), this, SLOT(configureObjectSelection(void))); + connect(scene, SIGNAL(s_childrenSelectionChanged()), this, SLOT(configureObjectSelection(void))); connect(scene, SIGNAL(s_objectsSelectedInRange(void)), this, SLOT(configureObjectSelection(void))); - - connect(scene, &ObjectsScene::s_extAttributesToggled, [&](){ modified = true; }); - + connect(scene, &ObjectsScene::s_collapseModeChanged, [&](){ modified = true; }); + connect(scene, &ObjectsScene::s_paginationToggled, [&](){ modified = true; }); + connect(scene, &ObjectsScene::s_currentPageChanged, [&](){ modified = true; }); + connect(scene, &ObjectsScene::s_objectsMovedLayer, [&](){ modified = true; }); + connect(scene, SIGNAL(s_layersChanged()), this, SLOT(updateModelLayers())); + connect(scene, SIGNAL(s_activeLayersChanged()), this, SLOT(updateModelLayers())); connect(scene, SIGNAL(s_popupMenuRequested(BaseObject*)), new_obj_overlay_wgt, SLOT(hide())); connect(scene, SIGNAL(s_popupMenuRequested(void)), new_obj_overlay_wgt, SLOT(hide())); connect(scene, SIGNAL(s_objectSelected(BaseGraphicObject*,bool)), new_obj_overlay_wgt, SLOT(hide())); + connect(scene, SIGNAL(s_childrenSelectionChanged()), new_obj_overlay_wgt, SLOT(hide())); connect(scene, SIGNAL(s_objectsScenePressed(Qt::MouseButtons)), new_obj_overlay_wgt, SLOT(hide())); viewport->installEventFilter(this); @@ -494,10 +531,6 @@ ModelWidget::~ModelWidget(void) delete(viewport); delete(scene); - - op_list->removeOperations(); - db_model->destroyObjects(); - delete(op_list); delete(db_model); } @@ -542,10 +575,12 @@ bool ModelWidget::eventFilter(QObject *object, QEvent *event) object == viewport->verticalScrollBar()) && event->type() == QEvent::Wheel && w_event->modifiers()==Qt::ControlModifier) { + double zoom_inc = round(fabs(w_event->angleDelta().y())/120) * ZoomIncrement; + if(w_event->angleDelta().y() < 0) - this->applyZoom(this->current_zoom - ZOOM_INCREMENT); + this->applyZoom(this->current_zoom - zoom_inc); else - this->applyZoom(this->current_zoom + ZOOM_INCREMENT); + this->applyZoom(this->current_zoom + zoom_inc); return(true); } @@ -671,7 +706,7 @@ void ModelWidget::mousePressEvent(QMouseEvent *event) { /* If the user is adding a graphical object, the left click will set the initial position and show the editing form related to the object type */ - if(!simple_obj_creation && (new_obj_type==OBJ_TABLE || new_obj_type==OBJ_TEXTBOX || new_obj_type==OBJ_VIEW)) + if(!simple_obj_creation && (new_obj_type==ObjectType::Table || new_obj_type==ObjectType::Textbox || new_obj_type==ObjectType::View)) { this->scene->enableRangeSelection(false); this->showObjectForm(new_obj_type, nullptr, nullptr, viewport->mapToScene(event->pos())); @@ -733,10 +768,10 @@ void ModelWidget::restoreLastCanvasPosition(void) void ModelWidget::applyZoom(double zoom) { - if(zoom < MINIMUM_ZOOM) - zoom = MINIMUM_ZOOM; - else if(zoom > MAXIMUM_ZOOM) - zoom = MAXIMUM_ZOOM; + if(zoom < MinimumZoom) + zoom = MinimumZoom; + else if(zoom > MaximumZoom) + zoom = MaximumZoom; viewport->resetTransform(); viewport->scale(zoom, zoom); @@ -765,20 +800,20 @@ void ModelWidget::handleObjectAddition(BaseObject *object) switch(obj_type) { - case OBJ_TABLE: + case ObjectType::Table: item=new TableView(dynamic_cast
(graph_obj)); break; - case OBJ_VIEW: + case ObjectType::View: item=new GraphicalView(dynamic_cast(graph_obj)); break; - case OBJ_RELATIONSHIP: - case BASE_RELATIONSHIP: - item=new RelationshipView(dynamic_cast(graph_obj)); break; + case ObjectType::Relationship: + case ObjectType::BaseRelationship: + item=new RelationshipView(dynamic_cast(graph_obj)); break; - case OBJ_SCHEMA: + case ObjectType::Schema: if(!graph_obj->isSystemObject() || (graph_obj->isSystemObject() && graph_obj->getName()==QString("public"))) { @@ -787,7 +822,7 @@ void ModelWidget::handleObjectAddition(BaseObject *object) break; default: - item=new StyledTextboxView(dynamic_cast(graph_obj)); break; + item=new StyledTextboxView(dynamic_cast(graph_obj)); break; } @@ -813,13 +848,13 @@ void ModelWidget::addNewObject(void) these types after select a table or schema, respectively */ if(selected_objects.size()==1 && (TableObject::isTableObject(obj_type) || - selected_objects[0]->getObjectType()==OBJ_SCHEMA)) + selected_objects[0]->getObjectType()==ObjectType::Schema)) parent_obj=selected_objects[0]; //Creating a table or view inside a schema - if(parent_obj && parent_obj->getObjectType()==OBJ_SCHEMA && (obj_type==OBJ_TABLE || obj_type==OBJ_VIEW)) + if(parent_obj && parent_obj->getObjectType()==ObjectType::Schema && (obj_type==ObjectType::Table || obj_type==ObjectType::View)) { - BaseObjectView *sch_graph=dynamic_cast(dynamic_cast(parent_obj)->getReceiverObject()); + BaseObjectView *sch_graph=dynamic_cast(dynamic_cast(parent_obj)->getOverlyingObject()); QSizeF size = sch_graph->boundingRect().size(); QPointF pos, menu_pos = viewport->mapToScene(this->mapFromGlobal(popup_menu.pos())); QRectF rect = QRectF(sch_graph->pos(), size); @@ -829,22 +864,22 @@ void ModelWidget::addNewObject(void) pos=menu_pos; //Otherwise inserts the new object at the middle of bounding rect else - pos=QPointF(sch_graph->pos().x() + (size.width()/2.0f), - sch_graph->pos().y() + (size.height()/2.0f)); + pos=QPointF(sch_graph->pos().x() + (size.width()/2.0), + sch_graph->pos().y() + (size.height()/2.0)); this->showObjectForm(obj_type, nullptr, parent_obj, pos); } - else if(obj_type!=OBJ_TABLE && obj_type!=OBJ_VIEW && - obj_type!=OBJ_TEXTBOX && obj_type <= BASE_TABLE) + else if(obj_type!=ObjectType::Table && obj_type!=ObjectType::View && + obj_type!=ObjectType::Textbox && obj_type <= ObjectType::BaseTable) this->showObjectForm(obj_type, nullptr, parent_obj); else { /* A small checking to enable the overlay widget to create relationships and other graphical objects without the user click on the canvas area */ - if((obj_type > BASE_OBJECT && + if((obj_type > ObjectType::BaseObject && selected_objects.size()==2 && - selected_objects.at(0)->getObjectType()==OBJ_TABLE && - selected_objects.at(1)->getObjectType()==OBJ_TABLE)) + selected_objects.at(0)->getObjectType()==ObjectType::Table && + selected_objects.at(1)->getObjectType()==ObjectType::Table)) { this->showObjectForm(obj_type); } @@ -852,7 +887,7 @@ void ModelWidget::addNewObject(void) { //Simple table|view|textbox creation if(simple_obj_creation && - (obj_type==OBJ_TABLE || obj_type==OBJ_VIEW || obj_type==OBJ_TEXTBOX)) + (obj_type==ObjectType::Table || obj_type==ObjectType::View || obj_type==ObjectType::Textbox)) this->showObjectForm(obj_type, nullptr, parent_obj, viewport->mapToScene(viewport->rect().center())); else { @@ -865,7 +900,7 @@ void ModelWidget::addNewObject(void) * we force the enabling of the relationship creation steps. This will automatically selects the current table * as source table of the relationship */ if(selected_objects.size() == 1 && - selected_objects[0]->getObjectType() == OBJ_TABLE && new_obj_type > BASE_TABLE) + selected_objects[0]->getObjectType() == ObjectType::Table && new_obj_type > ObjectType::BaseTable) configureObjectSelection(); } } @@ -879,11 +914,11 @@ void ModelWidget::handleObjectRemoval(BaseObject *object) if(graph_obj) { - scene->removeItem(dynamic_cast(graph_obj->getReceiverObject())); + scene->removeItem(dynamic_cast(graph_obj->getOverlyingObject())); //Updates the parent schema if the removed object were a table or view if(graph_obj->getSchema() && - (graph_obj->getObjectType()==OBJ_TABLE || graph_obj->getObjectType()==OBJ_VIEW)) + (graph_obj->getObjectType()==ObjectType::Table || graph_obj->getObjectType()==ObjectType::View)) dynamic_cast(graph_obj->getSchema())->setModified(true); } @@ -895,7 +930,7 @@ void ModelWidget::handleObjectDoubleClick(BaseGraphicObject *object) if(object) this->showObjectForm(object->getObjectType(), object, nullptr, object->getPosition()); else - this->showObjectForm(OBJ_DATABASE, db_model); + this->showObjectForm(ObjectType::Database, db_model); } void ModelWidget::handleObjectsMovement(bool end_moviment) @@ -916,6 +951,8 @@ void ModelWidget::handleObjectsMovement(bool end_moviment) while(itr!=itr_end) { obj=dynamic_cast(*itr); + itr++; + if(!obj) continue; if(!dynamic_cast(obj) && (obj && !obj->isProtected())) { @@ -923,22 +960,20 @@ void ModelWidget::handleObjectsMovement(bool end_moviment) //Register the object if it is not a schema or a table already registered if(!schema && std::find(reg_tables.begin(), reg_tables.end(), obj)==reg_tables.end()) - op_list->registerObject(obj, Operation::OBJECT_MOVED); + op_list->registerObject(obj, Operation::ObjectMoved); else if(schema) { //For schemas, when they are moved, the original position of tables are registered instead of the position of schema itself - tables=dynamic_cast(schema->getReceiverObject())->getChildren(); + tables=dynamic_cast(schema->getOverlyingObject())->getChildren(); for(auto &tab : tables) { - op_list->registerObject(tab->getSourceObject(), Operation::OBJECT_MOVED); + op_list->registerObject(tab->getUnderlyingObject(), Operation::ObjectMoved); //Registers the table on a auxiliary list to avoid multiple registration on operation history - reg_tables.push_back(tab->getSourceObject()); + reg_tables.push_back(tab->getUnderlyingObject()); } } - } - - itr++; + } } } else @@ -947,10 +982,11 @@ void ModelWidget::handleObjectsMovement(bool end_moviment) while(itr!=itr_end) { - obj=dynamic_cast(*itr); + obj = dynamic_cast(*itr); itr++; + if(!obj) continue; - if(obj->getObjectType()==OBJ_TABLE || obj->getObjectType()==OBJ_VIEW) + if(obj->getObjectType()==ObjectType::Table || obj->getObjectType()==ObjectType::View) { Schema *schema=dynamic_cast(dynamic_cast(obj)->getSchema()); @@ -974,7 +1010,7 @@ void ModelWidget::handleObjectsMovement(bool end_moviment) void ModelWidget::handleObjectModification(BaseGraphicObject *object) { - op_list->registerObject(object, Operation::OBJECT_MODIFIED); + op_list->registerObject(object, Operation::ObjectModified); this->modified=true; if(object->getSchema()) @@ -990,9 +1026,12 @@ void ModelWidget::emitSceneInteracted(void) else if(selected_objects.size() == 1) { BaseGraphicObject *base_obj = dynamic_cast(selected_objects[0]); + TableObject *tab_obj=dynamic_cast(selected_objects[0]); if(base_obj) - emit s_sceneInteracted(dynamic_cast(base_obj->getReceiverObject())); + emit s_sceneInteracted(dynamic_cast(base_obj->getOverlyingObject())); + else if(tab_obj) + emit s_sceneInteracted(1, QRect()); else emit s_sceneInteracted(nullptr); } @@ -1024,13 +1063,13 @@ void ModelWidget::configureObjectSelection(void) while(itr!=objs_map.end()) { item=dynamic_cast(itr->second); - selected_objects.push_back(item->getSourceObject()); + selected_objects.push_back(item->getUnderlyingObject()); itr++; } - /* Case the new_obj_type is a value greater the BASE_TABLE indicates that the user + /* Case the new_obj_type is a value greater the ObjectType::ObjBaseTable indicates that the user (un)selected a object using some "Relationship" action */ - if(new_obj_type > BASE_TABLE) + if(new_obj_type > ObjectType::BaseTable) { unsigned count=selected_objects.size(); ObjectType obj_type1, obj_type2; @@ -1042,29 +1081,29 @@ void ModelWidget::configureObjectSelection(void) { //Get the selected objects types obj_type1=selected_objects[0]->getObjectType(); - obj_type2=(count==2 ? selected_objects[1]->getObjectType() : BASE_OBJECT); + obj_type2=(count==2 ? selected_objects[1]->getObjectType() : ObjectType::BaseObject); //If there is only one selected object and this is a table, activates the relationship creation if(!scene->isRelationshipLineVisible() && - count==1 && obj_type1==OBJ_TABLE && new_obj_type > BASE_TABLE && QApplication::keyboardModifiers()==0) + count==1 && obj_type1==ObjectType::Table && new_obj_type > ObjectType::BaseTable && QApplication::keyboardModifiers()==0) { BaseGraphicObject *graph_obj=dynamic_cast(selected_objects[0]); - BaseObjectView *object=dynamic_cast(graph_obj->getReceiverObject()); + BaseObjectView *object=dynamic_cast(graph_obj->getOverlyingObject()); scene->showRelationshipLine(true, QPointF(object->scenePos().x() + object->boundingRect().width()/2, object->scenePos().y() + object->boundingRect().height()/2)); } //If the user has selected object that are not tables, cancel the operation - else if(obj_type1!=OBJ_TABLE || (obj_type2!=OBJ_TABLE && obj_type2!=BASE_OBJECT)) + else if(obj_type1!=ObjectType::Table || (obj_type2!=ObjectType::Table && obj_type2!=ObjectType::BaseObject)) { this->cancelObjectAddition(); } /* Case there is only one selected object (table) and the SHIFT key is pressed too, creates a self-relationship. Case there is two selected objects, create a relationship between them */ - else if((count==1 && obj_type1==OBJ_TABLE && QApplication::keyboardModifiers()==Qt::ShiftModifier) || - (count==2 && obj_type1==OBJ_TABLE && obj_type2==OBJ_TABLE)) + else if((count==1 && obj_type1==ObjectType::Table && QApplication::keyboardModifiers()==Qt::ShiftModifier) || + (count==2 && obj_type1==ObjectType::Table && obj_type2==ObjectType::Table)) { /* Forcing no signals to be emitted by the scene while the relationship is being configured to avoid this * method to be called unecessarily */ @@ -1093,7 +1132,7 @@ void ModelWidget::selectAllObjects(void) ObjectType obj_type = static_cast(act->data().toUInt()); - if(obj_type == BASE_OBJECT) + if(obj_type == ObjectType::BaseObject) { QPainterPath pth; pth.addRect(scene->sceneRect()); @@ -1107,12 +1146,12 @@ void ModelWidget::selectAllObjects(void) BaseObjectView *obj_view = nullptr; vector objs = *db_model->getObjectList(obj_type); - if(obj_type == OBJ_RELATIONSHIP) - objs.insert(objs.end(), db_model->getObjectList(BASE_RELATIONSHIP)->begin(), db_model->getObjectList(BASE_RELATIONSHIP)->end()); + if(obj_type == ObjectType::Relationship) + objs.insert(objs.end(), db_model->getObjectList(ObjectType::BaseRelationship)->begin(), db_model->getObjectList(ObjectType::BaseRelationship)->end()); for(auto &obj : objs) { - obj_view = dynamic_cast(dynamic_cast(obj)->getReceiverObject()); + obj_view = dynamic_cast(dynamic_cast(obj)->getOverlyingObject()); if(obj_view) { @@ -1133,11 +1172,11 @@ void ModelWidget::convertRelationshipNN(void) if(rel) { //Converts only Many-to-Many relationship - if(rel->getRelationshipType()==Relationship::RELATIONSHIP_NN) + if(rel->getRelationshipType()==Relationship::RelationshipNn) { Messagebox msg_box; msg_box.show(trUtf8("Do you really want to convert the relationship into an intermediate table?"), - Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); if(msg_box.result()==QDialog::Accepted) { @@ -1147,8 +1186,8 @@ void ModelWidget::convertRelationshipNN(void) { Relationship *rel1=nullptr, *rel2=nullptr; Table *tab=nullptr, *tab_nn=nullptr, - *src_tab=dynamic_cast
(rel->getTable(Relationship::SRC_TABLE)), - *dst_tab=dynamic_cast
(rel->getTable(Relationship::DST_TABLE)); + *src_tab=dynamic_cast
(rel->getTable(Relationship::SrcTable)), + *dst_tab=dynamic_cast
(rel->getTable(Relationship::DstTable)); Constraint *constr=nullptr, *aux_constr=nullptr, *pk=nullptr; Column *col=nullptr; bool src_mand=true, dst_mand=true; @@ -1169,10 +1208,10 @@ void ModelWidget::convertRelationshipNN(void) { /* Checking if there is some attribute that is a pk too. If so, store their names in a list in order to create the pk further in this method */ - count=pk->getColumnCount(Constraint::SOURCE_COLS); + count=pk->getColumnCount(Constraint::SourceCols); for(i=0; i < count; i++) { - col=pk->getColumn(i, Constraint::SOURCE_COLS); + col=pk->getColumn(i, Constraint::SourceCols); attr_idx=rel->getObjectIndex(col); if(attr_idx >= 0) @@ -1180,7 +1219,7 @@ void ModelWidget::convertRelationshipNN(void) } } - xml_buf=tab_nn->getCodeDefinition(SchemaParser::XML_DEFINITION); + xml_buf=tab_nn->getCodeDefinition(SchemaParser::XmlDefinition); //Creates the table from the xml code xmlparser->restartParser(); @@ -1192,7 +1231,7 @@ void ModelWidget::convertRelationshipNN(void) if(rel->isSiglePKColumn()) { col=new Column; - (*col)=(*pk->getColumn(0, Constraint::SOURCE_COLS)); + (*col)=(*pk->getColumn(0, Constraint::SourceCols)); col->setParentTable(nullptr); tab->addColumn(col); pk_cols.push_back(col->getName()); @@ -1215,7 +1254,7 @@ void ModelWidget::convertRelationshipNN(void) count=tab_nn->getConstraintCount(); for(idx=0; idx < count; idx++) { - xml_buf=tab_nn->getConstraint(idx)->getCodeDefinition(SchemaParser::XML_DEFINITION,true); + xml_buf=tab_nn->getConstraint(idx)->getCodeDefinition(SchemaParser::XmlDefinition,true); xmlparser->restartParser(); xmlparser->loadXMLBuffer(xml_buf); @@ -1247,7 +1286,7 @@ void ModelWidget::convertRelationshipNN(void) constr->removeColumns(); constr->setParentTable(nullptr); - for(x=Constraint::SOURCE_COLS; x <= Constraint::REFERENCED_COLS; x++) + for(x=Constraint::SourceCols; x <= Constraint::ReferencedCols; x++) { count1=aux_constr->getColumnCount(x); for(idx1=0; idx1 < count1; idx1++) @@ -1262,28 +1301,28 @@ void ModelWidget::convertRelationshipNN(void) //Renames the table if there is other with the same name on the model avoiding conflicts tab->setName(tab_name); - tab->setName(PgModelerNS::generateUniqueName(tab, *db_model->getObjectList(OBJ_TABLE))); + tab->setName(PgModelerNs::generateUniqueName(tab, *db_model->getObjectList(ObjectType::Table))); op_list->startOperationChain(); //Removes the many-to-many relationship from the model - op_list->registerObject(rel, Operation::OBJECT_REMOVED); + op_list->registerObject(rel, Operation::ObjectRemoved); //The default position for the table will be the middle point between the relationship participant tables - pnt.setX((src_tab->getPosition().x() + dst_tab->getPosition().x())/2.0f); - pnt.setY((src_tab->getPosition().y() + dst_tab->getPosition().y())/2.0f); + pnt.setX((src_tab->getPosition().x() + dst_tab->getPosition().x())/2.0); + pnt.setY((src_tab->getPosition().y() + dst_tab->getPosition().y())/2.0); tab->setPosition(pnt); //Adds the new table to the model db_model->addObject(tab); - op_list->registerObject(tab, Operation::OBJECT_CREATED); + op_list->registerObject(tab, Operation::ObjectCreated); if(rel->isSelfRelationship()) { //For self relationships register the created foreign keys on the operation list while(!fks.empty()) { - op_list->registerObject(fks.back(), Operation::OBJECT_CREATED, -1, fks.back()->getParentTable()); + op_list->registerObject(fks.back(), Operation::ObjectCreated, -1, fks.back()->getParentTable()); fks.pop_back(); } } @@ -1296,27 +1335,27 @@ void ModelWidget::convertRelationshipNN(void) aux_constr=new Constraint; for(QString pk_col : pk_cols) - aux_constr->addColumn(tab->getColumn(pk_col), Constraint::SOURCE_COLS); + aux_constr->addColumn(tab->getColumn(pk_col), Constraint::SourceCols); - aux_constr->setName(PgModelerNS::generateUniqueName(tab, *tab->getObjectList(OBJ_CONSTRAINT), false, QString("_pk"))); + aux_constr->setName(PgModelerNs::generateUniqueName(tab, *tab->getObjectList(ObjectType::Constraint), false, QString("_pk"))); tab->addConstraint(aux_constr); - op_list->registerObject(aux_constr, Operation::OBJECT_CREATED, -1, tab); + op_list->registerObject(aux_constr, Operation::ObjectCreated, -1, tab); } /* Creates a one-to-many relationship that links the source table of the many-to-many rel. to the created table The relationship will be identifier if the single pk column attribute of the original relationship is false */ - rel1=new Relationship(Relationship::RELATIONSHIP_1N, + rel1=new Relationship(Relationship::Relationship1n, src_tab, tab, src_mand, false, !rel->isSiglePKColumn()); db_model->addRelationship(rel1); - op_list->registerObject(rel1, Operation::OBJECT_CREATED); + op_list->registerObject(rel1, Operation::ObjectCreated); /*Creates a one-to-many relationship that links the destination table of the many-to-many rel. to the created table The relationship will be identifier if the single pk column attribute of the original relationship is false */ - rel2=new Relationship(Relationship::RELATIONSHIP_1N, + rel2=new Relationship(Relationship::Relationship1n, dst_tab, tab, dst_mand, false, !rel->isSiglePKColumn()); db_model->addRelationship(rel2); - op_list->registerObject(rel2, Operation::OBJECT_CREATED); + op_list->registerObject(rel2, Operation::ObjectCreated); } op_list->finishOperationChain(); @@ -1342,7 +1381,7 @@ void ModelWidget::convertRelationshipNN(void) op_list->ignoreOperationChain(false); } - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } } @@ -1356,6 +1395,7 @@ void ModelWidget::loadModel(const QString &filename) try { connect(db_model, SIGNAL(s_objectLoaded(int,QString,unsigned)), &task_prog_wgt, SLOT(updateProgress(int,QString,unsigned))); + task_prog_wgt.addIcon(enum_cast(ObjectType::BaseObject), QPixmap(PgModelerUiNs::getIconPath("design"))); task_prog_wgt.setWindowTitle(trUtf8("Loading database model")); task_prog_wgt.show(); @@ -1364,6 +1404,14 @@ void ModelWidget::loadModel(const QString &filename) this->adjustSceneSize(); this->updateObjectsOpacity(); + scene->blockSignals(true); + + for(auto &layer : db_model->getLayers()) + scene->addLayer(layer); + + scene->setActiveLayers(db_model->getActiveLayers()); + scene->blockSignals(false); + task_prog_wgt.close(); protected_model_frm->setVisible(db_model->isProtected()); this->modified=false; @@ -1372,16 +1420,13 @@ void ModelWidget::loadModel(const QString &filename) { task_prog_wgt.close(); this->modified=false; - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void ModelWidget::adjustSceneSize(void) { QRectF scene_rect, objs_rect; - bool align_objs, show_grid, show_delims; - - ObjectsScene::getGridOptions(show_grid, align_objs, show_delims); scene_rect=scene->sceneRect(); objs_rect=scene->itemsBoundingRect(); @@ -1395,10 +1440,10 @@ void ModelWidget::adjustSceneSize(void) scene->setSceneRect(scene_rect); viewport->centerOn(0,0); - if(align_objs) + if(ObjectsScene::isAlignObjectsToGrid()) { scene->alignObjectsToGrid(); - db_model->setObjectsModified({ OBJ_RELATIONSHIP, BASE_RELATIONSHIP }); + db_model->setObjectsModified({ ObjectType::Relationship, ObjectType::BaseRelationship }); } emit s_sceneInteracted(scene_rect.size()); @@ -1411,7 +1456,7 @@ void ModelWidget::printModel(QPrinter *printer, bool print_grid, bool print_page bool show_grid, align_objs, show_delims; unsigned page_cnt, page, h_page_cnt, v_page_cnt, h_pg_id, v_pg_id; vector pages; - QRectF margins, page_rect; + QRectF margins; QPrinter::PaperSize paper_size_id; QPrinter::Orientation orient; QSizeF paper_size, custom_p_size; @@ -1422,7 +1467,9 @@ void ModelWidget::printModel(QPrinter *printer, bool print_grid, bool print_page h_top_mid, h_bottom_mid, v_left_mid, v_right_mid, dx, dy, dx1, dy1; //Make a backup of the current grid options - ObjectsScene::getGridOptions(show_grid, align_objs, show_delims); + show_grid = ObjectsScene::isShowGrid(); + align_objs = ObjectsScene::isAlignObjectsToGrid(); + show_delims = ObjectsScene::isShowPageDelimiters(); //Reconfigure the grid options based upon the passed settings ObjectsScene::setGridOptions(print_grid, align_objs, false); @@ -1444,9 +1491,9 @@ void ModelWidget::printModel(QPrinter *printer, bool print_grid, bool print_page //Creates a painter to draw the model directly on the printer QPainter painter(printer); painter.setRenderHint(QPainter::Antialiasing); - font.setPointSizeF(7.5f); + font.setPointSizeF(7.5); pen.setColor(QColor(120,120,120)); - pen.setWidthF(1.0f); + pen.setWidthF(1.0); //Calculates the auxiliary points to draw the page delimiter lines top_left.setX(0); top_left.setY(0); @@ -1569,6 +1616,9 @@ void ModelWidget::saveModel(void) void ModelWidget::saveModel(const QString &filename) { TaskProgressWidget task_prog_wgt(this); + QString bkpfile; + QTemporaryFile tmpfile; + bool exists = QFile::exists(filename); try { @@ -1576,20 +1626,57 @@ void ModelWidget::saveModel(const QString &filename) task_prog_wgt.setWindowTitle(trUtf8("Saving database model")); task_prog_wgt.show(); - saveLastCanvasPosition(); - db_model->saveModel(filename, SchemaParser::XML_DEFINITION); + /* If the original file exists we need to make a back first to avoid + * in order to recover it in case of failures */ + if(exists) + { + // Generate a temporary backup file + tmpfile.setAutoRemove(false); + tmpfile.setFileTemplate(GlobalAttributes::TemporaryDir + + GlobalAttributes::DirSeparator + + QString("%1_XXXXXX.dbk").arg(this->db_model->getName())); + tmpfile.open(); + bkpfile = tmpfile.fileName(); + tmpfile.close(); + tmpfile.remove(); + + /* Copy the original database model file prior to the saving to store + * its last state in a safe place (temporary storage of the tool ~/.config/pgmodeler by default */ + QFile::copy(filename, bkpfile); + + // Remove the original filename before create a new one in the same path + QFile::remove(filename); + } + saveLastCanvasPosition(); + db_model->saveModel(filename, SchemaParser::XmlDefinition); this->filename=filename; task_prog_wgt.close(); disconnect(db_model, nullptr, &task_prog_wgt, nullptr); this->modified=false; + + /* Doing a final check to the file regarding its size. + * If we have a zero-byte file something went wrong during the saving process (disk failure, thread errors, etc) + * so we raise an error to the user and restore the backup file to its original path */ + if(QFileInfo(filename).size() == 0) + throw Exception(Exception::getErrorMessage(ErrorCode::ModelFileInvalidSize).arg(filename).arg(bkpfile), + ErrorCode::ModelFileInvalidSize,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + if(exists) + QFile::remove(bkpfile); } catch(Exception &e) { + if(exists && QFile::exists(bkpfile)) + { + QFile::remove(filename); + QFile::copy(bkpfile, filename); + } + task_prog_wgt.close(); disconnect(db_model, nullptr, &task_prog_wgt, nullptr); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -1607,14 +1694,27 @@ int ModelWidget::openEditingForm(QWidget *widget, unsigned button_conf) { BaseForm editing_form(this); BaseObjectWidget *base_obj_wgt=qobject_cast(widget); + QString class_name = widget->metaObject()->className(); + int res = 0; if(base_obj_wgt) + { + BaseRelationship *rel = dynamic_cast(base_obj_wgt->getHandledObject()); editing_form.setMainWidget(base_obj_wgt); + + if(rel) + class_name.prepend(rel->getRelationshipTypeName().replace(QRegExp("( )+|(\\-)+"), QString())); + } else editing_form.setMainWidget(widget); editing_form.setButtonConfiguration(button_conf); - return(editing_form.exec()); + + GeneralConfigWidget::restoreWidgetGeometry(&editing_form, class_name); + res = editing_form.exec(); + GeneralConfigWidget::saveWidgetGeometry(&editing_form, class_name); + + return(res); } template @@ -1645,27 +1745,28 @@ void ModelWidget::showObjectForm(ObjectType obj_type, BaseObject *object, BaseOb { try { - unsigned rel_type=0, res = QDialog::Rejected; + unsigned rel_type=0; + int res = QDialog::Rejected; Schema *sel_schema=dynamic_cast(parent_obj); QPointF obj_pos=pos; - /* Case the obj_type is greater than BASE_TABLE indicates that the object type is a + /* Case the obj_type is greater than ObjectType::ObjBaseTable indicates that the object type is a relationship. To get the specific relationship id (1-1, 1-n, n-n, gen, dep) is necessary - to subtract the OBJ_RELATIONSHIP from the obj_type parameter, the result will point + to subtract the ObjectType::ObjRelationship from the obj_type parameter, the result will point to the BaseRelationship::RELATIONSHIP_??? constant. */ - if(obj_type > BASE_TABLE) + if(obj_type > ObjectType::BaseTable) { - rel_type=obj_type - OBJ_RELATIONSHIP; - obj_type=OBJ_RELATIONSHIP; + rel_type=enum_cast(obj_type) - enum_cast(ObjectType::Relationship); + obj_type=ObjectType::Relationship; } - if(obj_type!=OBJ_PERMISSION) + if(obj_type!=ObjectType::Permission) { if(object && obj_type!=object->getObjectType()) - throw Exception(ERR_OPR_OBJ_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprObjectInvalidType,__PRETTY_FUNCTION__,__FILE__,__LINE__); //If the user try to call the table object form without specify a parent object else if(!parent_obj && TableObject::isTableObject(obj_type)) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); } if(object && dynamic_cast(object)) @@ -1674,83 +1775,83 @@ void ModelWidget::showObjectForm(ObjectType obj_type, BaseObject *object, BaseOb /* Raises an error if the user try to edit a reserverd object. The only exception is for "public" schema that can be edited only on its fill color an rectangle attributes */ if(object && object->isSystemObject() && - (object->getObjectType()!=OBJ_SCHEMA || object->getName()!="public")) - throw Exception(Exception::getErrorMessage(ERR_OPR_RESERVED_OBJECT) - .arg(object->getName()).arg(object->getTypeName()), - ERR_OPR_RESERVED_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + (object->getObjectType()!=ObjectType::Schema || object->getName()!="public")) + throw Exception(Exception::getErrorMessage(ErrorCode::OprReservedObject) + .arg(object->getName()).arg(object->getTypeName()), + ErrorCode::OprReservedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(obj_type==OBJ_SCHEMA) + if(obj_type==ObjectType::Schema) res=openEditingForm(object); - else if(obj_type==OBJ_ROLE) + else if(obj_type==ObjectType::Role) res=openEditingForm(object); - else if(obj_type==OBJ_TABLESPACE) + else if(obj_type==ObjectType::Tablespace) res=openEditingForm(object); - else if(obj_type==OBJ_LANGUAGE) + else if(obj_type==ObjectType::Language) res=openEditingForm(object); - else if(obj_type==OBJ_CAST) + else if(obj_type==ObjectType::Cast) res=openEditingForm(object); - else if(obj_type==OBJ_TAG) + else if(obj_type==ObjectType::Tag) res=openEditingForm(object); - else if(obj_type== OBJ_EVENT_TRIGGER) + else if(obj_type== ObjectType::EventTrigger) res=openEditingForm(object); - else if(obj_type==OBJ_FUNCTION) + else if(obj_type==ObjectType::Function) res=openEditingForm(object, sel_schema); - else if(obj_type==OBJ_CONVERSION) + else if(obj_type==ObjectType::Conversion) res=openEditingForm(object, sel_schema); - else if(obj_type==OBJ_DOMAIN) + else if(obj_type==ObjectType::Domain) res=openEditingForm(object, sel_schema); - else if(obj_type==OBJ_AGGREGATE) + else if(obj_type==ObjectType::Aggregate) res=openEditingForm(object, sel_schema); - else if(obj_type==OBJ_SEQUENCE) + else if(obj_type==ObjectType::Sequence) res=openEditingForm(object, sel_schema); - else if(obj_type==OBJ_OPERATOR) + else if(obj_type==ObjectType::Operator) res=openEditingForm(object, sel_schema); - else if(obj_type==OBJ_OPFAMILY) + else if(obj_type==ObjectType::OpFamily) res=openEditingForm(object, sel_schema); - else if(obj_type==OBJ_OPCLASS) + else if(obj_type==ObjectType::OpClass) res=openEditingForm(object, sel_schema); - else if(obj_type==OBJ_TYPE) + else if(obj_type==ObjectType::Type) res=openEditingForm(object, sel_schema); - else if(obj_type==OBJ_COLLATION) + else if(obj_type==ObjectType::Collation) res=openEditingForm(object, sel_schema); - else if(obj_type==OBJ_EXTENSION) + else if(obj_type==ObjectType::Extension) res=openEditingForm(object, sel_schema); - else if(obj_type==OBJ_TABLE) + else if(obj_type==ObjectType::Table) res=openEditingForm(object, sel_schema, obj_pos); - else if(obj_type==OBJ_VIEW) + else if(obj_type==ObjectType::View) res=openEditingForm(object, sel_schema, obj_pos); - else if(obj_type==OBJ_RULE) + else if(obj_type==ObjectType::Rule) res=openEditingForm(object, parent_obj); - else if(obj_type== OBJ_TRIGGER) + else if(obj_type== ObjectType::Trigger) res=openEditingForm(object, parent_obj); - else if(obj_type== OBJ_INDEX) + else if(obj_type== ObjectType::Index) res=openEditingForm(object, parent_obj); - else if(obj_type== OBJ_POLICY) + else if(obj_type== ObjectType::Policy) res=openEditingForm(object, parent_obj); - else if(obj_type==OBJ_COLUMN || obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Column || obj_type==ObjectType::Constraint) { TableObject *tab_obj=dynamic_cast(object); - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) res=openEditingForm(object, parent_obj); else res=openEditingForm(object, parent_obj); if(res==QDialog::Accepted) { - if(tab_obj && parent_obj->getObjectType()==OBJ_TABLE) + if(tab_obj && parent_obj->getObjectType()==ObjectType::Table) db_model->validateRelationships(tab_obj, dynamic_cast
(parent_obj)); else db_model->validateRelationships(); } } - else if(obj_type==BASE_RELATIONSHIP || obj_type==OBJ_RELATIONSHIP) + else if(obj_type==ObjectType::BaseRelationship || obj_type==ObjectType::Relationship) { RelationshipWidget *relationship_wgt=new RelationshipWidget; if(!object && rel_type > 0 && selected_objects.size() > 0 && - selected_objects[0]->getObjectType()==OBJ_TABLE) + selected_objects[0]->getObjectType()==ObjectType::Table) { Table *tab1=dynamic_cast
(selected_objects[0]), *tab2=(selected_objects.size()==2 ? @@ -1763,25 +1864,31 @@ void ModelWidget::showObjectForm(ObjectType obj_type, BaseObject *object, BaseOb res=openEditingForm(relationship_wgt); scene->clearSelection(); } - else if(obj_type==OBJ_TEXTBOX) + else if(obj_type==ObjectType::Textbox) { TextboxWidget *textbox_wgt=new TextboxWidget; textbox_wgt->setAttributes(db_model, op_list, dynamic_cast(object), obj_pos.x(), obj_pos.y()); res=openEditingForm(textbox_wgt); } - else if(obj_type==OBJ_PERMISSION) + else if(obj_type==ObjectType::Permission) { PermissionWidget *permission_wgt=new PermissionWidget; Permission *perm=dynamic_cast(object); permission_wgt->setAttributes(db_model, nullptr, (perm ? perm->getObject() : object)); - res=openEditingForm(permission_wgt, Messagebox::OK_BUTTON); + res=openEditingForm(permission_wgt, Messagebox::OkButton); } - else if(obj_type==OBJ_GENERIC_SQL) + else if(obj_type==ObjectType::GenericSql) { GenericSQLWidget *genericsql_wgt=new GenericSQLWidget; genericsql_wgt->setAttributes(db_model, op_list, dynamic_cast(object)); res=openEditingForm(genericsql_wgt); } + else if(obj_type==ObjectType::ForeignDataWrapper) + res = openEditingForm(object); + else if(obj_type==ObjectType::ForeignServer) + res = openEditingForm(object); + else if(obj_type==ObjectType::UserMapping) + res = openEditingForm(object); else { DatabaseWidget *database_wgt=new DatabaseWidget; @@ -1796,7 +1903,7 @@ void ModelWidget::showObjectForm(ObjectType obj_type, BaseObject *object, BaseOb emit s_objectManipulated(); } else - emit s_manipulationCanceled(); + emit s_manipulationCanceled(); this->setFocus(); } @@ -1819,7 +1926,7 @@ void ModelWidget::showDependenciesReferences(void) { ObjectDepsRefsWidget *deps_refs_wgt=new ObjectDepsRefsWidget; deps_refs_wgt->setAttributes(this, object); - openEditingForm(deps_refs_wgt, Messagebox::OK_BUTTON); + openEditingForm(deps_refs_wgt, Messagebox::OkButton); } } } @@ -1836,7 +1943,7 @@ void ModelWidget::showSourceCode(void) { SourceCodeWidget *sourcecode_wgt=new SourceCodeWidget; sourcecode_wgt->setAttributes(this->db_model, object); - openEditingForm(sourcecode_wgt, Messagebox::OK_BUTTON); + openEditingForm(sourcecode_wgt, Messagebox::OkButton); } } } @@ -1844,7 +1951,7 @@ void ModelWidget::showSourceCode(void) void ModelWidget::cancelObjectAddition(void) { //Reset the new object type to a invalid one forcing the user to select a correct type again - new_obj_type=BASE_OBJECT; + new_obj_type=ObjectType::BaseObject; //Restore the cursor icon viewport->setCursor(QCursor(Qt::ArrowCursor)); @@ -1861,9 +1968,9 @@ void ModelWidget::renameObject(void) BaseObject *obj=reinterpret_cast(act->data().value()); if(obj->isSystemObject()) - throw Exception(Exception::getErrorMessage(ERR_OPR_RESERVED_OBJECT) + throw Exception(Exception::getErrorMessage(ErrorCode::OprReservedObject) .arg(obj->getName()).arg(obj->getTypeName()), - ERR_OPR_RESERVED_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::OprReservedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); ObjectRenameWidget objectrename_wgt(this); objectrename_wgt.setAttributes(obj, this->db_model, this->op_list); @@ -1895,7 +2002,7 @@ void ModelWidget::moveToSchema(void) //Change the object's schema only if the new schema is different from the current if(obj->acceptsSchema() && obj->getSchema()!=schema) { - op_id=op_list->registerObject(obj, Operation::OBJECT_MODIFIED, -1); + op_id=op_list->registerObject(obj, Operation::ObjectModified, -1); obj->setSchema(schema); obj_graph=dynamic_cast(obj); @@ -1903,14 +2010,14 @@ void ModelWidget::moveToSchema(void) //If the object is a graphical one, move it to a position near to the new schema box if(obj_graph) { - SchemaView *dst_schema=dynamic_cast(schema->getReceiverObject()); + SchemaView *dst_schema=dynamic_cast(schema->getOverlyingObject()); QPointF p; if(dst_schema && dst_schema->isVisible()) { p.setX(dst_schema->pos().x()); - p.setY(dst_schema->pos().y() + dst_schema->boundingRect().height() + BaseObjectView::VERT_SPACING); - dynamic_cast(obj_graph->getReceiverObject())->setPos(p); + p.setY(dst_schema->pos().y() + dst_schema->boundingRect().height() + BaseObjectView::VertSpacing); + dynamic_cast(obj_graph->getOverlyingObject())->setPos(p); } } @@ -1937,10 +2044,27 @@ void ModelWidget::moveToSchema(void) if(op_id >=0 && op_id > op_curr_idx) op_list->removeLastOperation(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } +void ModelWidget::moveToLayer(void) +{ + QAction *act = dynamic_cast(sender()); + BaseGraphicObject *graph_obj = nullptr; + unsigned layer_id = act->data().toUInt(); + + for(auto &obj : selected_objects) + { + graph_obj = dynamic_cast(obj); + graph_obj->setLayer(layer_id); + } + + QApplication::setOverrideCursor(Qt::WaitCursor); + scene->updateActiveLayers(); + QApplication::restoreOverrideCursor(); +} + void ModelWidget::changeOwner(void) { QAction *act=dynamic_cast(sender()); @@ -1962,14 +2086,14 @@ void ModelWidget::changeOwner(void) if(obj->acceptsOwner() && obj->getOwner()!=owner) { if(obj->isSystemObject()) - throw Exception(Exception::getErrorMessage(ERR_OPR_RESERVED_OBJECT) + throw Exception(Exception::getErrorMessage(ErrorCode::OprReservedObject) .arg(obj->getName()) .arg(obj->getTypeName()), - ERR_OPR_RESERVED_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::OprReservedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Register an operation only if the object is not the database itself - if(obj->getObjectType()!=OBJ_DATABASE) - op_id=op_list->registerObject(obj, Operation::OBJECT_MODIFIED, -1); + if(obj->getObjectType()!=ObjectType::Database) + op_id=op_list->registerObject(obj, Operation::ObjectModified, -1); obj->setOwner(owner); } @@ -1983,7 +2107,7 @@ void ModelWidget::changeOwner(void) if(op_id >=0 && op_id >= op_curr_idx) op_list->removeLastOperation(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -2004,13 +2128,15 @@ void ModelWidget::setTag(void) if(tab) { - op_id=op_list->registerObject(obj, Operation::OBJECT_MODIFIED, -1); + op_id=op_list->registerObject(obj, Operation::ObjectModified, -1); tab->setTag(dynamic_cast(tag)); - tab->setModified(true); } } op_list->finishOperationChain(); + db_model->setObjectsModified(selected_objects); + scene->clearSelection(); + emit s_objectModified(); } catch(Exception &e) @@ -2018,7 +2144,7 @@ void ModelWidget::setTag(void) if(op_id >=0 && op_id > op_curr_idx) op_list->removeLastOperation(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -2029,7 +2155,7 @@ void ModelWidget::editPermissions(void) BaseObject *obj=reinterpret_cast(act->data().value()); permission_wgt->setAttributes(this->db_model, nullptr, obj); - openEditingForm(permission_wgt, Messagebox::OK_BUTTON); + openEditingForm(permission_wgt, Messagebox::OkButton); this->setModified(true); emit s_objectManipulated(); @@ -2065,7 +2191,7 @@ void ModelWidget::selectSchemaChildren(void) scene->clearSelection(); dynamic_cast( - dynamic_cast(schema->getReceiverObject()))->selectChildren(); + dynamic_cast(schema->getOverlyingObject()))->selectChildren(); } void ModelWidget::selectTaggedTables(void) @@ -2084,7 +2210,7 @@ void ModelWidget::selectTaggedTables(void) for(auto object : objects) { - obj_view = dynamic_cast(dynamic_cast(object)->getReceiverObject()); + obj_view = dynamic_cast(dynamic_cast(object)->getOverlyingObject()); obj_view->setSelected(true); } } @@ -2096,53 +2222,14 @@ void ModelWidget::protectObject(void) QObject *obj_sender=sender(); ObjectType obj_type; TableObject *tab_obj=nullptr; - BaseObject *object=nullptr; - BaseGraphicObject *graph_obj=nullptr; bool protect=false; - vector::iterator itr, itr_end; + QList upd_objects; + Messagebox msgbox; scene->blockSignals(true); - if(this->selected_objects.size()==1) - { - tab_obj=dynamic_cast(this->selected_objects[0]); - graph_obj=dynamic_cast(this->selected_objects[0]); - - if(graph_obj) - { - bool protect=!graph_obj->isProtected(); - - if(graph_obj->getObjectType()==OBJ_SCHEMA) - { - Messagebox msgbox; - msgbox.show(QString(QT_TR_NOOP("Do you want to %1 the selected schema's children too?")).arg(protect ? QT_TR_NOOP("protect") : QT_TR_NOOP("unprotect")), - Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); - - if(msgbox.result()==QDialog::Accepted) - { - vector objects(db_model->getObjects(this->selected_objects[0])); - - for(BaseObject *obj : objects) - obj->setProtected(protect); - } - } - - graph_obj->setProtected(protect); - } - else if(tab_obj) - { - tab_obj->setProtected(!tab_obj->isProtected()); - - //Force the update of the parent table - dynamic_cast
(tab_obj->getParentTable())->setModified(true); - } - else - { - this->selected_objects[0]->setProtected(!this->selected_objects[0]->isProtected()); - } - } //Protects the whole model if there is no selected object - else if(this->selected_objects.empty()) + if(this->selected_objects.empty()) { if(obj_sender==action_protect || obj_sender==action_unprotect) db_model->setProtected(!db_model->isProtected()); @@ -2150,34 +2237,55 @@ void ModelWidget::protectObject(void) //If there is more than one selected object, make a batch protection/unprotection else { - itr=this->selected_objects.begin(); - itr_end=this->selected_objects.end(); protect=(!this->selected_objects[0]->isProtected()); - while(itr!=itr_end) + for(auto &object : selected_objects) { - object=(*itr); - - itr++; - obj_type=object->getObjectType(); - if(obj_type==OBJ_COLUMN || obj_type==OBJ_CONSTRAINT) + if(obj_type==ObjectType::Column || obj_type==ObjectType::Constraint) { tab_obj=dynamic_cast(object); if(tab_obj->isAddedByRelationship()) { - throw Exception(QString(Exception::getErrorMessage(ERR_OPR_REL_INCL_OBJECT)) + throw Exception(Exception::getErrorMessage(ErrorCode::OprRelationshipAddedObject) .arg(object->getName()).arg(object->getTypeName()), - ERR_OPR_REL_INCL_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::OprRelationshipAddedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + } + + // Applying protection status for the schema children objects + if(obj_type==ObjectType::Schema) + { + if(!msgbox.isCustomOptionChecked()) + { + msgbox.setCustomOptionText("Apply to all other selected schemas"); + msgbox.show(QString(QT_TR_NOOP("Do you want to %1 the children of the schema %2 too?")) + .arg(protect ? QT_TR_NOOP("protect") : QT_TR_NOOP("unprotect")).arg(object->getName()), + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); + } + + if(msgbox.result()==QDialog::Accepted || msgbox.isCustomOptionChecked()) + { + vector objects(db_model->getObjects(object)); + + for(BaseObject *obj : objects) + obj->setProtected(protect); } } object->setProtected(protect); + tab_obj = dynamic_cast(object); + + if(tab_obj && !upd_objects.contains(tab_obj->getParentTable())) + upd_objects.push_back(tab_obj->getParentTable()); } } + for(auto &obj : upd_objects) + obj->setModified(true); + protected_model_frm->setVisible(db_model->isProtected()); scene->blockSignals(false); scene->clearSelection(); @@ -2187,7 +2295,7 @@ void ModelWidget::protectObject(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -2210,9 +2318,9 @@ void ModelWidget::copyObjects(bool duplicate_mode) vector deps; BaseObject *object=nullptr; TableObject *tab_obj=nullptr; - Table *table=nullptr; + BaseTable *table=nullptr; Constraint *constr=nullptr; - ObjectType types[]={ OBJ_TRIGGER, OBJ_INDEX, OBJ_CONSTRAINT }; + ObjectType types[]={ ObjectType::Trigger, ObjectType::Rule, ObjectType::Index, ObjectType::Constraint, ObjectType::Policy }; unsigned i, type_id, count; Messagebox msg_box; @@ -2220,16 +2328,16 @@ void ModelWidget::copyObjects(bool duplicate_mode) { //Raise an error if the user try to copy a reserved object if(selected_objects[0]->isSystemObject()) - throw Exception(Exception::getErrorMessage(ERR_OPR_RESERVED_OBJECT) - .arg(selected_objects[0]->getName()).arg(selected_objects[0]->getTypeName()), - ERR_OPR_RESERVED_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::OprReservedObject) + .arg(selected_objects[0]->getName()).arg(selected_objects[0]->getTypeName()), + ErrorCode::OprReservedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); } if(!duplicate_mode) { //Ask for confirmation to copy the dependencies of the object(s) msg_box.show(trUtf8("Also copy all dependencies of selected objects? This minimizes the breakdown of references when copied objects are pasted into another model."), - Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); } /* When in cut operation is necessary to store the selected objects in a separeted list @@ -2245,7 +2353,7 @@ void ModelWidget::copyObjects(bool duplicate_mode) object=(*itr); //Table-view relationships and FK relationship aren't copied since they are created automatically when pasting the tables/views - if(object->getObjectType()!=BASE_RELATIONSHIP) + if(object->getObjectType()!=ObjectType::BaseRelationship) { if(msg_box.result()==QDialog::Accepted) db_model->getObjectDependecies(object, deps, true); @@ -2254,11 +2362,11 @@ void ModelWidget::copyObjects(bool duplicate_mode) /* Copying the special objects (which references columns added by relationship) in order to be correclty created when pasted */ - if(object->getObjectType()==OBJ_TABLE) + if(object->getObjectType()==ObjectType::Table || object->getObjectType() == ObjectType::View) { - table=dynamic_cast
(object); + table=dynamic_cast(object); - for(type_id=0; type_id < 3; type_id++) + for(type_id=0; type_id <= 4; type_id++) { count=table->getObjectCount(types[type_id]); @@ -2270,15 +2378,19 @@ void ModelWidget::copyObjects(bool duplicate_mode) /* The object is only inserted at the list when it was not included by relationship but references columns added by relationship. Case the object is a constraint, it cannot be a primary key because this type of constraint is treated separetely by relationships */ - if(!tab_obj->isAddedByRelationship() && - ((constr && - (constr->getConstraintType()==ConstraintType::foreign_key || - (constr->getConstraintType()==ConstraintType::unique && - constr->isReferRelationshipAddedColumn()))) || - (types[type_id]==OBJ_TRIGGER && dynamic_cast(tab_obj)->isReferRelationshipAddedColumn()) || - (types[type_id]==OBJ_INDEX && dynamic_cast(tab_obj)->isReferRelationshipAddedColumn()))) + if(duplicate_mode || + (!duplicate_mode && + !tab_obj->isAddedByRelationship() && + (!constr || + (((constr && + (constr->getConstraintType()==ConstraintType::ForeignKey || + (constr->getConstraintType()==ConstraintType::Unique && + constr->isReferRelationshipAddedColumn())))))))) deps.push_back(tab_obj); } + + if(object->getObjectType() == ObjectType::View && type_id >= 2) + break; } } } @@ -2310,7 +2422,7 @@ void ModelWidget::copyObjects(bool duplicate_mode) } } -void ModelWidget::pasteObjects(void) +void ModelWidget::pasteObjects(bool duplicate_mode) { map xml_objs; BaseTable *orig_parent_tab=nullptr; @@ -2318,7 +2430,7 @@ void ModelWidget::pasteObjects(void) map orig_obj_names; BaseObject *object=nullptr, *aux_object=nullptr; TableObject *tab_obj=nullptr; - Table *sel_table=nullptr; + Table *sel_table=nullptr, *aux_table = nullptr; View *sel_view=nullptr; BaseTable *parent=nullptr; Function *func=nullptr; @@ -2352,17 +2464,17 @@ void ModelWidget::pasteObjects(void) tab_obj=dynamic_cast(object); itr++; pos++; - task_prog_wgt.updateProgress((pos/static_cast(copied_objects.size()))*100, + task_prog_wgt.updateProgress((pos/static_cast(copied_objects.size()))*100, trUtf8("Validating object: `%1' (%2)").arg(object->getName()) .arg(object->getTypeName()), - object->getObjectType()); + enum_cast(object->getObjectType())); if(!tab_obj || ((sel_table || sel_view) && tab_obj)) { /* The first validation is to check if the object to be pasted does not conflict with any other object of the same type on the model */ - if(obj_type==OBJ_FUNCTION) + if(obj_type==ObjectType::Function) dynamic_cast(object)->createSignature(true); else if(tab_obj) aux_name=tab_obj->getName(true); @@ -2374,7 +2486,7 @@ void ModelWidget::pasteObjects(void) aux_object=db_model->getObject(aux_name, obj_type); else { - if(sel_view && (obj_type==OBJ_TRIGGER || obj_type==OBJ_RULE)) + if(sel_view && (obj_type==ObjectType::Trigger || obj_type==ObjectType::Rule || obj_type==ObjectType::Index)) aux_object=sel_view->getObject(aux_name, obj_type); else if(sel_table) aux_object=sel_table->getObject(aux_name, obj_type); @@ -2389,11 +2501,11 @@ void ModelWidget::pasteObjects(void) (aux_object && (dynamic_cast(object) || (aux_object->getDatabase()==object->getDatabase()) || - (aux_object->getCodeDefinition(SchemaParser::SchemaParser::XML_DEFINITION) != - object->getCodeDefinition(SchemaParser::SchemaParser::XML_DEFINITION))))) + (aux_object->getCodeDefinition(SchemaParser::SchemaParser::XmlDefinition) != + object->getCodeDefinition(SchemaParser::SchemaParser::XmlDefinition))))) { //Resolving name conflicts - if(obj_type!=OBJ_CAST) + if(obj_type!=ObjectType::Cast) { func=nullptr; oper=nullptr; @@ -2403,26 +2515,31 @@ void ModelWidget::pasteObjects(void) /* For each object type as follow configures the name and the suffix and store them on the 'copy_obj_name' variable. This string is used to check if there are objects with the same name on model. While the 'copy_obj_name' conflicts with other objects (of same type) this validation is made */ - if(obj_type==OBJ_FUNCTION) + if(obj_type==ObjectType::Function) { func=dynamic_cast(object); - func->setName(PgModelerNS::generateUniqueName(func, (*db_model->getObjectList(OBJ_FUNCTION)), false, QString("_cp"))); + func->setName(PgModelerNs::generateUniqueName(func, (*db_model->getObjectList(ObjectType::Function)), false, QString("_cp"))); copy_obj_name=func->getName(); func->setName(orig_obj_names[object]); } - else if(obj_type==OBJ_OPERATOR) + else if(obj_type==ObjectType::Operator) { oper=dynamic_cast(object); - oper->setName(PgModelerNS::generateUniqueName(oper, (*db_model->getObjectList(OBJ_OPERATOR)))); + oper->setName(PgModelerNs::generateUniqueName(oper, (*db_model->getObjectList(ObjectType::Operator)))); copy_obj_name=oper->getName(); oper->setName(orig_obj_names[object]); } else { if(tab_obj) - tab_obj->setName(PgModelerNS::generateUniqueName(tab_obj, (*sel_table->getObjectList(tab_obj->getObjectType())), false, QString("_cp"), true)); + { + if(sel_table) + tab_obj->setName(PgModelerNs::generateUniqueName(tab_obj, (*sel_table->getObjectList(tab_obj->getObjectType())), false, QString("_cp"), true)); + else + tab_obj->setName(PgModelerNs::generateUniqueName(tab_obj, (*sel_view->getObjectList(tab_obj->getObjectType())), false, QString("_cp"), true)); + } else - object->setName(PgModelerNS::generateUniqueName(object, (*db_model->getObjectList(object->getObjectType())), false, QString("_cp"), true)); + object->setName(PgModelerNs::generateUniqueName(object, (*db_model->getObjectList(object->getObjectType())), false, QString("_cp"), true)); copy_obj_name=object->getName(); object->setName(orig_obj_names[object]); @@ -2449,14 +2566,24 @@ void ModelWidget::pasteObjects(void) itr++; pos++; - task_prog_wgt.updateProgress((pos/static_cast(copied_objects.size()))*100, + task_prog_wgt.updateProgress((pos/static_cast(copied_objects.size()))*100, trUtf8("Generating XML for: `%1' (%2)").arg(object->getName()) .arg(object->getTypeName()), - object->getObjectType()); + enum_cast(object->getObjectType())); if(!tab_obj) + { + aux_table = dynamic_cast
(object);; + //Stores the XML definition on a xml buffer map - xml_objs[object]=object->getCodeDefinition(SchemaParser::XML_DEFINITION); + if(duplicate_mode && aux_table) + { + xml_objs[object] = aux_table->__getCodeDefinition(SchemaParser::XmlDefinition, true); + object->setCodeInvalidated(true); + } + else + xml_objs[object]=object->getCodeDefinition(SchemaParser::XmlDefinition); + } //Store the original parent table of the object else if(tab_obj && (sel_table || sel_view)) @@ -2467,20 +2594,29 @@ void ModelWidget::pasteObjects(void) parent=sel_view; /* Only generates the XML for a table object when the selected receiver object - is a table or is a view and the current object is a trigger or rule (because - view's only accepts this two types) */ + * is a table or is a view and the current object is a trigger, index, or rule (because + * view's only accepts this two types) */ if(sel_table || - (sel_view && (tab_obj->getObjectType()==OBJ_TRIGGER || - tab_obj->getObjectType()==OBJ_RULE))) + (sel_view && (tab_obj->getObjectType()==ObjectType::Trigger || + tab_obj->getObjectType()==ObjectType::Rule || + tab_obj->getObjectType()==ObjectType::Index))) { //Backups the original parent table orig_parent_tab=tab_obj->getParentTable(); + constr = dynamic_cast(tab_obj); + //Set the parent table as the selected table/view tab_obj->setParentTable(parent); //Generates the XML code with the new parent table - xml_objs[object]=object->getCodeDefinition(SchemaParser::XML_DEFINITION); + if(constr) + { + xml_objs[object]=constr->getCodeDefinition(SchemaParser::XmlDefinition, duplicate_mode); + tab_obj->setCodeInvalidated(true); + } + else + xml_objs[object]=object->getCodeDefinition(SchemaParser::XmlDefinition); //Restore the original parent table tab_obj->setParentTable(orig_parent_tab); @@ -2489,7 +2625,15 @@ void ModelWidget::pasteObjects(void) else if(tab_obj) { //Generates the XML code with the new parent table - xml_objs[object]=tab_obj->getCodeDefinition(SchemaParser::XML_DEFINITION); + constr = dynamic_cast(tab_obj); + + if(constr) + { + xml_objs[object]=constr->getCodeDefinition(SchemaParser::XmlDefinition, duplicate_mode); + tab_obj->setCodeInvalidated(true); + } + else + xml_objs[object]=tab_obj->getCodeDefinition(SchemaParser::XmlDefinition); } } @@ -2499,10 +2643,11 @@ void ModelWidget::pasteObjects(void) while(itr!=itr_end) { - object=(*itr); + object = (*itr); + obj_type = object->getObjectType(); itr++; - if(orig_obj_names[object].count() && obj_type!=OBJ_CAST) + if(orig_obj_names[object].count() && obj_type!=ObjectType::Cast) object->setName(orig_obj_names[object]); } @@ -2526,10 +2671,10 @@ void ModelWidget::pasteObjects(void) try { pos++; - task_prog_wgt.updateProgress((pos/static_cast(copied_objects.size()))*100, + task_prog_wgt.updateProgress((pos/static_cast(copied_objects.size()))*100, trUtf8("Pasting object: `%1' (%2)").arg(object->getName()) .arg(object->getTypeName()), - object->getObjectType()); + enum_cast(object->getObjectType())); //Creates the object from the XML object=db_model->createObject(BaseObject::getObjectType(xmlparser->getElementName())); @@ -2537,11 +2682,11 @@ void ModelWidget::pasteObjects(void) constr=dynamic_cast(tab_obj); /* Once created, the object is added on the model, except for relationships and table objects - because they are inserted automatically */ + * because they are inserted automatically */ if(object && !tab_obj && !dynamic_cast(object)) { if(db_model->getObjectIndex(object->getSignature(), object->getObjectType()) >= 0) - object->setName(PgModelerNS::generateUniqueName(object, *db_model->getObjectList(object->getObjectType()), false, QString("_cp"))); + object->setName(PgModelerNs::generateUniqueName(object, *db_model->getObjectList(object->getObjectType()), false, QString("_cp"))); db_model->addObject(object); } @@ -2549,26 +2694,27 @@ void ModelWidget::pasteObjects(void) //Special case for table objects if(tab_obj) { - if(sel_table && - (tab_obj->getObjectType()==OBJ_COLUMN || tab_obj->getObjectType()==OBJ_RULE)) + if(sel_table && tab_obj->getObjectType()==ObjectType::Column) { sel_table->addObject(tab_obj); sel_table->setModified(true); } - else if(sel_view && tab_obj->getObjectType()==OBJ_RULE) + else if(constr && duplicate_mode && + constr->getConstraintType() == ConstraintType::PrimaryKey && + constr->getParentTable()->getObjectIndex(constr) < 0) { - sel_view->addObject(tab_obj); - sel_view->setModified(true); + constr->getParentTable()->addObject(constr); + constr->getParentTable()->setModified(true); } //Updates the fk relationships if the constraint is a foreign-key - if(constr && constr->getConstraintType()==ConstraintType::foreign_key) + if(constr && constr->getConstraintType()==ConstraintType::ForeignKey) db_model->updateTableFKRelationships(dynamic_cast
(tab_obj->getParentTable())); - op_list->registerObject(tab_obj, Operation::OBJECT_CREATED, -1, tab_obj->getParentTable()); + op_list->registerObject(tab_obj, Operation::ObjectCreated, -1, tab_obj->getParentTable()); } else - op_list->registerObject(object, Operation::OBJECT_CREATED); + op_list->registerObject(object, Operation::ObjectCreated); } catch(Exception &e) { @@ -2588,14 +2734,14 @@ void ModelWidget::pasteObjects(void) if(!errors.empty()) { Messagebox msg_box; - msg_box.show(Exception(trUtf8("Not all objects were pasted to the model due to errors returned during the process! Refer to error stack for more details!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__, errors), - QString(), - Messagebox::ALERT_ICON); + msg_box.show(Exception(trUtf8("Not all objects were pasted to the model due to errors returned during the process! Refer to error stack for more details!"), + ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__, errors), QString(), + Messagebox::AlertIcon); } if(!ModelWidget::cut_operation) { - copied_objects.clear(); + //copied_objects.clear(); emit s_objectCreated(); } //If its a cut operatoin @@ -2631,29 +2777,79 @@ void ModelWidget::duplicateObject(void) try { - if(selected_objects.size() == 1 && TableObject::isTableObject(selected_objects[0]->getObjectType())) + if(scene->hasOnlyTableChildrenSelection() || + (selected_objects.size() == 1 && TableObject::isTableObject(selected_objects[0]->getObjectType()))) { - BaseObject *object = selected_objects[0], *dup_object=nullptr; + Schema *schema = nullptr; + BaseObject *dup_object=nullptr; BaseTable *table = nullptr; - ObjectType obj_type = object->getObjectType(); + ObjectType obj_type; + QList upd_schemas; + QList upd_view_ref_tables; + QList upd_tables; + QList upd_fk_rels; - table = dynamic_cast(object)->getParentTable(); - PgModelerNS::copyObject(&dup_object, object, obj_type); - dup_object->setName(PgModelerNS::generateUniqueName(dup_object, *dynamic_cast
(table)->getObjectList(obj_type), false, QString("_cp"))); + op_list->startOperationChain(); - op_id=op_list->registerObject(dup_object, Operation::OBJECT_CREATED, -1, table); - table->addObject(dup_object); - table->setModified(true); + for(auto &tab_obj : selected_objects) + { + dup_object=nullptr; + obj_type = tab_obj->getObjectType(); + table = dynamic_cast(tab_obj)->getParentTable(); + schema = dynamic_cast(table->getSchema()); + PgModelerNs::copyObject(&dup_object, tab_obj, obj_type); + + if(table->getObjectType() == ObjectType::Table) + dup_object->setName(PgModelerNs::generateUniqueName(dup_object, *dynamic_cast
(table)->getObjectList(obj_type), false, QString("_cp"))); + else + dup_object->setName(PgModelerNs::generateUniqueName(dup_object, *dynamic_cast(table)->getObjectList(obj_type), false, QString("_cp"))); + + op_id=op_list->registerObject(dup_object, Operation::ObjectCreated, -1, table); + table->addObject(dup_object); + + // Flagging the table to be repainted + if(!upd_tables.contains(table)) + upd_tables.append(table); + + // Flagging the schema to be repainted + if(!upd_schemas.contains(schema)) + upd_schemas.append(schema); + + // Flagging the table to have the view references (relationships) updated + if(!upd_view_ref_tables.contains(table) && obj_type == ObjectType::Column) + upd_view_ref_tables.append(table); + // Flagging the table to have its fk relationships updated + else if(!upd_fk_rels.contains(table) && + obj_type == ObjectType::Constraint && + dynamic_cast(tab_obj)->getConstraintType() == ConstraintType::ForeignKey) + upd_fk_rels.append(table); + } + + op_list->finishOperationChain(); + scene->clearSelection(); + + for(auto &tab : upd_tables) + tab->setModified(true); + + for(auto &sch : upd_schemas) + sch->setModified(true); - if(obj_type == OBJ_COLUMN) + for(auto &tab : upd_view_ref_tables) + { db_model->validateRelationships(); + db_model->updateViewsReferencingTable(dynamic_cast
(tab)); + } + for(auto &tab : upd_fk_rels) + db_model->updateTableFKRelationships(dynamic_cast
(tab)); + + this->setModified(true); emit s_objectCreated(); } else if(!selected_objects.empty()) { copyObjects(true); - pasteObjects(); + pasteObjects(true); } } catch(Exception &e) @@ -2662,7 +2858,7 @@ void ModelWidget::duplicateObject(void) if(op_id >= 0) op_list->removeLastOperation(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -2674,10 +2870,10 @@ void ModelWidget::removeObjects(bool cascade) BaseTable *table=nullptr, *src_table=nullptr, *dst_table=nullptr; BaseRelationship *rel=nullptr; TableObject *tab_obj=nullptr; - ObjectType obj_type=BASE_OBJECT, parent_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject, parent_type=ObjectType::BaseObject; BaseObject *object=nullptr, *aux_obj=nullptr; vector sel_objs, aux_sel_objs; - vector constrs; + map> objs_map; map>::reverse_iterator ritr, ritr_end; QAction *obj_sender=dynamic_cast(sender()); @@ -2708,20 +2904,20 @@ void ModelWidget::removeObjects(bool cascade) { if(cascade) msg_box.show(trUtf8("CAUTION: You are about to delete objects in cascade mode which means more objects than the selected will be dropped too. Do you really want to proceed?"), - Messagebox::ALERT_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::AlertIcon, Messagebox::YesNoButtons); else if(sel_objs.size() > 1) { msg_box.show(trUtf8("CAUTION: Remove multiple objects at once can cause irreversible invalidations to other objects in the model causing such invalid objects to be deleted too. Do you really want to proceed?"), - Messagebox::ALERT_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::AlertIcon, Messagebox::YesNoButtons); } else { - if(sel_objs[0]->getObjectType()==OBJ_RELATIONSHIP) + if(sel_objs[0]->getObjectType()==ObjectType::Relationship) msg_box.show(trUtf8("CAUTION: Remove a relationship can cause irreversible invalidations to other objects in the model causing such invalid objects to be deleted too. Do you really want to proceed?"), - Messagebox::ALERT_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::AlertIcon, Messagebox::YesNoButtons); else msg_box.show(trUtf8("Do you really want to delete the selected object?"), - Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); } } @@ -2746,7 +2942,7 @@ void ModelWidget::removeObjects(bool cascade) tab_obj=dynamic_cast(ref_obj); //Store the base relationships in a auxiliary list to be processed ahead - if(ref_obj->getObjectType()==BASE_RELATIONSHIP) + if(ref_obj->getObjectType()==ObjectType::BaseRelationship) { aux_sel_objs.push_back(ref_obj); } @@ -2754,7 +2950,7 @@ void ModelWidget::removeObjects(bool cascade) else if(objs_map.count(obj_id)==0 && (!tab_obj || (tab_obj && !tab_obj->isAddedByRelationship()))) { - parent_type=(tab_obj ? tab_obj->getParentTable()->getObjectType() : OBJ_DATABASE); + parent_type=(tab_obj ? tab_obj->getParentTable()->getObjectType() : ObjectType::Database); parent_name=(tab_obj ? tab_obj->getParentTable()->getName(true) : QString()); obj_name=(tab_obj ? tab_obj->getName() : ref_obj->getSignature()); @@ -2776,42 +2972,11 @@ void ModelWidget::removeObjects(bool cascade) obj_id=object->getObjectId(); //If the object is as FK relationship remove the foreign keys that generates it - if(obj_type==BASE_RELATIONSHIP) + if(obj_type==ObjectType::BaseRelationship) { - /*rel=dynamic_cast(object); - if(rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_FK) - { - aux_table=dynamic_cast
(rel->getTable(BaseRelationship::DST_TABLE)); - dynamic_cast
(rel->getTable(BaseRelationship::SRC_TABLE))->getForeignKeys(constrs,false, aux_table); - - if(!rel->isSelfRelationship()) - { - aux_table=dynamic_cast
(rel->getTable(BaseRelationship::SRC_TABLE)); - dynamic_cast
(rel->getTable(BaseRelationship::DST_TABLE))->getForeignKeys(constrs,false, aux_table); - } - - //Adds the fks to the map of objects to be removed - while(!constrs.empty()) - { - tab_obj=constrs.back(); - obj_id=tab_obj->getObjectId(); - - if(objs_map.count(obj_id)==0) - { - objs_map[tab_obj->getObjectId()]=std::make_tuple(tab_obj, - tab_obj->getName(true), - tab_obj->getObjectType(), - tab_obj->getParentTable()->getName(true), - tab_obj->getParentTable()->getObjectType()); - - } - constrs.pop_back(); - } - }*/ - rel = dynamic_cast(object); - if(rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_FK) + if(rel->getRelationshipType()==BaseRelationship::RelationshipFk) { tab_obj=rel->getReferenceForeignKey(); obj_id=tab_obj->getObjectId(); @@ -2819,10 +2984,10 @@ void ModelWidget::removeObjects(bool cascade) if(objs_map.count(obj_id)==0) { objs_map[tab_obj->getObjectId()]=std::make_tuple(tab_obj, - tab_obj->getName(true), - tab_obj->getObjectType(), - tab_obj->getParentTable()->getName(true), - tab_obj->getParentTable()->getObjectType()); + tab_obj->getName(true), + tab_obj->getObjectType(), + tab_obj->getParentTable()->getName(true), + ObjectType::Table); } } @@ -2833,7 +2998,7 @@ void ModelWidget::removeObjects(bool cascade) obj_name=(tab_obj ? object->getName(true) : object->getSignature()); parent_name=(tab_obj ? tab_obj->getParentTable()->getName(true) : QString()); - parent_type=(tab_obj ? tab_obj->getParentTable()->getObjectType() : OBJ_DATABASE); + parent_type=(tab_obj ? tab_obj->getParentTable()->getObjectType() : ObjectType::Database); objs_map[object->getObjectId()]=std::make_tuple(object, obj_name, @@ -2859,12 +3024,12 @@ void ModelWidget::removeObjects(bool cascade) parent_type=std::get<4>(ritr->second); ritr++; - if(obj_type==BASE_RELATIONSHIP) + if(obj_type==ObjectType::BaseRelationship) continue; - else if(parent_type!=OBJ_DATABASE) + else if(parent_type!=ObjectType::Database) { /* If the parent table does not exist on the model of the object to be removed - does not exists in parent table, it'll not be processed */ + * does not exists in parent table, it'll not be processed */ table=dynamic_cast(db_model->getObject(parent_name, parent_type)); if(!table || (table && table->getObjectIndex(obj_name, obj_type) < 0)) continue; @@ -2879,16 +3044,16 @@ void ModelWidget::removeObjects(bool cascade) //Raises an error if the user try to remove a reserved object if(object->isSystemObject()) - throw Exception(Exception::getErrorMessage(ERR_OPR_RESERVED_OBJECT) - .arg(object->getName()).arg(object->getTypeName()), - ERR_OPR_RESERVED_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::OprReservedObject) + .arg(object->getName()).arg(object->getTypeName()), + ErrorCode::OprReservedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raises an error if the user try to remove a protected object else if(object->isProtected()) { - throw Exception(QString(Exception::getErrorMessage(ERR_REM_PROTECTED_OBJECT)) - .arg(object->getName(true)) - .arg(object->getTypeName()), - ERR_REM_PROTECTED_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::RemProtectedObject) + .arg(object->getName(true)) + .arg(object->getTypeName()), + ErrorCode::RemProtectedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); } else { @@ -2896,24 +3061,33 @@ void ModelWidget::removeObjects(bool cascade) if(tab_obj) { + if(tab_obj->isAddedByRelationship()) + { + throw Exception(Exception::getErrorMessage(ErrorCode::RemProtectedObject) + .arg(tab_obj->getName(true)) + .arg(tab_obj->getTypeName()), + ErrorCode::RemProtectedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + table=dynamic_cast(tab_obj->getParentTable()); obj_idx=table->getObjectIndex(tab_obj->getName(true), obj_type); try { //If the object is a column validates the column removal before remove it - if(!cascade && obj_type==OBJ_COLUMN) + if(!cascade && obj_type==ObjectType::Column) db_model->validateColumnRemoval(dynamic_cast(tab_obj)); //Register the removed object on the operation list table->removeObject(obj_idx, obj_type); - op_list->registerObject(tab_obj, Operation::OBJECT_REMOVED, obj_idx, table); + op_list->registerObject(tab_obj, Operation::ObjectRemoved, obj_idx, table); db_model->removePermissions(tab_obj); aux_table=dynamic_cast
(table); - if(aux_table && obj_type==OBJ_CONSTRAINT && - dynamic_cast(tab_obj)->getConstraintType()==ConstraintType::foreign_key) + + if(aux_table && obj_type==ObjectType::Constraint && + dynamic_cast(tab_obj)->getConstraintType()==ConstraintType::ForeignKey) db_model->updateTableFKRelationships(aux_table); table->setModified(true); @@ -2921,17 +3095,20 @@ void ModelWidget::removeObjects(bool cascade) if(aux_table) db_model->validateRelationships(tab_obj, aux_table); + + if(obj_type == ObjectType::Column) + db_model->updateViewsReferencingTable(aux_table); } catch(Exception &e) { - if(cascade && (e.getErrorType()==ERR_INVALIDATED_OBJECTS || - e.getErrorType()==ERR_REM_DIRECT_REFERENCE || - e.getErrorType()==ERR_REM_INDIRECT_REFERENCE || - e.getErrorType()==ERR_REM_PROTECTED_OBJECT || - e.getErrorType()==ERR_OPR_RESERVED_OBJECT)) + if(cascade && (e.getErrorCode()==ErrorCode::RemInvalidatedObjects || + e.getErrorCode()==ErrorCode::RemDirectReference || + e.getErrorCode()==ErrorCode::RemInderectReference || + e.getErrorCode()==ErrorCode::RemProtectedObject || + e.getErrorCode()==ErrorCode::OprReservedObject)) errors.push_back(e); else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } else @@ -2940,28 +3117,28 @@ void ModelWidget::removeObjects(bool cascade) if(obj_idx >=0 ) { - if(obj_type==OBJ_RELATIONSHIP) + if(obj_type==ObjectType::Relationship) { rel=dynamic_cast(object); - src_table=rel->getTable(BaseRelationship::SRC_TABLE); - dst_table=rel->getTable(BaseRelationship::DST_TABLE); + src_table=rel->getTable(BaseRelationship::SrcTable); + dst_table=rel->getTable(BaseRelationship::DstTable); } try { db_model->removeObject(object, obj_idx); - op_list->registerObject(object, Operation::OBJECT_REMOVED, obj_idx); + op_list->registerObject(object, Operation::ObjectRemoved, obj_idx); } catch(Exception &e) { - if(cascade && (e.getErrorType()==ERR_INVALIDATED_OBJECTS || - e.getErrorType()==ERR_REM_DIRECT_REFERENCE || - e.getErrorType()==ERR_REM_INDIRECT_REFERENCE || - e.getErrorType()==ERR_REM_PROTECTED_OBJECT || - e.getErrorType()==ERR_OPR_RESERVED_OBJECT)) + if(cascade && (e.getErrorCode()==ErrorCode::RemInvalidatedObjects || + e.getErrorCode()==ErrorCode::RemDirectReference || + e.getErrorCode()==ErrorCode::RemInderectReference || + e.getErrorCode()==ErrorCode::RemProtectedObject || + e.getErrorCode()==ErrorCode::OprReservedObject)) errors.push_back(e); else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } if(rel) @@ -2985,16 +3162,13 @@ void ModelWidget::removeObjects(bool cascade) if(!errors.empty()) { - msg_box.show(Exception(ERR_INVALIDATED_OBJECTS, __PRETTY_FUNCTION__,__FILE__,__LINE__, errors), + msg_box.show(Exception(ErrorCode::RemInvalidatedObjects, __PRETTY_FUNCTION__,__FILE__,__LINE__, errors), trUtf8("The cascade deletion found some problems when running! Some objects could not be deleted or registered in the operation's history! Please, refer to error stack for more details."), - Messagebox::ALERT_ICON); + Messagebox::AlertIcon); } } catch(Exception &e) { - //if(e.getErrorType()==ERR_INVALIDATED_OBJECTS) - // op_list->removeOperations(); - if(op_list->isOperationChainStarted()) op_list->finishOperationChain(); @@ -3014,6 +3188,10 @@ void ModelWidget::removeObjects(bool cascade) emit s_objectRemoved(); msg_box.show(e); } + + /* In case of any object removal we clear the copied objects list in order to avoid + * segfaults when trying to paste an object that was removed previously */ + copied_objects.clear(); } } } @@ -3046,7 +3224,7 @@ void ModelWidget::showObjectMenu(void) if(tab_obj && tab_obj->getParentTable()) //Get the graphical representation for table - tab=dynamic_cast(tab_obj->getParentTable()->getReceiverObject()); + tab=dynamic_cast(tab_obj->getParentTable()->getOverlyingObject()); } magnifier_area_lbl->hide(); @@ -3090,9 +3268,10 @@ void ModelWidget::enableModelActions(bool value) void ModelWidget::configureSubmenu(BaseObject *object) { + QAction *act=nullptr; vector sel_objs; - ObjectType obj_type=BASE_OBJECT; - bool tab_or_view=false, accepts_owner=false, accepts_schema=false; + ObjectType obj_type=ObjectType::BaseObject; + bool tab_or_view=false, is_graph_obj = false, accepts_owner=false, accepts_schema=false; if(object) sel_objs.push_back(object); @@ -3106,7 +3285,10 @@ void ModelWidget::configureSubmenu(BaseObject *object) obj_type=obj->getObjectType(); if(!tab_or_view) - tab_or_view=(obj_type==OBJ_TABLE || obj_type==OBJ_VIEW); + tab_or_view=(obj_type==ObjectType::Table || obj_type==ObjectType::View); + + if(!is_graph_obj) + is_graph_obj = BaseGraphicObject::isGraphicObject(obj_type); if(!accepts_owner) accepts_owner=obj->acceptsOwner(); @@ -3122,21 +3304,20 @@ void ModelWidget::configureSubmenu(BaseObject *object) { if(accepts_owner || accepts_schema) { - QAction *act=nullptr; vector obj_list; map act_map; QStringList name_list; QMenu *menus[]={ &schemas_menu, &owners_menu, &tags_menu }; - ObjectType types[]={ OBJ_SCHEMA, OBJ_ROLE, OBJ_TAG }; + ObjectType types[]={ ObjectType::Schema, ObjectType::Role, ObjectType::Tag }; for(unsigned i=0; i < 3; i++) { menus[i]->clear(); //Configuring actions "Move to schema", "Change Owner" and "Set tag" - if((i==0 && accepts_schema) || - (i==1 && accepts_owner) || - (i==2 && tab_or_view)) + if((types[i] == ObjectType::Schema && accepts_schema) || + (types[i] == ObjectType::Role && accepts_owner) || + (types[i]==ObjectType::Tag && tab_or_view)) { obj_list=db_model->getObjects(types[i]); @@ -3147,10 +3328,16 @@ void ModelWidget::configureSubmenu(BaseObject *object) } else { + if(types[i] == ObjectType::Tag) + { + menus[i]->addAction(trUtf8("None"), this, SLOT(setTag())); + menus[i]->addSeparator(); + } + while(!obj_list.empty()) { act=new QAction(obj_list.back()->getName(), menus[i]); - act->setIcon(QPixmap(PgModelerUiNS::getIconPath(types[i]))); + act->setIcon(QPixmap(PgModelerUiNs::getIconPath(types[i]))); /* Check the current action only if there is only one selected object and the object representing the action is assigned to the selected object */ @@ -3188,8 +3375,22 @@ void ModelWidget::configureSubmenu(BaseObject *object) } } + // Configuring the layers menu + if(is_graph_obj) + { + unsigned layer_id = ObjectsScene::DefaultLayer; + layers_menu.clear(); + + for(auto &layer : scene->getLayers()) + { + act = layers_menu.addAction(layer); + act->setData(layer_id++); + connect(act, SIGNAL(triggered(bool)), this, SLOT(moveToLayer())); + } + } + //Display the quick rename action is a single object is selected - if(object && obj_type!=OBJ_CAST) + if(object && obj_type!=ObjectType::Cast) { quick_actions_menu.addAction(action_rename); action_rename->setData(QVariant::fromValue(object)); @@ -3198,20 +3399,24 @@ void ModelWidget::configureSubmenu(BaseObject *object) if(accepts_schema) quick_actions_menu.addAction(action_moveto_schema); + if(is_graph_obj) + quick_actions_menu.addAction(action_moveto_layer); + if(accepts_owner) quick_actions_menu.addAction(action_change_owner); if(tab_or_view) quick_actions_menu.addAction(action_set_tag); - //Display the "Edit permissions" action a single object is selected and it accepts permissions - if(object && Permission::objectAcceptsPermission(obj_type)) + if(object && Permission::acceptsPermission(obj_type)) { quick_actions_menu.addAction(action_edit_perms); action_edit_perms->setData(QVariant::fromValue(object)); } - //Display the "Edit permissions" action a single object is selected and it accepts permissions + if(object && obj_type == ObjectType::Table) + quick_actions_menu.addAction(action_edit_data); + if(object && BaseObject::acceptsCustomSQL(obj_type)) { action_append_sql->setData(QVariant::fromValue(object)); @@ -3219,7 +3424,7 @@ void ModelWidget::configureSubmenu(BaseObject *object) } if(object && - ((!TableObject::isTableObject(obj_type) && obj_type!=OBJ_TEXTBOX && obj_type!=BASE_RELATIONSHIP) || + ((!TableObject::isTableObject(obj_type) && obj_type!=ObjectType::Textbox && obj_type!=ObjectType::BaseRelationship) || (TableObject::isTableObject(obj_type) && !dynamic_cast(object)->isAddedByRelationship()))) { action_enable_sql->setData(QVariant::fromValue(object)); @@ -3240,12 +3445,12 @@ void ModelWidget::configureSubmenu(BaseObject *object) void ModelWidget::configureFadeMenu(void) { bool is_db_selected = (selected_objects.empty() || - (selected_objects.size() == 1 && selected_objects[0]->getObjectType() == OBJ_DATABASE)); + (selected_objects.size() == 1 && selected_objects[0]->getObjectType() == ObjectType::Database)); fade_menu.clear(); fade_in_menu.clear(); fade_out_menu.clear(); - if(is_db_selected || selected_objects.size() > 1) + if(is_db_selected || (selected_objects.size() > 1 && !scene->hasOnlyTableChildrenSelection())) { fade_menu.addAction(action_fade_in); fade_menu.addAction(action_fade_out); @@ -3255,21 +3460,21 @@ void ModelWidget::configureFadeMenu(void) if(is_db_selected) { QAction *action = nullptr; - vector types = { OBJ_SCHEMA, OBJ_TABLE, OBJ_VIEW, OBJ_RELATIONSHIP, OBJ_TEXTBOX }; + vector types = { ObjectType::Schema, ObjectType::Table, ObjectType::View, ObjectType::Relationship, ObjectType::Textbox }; QStringList labels = { trUtf8("Schemas"), trUtf8("Tables"), trUtf8("Views"), trUtf8("Relationships"), trUtf8("Textboxes") }; unsigned id = 0; for(ObjectType type : types) { - action = new QAction(QPixmap(PgModelerUiNS::getIconPath(BaseObject::getSchemaName(type) + QString("_grp"))), + action = new QAction(QPixmap(PgModelerUiNs::getIconPath(BaseObject::getSchemaName(type) + QString("_grp"))), labels[id], &fade_in_menu); - action->setData(type); + action->setData(enum_cast(type)); fade_in_menu.addAction(action); connect(action, SIGNAL(triggered(bool)), this, SLOT(fadeObjectsIn())); - action = new QAction(QPixmap(PgModelerUiNS::getIconPath(BaseObject::getSchemaName(type) + QString("_grp"))), + action = new QAction(QPixmap(PgModelerUiNs::getIconPath(BaseObject::getSchemaName(type) + QString("_grp"))), labels[id], &fade_out_menu); - action->setData(type); + action->setData(enum_cast(type)); fade_out_menu.addAction(action); id++; @@ -3277,13 +3482,13 @@ void ModelWidget::configureFadeMenu(void) } action = new QAction(trUtf8("All objects"), &fade_in_menu); - action->setData(BASE_OBJECT); + action->setData(enum_cast(ObjectType::BaseObject)); connect(action, SIGNAL(triggered(bool)), this, SLOT(fadeObjectsIn())); fade_in_menu.addSeparator(); fade_in_menu.addAction(action); action = new QAction(trUtf8("All objects"), &fade_out_menu); - action->setData(BASE_OBJECT); + action->setData(enum_cast(ObjectType::BaseObject)); connect(action, SIGNAL(triggered(bool)), this, SLOT(fadeObjectsOut())); fade_out_menu.addSeparator(); fade_out_menu.addAction(action); @@ -3294,11 +3499,11 @@ void ModelWidget::configureFadeMenu(void) action_fade_out->setMenu(nullptr); } } - else + else if(selected_objects.size() == 1) { ObjectType obj_type = selected_objects[0]->getObjectType(); - if(obj_type == OBJ_TAG) + if(obj_type == ObjectType::Tag) { fade_menu.addAction(action_fade_in); fade_menu.addAction(action_fade_out); @@ -3307,7 +3512,7 @@ void ModelWidget::configureFadeMenu(void) } else { - BaseObjectView *obj_view = dynamic_cast(dynamic_cast(selected_objects[0])->getReceiverObject()); + BaseObjectView *obj_view = dynamic_cast(dynamic_cast(selected_objects[0])->getOverlyingObject()); if(obj_view) { @@ -3323,8 +3528,11 @@ void ModelWidget::configureFadeMenu(void) } } - if(obj_type == OBJ_TABLE || obj_type == OBJ_VIEW) + if(obj_type == ObjectType::Table || obj_type == ObjectType::View) + { fade_menu.addAction(action_fade_rels); + action_fade_rels->setText(trUtf8("Table && Relationships")); + } } } } @@ -3332,13 +3540,17 @@ void ModelWidget::configureFadeMenu(void) void ModelWidget::fadeObjects(const vector &objects, bool fade_in) { BaseObjectView *obj_view = nullptr; + Schema *schema = nullptr; for(auto obj : objects) { - if(!BaseGraphicObject::isGraphicObject(obj->getObjectType())) + schema = dynamic_cast(obj); + + if(!BaseGraphicObject::isGraphicObject(obj->getObjectType()) || + (schema && !schema->isRectVisible())) continue; - obj_view = dynamic_cast(dynamic_cast(obj)->getReceiverObject()); + obj_view = dynamic_cast(dynamic_cast(obj)->getOverlyingObject()); if(obj_view) { @@ -3347,7 +3559,7 @@ void ModelWidget::fadeObjects(const vector &objects, bool fade_in) obj_view->setOpacity(fade_in ? 1 : min_object_opacity); //If the minimum opacity is zero the object hidden - obj_view->setVisible(fade_in || (!fade_in && min_object_opacity > 0)); + obj_view->setVisible(scene->isLayerActive(obj_view->getLayer()) && (fade_in || (!fade_in && min_object_opacity > 0))); this->modified = true; } @@ -3362,18 +3574,17 @@ void ModelWidget::fadeObjects(QAction *action, bool fade_in) return; vector list; - //BaseObjectView *obj_view = nullptr; //If the database object is selected or there is no object select - if(selected_objects.empty() || (selected_objects.size() == 1 && selected_objects[0]->getObjectType() == OBJ_DATABASE)) + if(selected_objects.empty() || (selected_objects.size() == 1 && selected_objects[0]->getObjectType() == ObjectType::Database)) { ObjectType obj_type = static_cast(action->data().toUInt()); - //If the action contains a data of type BASE_OBJECT means that the user wants to fade all objects - if(obj_type == BASE_OBJECT) + //If the action contains a data of type ObjectType::ObjBaseObject means that the user wants to fade all objects + if(obj_type == ObjectType::BaseObject) { - vector types = { OBJ_SCHEMA, OBJ_TABLE, OBJ_VIEW, - OBJ_RELATIONSHIP, BASE_RELATIONSHIP, OBJ_TEXTBOX}; + vector types = { ObjectType::Schema, ObjectType::Table, ObjectType::View, + ObjectType::Relationship, ObjectType::BaseRelationship, ObjectType::Textbox}; for(ObjectType type : types) { @@ -3387,18 +3598,18 @@ void ModelWidget::fadeObjects(QAction *action, bool fade_in) //Fading objects of a certain type list = *db_model->getObjectList(obj_type); - if(obj_type == OBJ_RELATIONSHIP) + if(obj_type == ObjectType::Relationship) { list.insert(list.end(), - db_model->getObjectList(BASE_RELATIONSHIP)->begin(), - db_model->getObjectList(BASE_RELATIONSHIP)->end()); + db_model->getObjectList(ObjectType::BaseRelationship)->begin(), + db_model->getObjectList(ObjectType::BaseRelationship)->end()); } } } else { //For tag object the fade is applied in the tables/views related to it - if(selected_objects.size() == 1 && selected_objects[0]->getObjectType() == OBJ_TAG) + if(selected_objects.size() == 1 && selected_objects[0]->getObjectType() == ObjectType::Tag) db_model->getObjectReferences(selected_objects[0], list); else { @@ -3408,7 +3619,16 @@ void ModelWidget::fadeObjects(QAction *action, bool fade_in) vector rel_list = db_model->getRelationships(dynamic_cast(selected_objects[0])); for(auto rel : rel_list) + { list.push_back(rel); + list.push_back(rel->getTable(BaseRelationship::SrcTable)); + list.push_back(rel->getTable(BaseRelationship::DstTable)); + } + + vector::iterator end; + std::sort(list.begin(), list.end()); + end=std::unique(list.begin(), list.end()); + list.erase(end, list.end()); } else //Applying fade to the selected objects @@ -3416,23 +3636,6 @@ void ModelWidget::fadeObjects(QAction *action, bool fade_in) } } - /*for(auto obj : list) - { - obj_view = dynamic_cast(dynamic_cast(obj)->getReceiverObject()); - - if(obj_view) - { - dynamic_cast(obj)->setFadedOut(!fade_in); - - obj_view->setOpacity(fade_in ? 1 : min_object_opacity); - - //If the minimum opacity is zero the object hidden - obj_view->setVisible(fade_in || (!fade_in && min_object_opacity > 0)); - - this->modified = true; - } - } */ - fadeObjects(list, fade_in); scene->clearSelection(); } @@ -3447,16 +3650,36 @@ void ModelWidget::fadeObjectsOut(void) fadeObjects(qobject_cast(sender()), false); } -void ModelWidget::toggleExtendedAttributes(void) +void ModelWidget::setAllCollapseMode(CollapseMode mode) +{ + BaseTable *base_tab = nullptr; + vector objects; + + this->scene->clearSelection(); + objects.assign(db_model->getObjectList(ObjectType::Table)->begin(), db_model->getObjectList(ObjectType::Table)->end()); + objects.insert(objects.end(), db_model->getObjectList(ObjectType::View)->begin(), db_model->getObjectList(ObjectType::View)->end()); + + for(auto obj : objects) + { + base_tab = dynamic_cast(obj); + + if(base_tab) + base_tab->setCollapseMode(mode); + } + + this->setModified(true); +} + +void ModelWidget::setCollapseMode(void) { - bool hide = sender() == action_hide_ext_attribs; + CollapseMode mode = static_cast(dynamic_cast(sender())->data().toUInt()); BaseTable *base_tab = nullptr; vector objects; if(selected_objects.empty() || (selected_objects.size() == 1 && selected_objects[0] == db_model)) { - objects.assign(db_model->getObjectList(OBJ_TABLE)->begin(), db_model->getObjectList(OBJ_TABLE)->end()); - objects.insert(objects.end(), db_model->getObjectList(OBJ_VIEW)->begin(), db_model->getObjectList(OBJ_VIEW)->end()); + objects.assign(db_model->getObjectList(ObjectType::Table)->begin(), db_model->getObjectList(ObjectType::Table)->end()); + objects.insert(objects.end(), db_model->getObjectList(ObjectType::View)->begin(), db_model->getObjectList(ObjectType::View)->end()); } else objects = selected_objects; @@ -3465,14 +3688,43 @@ void ModelWidget::toggleExtendedAttributes(void) { base_tab = dynamic_cast(obj); - if(base_tab && base_tab->isExtAttribsHidden() != hide) + if(base_tab && base_tab->getCollapseMode() != mode) { - base_tab->setExtAttribsHidden(hide); + base_tab->setCollapseMode(mode); base_tab->setModified(true); } } - db_model->setObjectsModified({ OBJ_SCHEMA }); + db_model->setObjectsModified({ ObjectType::Schema }); + this->setModified(true); +} + +void ModelWidget::togglePagination(void) +{ + bool enable = dynamic_cast(sender())->data().toBool(); + BaseTable *base_tab = nullptr; + vector objects; + + if(selected_objects.empty() || (selected_objects.size() == 1 && selected_objects[0] == db_model)) + { + objects.assign(db_model->getObjectList(ObjectType::Table)->begin(), db_model->getObjectList(ObjectType::Table)->end()); + objects.insert(objects.end(), db_model->getObjectList(ObjectType::View)->begin(), db_model->getObjectList(ObjectType::View)->end()); + } + else + objects = selected_objects; + + for(auto obj : objects) + { + base_tab = dynamic_cast(obj); + + if(base_tab && base_tab->isPaginationEnabled() != enable) + { + base_tab->setPaginationEnabled(enable); + base_tab->setModified(true); + } + } + + db_model->setObjectsModified({ ObjectType::Schema }); this->setModified(true); } @@ -3481,7 +3733,7 @@ void ModelWidget::toggleSchemasRectangles(void) bool visible = sender() == action_show_schemas_rects; Schema *schema = nullptr; - for(auto obj : *db_model->getObjectList(OBJ_SCHEMA)) + for(auto obj : *db_model->getObjectList(ObjectType::Schema)) { schema = dynamic_cast(obj); @@ -3497,8 +3749,8 @@ void ModelWidget::toggleSchemasRectangles(void) void ModelWidget::updateObjectsOpacity(void) { - vector types = { OBJ_SCHEMA, OBJ_TABLE, OBJ_VIEW, - OBJ_RELATIONSHIP, BASE_RELATIONSHIP, OBJ_TEXTBOX}; + vector types = { ObjectType::Schema, ObjectType::Table, ObjectType::View, + ObjectType::Relationship, ObjectType::BaseRelationship, ObjectType::Textbox}; BaseObjectView *obj_view = nullptr; BaseGraphicObject *base_obj = nullptr; @@ -3507,7 +3759,7 @@ void ModelWidget::updateObjectsOpacity(void) for(auto object : *db_model->getObjectList(type)) { base_obj = dynamic_cast(object); - obj_view = dynamic_cast(base_obj->getReceiverObject()); + obj_view = dynamic_cast(base_obj->getOverlyingObject()); if(obj_view && ((base_obj->isFadedOut() && obj_view->opacity() == 1) || @@ -3545,16 +3797,12 @@ void ModelWidget::configurePopupMenu(const vector &objects) //Case there is no selected object or the selected object is the database model if(objects.empty() || (objects.size()==1 && objects[0]==db_model)) { - ObjectType types[]={ OBJ_AGGREGATE, OBJ_CAST, OBJ_EVENT_TRIGGER, OBJ_COLLATION, OBJ_CONVERSION, OBJ_DOMAIN, - OBJ_EXTENSION, OBJ_FUNCTION, OBJ_GENERIC_SQL, OBJ_LANGUAGE, OBJ_OPCLASS, OBJ_OPERATOR, - OBJ_OPFAMILY, OBJ_RELATIONSHIP, OBJ_ROLE, OBJ_SCHEMA, OBJ_SEQUENCE, - OBJ_TABLE, OBJ_TABLESPACE, OBJ_TEXTBOX, OBJ_TYPE, OBJ_VIEW, OBJ_TAG }; - unsigned cnt = sizeof(types)/sizeof(ObjectType); - - //Configures the "New object" menu with the types at database level - for(i=0; i < cnt; i++) - new_object_menu.addAction(actions_new_objects[types[i]]); - + new_object_menu.addAction(action_database_category); + new_object_menu.addAction(action_schema_category); + new_object_menu.addAction(actions_new_objects[ObjectType::Relationship]); + new_object_menu.addAction(actions_new_objects[ObjectType::GenericSql]); + new_object_menu.addAction(actions_new_objects[ObjectType::Tag]); + new_object_menu.addAction(actions_new_objects[ObjectType::Textbox]); action_new_object->setMenu(&new_object_menu); popup_menu.addAction(action_new_object); @@ -3585,34 +3833,34 @@ void ModelWidget::configurePopupMenu(const vector &objects) configureSubmenu(obj); popup_menu.addAction(action_edit); - if((obj_type==OBJ_SCHEMA && obj->isSystemObject()) || - (!obj->isProtected() && (obj_type==OBJ_TABLE || obj_type==BASE_RELATIONSHIP || - obj_type==OBJ_RELATIONSHIP || obj_type==OBJ_SCHEMA || - obj_type == OBJ_TAG || obj_type==OBJ_VIEW))) + if((obj_type==ObjectType::Schema && obj->isSystemObject()) || + (!obj->isProtected() && (obj_type==ObjectType::Table || obj_type==ObjectType::BaseRelationship || + obj_type==ObjectType::Relationship || obj_type==ObjectType::Schema || + obj_type == ObjectType::Tag || obj_type==ObjectType::View))) { - if(obj_type==OBJ_TABLE || obj_type == OBJ_VIEW) + if(obj_type==ObjectType::Table || obj_type == ObjectType::View) { for(auto type : BaseObject::getChildObjectTypes(obj_type)) new_object_menu.addAction(actions_new_objects[type]); - if(obj_type==OBJ_TABLE) - new_object_menu.addAction(actions_new_objects[OBJ_RELATIONSHIP]); + if(obj_type==ObjectType::Table) + new_object_menu.addAction(actions_new_objects[ObjectType::Relationship]); action_new_object->setMenu(&new_object_menu); popup_menu.insertAction(action_quick_actions, action_new_object); } - else if(obj_type==OBJ_RELATIONSHIP || obj_type==BASE_RELATIONSHIP) + else if(obj_type==ObjectType::Relationship || obj_type==ObjectType::BaseRelationship) { - if(obj_type==OBJ_RELATIONSHIP) + if(obj_type==ObjectType::Relationship) { - new_object_menu.addAction(actions_new_objects[OBJ_COLUMN]); - new_object_menu.addAction(actions_new_objects[OBJ_CONSTRAINT]); + new_object_menu.addAction(actions_new_objects[ObjectType::Column]); + new_object_menu.addAction(actions_new_objects[ObjectType::Constraint]); action_new_object->setMenu(&new_object_menu); popup_menu.insertAction(action_quick_actions, action_new_object); } - if(rel->getRelationshipType()==Relationship::RELATIONSHIP_NN) + if(rel->getRelationshipType()==Relationship::RelationshipNn) { action_convert_relnn->setData(QVariant::fromValue(rel)); popup_menu.addAction(action_convert_relnn); @@ -3634,18 +3882,18 @@ void ModelWidget::configurePopupMenu(const vector &objects) popup_menu.addAction(action_jump_to_table); jump_to_tab_menu.clear(); - action = jump_to_tab_menu.addAction(QIcon(PgModelerUiNS::getIconPath(rel->getTable(BaseRelationship::SRC_TABLE)->getObjectType())), - rel->getTable(BaseRelationship::SRC_TABLE)->getSignature(), this, SLOT(jumpToTable())); - action->setData(QVariant::fromValue(reinterpret_cast(rel->getTable(BaseRelationship::SRC_TABLE)))); + action = jump_to_tab_menu.addAction(QIcon(PgModelerUiNs::getIconPath(rel->getTable(BaseRelationship::SrcTable)->getObjectType())), + rel->getTable(BaseRelationship::SrcTable)->getSignature(), this, SLOT(jumpToTable())); + action->setData(QVariant::fromValue(reinterpret_cast(rel->getTable(BaseRelationship::SrcTable)))); - action = jump_to_tab_menu.addAction(QIcon(PgModelerUiNS::getIconPath(rel->getTable(BaseRelationship::DST_TABLE)->getObjectType())), - rel->getTable(BaseRelationship::DST_TABLE)->getSignature(), this, SLOT(jumpToTable())); - action->setData(QVariant::fromValue(reinterpret_cast(rel->getTable(BaseRelationship::DST_TABLE)))); + action = jump_to_tab_menu.addAction(QIcon(PgModelerUiNs::getIconPath(rel->getTable(BaseRelationship::DstTable)->getObjectType())), + rel->getTable(BaseRelationship::DstTable)->getSignature(), this, SLOT(jumpToTable())); + action->setData(QVariant::fromValue(reinterpret_cast(rel->getTable(BaseRelationship::DstTable)))); } } - else if(obj_type == OBJ_SCHEMA) + else if(obj_type == ObjectType::Schema) { - for(auto type : BaseObject::getChildObjectTypes(OBJ_SCHEMA)) + for(auto type : BaseObject::getChildObjectTypes(ObjectType::Schema)) new_object_menu.addAction(actions_new_objects[type]); action_new_object->setMenu(&new_object_menu); @@ -3654,7 +3902,7 @@ void ModelWidget::configurePopupMenu(const vector &objects) popup_menu.addAction(action_sel_sch_children); action_sel_sch_children->setData(QVariant::fromValue(obj)); } - else if(obj_type == OBJ_TAG) + else if(obj_type == ObjectType::Tag) { popup_menu.addAction(action_sel_tagged_tabs); action_sel_tagged_tabs->setData(QVariant::fromValue(obj)); @@ -3675,7 +3923,7 @@ void ModelWidget::configurePopupMenu(const vector &objects) action_deps_refs->setData(QVariant::fromValue(obj)); tab_obj=dynamic_cast(obj); - if(tab_obj && tab_obj->getObjectType()==OBJ_COLUMN) + if(tab_obj && tab_obj->getObjectType()==ObjectType::Column) { Column *col=dynamic_cast(tab_obj); @@ -3714,7 +3962,7 @@ void ModelWidget::configurePopupMenu(const vector &objects) for(auto &obj : objects) { - rem_points = obj->getObjectType() == OBJ_RELATIONSHIP || obj->getObjectType() == BASE_RELATIONSHIP; + rem_points = obj->getObjectType() == ObjectType::Relationship || obj->getObjectType() == ObjectType::BaseRelationship; if(!rem_points) break; } @@ -3734,7 +3982,7 @@ void ModelWidget::configurePopupMenu(const vector &objects) /* Special case for systema objects: The actions protect/unprotect will be displayed only for system schemas. The rest of system objects those actions aren't available */ if(!objects[0]->isSystemObject() || - (objects[0]->isSystemObject() && objects[0]->getObjectType()==OBJ_SCHEMA)) + (objects[0]->isSystemObject() && objects[0]->getObjectType()==ObjectType::Schema)) { if(!objects[0]->isProtected()) popup_menu.addAction(action_protect); @@ -3745,10 +3993,10 @@ void ModelWidget::configurePopupMenu(const vector &objects) //Adding the extended attributes action (only for table/view/database) if(objects.size() > 1 || - (objects.empty() && (db_model->getObjectCount(OBJ_TABLE) > 0 || db_model->getObjectCount(OBJ_VIEW) > 0)) || - (objects.size() == 1 && (objects[0]->getObjectType() == OBJ_TABLE || - objects[0]->getObjectType() == OBJ_VIEW || - objects[0]->getObjectType() == OBJ_DATABASE))) + (objects.empty() && (db_model->getObjectCount(ObjectType::Table) > 0 || db_model->getObjectCount(ObjectType::View) > 0)) || + (objects.size() == 1 && (objects[0]->getObjectType() == ObjectType::Table || + objects[0]->getObjectType() == ObjectType::View || + objects[0]->getObjectType() == ObjectType::Database))) { bool tab_or_view = false; @@ -3756,22 +4004,25 @@ void ModelWidget::configurePopupMenu(const vector &objects) { if(!tab_or_view) { - tab_or_view=(obj->getObjectType()==OBJ_TABLE || obj->getObjectType()==OBJ_VIEW); + tab_or_view=(obj->getObjectType()==ObjectType::Table || obj->getObjectType()==ObjectType::View); break; } } if(tab_or_view || objects.empty() || objects.size() == 1) - popup_menu.addAction(action_extended_attribs); + { + popup_menu.addAction(action_collapse_mode); + popup_menu.addAction(action_pagination); + } - if(objects.empty() || (objects.size() == 1 && objects[0]->getObjectType() == OBJ_DATABASE)) + if(objects.empty() || (objects.size() == 1 && objects[0]->getObjectType() == ObjectType::Database)) popup_menu.addAction(action_schemas_rects); } if(!tab_obj && - (objects.empty() || objects.size() > 1 || - (objects.size() == 1 && (objects[0]->getObjectType() == OBJ_DATABASE || - objects[0]->getObjectType() == OBJ_TAG || + (objects.empty() || (objects.size() > 1 && !scene->hasOnlyTableChildrenSelection()) || + (objects.size() == 1 && (objects[0]->getObjectType() == ObjectType::Database || + objects[0]->getObjectType() == ObjectType::Tag || BaseGraphicObject::isGraphicObject(objects[0]->getObjectType()))))) { //Adding fade inout action only for graphical objects or when there is no objects selected or many objects seleted @@ -3782,7 +4033,7 @@ void ModelWidget::configurePopupMenu(const vector &objects) //Adding the copy and paste if there is selected objects if(!model_protected && - !(objects.size()==1 && (objects[0]==db_model || objects[0]->getObjectType()==BASE_RELATIONSHIP)) && + !(objects.size()==1 && (objects[0]==db_model || objects[0]->getObjectType()==ObjectType::BaseRelationship)) && !objects.empty()) { popup_menu.addAction(action_copy); @@ -3809,9 +4060,9 @@ void ModelWidget::configurePopupMenu(const vector &objects) 4) The object is a base relationship (table-view) */ if((tab_obj && !tab_obj->isAddedByRelationship() && !tab_obj->isProtected()) || (objects.size()==1 && objects[0]->isProtected()) || - (!tab_obj && objects.size()==1 && objects[0]!=db_model && objects[0]->getObjectType()!=BASE_RELATIONSHIP) || - (objects.size()==1 && objects[0]->getObjectType()==BASE_RELATIONSHIP && - dynamic_cast(objects[0])->getRelationshipType()==BaseRelationship::RELATIONSHIP_FK) || + (!tab_obj && objects.size()==1 && objects[0]!=db_model && objects[0]->getObjectType()!=ObjectType::BaseRelationship) || + (objects.size()==1 && objects[0]->getObjectType()==ObjectType::BaseRelationship && + dynamic_cast(objects[0])->getRelationshipType()==BaseRelationship::RelationshipFk) || objects.size() > 1) { popup_menu.addAction(action_remove); @@ -3823,7 +4074,7 @@ void ModelWidget::configurePopupMenu(const vector &objects) { table=dynamic_cast
(tab_obj->getParentTable()); - if(tab_obj->getObjectType()==OBJ_COLUMN) + if(tab_obj->getObjectType()==ObjectType::Column) { count=table->getConstraintCount(); @@ -3834,27 +4085,27 @@ void ModelWidget::configurePopupMenu(const vector &objects) { switch(!constr->getConstraintType()) { - case ConstraintType::primary_key: str_aux=QString("_%1").arg(TableObjectView::TXT_PRIMARY_KEY); break; - case ConstraintType::foreign_key: str_aux=QString("_%1").arg(TableObjectView::TXT_FOREIGN_KEY); break; - case ConstraintType::check: str_aux=QString("_%1").arg(TableObjectView::TXT_CHECK); break; - case ConstraintType::unique: str_aux=QString("_%1").arg(TableObjectView::TXT_UNIQUE); break; - case ConstraintType::exclude: str_aux=QString("_%1").arg(TableObjectView::TXT_EXCLUDE); break; + case ConstraintType::PrimaryKey: str_aux=QString("_%1").arg(TableObjectView::TextPrimaryKey); break; + case ConstraintType::ForeignKey: str_aux=QString("_%1").arg(TableObjectView::TextForeignKey); break; + case ConstraintType::Check: str_aux=QString("_%1").arg(TableObjectView::TextCheck); break; + case ConstraintType::Unique: str_aux=QString("_%1").arg(TableObjectView::TextUnique); break; + case ConstraintType::Exclude: str_aux=QString("_%1").arg(TableObjectView::TextExclude); break; } //For each constaint is created a menu with the edit, source code, protect/unprotect and delete actions submenu=new QMenu(&popup_menu); - submenu->setIcon(QPixmap(PgModelerUiNS::getIconPath(BaseObject::getSchemaName(OBJ_CONSTRAINT) + str_aux))); + submenu->setIcon(QPixmap(PgModelerUiNs::getIconPath(BaseObject::getSchemaName(ObjectType::Constraint) + str_aux))); submenu->setTitle(constr->getName()); action=new QAction(dynamic_cast(submenu)); - action->setIcon(QPixmap(PgModelerUiNS::getIconPath("editar"))); + action->setIcon(QPixmap(PgModelerUiNs::getIconPath("editar"))); action->setText(trUtf8("Properties")); action->setData(QVariant::fromValue(dynamic_cast(constr))); connect(action, SIGNAL(triggered(bool)), this, SLOT(editObject(void))); submenu->addAction(action); action=new QAction(dynamic_cast(submenu)); - action->setIcon(QPixmap(PgModelerUiNS::getIconPath("codigosql"))); + action->setIcon(QPixmap(PgModelerUiNs::getIconPath("codigosql"))); action->setText(trUtf8("Source code")); action->setData(QVariant::fromValue(dynamic_cast(constr))); connect(action, SIGNAL(triggered(bool)), this, SLOT(showSourceCode(void))); @@ -3871,25 +4122,25 @@ void ModelWidget::configurePopupMenu(const vector &objects) if(constr->isProtected()) { - action->setIcon(QPixmap(PgModelerUiNS::getIconPath("desbloqobjeto"))); + action->setIcon(QPixmap(PgModelerUiNs::getIconPath("desbloqobjeto"))); action->setText(trUtf8("Unprotect")); } else { - action->setIcon(QPixmap(PgModelerUiNS::getIconPath("bloqobjeto"))); + action->setIcon(QPixmap(PgModelerUiNs::getIconPath("bloqobjeto"))); action->setText(trUtf8("Protect")); } } action=new QAction(dynamic_cast(submenu)); - action->setIcon(QPixmap(PgModelerUiNS::getIconPath("excluir"))); + action->setIcon(QPixmap(PgModelerUiNs::getIconPath("excluir"))); action->setData(QVariant::fromValue(dynamic_cast(constr))); action->setText(trUtf8("Delete")); submenu->addAction(action); connect(action, SIGNAL(triggered()), this, SLOT(removeObjects())); action=new QAction(dynamic_cast(submenu)); - action->setIcon(QPixmap(PgModelerUiNS::getIconPath("delcascade"))); + action->setIcon(QPixmap(PgModelerUiNs::getIconPath("delcascade"))); action->setData(QVariant::fromValue(dynamic_cast(constr))); action->setText(trUtf8("Del. cascade")); submenu->addAction(action); @@ -3904,7 +4155,7 @@ void ModelWidget::configurePopupMenu(const vector &objects) { submenu=new QMenu(&popup_menu); submenu->setTitle(trUtf8("Constraints")); - submenu->setIcon(QPixmap(PgModelerUiNS::getIconPath(BaseObject::getSchemaName(OBJ_CONSTRAINT) + QString("_grp")))); + submenu->setIcon(QPixmap(PgModelerUiNs::getIconPath(BaseObject::getSchemaName(ObjectType::Constraint) + QString("_grp")))); count=submenus.size(); for(i=0; i < count; i++) submenu->addMenu(submenus[i]); @@ -3924,7 +4175,7 @@ void ModelWidget::configurePopupMenu(const vector &objects) actions.pop_back(); } - if(objects.empty() || (objects.size()==1 && objects[0]==db_model)) + if(objects.size() <= 2 && !scene->hasOnlyTableChildrenSelection()) { popup_menu.addSeparator(); popup_menu.addAction(action_edit_creation_order); @@ -3966,7 +4217,7 @@ void ModelWidget::setMinimumObjectOpacity(unsigned min_opacity) if(min_opacity > 70) min_opacity = 70; - ModelWidget::min_object_opacity = static_cast(min_opacity)/100.0f; + ModelWidget::min_object_opacity = static_cast(min_opacity)/100.0; } void ModelWidget::highlightObject(void) @@ -3980,7 +4231,7 @@ void ModelWidget::highlightObject(void) if(graph_obj) { - BaseObjectView *obj_view=dynamic_cast(graph_obj->getReceiverObject()); + BaseObjectView *obj_view=dynamic_cast(graph_obj->getOverlyingObject()); scene->clearSelection(); obj_view->setSelected(true); @@ -3992,7 +4243,7 @@ void ModelWidget::highlightObject(void) void ModelWidget::toggleNewObjectOverlay(void) { if(new_obj_overlay_wgt->isHidden() && - (selected_objects.empty() || selected_objects[0]->getObjectType()!=BASE_RELATIONSHIP)) + (selected_objects.empty() || selected_objects[0]->getObjectType()!=ObjectType::BaseRelationship)) { new_obj_overlay_wgt->raise(); new_obj_overlay_wgt->show(); @@ -4019,7 +4270,7 @@ void ModelWidget::toggleObjectSQL(void) if(action) { BaseObject *object=reinterpret_cast(action->data().value()); - PgModelerUiNS::disableObjectSQL(object, !object->isSQLDisabled()); + PgModelerUiNs::disableObjectSQL(object, !object->isSQLDisabled()); this->modified=true; emit s_objectModified(); } @@ -4039,17 +4290,17 @@ void ModelWidget::createSequenceFromColumn(void) //Creates a sequence which name is like the ones auto generated by PostgreSQL seq=new Sequence; seq->setName(BaseObject::formatName(tab->getName() + QString("_") + col->getName() + QString("_seq"))); - seq->setName(PgModelerNS::generateUniqueName(seq, *db_model->getObjectList(OBJ_SEQUENCE), false)); + seq->setName(PgModelerNs::generateUniqueName(seq, *db_model->getObjectList(ObjectType::Sequence), false)); seq->setSchema(tab->getSchema()); seq->setDefaultValues(col->getType()); - op_list->registerObject(seq, Operation::OBJECT_CREATED); + op_list->registerObject(seq, Operation::ObjectCreated); db_model->addSequence(seq); BaseObject::swapObjectsIds(tab, seq, false); - op_list->registerObject(col, Operation::OBJECT_MODIFIED, -1, tab); + op_list->registerObject(col, Operation::ObjectModified, -1, tab); //Changes the column type to the alias for serial type col->setType(col->getType().getAliasType()); col->setSequence(seq); @@ -4066,7 +4317,7 @@ void ModelWidget::createSequenceFromColumn(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -4077,15 +4328,15 @@ void ModelWidget::convertIntegerToSerial(void) QAction *action=dynamic_cast(sender()); Column *col=reinterpret_cast(action->data().value()); Table *tab=dynamic_cast
(col->getParentTable()); - PgSQLType col_type=col->getType(); + PgSqlType col_type=col->getType(); QRegExp regexp(QString("^nextval\\(.+\\:\\:regclass\\)")); QString serial_tp; if(!col_type.isIntegerType() || (!col->getDefaultValue().contains(regexp) && !col->getSequence())) - throw Exception(Exception::getErrorMessage(ERR_INV_CONV_INTEGER_TO_SERIAL).arg(col->getName()), - ERR_INV_CONV_INTEGER_TO_SERIAL ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::InvConversionIntegerToSerial).arg(col->getName()), + ErrorCode::InvConversionIntegerToSerial ,__PRETTY_FUNCTION__,__FILE__,__LINE__); - op_list->registerObject(col, Operation::OBJECT_MODIFIED, -1, tab); + op_list->registerObject(col, Operation::ObjectModified, -1, tab); if(col_type==QString("integer") || col_type==QString("int4")) serial_tp=QString("serial"); @@ -4094,7 +4345,7 @@ void ModelWidget::convertIntegerToSerial(void) else serial_tp=QString("bigserial"); - col->setType(PgSQLType(serial_tp)); + col->setType(PgSqlType(serial_tp)); col->setDefaultValue(QString()); //Revalidate the relationships since the modified column can be a primary key @@ -4106,7 +4357,7 @@ void ModelWidget::convertIntegerToSerial(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -4117,7 +4368,7 @@ void ModelWidget::breakRelationshipLine(void) QAction *action=dynamic_cast(sender()); BaseRelationship *rel=dynamic_cast(selected_objects[0]); - op_list->registerObject(rel, Operation::OBJECT_MODIFIED); + op_list->registerObject(rel, Operation::ObjectModified); breakRelationshipLine(rel, action->data().toUInt()); rel->setModified(true); this->setModified(true); @@ -4126,7 +4377,7 @@ void ModelWidget::breakRelationshipLine(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -4136,18 +4387,18 @@ void ModelWidget::breakRelationshipLine(BaseRelationship *rel, unsigned break_ty try { - RelationshipView *rel_view=dynamic_cast(rel->getReceiverObject()); + RelationshipView *rel_view=dynamic_cast(rel->getOverlyingObject()); double dx, dy; QPointF src_pnt, dst_pnt; - src_pnt=rel_view->getConnectionPoint(BaseRelationship::SRC_TABLE); - dst_pnt=rel_view->getConnectionPoint(BaseRelationship::DST_TABLE); + src_pnt=rel_view->getConnectionPoint(BaseRelationship::SrcTable); + dst_pnt=rel_view->getConnectionPoint(BaseRelationship::DstTable); - if(break_type==BREAK_VERT_NINETY_DEGREES) + if(break_type==BreakVertNinetyDegrees) rel->setPoints({ QPointF(src_pnt.x(), dst_pnt.y()) }); - else if(break_type==BREAK_HORIZ_NINETY_DEGREES) + else if(break_type==BreakHorizNinetyDegrees) rel->setPoints({ QPointF(dst_pnt.x(), src_pnt.y()) }); - else if(break_type==BREAK_HORIZ_2NINETY_DEGREES) + else if(break_type==BreakHoriz2NinetyDegrees) { //Calculates the midle vertical point between the tables centers dy=(src_pnt.y() + dst_pnt.y())/2; @@ -4166,7 +4417,7 @@ void ModelWidget::breakRelationshipLine(BaseRelationship *rel, unsigned break_ty } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -4182,8 +4433,8 @@ void ModelWidget::removeRelationshipPoints(void) { vector rels; - rels = *db_model->getObjectList(BASE_RELATIONSHIP); - rels.insert(rels.end(), db_model->getObjectList(OBJ_RELATIONSHIP)->begin(), db_model->getObjectList(OBJ_RELATIONSHIP)->end()); + rels = *db_model->getObjectList(ObjectType::BaseRelationship); + rels.insert(rels.end(), db_model->getObjectList(ObjectType::Relationship)->begin(), db_model->getObjectList(ObjectType::Relationship)->end()); op_list->startOperationChain(); for(auto &obj : rels) @@ -4192,7 +4443,7 @@ void ModelWidget::removeRelationshipPoints(void) if(!rel->isProtected()) { - op_list->registerObject(rel, Operation::OBJECT_MODIFIED); + op_list->registerObject(rel, Operation::ObjectModified); rel->setPoints({}); rel->setModified(true); } @@ -4201,7 +4452,7 @@ void ModelWidget::removeRelationshipPoints(void) } else { - op_list->registerObject(rel, Operation::OBJECT_MODIFIED); + op_list->registerObject(rel, Operation::ObjectModified); rel->setPoints({}); rel->setModified(true); } @@ -4212,7 +4463,7 @@ void ModelWidget::removeRelationshipPoints(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -4224,7 +4475,7 @@ void ModelWidget::rearrangeSchemasInGrid(QPointF origin, unsigned tabs_per_row, unsigned sch_id=0; double x=origin.x(), y=origin.y(), max_y=-1, cy=0; - objects=db_model->getObjectList(OBJ_SCHEMA); + objects=db_model->getObjectList(ObjectType::Schema); for(BaseObject *obj : *objects) { @@ -4234,7 +4485,7 @@ void ModelWidget::rearrangeSchemasInGrid(QPointF origin, unsigned tabs_per_row, schemas over the screen */ schema->setRectVisible(true); - sch_view=dynamic_cast(schema->getReceiverObject()); + sch_view=dynamic_cast(schema->getOverlyingObject()); schema->setModified(true); //The schema is processed only there are tables inside of it @@ -4267,13 +4518,13 @@ void ModelWidget::rearrangeSchemasInGrid(QPointF origin, unsigned tabs_per_row, } } - objects=db_model->getObjectList(OBJ_RELATIONSHIP); + objects=db_model->getObjectList(ObjectType::Relationship); for(BaseObject *obj : *objects) { dynamic_cast(obj)->setModified(true); } - objects=db_model->getObjectList(BASE_RELATIONSHIP); + objects=db_model->getObjectList(ObjectType::BaseRelationship); for(BaseObject *obj : *objects) { dynamic_cast(obj)->setModified(true); @@ -4295,15 +4546,15 @@ void ModelWidget::rearrangeTablesInGrid(Schema *schema, QPointF origin, unsigned double max_y=-1, x=origin.x(), y=origin.y(), cy=0; //Get the tables and views for the specified schema - tables=db_model->getObjects(OBJ_TABLE, schema); - views=db_model->getObjects(OBJ_VIEW, schema); + tables=db_model->getObjects(ObjectType::Table, schema); + views=db_model->getObjects(ObjectType::View, schema); tables.insert(tables.end(), views.begin(), views.end()); itr=tables.begin(); while(itr!=tables.end()) { base_tab=dynamic_cast(*itr); - tab_view=dynamic_cast(base_tab->getReceiverObject()); + tab_view=dynamic_cast(base_tab->getOverlyingObject()); tab_view->setPos(QPointF(x,y)); //Defining the maximum y position to avoid table boxes colliding vertically @@ -4337,6 +4588,9 @@ void ModelWidget::editCreationOrder(void) swap_ids_wgt->setModel(this->getDatabaseModel()); + if(!selected_objects.empty()) + swap_ids_wgt->setSelectedObjects(selected_objects[0], selected_objects.size() == 2 ? selected_objects[1] : nullptr); + connect(swap_ids_wgt, &SwapObjectsIdsWidget::s_objectsIdsSwapped, [&](){ this->op_list->removeOperations(); emit s_objectManipulated(); @@ -4358,11 +4612,31 @@ void ModelWidget::jumpToTable(void) tab = reinterpret_cast(act->data().value()); scene->clearSelection(); - tab_view = dynamic_cast(tab->getReceiverObject()); + tab_view = dynamic_cast(tab->getOverlyingObject()); tab_view->setSelected(true); viewport->centerOn(tab_view); } +void ModelWidget::editTableData(void) +{ + TableDataWidget *tab_data_wgt=new TableDataWidget; + + tab_data_wgt->setAttributes(db_model, dynamic_cast
(selected_objects.at(0))); + openEditingForm(tab_data_wgt); + this->setModified(true); + emit s_objectManipulated(); +} + +void ModelWidget::updateModelLayers(void) +{ + QStringList layers = scene->getLayers(); + + layers.removeAt(0); + db_model->setLayers(layers); + db_model->setActiveLayers(scene->getActiveLayersIds()); + modified = true; +} + void ModelWidget::rearrangeTablesHierarchically(void) { vector objects; @@ -4372,8 +4646,8 @@ void ModelWidget::rearrangeTablesHierarchically(void) scene->clearSelection(); - objects.assign(db_model->getObjectList(OBJ_TABLE)->begin(), db_model->getObjectList(OBJ_TABLE)->end()); - objects.insert(objects.end(), db_model->getObjectList(OBJ_VIEW)->begin(), db_model->getObjectList(OBJ_VIEW)->end()); + objects.assign(db_model->getObjectList(ObjectType::Table)->begin(), db_model->getObjectList(ObjectType::Table)->end()); + objects.insert(objects.end(), db_model->getObjectList(ObjectType::View)->begin(), db_model->getObjectList(ObjectType::View)->end()); //We determine the root by searching the table/view which contains the more amount of relationships connected for(auto obj : objects) @@ -4381,7 +4655,7 @@ void ModelWidget::rearrangeTablesHierarchically(void) graph_obj = dynamic_cast(obj); dynamic_cast(graph_obj->getSchema())->setRectVisible(false); - tab_view = dynamic_cast(graph_obj->getReceiverObject()); + tab_view = dynamic_cast(graph_obj->getOverlyingObject()); if(tab_view->getConnectRelsCount() > num_rels) { @@ -4400,13 +4674,13 @@ void ModelWidget::rearrangeTablesHierarchically(void) //Positioning the root object at the top-left portion of canvas root->setPos(QPointF(50, 50)); - evaluated_tabs.push_back(root->getSourceObject()); + evaluated_tabs.push_back(root->getUnderlyingObject()); items_rect = rearrangeTablesHierarchically(root, evaluated_tabs); max_w = items_rect.width(); objects.clear(); - objects.assign(db_model->getObjectList(OBJ_TABLE)->begin(), db_model->getObjectList(OBJ_TABLE)->end()); - objects.insert(objects.end(), db_model->getObjectList(OBJ_VIEW)->begin(), db_model->getObjectList(OBJ_VIEW)->end()); + objects.assign(db_model->getObjectList(ObjectType::Table)->begin(), db_model->getObjectList(ObjectType::Table)->end()); + objects.insert(objects.end(), db_model->getObjectList(ObjectType::View)->begin(), db_model->getObjectList(ObjectType::View)->end()); //Retrieving the rest of tables/views that were not evaluated in the previous iteration std::sort(objects.begin(), objects.end()); @@ -4425,7 +4699,7 @@ void ModelWidget::rearrangeTablesHierarchically(void) //Determining which table has the greater number of relationships attached for(auto &tab : not_evaluated) { - tab_view = dynamic_cast(dynamic_cast(tab)->getReceiverObject()); + tab_view = dynamic_cast(dynamic_cast(tab)->getOverlyingObject()); if(tab_view->getConnectRelsCount() > num_rels) { @@ -4435,19 +4709,19 @@ void ModelWidget::rearrangeTablesHierarchically(void) } //Once determined the new root we perform the positioning of its "children" - if(root && std::find(evaluated_tabs.begin(), evaluated_tabs.end(), root->getSourceObject()) == evaluated_tabs.end()) + if(root && std::find(evaluated_tabs.begin(), evaluated_tabs.end(), root->getUnderlyingObject()) == evaluated_tabs.end()) { root->setPos(QPointF(50, items_rect.bottom() + 50)); - evaluated_tabs.push_back(root->getSourceObject()); + evaluated_tabs.push_back(root->getUnderlyingObject()); items_rect = rearrangeTablesHierarchically(root, evaluated_tabs); - not_evaluated.erase(std::find(not_evaluated.begin(), not_evaluated.end(), root->getSourceObject())); + not_evaluated.erase(std::find(not_evaluated.begin(), not_evaluated.end(), root->getUnderlyingObject())); if(items_rect.width() > max_w) max_w = items_rect.width(); } else { - tab_view = dynamic_cast(dynamic_cast(not_evaluated.front())->getReceiverObject()); + tab_view = dynamic_cast(dynamic_cast(not_evaluated.front())->getOverlyingObject()); //If the table/view has not relationships connected we separate it in a new list for further rearrangement if(tab_view->getConnectRelsCount() == 0) @@ -4460,7 +4734,7 @@ void ModelWidget::rearrangeTablesHierarchically(void) //Repositioning remaining tables (without relationships) and textboxes objects.clear(); objects.assign(not_linked_tabs.begin(), not_linked_tabs.end()); - objects.insert(objects.end(), db_model->getObjectList(OBJ_TEXTBOX)->begin(), db_model->getObjectList(OBJ_TEXTBOX)->end()); + objects.insert(objects.end(), db_model->getObjectList(ObjectType::Textbox)->begin(), db_model->getObjectList(ObjectType::Textbox)->end()); px = 50; py = items_rect.bottom() + 100; @@ -4468,7 +4742,7 @@ void ModelWidget::rearrangeTablesHierarchically(void) for(auto &obj : objects) { - obj_view = dynamic_cast(dynamic_cast(obj)->getReceiverObject()); + obj_view = dynamic_cast(dynamic_cast(obj)->getOverlyingObject()); obj_view->setPos(px, py); px += obj_view->boundingRect().width() + 100; @@ -4483,8 +4757,8 @@ void ModelWidget::rearrangeTablesHierarchically(void) } objects.clear(); - objects.assign(db_model->getObjectList(OBJ_RELATIONSHIP)->begin(), db_model->getObjectList(OBJ_RELATIONSHIP)->end()); - objects.insert(objects.end(), db_model->getObjectList(BASE_RELATIONSHIP)->begin(), db_model->getObjectList(BASE_RELATIONSHIP)->end()); + objects.assign(db_model->getObjectList(ObjectType::Relationship)->begin(), db_model->getObjectList(ObjectType::Relationship)->end()); + objects.insert(objects.end(), db_model->getObjectList(ObjectType::BaseRelationship)->begin(), db_model->getObjectList(ObjectType::BaseRelationship)->end()); for(auto obj : objects) { @@ -4493,12 +4767,12 @@ void ModelWidget::rearrangeTablesHierarchically(void) rel->resetLabelsDistance(); if(!RelationshipView::isCurvedLines() && - rel->getTable(BaseRelationship::SRC_TABLE)->getPosition().y() != - rel->getTable(BaseRelationship::DST_TABLE)->getPosition().y()) - breakRelationshipLine(dynamic_cast(obj), ModelWidget::BREAK_VERT_2NINETY_DEGREES); + rel->getTable(BaseRelationship::SrcTable)->getPosition().y() != + rel->getTable(BaseRelationship::DstTable)->getPosition().y()) + breakRelationshipLine(dynamic_cast(obj), ModelWidget::BreakVert2NinetyDegrees); } - db_model->setObjectsModified({ OBJ_TABLE, OBJ_VIEW, OBJ_SCHEMA, OBJ_RELATIONSHIP, BASE_RELATIONSHIP }); + db_model->setObjectsModified({ ObjectType::Table, ObjectType::View, ObjectType::Schema, ObjectType::Relationship, ObjectType::BaseRelationship }); } else { @@ -4512,7 +4786,7 @@ void ModelWidget::rearrangeTablesHierarchically(void) QRectF ModelWidget::rearrangeTablesHierarchically(BaseTableView *root, vector &evaluated_tabs) { - BaseTable *base_tab = dynamic_cast(root->getSourceObject()), + BaseTable *base_tab = dynamic_cast(root->getUnderlyingObject()), *src_tab = nullptr, *dst_tab = nullptr, *curr_tab = nullptr; vector rels ; double px = 0, py = 0, px1 = 0, py1 = 0; @@ -4524,7 +4798,7 @@ QRectF ModelWidget::rearrangeTablesHierarchically(BaseTableView *root, vector(base_tab->getReceiverObject()); + tab_view = dynamic_cast(base_tab->getOverlyingObject()); rels = db_model->getRelationships(base_tab); for(auto &rel : rels) @@ -4532,8 +4806,8 @@ QRectF ModelWidget::rearrangeTablesHierarchically(BaseTableView *root, vectorisSelfRelationship()) continue; - src_tab = rel->getTable(BaseRelationship::SRC_TABLE); - dst_tab = rel->getTable(BaseRelationship::DST_TABLE); + src_tab = rel->getTable(BaseRelationship::SrcTable); + dst_tab = rel->getTable(BaseRelationship::DstTable); if(src_tab != base_tab) curr_tab = src_tab; @@ -4556,7 +4830,7 @@ QRectF ModelWidget::rearrangeTablesHierarchically(BaseTableView *root, vector(next_tab->getReceiverObject()); + tab_view = dynamic_cast(next_tab->getOverlyingObject()); //Temporarily unprotecting the table so it can be moved if(next_tab->isProtected()) @@ -4591,8 +4865,8 @@ void ModelWidget::rearrangeTablesInSchema(Schema *schema, QPointF start) if(!schema) return; - tables = db_model->getObjects(OBJ_TABLE, schema); - views = db_model->getObjects(OBJ_VIEW, schema); + tables = db_model->getObjects(ObjectType::Table, schema); + views = db_model->getObjects(ObjectType::View, schema); tables.insert(tables.end(), views.begin(), views.end()); if(!tables.empty()) @@ -4604,14 +4878,14 @@ void ModelWidget::rearrangeTablesInSchema(Schema *schema, QPointF start) if(tables.size() <= 2) { base_tab = dynamic_cast(tables[0]); - curr_tab = dynamic_cast(base_tab->getReceiverObject()); + curr_tab = dynamic_cast(base_tab->getOverlyingObject()); curr_tab->setPos(start); if(tables.size() > 1) { tab_view = curr_tab; base_tab = dynamic_cast(tables[1]); - curr_tab = dynamic_cast(base_tab->getReceiverObject()); + curr_tab = dynamic_cast(base_tab->getOverlyingObject()); curr_tab->setPos(start + QPointF(tab_view->boundingRect().width() * 1.25, 0)); } } @@ -4632,20 +4906,20 @@ void ModelWidget::rearrangeTablesInSchema(Schema *schema, QPointF start) for(auto &tab : tables) { base_tab = dynamic_cast(tab); - curr_tab = dynamic_cast(base_tab->getReceiverObject()); + curr_tab = dynamic_cast(base_tab->getOverlyingObject()); max_w += curr_tab->boundingRect().width(); max_h += curr_tab->boundingRect().height(); } if(tables.size() >= 4) { - max_w *= 0.50f; - max_h *= 0.50f; + max_w *= 0.50; + max_h *= 0.50; } else { - max_w *= 1.15f; - max_h *= 1.15f; + max_w *= 1.15; + max_h *= 1.15; } uniform_int_distribution dist_x(start.x(), start.x() + max_w), @@ -4655,7 +4929,7 @@ void ModelWidget::rearrangeTablesInSchema(Schema *schema, QPointF start) for(auto &tab : tables) { base_tab = dynamic_cast(tab); - curr_tab = dynamic_cast(base_tab->getReceiverObject()); + curr_tab = dynamic_cast(base_tab->getOverlyingObject()); pos.setX(dist_x(rand_num_engine)); pos.setY(dist_y(rand_num_engine)); curr_tab->setPos(pos); @@ -4666,7 +4940,7 @@ void ModelWidget::rearrangeTablesInSchema(Schema *schema, QPointF start) for(auto &tab : tables) { base_tab = dynamic_cast(tab); - curr_tab = dynamic_cast(base_tab->getReceiverObject()); + curr_tab = dynamic_cast(base_tab->getOverlyingObject()); curr_brect = QRectF(curr_tab->pos(), curr_tab->boundingRect().size()); tries = 0; @@ -4680,7 +4954,7 @@ void ModelWidget::rearrangeTablesInSchema(Schema *schema, QPointF start) continue; base_tab = dynamic_cast(tab1); - comp_tab = dynamic_cast(base_tab->getReceiverObject()); + comp_tab = dynamic_cast(base_tab->getOverlyingObject()); comp_brect = QRectF(comp_tab->pos(), comp_tab->boundingRect().size()); irect = comp_brect.intersected(curr_brect); @@ -4715,13 +4989,13 @@ void ModelWidget::rearrangeTablesInSchemas(void) random_device rand_seed; default_random_engine rand_num_engine; double max_w = 1000, max_h = 1000; - vector schemas = *db_model->getObjectList(OBJ_SCHEMA), rels; + vector schemas = *db_model->getObjectList(ObjectType::Schema), rels; bool has_collision = false; uniform_int_distribution dist_x(0, max_w), dist_y(0, max_h); unsigned tries = 0, - max_tries = (db_model->getObjectCount(OBJ_TABLE) + - db_model->getObjectCount(OBJ_VIEW) + - db_model->getObjectCount(OBJ_SCHEMA)) * 100; + max_tries = (db_model->getObjectCount(ObjectType::Table) + + db_model->getObjectCount(ObjectType::View) + + db_model->getObjectCount(ObjectType::Schema)) * 100; rand_num_engine.seed(rand_seed()); @@ -4732,7 +5006,7 @@ void ModelWidget::rearrangeTablesInSchemas(void) for(auto &sch : schemas) { schema = dynamic_cast(sch); - sch_view = dynamic_cast(schema->getReceiverObject()); + sch_view = dynamic_cast(schema->getOverlyingObject()); if(!sch_view) continue; @@ -4753,7 +5027,7 @@ void ModelWidget::rearrangeTablesInSchemas(void) for(auto &sch : schemas) { schema = dynamic_cast(sch); - sch_view = dynamic_cast(schema->getReceiverObject()); + sch_view = dynamic_cast(schema->getOverlyingObject()); tries = 0; if(!sch_view) continue; @@ -4767,7 +5041,7 @@ void ModelWidget::rearrangeTablesInSchemas(void) for(auto &sch1 : schemas) { schema = dynamic_cast(sch1); - sch_view_aux = dynamic_cast(schema->getReceiverObject()); + sch_view_aux = dynamic_cast(schema->getOverlyingObject()); if(sch == sch1 || !sch_view_aux) continue; @@ -4790,8 +5064,8 @@ void ModelWidget::rearrangeTablesInSchemas(void) } //Removing all custom points from relationships - rels.assign(db_model->getObjectList(OBJ_RELATIONSHIP)->begin(), db_model->getObjectList(OBJ_RELATIONSHIP)->end()); - rels.insert(rels.end(), db_model->getObjectList(BASE_RELATIONSHIP)->begin(), db_model->getObjectList(BASE_RELATIONSHIP)->end()); + rels.assign(db_model->getObjectList(ObjectType::Relationship)->begin(), db_model->getObjectList(ObjectType::Relationship)->end()); + rels.insert(rels.end(), db_model->getObjectList(ObjectType::BaseRelationship)->begin(), db_model->getObjectList(ObjectType::BaseRelationship)->end()); for(auto &rel : rels) { @@ -4800,7 +5074,7 @@ void ModelWidget::rearrangeTablesInSchemas(void) base_rel->resetLabelsDistance(); } - db_model->setObjectsModified({ OBJ_TABLE, OBJ_VIEW, OBJ_SCHEMA, OBJ_RELATIONSHIP, BASE_RELATIONSHIP }); + db_model->setObjectsModified({ ObjectType::Table, ObjectType::View, ObjectType::Schema, ObjectType::Relationship, ObjectType::BaseRelationship }); adjustSceneSize(); viewport->updateScene({ scene->sceneRect() }); } diff --git a/libpgmodeler_ui/src/modelwidget.h b/libpgmodeler_ui/src/modelwidget.h index 375ff61fc5..771ac531fb 100644 --- a/libpgmodeler_ui/src/modelwidget.h +++ b/libpgmodeler_ui/src/modelwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -37,7 +37,7 @@ class ModelWidget: public QWidget { private: Q_OBJECT - XMLParser *xmlparser; + XmlParser *xmlparser; NewObjectOverlayWidget *new_obj_overlay_wgt; @@ -63,7 +63,7 @@ class ModelWidget: public QWidget { disable_render_smooth; //! \brief Indicates if the minimum object opacity used when appliyng fade out to objects - static float min_object_opacity; + static double min_object_opacity; /*! \brief Stores the model that generates the copy/cut operation. This model is updated from the destination model whenever a past/cut operation is done. */ @@ -102,6 +102,9 @@ class ModelWidget: public QWidget { //! \brief Stores the tags used by the "set tag" operation tags_menu, + //! \brief Stores the layers used by the "move to layer" operation + layers_menu, + break_rel_menu, fade_menu, @@ -114,11 +117,17 @@ class ModelWidget: public QWidget { toggle_attrs_menu, + pagination_menu, + select_all_menu, jump_to_tab_menu, - toggle_sch_rects_menu; + toggle_sch_rects_menu, + + database_category_menu, + + schema_category_menu; //! \brief Stores the selected object on the scene vector selected_objects; @@ -150,7 +159,7 @@ class ModelWidget: public QWidget { QTimer zoom_info_timer; //! \brief Creates a BaseForm instance and insert the widget into it. A custom configuration for dialog buttons can be passed - int openEditingForm(QWidget *widget, unsigned button_conf = Messagebox::OK_CANCEL_BUTTONS); + int openEditingForm(QWidget *widget, unsigned button_conf = Messagebox::OkCancelButtons); //! \brief Opens a editing form for objects at database level template @@ -194,10 +203,10 @@ class ModelWidget: public QWidget { void showMagnifierArea(bool show); protected: - static const unsigned BREAK_VERT_NINETY_DEGREES, //Break vertically the line in one 90° angle - BREAK_HORIZ_NINETY_DEGREES, //Break horizontally the line in one 90° angle - BREAK_VERT_2NINETY_DEGREES, //Break vertically the line in two 90° angles - BREAK_HORIZ_2NINETY_DEGREES;//Break horizontally the line in two 90° angles + static constexpr unsigned BreakVertNinetyDegrees=0, //Break vertically the line in one 90° angle + BreakHorizNinetyDegrees=1, //Break horizontally the line in one 90° angle + BreakVert2NinetyDegrees=2, //Break vertically the line in two 90° angles + BreakHoriz2NinetyDegrees=3;//Break horizontally the line in two 90° angles QAction *action_source_code, *action_edit, @@ -227,6 +236,7 @@ class ModelWidget: public QWidget { *action_break_rel_line, *action_remove_rel_points, *action_set_tag, + *action_moveto_layer, *action_disable_sql, *action_enable_sql, *action_duplicate, @@ -236,14 +246,19 @@ class ModelWidget: public QWidget { *action_fade_rels, *action_fade_rels_in, *action_fade_rels_out, - *action_extended_attribs, - *action_show_ext_attribs, - *action_hide_ext_attribs, + *action_pagination, + *action_collapse_mode, + *action_collapse_ext_attribs, + *action_collpase_all_attribs, + *action_no_collapse_attribs, *action_edit_creation_order, *action_jump_to_table, *action_schemas_rects, *action_show_schemas_rects, - *action_hide_schemas_rects; + *action_hide_schemas_rects, + *action_edit_data, + *action_database_category, + *action_schema_category; //! \brief Actions used to create new objects on the model map actions_new_objects; @@ -273,12 +288,14 @@ class ModelWidget: public QWidget { void fadeObjects(const vector &objects, bool fade_in); + void setAllCollapseMode(CollapseMode mode); + public: - static constexpr double MINIMUM_ZOOM=0.050000, - MAXIMUM_ZOOM=5.000001, - ZOOM_INCREMENT=0.050000; + static constexpr double MinimumZoom=0.050000, + MaximumZoom=5.000001, + ZoomIncrement=0.050000; - ModelWidget(QWidget *parent = 0); + ModelWidget(QWidget *parent = nullptr); ~ModelWidget(void); /*! \brief Configures the scene aligning the object to the grid and resizing the scene @@ -295,7 +312,7 @@ class ModelWidget: public QWidget { QString getTempFilename(void); //! \brief Shows the editing form according to the passed object type - void showObjectForm(ObjectType obj_type, BaseObject *object=nullptr, BaseObject *parent_obj=nullptr, const QPointF &pos=QPointF(NAN, NAN)); + void showObjectForm(ObjectType obj_type, BaseObject *object=nullptr, BaseObject *parent_obj=nullptr, const QPointF &pos=QPointF(DNaN, DNaN)); //! \brief Applies a zoom factor to the model void applyZoom(double zoom); @@ -389,6 +406,9 @@ class ModelWidget: public QWidget { //! \brief Move the selected object to a schema (selectable via menu) void moveToSchema(void); + //! \brief Move the selected object to a layer (selectable via menu) + void moveToLayer(void); + //! \brief Quickly changes the object's owner via popup menu void changeOwner(void); @@ -417,7 +437,7 @@ class ModelWidget: public QWidget { void copyObjects(bool duplicate_mode = false); //! \brief Paste all the objects copied previously - void pasteObjects(void); + void pasteObjects(bool duplicate_mode = false); //! \brief Duplicate the selected table object in its parent table void duplicateObject(void); @@ -468,7 +488,9 @@ class ModelWidget: public QWidget { void fadeObjectsOut(void); - void toggleExtendedAttributes(void); + void setCollapseMode(void); + + void togglePagination(void); void toggleSchemasRectangles(void); @@ -476,6 +498,10 @@ class ModelWidget: public QWidget { void jumpToTable(void); + void editTableData(void); + + void updateModelLayers(void); + public slots: void loadModel(const QString &filename); void saveModel(const QString &filename); @@ -512,6 +538,7 @@ class ModelWidget: public QWidget { friend class DatabaseImportForm; friend class ObjectFinderWidget; friend class NewObjectOverlayWidget; + friend class LayersWidget; }; #endif diff --git a/libpgmodeler_ui/src/newobjectoverlaywidget.cpp b/libpgmodeler_ui/src/newobjectoverlaywidget.cpp index 9435231c64..a272afd0c4 100644 --- a/libpgmodeler_ui/src/newobjectoverlaywidget.cpp +++ b/libpgmodeler_ui/src/newobjectoverlaywidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -29,40 +29,45 @@ NewObjectOverlayWidget::NewObjectOverlayWidget(ModelWidget *parent): QWidget(par int action_idx=0; QList rel_actions=parent->rels_menu->actions(); map> obj_shortcuts={ - { aggregate_tb, std::make_tuple(trUtf8("A"), OBJ_AGGREGATE) }, - { cast_tb, std::make_tuple(trUtf8("G"), OBJ_CAST) }, - { eventtrigger_tb, std::make_tuple(trUtf8("K"), OBJ_EVENT_TRIGGER)}, - { collation_tb, std::make_tuple(trUtf8("H"), OBJ_COLLATION) }, - { conversion_tb, std::make_tuple(trUtf8("J"), OBJ_CONVERSION) }, - { domain_tb, std::make_tuple(trUtf8("D"), OBJ_DOMAIN) }, - { extension_tb, std::make_tuple(trUtf8("E"), OBJ_EXTENSION) }, - { function_tb, std::make_tuple(trUtf8("F"), OBJ_FUNCTION) }, - { language_tb, std::make_tuple(trUtf8("L"), OBJ_LANGUAGE) }, - { opclass_tb, std::make_tuple(trUtf8("O"), OBJ_OPCLASS) }, - { operator_tb, std::make_tuple(trUtf8("U"), OBJ_OPERATOR) }, - { opfamily_tb, std::make_tuple(trUtf8("I"), OBJ_OPFAMILY) }, - { role_tb, std::make_tuple(trUtf8("R"), OBJ_ROLE) }, - { schema_tb, std::make_tuple(trUtf8("S"), OBJ_SCHEMA) }, - { sequence_tb, std::make_tuple(trUtf8("Q"), OBJ_SEQUENCE) }, - { table_tb, std::make_tuple(trUtf8("T"), OBJ_TABLE) }, - { tablespace_tb, std::make_tuple(trUtf8("P"), OBJ_TABLESPACE) }, - { textbox_tb, std::make_tuple(trUtf8("M"), OBJ_TEXTBOX) }, - { type_tb, std::make_tuple(trUtf8("Y"), OBJ_TYPE) }, - { view_tb, std::make_tuple(trUtf8("W"), OBJ_VIEW) }, - { tag_tb, std::make_tuple(trUtf8("9"), OBJ_TAG) }, - { constraint_tb, std::make_tuple(trUtf8("Z"), OBJ_CONSTRAINT) }, - { index_tb, std::make_tuple(trUtf8("X"), OBJ_INDEX) }, - { column_tb, std::make_tuple(trUtf8("C"), OBJ_COLUMN) }, - { rule_tb, std::make_tuple(trUtf8("V"), OBJ_RULE) }, - { trigger_tb, std::make_tuple(trUtf8("B"), OBJ_TRIGGER) }, - { policy_tb, std::make_tuple(trUtf8("9"), OBJ_POLICY) }, - { genericsql_tb, std::make_tuple(trUtf8("8"), OBJ_GENERIC_SQL) } }; - - map> rel_shortcuts={ { rel11_tb, std::make_tuple(trUtf8("1"), 0) }, - { rel1n_tb, std::make_tuple(trUtf8("2"), 1) }, - { relnn_tb, std::make_tuple(trUtf8("3"), 2) }, - { reldep_tb, std::make_tuple(trUtf8("5"), 3) }, - { relgen_tb, std::make_tuple(trUtf8("4"), 4) } }; + { aggregate_tb, std::make_tuple(trUtf8("A"), ObjectType::Aggregate) }, + { cast_tb, std::make_tuple(trUtf8("G"), ObjectType::Cast) }, + { eventtrigger_tb, std::make_tuple(trUtf8("K"), ObjectType::EventTrigger)}, + { collation_tb, std::make_tuple(trUtf8("H"), ObjectType::Collation) }, + { conversion_tb, std::make_tuple(trUtf8("J"), ObjectType::Conversion) }, + { domain_tb, std::make_tuple(trUtf8("D"), ObjectType::Domain) }, + { extension_tb, std::make_tuple(trUtf8("E"), ObjectType::Extension) }, + { function_tb, std::make_tuple(trUtf8("F"), ObjectType::Function) }, + { language_tb, std::make_tuple(trUtf8("L"), ObjectType::Language) }, + { opclass_tb, std::make_tuple(trUtf8("O"), ObjectType::OpClass) }, + { operator_tb, std::make_tuple(trUtf8("U"), ObjectType::Operator) }, + { opfamily_tb, std::make_tuple(trUtf8("I"), ObjectType::OpFamily) }, + { role_tb, std::make_tuple(trUtf8("R"), ObjectType::Role) }, + { schema_tb, std::make_tuple(trUtf8("S"), ObjectType::Schema) }, + { sequence_tb, std::make_tuple(trUtf8("Q"), ObjectType::Sequence) }, + { table_tb, std::make_tuple(trUtf8("T"), ObjectType::Table) }, + { tablespace_tb, std::make_tuple(trUtf8("P"), ObjectType::Tablespace) }, + { textbox_tb, std::make_tuple(trUtf8("M"), ObjectType::Textbox) }, + { type_tb, std::make_tuple(trUtf8("Y"), ObjectType::Type) }, + { view_tb, std::make_tuple(trUtf8("W"), ObjectType::View) }, + { tag_tb, std::make_tuple(trUtf8("9"), ObjectType::Tag) }, + { constraint_tb, std::make_tuple(trUtf8("Z"), ObjectType::Constraint) }, + { index_tb, std::make_tuple(trUtf8("X"), ObjectType::Index) }, + { column_tb, std::make_tuple(trUtf8("C"), ObjectType::Column) }, + { rule_tb, std::make_tuple(trUtf8("V"), ObjectType::Rule) }, + { trigger_tb, std::make_tuple(trUtf8("B"), ObjectType::Trigger) }, + { policy_tb, std::make_tuple(trUtf8("9"), ObjectType::Policy) }, + { genericsql_tb, std::make_tuple(trUtf8("8"), ObjectType::GenericSql) }, + { fdw_tb, std::make_tuple(trUtf8("7"), ObjectType::ForeignDataWrapper) }, + { server_tb, std::make_tuple(trUtf8("6"), ObjectType::ForeignServer) }, + { user_mapping_tb, std::make_tuple(trUtf8("5"), ObjectType::UserMapping) }}; + + map> rel_shortcuts={ + { rel11_tb, std::make_tuple(trUtf8("1"), 0) }, + { rel1n_tb, std::make_tuple(trUtf8("2"), 1) }, + { relnn_tb, std::make_tuple(trUtf8("3"), 2) }, + { reldep_tb, std::make_tuple(trUtf8("5"), 3) }, + { relgen_tb, std::make_tuple(trUtf8("4"), 4) }, + { relpart_tb, std::make_tuple(trUtf8("5"), 5) }}; vector permission_btns={db_sch_perms_tb, tab_perms_tb }; @@ -106,25 +111,26 @@ NewObjectOverlayWidget::NewObjectOverlayWidget(ModelWidget *parent): QWidget(par void NewObjectOverlayWidget::setSelectedObjects(vector &sel_objs) { - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; if(sel_objs.size()==1) obj_type=sel_objs.at(0)->getObjectType(); else if(sel_objs.empty()) - obj_type=OBJ_DATABASE; - - db_objs_btns_wgt->setVisible(obj_type==OBJ_DATABASE); - sch_objs_btns_wgt->setVisible(obj_type==OBJ_DATABASE || obj_type==OBJ_SCHEMA); - - tab_objs_btns_wgt->setVisible(obj_type==OBJ_TABLE || obj_type==OBJ_VIEW || obj_type==OBJ_RELATIONSHIP); - column_tb->setDisabled(obj_type==OBJ_VIEW); - constraint_tb->setDisabled(obj_type==OBJ_VIEW); - index_tb->setVisible(obj_type==OBJ_TABLE || obj_type==OBJ_VIEW); - rule_tb->setVisible(obj_type==OBJ_TABLE || obj_type==OBJ_VIEW); - trigger_tb->setVisible(obj_type==OBJ_TABLE || obj_type==OBJ_VIEW); - tab_perms_tb->setVisible(obj_type==OBJ_TABLE || obj_type==OBJ_VIEW); - rel_btns_wgt->setVisible((sel_objs.size()==1 && sel_objs.at(0)->getObjectType()==OBJ_TABLE) || - (sel_objs.size()==2 && sel_objs.at(0)->getObjectType()==OBJ_TABLE && sel_objs.at(1)->getObjectType()==OBJ_TABLE)); + obj_type=ObjectType::Database; + + db_objs_grp->setVisible(obj_type==ObjectType::Database); + sch_objs_grp->setVisible(obj_type==ObjectType::Database || obj_type==ObjectType::Schema); + + tab_objs_grp->setVisible(obj_type==ObjectType::Table || obj_type==ObjectType::View || obj_type==ObjectType::Relationship); + column_tb->setDisabled(obj_type==ObjectType::View); + constraint_tb->setDisabled(obj_type==ObjectType::View); + index_tb->setVisible(obj_type==ObjectType::Table || obj_type==ObjectType::View); + rule_tb->setVisible(obj_type==ObjectType::Table || obj_type==ObjectType::View); + trigger_tb->setVisible(obj_type==ObjectType::Table || obj_type==ObjectType::View); + policy_tb->setVisible(obj_type==ObjectType::Table || obj_type==ObjectType::View); + tab_perms_tb->setVisible(obj_type==ObjectType::Table || obj_type==ObjectType::View); + rels_grp->setVisible((sel_objs.size()==1 && sel_objs.at(0)->getObjectType()==ObjectType::Table) || + (sel_objs.size()==2 && sel_objs.at(0)->getObjectType()==ObjectType::Table && sel_objs.at(1)->getObjectType()==ObjectType::Table)); overlay_frm->adjustSize(); this->adjustSize(); diff --git a/libpgmodeler_ui/src/newobjectoverlaywidget.h b/libpgmodeler_ui/src/newobjectoverlaywidget.h index eeec324a6c..20d113657c 100644 --- a/libpgmodeler_ui/src/newobjectoverlaywidget.h +++ b/libpgmodeler_ui/src/newobjectoverlaywidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libpgmodeler_ui/src/numberedtexteditor.cpp b/libpgmodeler_ui/src/numberedtexteditor.cpp index 56fec138ce..bcfa247388 100644 --- a/libpgmodeler_ui/src/numberedtexteditor.cpp +++ b/libpgmodeler_ui/src/numberedtexteditor.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -45,7 +45,7 @@ NumberedTextEditor::NumberedTextEditor(QWidget * parent, bool handle_ext_files) QHBoxLayout *hbox = new QHBoxLayout, *hbox1 = new QHBoxLayout; QFont font = this->font(); - font.setPointSizeF(font.pointSizeF() * 0.95f); + font.setPointSizeF(font.pointSizeF() * 0.95); top_widget = new QWidget(this); top_widget->setAutoFillBackground(true); @@ -63,7 +63,7 @@ NumberedTextEditor::NumberedTextEditor(QWidget * parent, bool handle_ext_files) msg_lbl->setTextInteractionFlags(Qt::TextSelectableByMouse); ico->setMaximumSize(22,22); - ico->setPixmap(QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta"))); + ico->setPixmap(QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta"))); ico->setScaledContents(true); editor_alert_wgt = new QWidget(this); @@ -77,7 +77,7 @@ NumberedTextEditor::NumberedTextEditor(QWidget * parent, bool handle_ext_files) hbox->addSpacerItem(new QSpacerItem(10,10, QSizePolicy::Expanding)); load_file_btn = new QToolButton(top_widget); - load_file_btn->setIcon(QPixmap(PgModelerUiNS::getIconPath("abrir"))); + load_file_btn->setIcon(QPixmap(PgModelerUiNs::getIconPath("abrir"))); load_file_btn->setIconSize(QSize(16,16)); load_file_btn->setAutoRaise(true); load_file_btn->setText(trUtf8("Load")); @@ -88,7 +88,7 @@ NumberedTextEditor::NumberedTextEditor(QWidget * parent, bool handle_ext_files) connect(load_file_btn, SIGNAL(clicked(bool)), this, SLOT(loadFile())); edit_src_btn = new QToolButton(top_widget); - edit_src_btn->setIcon(QPixmap(PgModelerUiNS::getIconPath("editar"))); + edit_src_btn->setIcon(QPixmap(PgModelerUiNs::getIconPath("editar"))); edit_src_btn->setIconSize(QSize(16,16)); edit_src_btn->setAutoRaise(true); edit_src_btn->setText(trUtf8("Edit")); @@ -99,7 +99,7 @@ NumberedTextEditor::NumberedTextEditor(QWidget * parent, bool handle_ext_files) connect(edit_src_btn, SIGNAL(clicked(bool)), this, SLOT(editSource())); clear_btn = new QToolButton(top_widget); - clear_btn->setIcon(QPixmap(PgModelerUiNS::getIconPath("limpartexto"))); + clear_btn->setIcon(QPixmap(PgModelerUiNs::getIconPath("limpartexto"))); clear_btn->setIconSize(QSize(16,16)); clear_btn->setAutoRaise(true); clear_btn->setText(trUtf8("Clear")); @@ -342,9 +342,9 @@ void NumberedTextEditor::loadFile(void) file.setFileName(sql_file_dlg.selectedFiles().at(0)); if(!file.open(QFile::ReadOnly)) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED) - .arg(sql_file_dlg.selectedFiles().at(0)) - ,ERR_FILE_DIR_NOT_ACCESSED ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed) + .arg(sql_file_dlg.selectedFiles().at(0)), + ErrorCode::FileDirectoryNotAccessed ,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->clear(); this->setPlainText(file.readAll()); @@ -360,15 +360,15 @@ void NumberedTextEditor::editSource(void) QByteArray buffer; QFile input; - tmp_src_file.setFileTemplate(GlobalAttributes::TEMPORARY_DIR + GlobalAttributes::DIR_SEPARATOR + QString("source_XXXXXX") + QString(".sql")); + tmp_src_file.setFileTemplate(GlobalAttributes::TemporaryDir + GlobalAttributes::DirSeparator + QString("source_XXXXXX") + QString(".sql")); tmp_src_file.open(); tmp_src_file.close(); input.setFileName(tmp_src_file.fileName()); if(!input.open(QFile::WriteOnly | QFile::Truncate)) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED) - .arg(tmp_src_file.fileName()) - ,ERR_FILE_DIR_NOT_ACCESSED ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed) + .arg(tmp_src_file.fileName()), + ErrorCode::FileDirectoryNotAccessed ,__PRETTY_FUNCTION__,__FILE__,__LINE__); buffer.append(this->toPlainText()); input.write(buffer); @@ -382,7 +382,7 @@ void NumberedTextEditor::editSource(void) src_editor_proc.waitForStarted(); if(src_editor_proc.state() == QProcess::Running) { - msg_lbl->setText(PgModelerUiNS::formatMessage(trUtf8("The source editor `%1' is running on `pid: %2'.") + msg_lbl->setText(PgModelerUiNs::formatMessage(trUtf8("The source editor `%1' is running on `pid: %2'.") .arg(src_editor_proc.program()).arg(src_editor_proc.processId()))); editor_alert_wgt->setVisible(true); load_file_btn->setEnabled(false); @@ -403,9 +403,9 @@ void NumberedTextEditor::updateSource(void) this->setReadOnly(false); if(!input.open(QFile::ReadOnly)) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED) - .arg(tmp_src_file.fileName()) - ,ERR_FILE_DIR_NOT_ACCESSED ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed) + .arg(tmp_src_file.fileName()), + ErrorCode::FileDirectoryNotAccessed ,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->setPlainText(input.readAll()); input.close(); @@ -415,8 +415,8 @@ void NumberedTextEditor::updateSource(void) void NumberedTextEditor::handleProcessError(void) { Messagebox msg_box; - msg_box.show(PgModelerUiNS::formatMessage(trUtf8("Could not start the source code editor application `%1'! Make to sure that the source editor path defined in the general settings points to a valid executable and the current user has permission to run the application. Error message returned: `%2'") - .arg(src_editor_proc.program()).arg(src_editor_proc.errorString())), Messagebox::ERROR_ICON); + msg_box.show(PgModelerUiNs::formatMessage(trUtf8("Could not start the source code editor application `%1'! Make to sure that the source editor path defined in the general settings points to a valid executable and the current user has permission to run the application. Error message returned: `%2'") + .arg(src_editor_proc.program()).arg(src_editor_proc.errorString())), Messagebox::ErrorIcon); } void NumberedTextEditor::setReadOnly(bool ro) diff --git a/libpgmodeler_ui/src/numberedtexteditor.h b/libpgmodeler_ui/src/numberedtexteditor.h index 168d12846c..125cd5dbe7 100644 --- a/libpgmodeler_ui/src/numberedtexteditor.h +++ b/libpgmodeler_ui/src/numberedtexteditor.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -85,7 +85,7 @@ class NumberedTextEditor : public QPlainTextEdit { void keyPressEvent(QKeyEvent *event); public: - NumberedTextEditor(QWidget * parent = 0, bool handle_ext_files = false); + NumberedTextEditor(QWidget * parent = nullptr, bool handle_ext_files = false); ~NumberedTextEditor(void); static void setDefaultFont(const QFont &font); diff --git a/libpgmodeler_ui/src/objectdepsrefswidget.cpp b/libpgmodeler_ui/src/objectdepsrefswidget.cpp index dd9e022078..d5cec676aa 100644 --- a/libpgmodeler_ui/src/objectdepsrefswidget.cpp +++ b/libpgmodeler_ui/src/objectdepsrefswidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -22,9 +22,9 @@ ObjectDepsRefsWidget::ObjectDepsRefsWidget(QWidget *parent): BaseObjectWidget(parent) { Ui_ObjectDepsRefsWidget::setupUi(this); - configureFormLayout(objectdepsrefs_grid, BASE_OBJECT); + configureFormLayout(objectdepsrefs_grid, ObjectType::BaseObject); - PgModelerUiNS::configureWidgetFont(message_lbl, PgModelerUiNS::MEDIUM_FONT_FACTOR); + PgModelerUiNs::configureWidgetFont(message_lbl, PgModelerUiNs::MediumFontFactor); model_wgt=nullptr; alert_frm->setVisible(false); @@ -41,20 +41,22 @@ void ObjectDepsRefsWidget::setAttributes(DatabaseModel *model, BaseObject *objec { BaseObjectWidget::setAttributes(model, object, parent_obj); + if(object->getObjectType() == ObjectType::Constraint || + object->getObjectType() == ObjectType::UserMapping) + name_edt->setText(object->getName()); + this->name_edt->setReadOnly(true); this->protected_obj_frm->setVisible(false); this->comment_edt->setVisible(false); this->comment_lbl->setVisible(false); - - obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath(object->getObjectType()))); - + obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath(object->getObjectType()))); updateObjectTables(); } void ObjectDepsRefsWidget::setAttributes(ModelWidget *model_wgt, BaseObject *object, BaseObject *parent_obj) { if(!model_wgt) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject ,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->model_wgt=model_wgt; setAttributes(model_wgt->getDatabaseModel(), object, parent_obj); @@ -84,12 +86,12 @@ void ObjectDepsRefsWidget::updateObjectTables(void) objs.erase(std::find(objs.begin(), objs.end(), this->object)); ObjectFinderWidget::updateObjectTable(dependences_tbw, objs); + objs.clear(); if(!inc_ind_refs_chk->isChecked()) model->getObjectReferences(object, objs); else model->__getObjectReferences(object, objs); - objs.clear(); ObjectFinderWidget::updateObjectTable(references_tbw, objs); references_tbw->resizeColumnsToContents(); @@ -116,7 +118,7 @@ void ObjectDepsRefsWidget::handleItemSelection(QTableWidgetItem *item) { parent=dynamic_cast(this->object)->getParentTable(); - if(parent->getObjectType()==OBJ_TABLE) + if(parent->getObjectType()==ObjectType::Table) parent_tab=dynamic_cast
(parent); else parent_view=dynamic_cast(parent); diff --git a/libpgmodeler_ui/src/objectdepsrefswidget.h b/libpgmodeler_ui/src/objectdepsrefswidget.h index 36aa66960e..cb0b2dfb57 100644 --- a/libpgmodeler_ui/src/objectdepsrefswidget.h +++ b/libpgmodeler_ui/src/objectdepsrefswidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -38,7 +38,7 @@ class ObjectDepsRefsWidget: public BaseObjectWidget, public Ui::ObjectDepsRefsWi void setAttributes(DatabaseModel *model, BaseObject *object, BaseObject *parent_obj); public: - ObjectDepsRefsWidget(QWidget * parent = 0); + ObjectDepsRefsWidget(QWidget * parent = nullptr); void setAttributes(ModelWidget *model_wgt, BaseObject *object, BaseObject *parent_obj=nullptr); public slots: diff --git a/libpgmodeler_ui/src/objectfinderwidget.cpp b/libpgmodeler_ui/src/objectfinderwidget.cpp index 5c2c22877a..f20934647f 100644 --- a/libpgmodeler_ui/src/objectfinderwidget.cpp +++ b/libpgmodeler_ui/src/objectfinderwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -19,6 +19,16 @@ #include "objectfinderwidget.h" #include "pgmodeleruins.h" +const QStringList ObjectFinderWidget::search_attribs = +{ Attributes::Name, Attributes::Comment, Attributes::Signature, + Attributes::Schema, Attributes::Owner, Attributes::Tablespace, + Attributes::Type, Attributes::ReturnType }; + +const QStringList ObjectFinderWidget::search_attribs_i18n = +{ QT_TR_NOOP("Name"), QT_TR_NOOP("Comment"), QT_TR_NOOP("Signature"), + QT_TR_NOOP("Schema"), QT_TR_NOOP("Owner"), QT_TR_NOOP("Tablespace"), + QT_TR_NOOP("Data type"), QT_TR_NOOP("Return type")}; + ObjectFinderWidget::ObjectFinderWidget(QWidget *parent) : QWidget(parent) { setupUi(this); @@ -49,6 +59,9 @@ ObjectFinderWidget::ObjectFinderWidget(QWidget *parent) : QWidget(parent) connect(select_all_btn, SIGNAL(clicked(void)), this, SLOT(setAllObjectsChecked(void))); connect(clear_all_btn, SIGNAL(clicked(void)), this, SLOT(setAllObjectsChecked(void))); + for(auto &attr : search_attribs_i18n) + search_attrs_cmb->addItem(attr); + this->setModel(nullptr); pattern_edt->installEventFilter(this); } @@ -104,7 +117,7 @@ void ObjectFinderWidget::fadeObjects(void) vector objects, other_objs; bool fade_listed = false; - for(auto obj_type : {OBJ_TABLE, OBJ_VIEW, OBJ_TEXTBOX, OBJ_RELATIONSHIP, BASE_RELATIONSHIP, OBJ_SCHEMA}) + for(auto obj_type : {ObjectType::Table, ObjectType::View, ObjectType::Textbox, ObjectType::Relationship, ObjectType::BaseRelationship, ObjectType::Schema}) { objects.insert(objects.end(), model_wgt->getDatabaseModel()->getObjectList(obj_type)->begin(), @@ -137,7 +150,7 @@ void ObjectFinderWidget::selectObjects(void) BaseGraphicObject *graph_obj = nullptr; bool sel_listed = false; - for(auto obj_type : {OBJ_TABLE, OBJ_VIEW, OBJ_TEXTBOX, OBJ_RELATIONSHIP, BASE_RELATIONSHIP, OBJ_SCHEMA}) + for(auto obj_type : {ObjectType::Table, ObjectType::View, ObjectType::Textbox, ObjectType::Relationship, ObjectType::BaseRelationship, ObjectType::Schema}) { objects.insert(objects.end(), model_wgt->getDatabaseModel()->getObjectList(obj_type)->begin(), @@ -168,7 +181,7 @@ void ObjectFinderWidget::selectObjects(void) if(graph_obj) { - obj_view = dynamic_cast(graph_obj->getReceiverObject()); + obj_view = dynamic_cast(graph_obj->getOverlyingObject()); if(obj_view) { @@ -216,6 +229,8 @@ void ObjectFinderWidget::findObjects(void) if(model_wgt) { vector types; + QString search_attr = search_attribs.at(search_attrs_cmb->currentIndex()); + QTableWidgetItem *item = result_tbw->horizontalHeaderItem(result_tbw->columnCount() - 1); clearResult(); @@ -227,19 +242,30 @@ void ObjectFinderWidget::findObjects(void) } //Search the objects on model - found_objs=model_wgt->getDatabaseModel()->findObjects(pattern_edt->text(), types, true, - case_sensitive_chk->isChecked(), regexp_chk->isChecked(), exact_match_chk->isChecked()); + found_objs=model_wgt->getDatabaseModel()->findObjects(pattern_edt->text(), types, + case_sensitive_chk->isChecked(), regexp_chk->isChecked(), + exact_match_chk->isChecked(), + search_attr); //Show the found objects on the result table - updateObjectTable(result_tbw, found_objs); + updateObjectTable(result_tbw, found_objs, search_attr); + + //Rename the last column of the results grid wth the name of the field used to search objects + if(search_attr != Attributes::Name && + search_attr != Attributes::Schema && + search_attr != Attributes::Comment) + item->setText(search_attrs_cmb->currentText()); + else + item->setText(trUtf8("Comment")); + found_lbl->setVisible(true); //Show a message indicating the number of found objects if(!found_objs.empty()) { found_lbl->setText(trUtf8("Found %1 object(s).").arg(found_objs.size())); - result_tbw->resizeColumnsToContents(); result_tbw->horizontalHeader()->setStretchLastSection(true); + result_tbw->resizeColumnsToContents(); } else found_lbl->setText(trUtf8("No objects found.")); @@ -269,10 +295,14 @@ void ObjectFinderWidget::selectObject(void) if(graph_obj) { - BaseObjectView *obj=dynamic_cast(graph_obj->getReceiverObject()); - model_wgt->scene->clearSelection(); - model_wgt->viewport->centerOn(obj); - obj->setSelected(true); + BaseObjectView *obj=dynamic_cast(graph_obj->getOverlyingObject()); + + if(obj) + { + model_wgt->scene->clearSelection(); + model_wgt->viewport->centerOn(obj); + obj->setSelected(true); + } } } //Showing the popup menu for the selected object in the result set @@ -288,8 +318,8 @@ void ObjectFinderWidget::editObject(void) { if(selected_obj) { - if(selected_obj->getObjectType()==OBJ_PERMISSION) - model_wgt->showObjectForm(OBJ_PERMISSION, dynamic_cast(selected_obj)->getObject()); + if(selected_obj->getObjectType()==ObjectType::Permission) + model_wgt->showObjectForm(ObjectType::Permission, dynamic_cast(selected_obj)->getObject()); else { vector vect; @@ -311,7 +341,7 @@ void ObjectFinderWidget::setAllObjectsChecked(void) obj_types_lst->item(i)->setCheckState((checked ? Qt::Checked : Qt::Unchecked)); } -void ObjectFinderWidget::updateObjectTable(QTableWidget *tab_wgt, vector &objs) +void ObjectFinderWidget::updateObjectTable(QTableWidget *tab_wgt, vector &objs, const QString &search_attr) { if(tab_wgt && tab_wgt->columnCount()!=0) { @@ -320,52 +350,61 @@ void ObjectFinderWidget::updateObjectTable(QTableWidget *tab_wgt, vectorrowCount() > 0) - tab_wgt->removeRow(0); - + tab_wgt->setUpdatesEnabled(false); tab_wgt->setSortingEnabled(false); for(lin_idx=0, i=0; i < objs.size(); i++) { - if(objs[i]->getObjectType()==BASE_RELATIONSHIP) + if(objs[i]->getObjectType()==ObjectType::BaseRelationship) str_aux=QString("tv"); else str_aux.clear(); - tab_wgt->insertRow(lin_idx); + new_row = false; + + if(static_cast(lin_idx) >= tab_wgt->rowCount()) + { + tab_wgt->insertRow(lin_idx); + new_row = true; + } //First column: Object id - tab_item=new QTableWidgetItem; - //tab_item->setFont(fnt); + tab_item=(new_row ? new QTableWidgetItem : tab_wgt->item(lin_idx, 0)); tab_item->setText(QString::number(objs[i]->getObjectId())); tab_item->setData(Qt::UserRole, QVariant::fromValue(reinterpret_cast(objs[i]))); - tab_wgt->setItem(lin_idx, 0, tab_item); - + if(new_row) tab_wgt->setItem(lin_idx, 0, tab_item); //Second column: Object name if(tab_wgt->columnCount() > 1) { - tab_item=new QTableWidgetItem; + tab_item=(new_row ? new QTableWidgetItem : tab_wgt->item(lin_idx, 1)); tab_item->setData(Qt::UserRole, QVariant::fromValue(reinterpret_cast(objs[i]))); fnt=tab_item->font(); tab_item->setText(objs[i]->getName()); - tab_item->setIcon(QPixmap(PgModelerUiNS::getIconPath(BaseObject::getSchemaName(objs[i]->getObjectType()) + str_aux))); - tab_wgt->setItem(lin_idx, 1, tab_item); + tab_item->setIcon(QPixmap(PgModelerUiNs::getIconPath(BaseObject::getSchemaName(objs[i]->getObjectType()) + str_aux))); + if(new_row) tab_wgt->setItem(lin_idx, 1, tab_item); if(objs[i]->isProtected() || objs[i]->isSystemObject()) { fnt.setItalic(true); - tab_item->setForeground(BaseObjectView::getFontStyle(ParsersAttributes::PROT_COLUMN).foreground()); + tab_item->setForeground(BaseObjectView::getFontStyle(Attributes::ProtColumn).foreground()); } else if(dynamic_cast(objs[i]) && dynamic_cast(objs[i])->isAddedByRelationship()) { fnt.setItalic(true); - tab_item->setForeground(BaseObjectView::getFontStyle(ParsersAttributes::INH_COLUMN).foreground()); + tab_item->setForeground(BaseObjectView::getFontStyle(Attributes::InhColumn).foreground()); + } + else + { + fnt.setItalic(false); + tab_item->setForeground(BaseObjectView::getFontStyle(Attributes::Column).foreground()); } + fnt.setStrikeOut(objs[i]->isSQLDisabled() && !objs[i]->isSystemObject()); tab_item->setFont(fnt); fnt.setStrikeOut(false); @@ -375,16 +414,16 @@ void ObjectFinderWidget::updateObjectTable(QTableWidget *tab_wgt, vectorcolumnCount() > 2) { fnt.setItalic(true); - tab_item=new QTableWidgetItem; + tab_item=(new_row ? new QTableWidgetItem : tab_wgt->item(lin_idx, 2)); tab_item->setFont(fnt); tab_item->setText(objs[i]->getTypeName()); - tab_wgt->setItem(lin_idx, 2, tab_item); + if(new_row) tab_wgt->setItem(lin_idx, 2, tab_item); } //Fourth column: Parent object name if(tab_wgt->columnCount() > 3) { - tab_item=new QTableWidgetItem; + tab_item=(new_row ? new QTableWidgetItem : tab_wgt->item(lin_idx, 3)); if(dynamic_cast(objs[i])) parent_obj=dynamic_cast(objs[i])->getParentTable(); @@ -397,36 +436,63 @@ void ObjectFinderWidget::updateObjectTable(QTableWidget *tab_wgt, vectorsetText(parent_obj ? parent_obj->getName() : QString("-")); tab_item->setData(Qt::UserRole, QVariant::fromValue(reinterpret_cast(parent_obj))); - - tab_wgt->setItem(lin_idx, 3, tab_item); + if(new_row) tab_wgt->setItem(lin_idx, 3, tab_item); if(parent_obj) { if(parent_obj->isProtected() || parent_obj->isSystemObject()) { fnt.setItalic(true); - tab_item->setFont(fnt); - tab_item->setForeground(BaseObjectView::getFontStyle(ParsersAttributes::PROT_COLUMN).foreground()); + tab_item->setForeground(BaseObjectView::getFontStyle(Attributes::ProtColumn).foreground()); + } + else + { + fnt.setItalic(false); + tab_item->setForeground(BaseObjectView::getFontStyle(Attributes::Column).foreground()); } - tab_item->setIcon(QPixmap(PgModelerUiNS::getIconPath(parent_obj->getObjectType()))); + tab_item->setFont(fnt); + tab_item->setIcon(QPixmap(PgModelerUiNs::getIconPath(parent_obj->getObjectType()))); } } //Fifth column: Parent object type if(tab_wgt->columnCount() > 4) { - tab_item=new QTableWidgetItem; + tab_item=(new_row ? new QTableWidgetItem : tab_wgt->item(lin_idx, 4)); fnt.setItalic(true); tab_item->setFont(fnt); tab_item->setText(parent_obj ? parent_obj->getTypeName() : QString("-")); - tab_wgt->setItem(lin_idx, 4, tab_item); + if(new_row) tab_wgt->setItem(lin_idx, 4, tab_item); + } + + //Sixth column: object comment + if(tab_wgt->columnCount() > 5) + { + tab_item=(new_row ? new QTableWidgetItem : tab_wgt->item(lin_idx, 5)); + fnt.setItalic(false); + tab_item->setFont(fnt); + + if(search_attr != Attributes::Name && + search_attr != Attributes::Schema && + search_attr != Attributes::Comment) + tab_item->setText(objs[i]->getSearchAttributes().at(search_attr)); + else + tab_item->setText(objs[i]->getComment()); + + if(new_row) tab_wgt->setItem(lin_idx, 5, tab_item); } lin_idx++; } + if(static_cast(objs.size()) != tab_wgt->rowCount()) + tab_wgt->setRowCount(objs.size()); + + tab_wgt->setUpdatesEnabled(true); tab_wgt->setSortingEnabled(true); + tab_wgt->resizeColumnsToContents(); + tab_wgt->resizeRowsToContents(); } } @@ -446,19 +512,19 @@ void ObjectFinderWidget::updateObjectTypeList(QListWidget *list_wgt) { item=new QListWidgetItem; - if(types[type_id]==BASE_RELATIONSHIP) + if(types[type_id]==ObjectType::BaseRelationship) str_aux=QString(BaseObject::getSchemaName(types[type_id])) + QString("tv"); else str_aux=QString(BaseObject::getSchemaName(types[type_id])); - icon=QPixmap(PgModelerUiNS::getIconPath(str_aux)); + icon=QPixmap(PgModelerUiNs::getIconPath(str_aux)); item->setText(BaseObject::getTypeName(types[type_id])); item->setIcon(icon); //By default all object types are checked item->setCheckState(Qt::Checked); - item->setData(Qt::UserRole, QVariant(types[type_id])); + item->setData(Qt::UserRole, QVariant(enum_cast(types[type_id]))); list_wgt->insertItem(type_id, item); } } diff --git a/libpgmodeler_ui/src/objectfinderwidget.h b/libpgmodeler_ui/src/objectfinderwidget.h index c0d6154df6..b307320fd8 100644 --- a/libpgmodeler_ui/src/objectfinderwidget.h +++ b/libpgmodeler_ui/src/objectfinderwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -34,6 +34,14 @@ class ObjectFinderWidget : public QWidget, public Ui::ObjectFinderWidget { private: Q_OBJECT + /*! \brief Store in a unordered list the attributes in order to allow the user + * select which attribute will be used to search objects */ + static const QStringList search_attribs, + + /*! \brief Store in a unordered list the attributes in a translated way in order to + * populate the combo box used to select which attribute will be used to search objects */ + search_attribs_i18n; + vector found_objs; QMenu select_menu, fade_menu; @@ -52,14 +60,14 @@ class ObjectFinderWidget : public QWidget, public Ui::ObjectFinderWidget { void resizeEvent(QResizeEvent *event); public: - ObjectFinderWidget(QWidget *parent = 0); + ObjectFinderWidget(QWidget *parent = nullptr); //! \brief Lists all valid types in a QListWidget static void updateObjectTypeList(QListWidget *list_wgt); /*! \brief Lists the objects of a vector in a QTableWidget. Any row of table contains the reference to the object on the first column */ - static void updateObjectTable(QTableWidget *tab_wgt, vector &objects); + static void updateObjectTable(QTableWidget *tab_wgt, vector &objects, const QString &search_attr = Attributes::Name); //! \brief Sets the database model to work on void setModel(ModelWidget *model_wgt); diff --git a/libpgmodeler_ui/src/objectrenamewidget.cpp b/libpgmodeler_ui/src/objectrenamewidget.cpp index ea92d20a6a..28856e7a64 100644 --- a/libpgmodeler_ui/src/objectrenamewidget.cpp +++ b/libpgmodeler_ui/src/objectrenamewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -38,19 +38,19 @@ void ObjectRenameWidget::setAttributes(BaseObject *object, DatabaseModel *model, TableObject *tab_obj=dynamic_cast(object); if(!object || !op_list) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(tab_obj && tab_obj->isAddedByRelationship()) - throw Exception(Exception::getErrorMessage(ERR_OPR_REL_INCL_OBJECT) - .arg(tab_obj->getName()) - .arg(tab_obj->getTypeName()) - ,ERR_OPR_REL_INCL_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::OprRelationshipAddedObject) + .arg(tab_obj->getName()) + .arg(tab_obj->getTypeName()), + ErrorCode::OprRelationshipAddedObject ,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->adjustSize(); this->object=object; this->op_list=op_list; this->model=model; - obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath(object->getSchemaName()))); + obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath(object->getSchemaName()))); obj_icon_lbl->setToolTip(object->getTypeName()); obj_name_lbl->setText(object->getName()); @@ -76,7 +76,7 @@ void ObjectRenameWidget::hideEvent(QHideEvent *) void ObjectRenameWidget::applyRenaming(void) { - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; try { @@ -92,13 +92,13 @@ void ObjectRenameWidget::applyRenaming(void) obj_type=object->getObjectType(); - if(obj_type!=OBJ_DATABASE) + if(obj_type!=ObjectType::Database) { //Register the object on operations list before the modification - op_list->registerObject(object, Operation::OBJECT_MODIFIED, -1, (tab_obj ? tab_obj->getParentTable() : nullptr)); + op_list->registerObject(object, Operation::ObjectModified, -1, (tab_obj ? tab_obj->getParentTable() : nullptr)); //Format the object name to check if it will have a conflicting name - fmt_name=BaseObject::formatName(new_name_edt->text().toUtf8(), obj_type==OBJ_OPERATOR); + fmt_name=BaseObject::formatName(new_name_edt->text().toUtf8(), obj_type==ObjectType::Operator); if(object->getSchema()) fmt_name=object->getSchema()->getName(true) + QString(".") + fmt_name; @@ -107,7 +107,7 @@ void ObjectRenameWidget::applyRenaming(void) if(tab_obj) { parent_obj=tab_obj->getParentTable(); - aux_obj=dynamic_cast
(tab_obj->getParentTable())->getObject(fmt_name, obj_type); + aux_obj=dynamic_cast(tab_obj->getParentTable())->getObject(fmt_name, obj_type); } //For database child object, check if there is another object with the same new name else @@ -119,12 +119,12 @@ void ObjectRenameWidget::applyRenaming(void) //Raises a error if another object is found if(aux_obj && aux_obj!=object) { - throw Exception(QString(Exception::getErrorMessage(ERR_ASG_DUPLIC_OBJECT)) - .arg(fmt_name) - .arg(object->getTypeName()) - .arg(parent_obj->getName(true)) - .arg(parent_obj->getTypeName()), - ERR_ASG_DUPLIC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::AsgDuplicatedObject) + .arg(fmt_name) + .arg(object->getTypeName()) + .arg(parent_obj->getName(true)) + .arg(parent_obj->getTypeName()), + ErrorCode::AsgDuplicatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } @@ -135,27 +135,33 @@ void ObjectRenameWidget::applyRenaming(void) { obj_graph->setModified(true); - if(obj_graph->getObjectType()==OBJ_TABLE || - obj_graph->getObjectType()==OBJ_VIEW) + if(obj_graph->getObjectType()==ObjectType::Table || + obj_graph->getObjectType()==ObjectType::View) { dynamic_cast(obj_graph->getSchema())->setModified(true); } } else if(tab_obj) { - Table *tab=dynamic_cast
(tab_obj->getParentTable()); + BaseTable *base_tab = tab_obj->getParentTable(); + Table *tab = dynamic_cast
(base_tab); Column *col=dynamic_cast(tab_obj); /* If the object is a column and some primary key on table is referencing it - the model relationship will be revalidated */ - if(col && tab->isConstraintRefColumn(col, ConstraintType::primary_key)) - model->validateRelationships(); + * the model relationship will be revalidated */ + if(col && tab) + { + if(tab->isConstraintRefColumn(col, ConstraintType::PrimaryKey)) + model->validateRelationships(); + else + model->updateViewsReferencingTable(tab); + } - tab->setModified(true); - tab->setCodeInvalidated(true); - dynamic_cast(tab->getSchema())->setModified(true); + base_tab->setModified(true); + base_tab->setCodeInvalidated(true); + dynamic_cast(base_tab->getSchema())->setModified(true); } - else if(object->getObjectType()==OBJ_SCHEMA) + else if(object->getObjectType()==ObjectType::Schema) { model->validateSchemaRenaming(dynamic_cast(object), obj_name_lbl->text().toUtf8()); dynamic_cast(object)->setModified(true); @@ -166,7 +172,7 @@ void ObjectRenameWidget::applyRenaming(void) for(auto &obj : ref_objs) { - if(obj->getObjectType()==OBJ_COLUMN) + if(obj->getObjectType()==ObjectType::Column) { col=dynamic_cast(obj); col->getParentTable()->setModified(true); @@ -184,7 +190,7 @@ void ObjectRenameWidget::applyRenaming(void) { Messagebox msg_box; - if(obj_type!=OBJ_DATABASE) + if(obj_type!=ObjectType::Database) op_list->removeLastOperation(); msg_box.show(e); diff --git a/libpgmodeler_ui/src/objectrenamewidget.h b/libpgmodeler_ui/src/objectrenamewidget.h index 5de5aa33bd..778b4a760a 100644 --- a/libpgmodeler_ui/src/objectrenamewidget.h +++ b/libpgmodeler_ui/src/objectrenamewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libpgmodeler_ui/src/objectsdiffinfo.cpp b/libpgmodeler_ui/src/objectsdiffinfo.cpp index d27beaf9fd..feebee3b90 100644 --- a/libpgmodeler_ui/src/objectsdiffinfo.cpp +++ b/libpgmodeler_ui/src/objectsdiffinfo.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,16 +18,16 @@ #include "objectsdiffinfo.h" -const unsigned ObjectsDiffInfo::CREATE_OBJECT=0; -const unsigned ObjectsDiffInfo::DROP_OBJECT=1; -const unsigned ObjectsDiffInfo::ALTER_OBJECT=2; -const unsigned ObjectsDiffInfo::IGNORE_OBJECT=3; -const unsigned ObjectsDiffInfo::NO_DIFFERENCE=4; +constexpr unsigned ObjectsDiffInfo::CreateObject; +constexpr unsigned ObjectsDiffInfo::DropObject; +constexpr unsigned ObjectsDiffInfo::AlterObject; +constexpr unsigned ObjectsDiffInfo::IgnoreObject; +constexpr unsigned ObjectsDiffInfo::NoDifference; ObjectsDiffInfo::ObjectsDiffInfo(void) { object=old_object=nullptr; - diff_type=NO_DIFFERENCE; + diff_type=NoDifference; } ObjectsDiffInfo::ObjectsDiffInfo(unsigned diff_type, BaseObject *object, BaseObject *new_object) @@ -46,9 +46,9 @@ QString ObjectsDiffInfo::getInfoMessage(void) { QString msg=QString("%1 `%2' (%3)"), obj_name; BaseObject *ref_obj=nullptr; - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; - if(diff_type==ALTER_OBJECT && old_object) + if(diff_type==AlterObject && old_object) ref_obj=old_object; else ref_obj=object; @@ -58,35 +58,35 @@ QString ObjectsDiffInfo::getInfoMessage(void) /* Forcing the usage of BaseObject::getSignature for the following object, since the custom getSignature for those types return some undesired SQL keywords for this context */ - if(obj_type==OBJ_CONSTRAINT || obj_type==OBJ_TRIGGER || obj_type==OBJ_RULE) + if(obj_type==ObjectType::Constraint || obj_type==ObjectType::Trigger || obj_type==ObjectType::Rule) obj_name=dynamic_cast(ref_obj)->TableObject::getSignature(); - else if(obj_type==OBJ_OPCLASS || obj_type==OBJ_OPFAMILY) + else if(obj_type==ObjectType::OpClass || obj_type==ObjectType::OpFamily) obj_name=ref_obj->BaseObject::getSignature(); else obj_name=ref_obj->getSignature(); - if(diff_type==NO_DIFFERENCE) + if(diff_type==NoDifference) return(QString()); - else if(diff_type==DROP_OBJECT) + else if(diff_type==DropObject) { msg=msg.arg(QString("DROP")) .arg(obj_name) .arg(ref_obj->getTypeName()); } - else if(diff_type==CREATE_OBJECT) + else if(diff_type==CreateObject) { msg=msg.arg(QString("CREATE")) .arg(obj_name) .arg(ref_obj->getTypeName()); } - else if(diff_type==ALTER_OBJECT) + else if(diff_type==AlterObject) { msg=msg.arg(QString("ALTER")) .arg(obj_name) .arg(ref_obj->getTypeName()); } - else if(diff_type==IGNORE_OBJECT) + else if(diff_type==IgnoreObject) { msg=msg.arg(QString("IGNORE")) .arg(obj_name) @@ -99,13 +99,13 @@ QString ObjectsDiffInfo::getInfoMessage(void) QString ObjectsDiffInfo::getDiffTypeString(void) { - if(diff_type==NO_DIFFERENCE) + if(diff_type==NoDifference) return(QString()); - else if(diff_type==DROP_OBJECT) + else if(diff_type==DropObject) return(QString("DROP")); - else if(diff_type==CREATE_OBJECT) + else if(diff_type==CreateObject) return(QString("CREATE")); - else if(diff_type==ALTER_OBJECT) + else if(diff_type==AlterObject) return(QString("ALTER")); else return(QString("IGNORE")); diff --git a/libpgmodeler_ui/src/objectsdiffinfo.h b/libpgmodeler_ui/src/objectsdiffinfo.h index 1e28a13ea0..49177263d4 100644 --- a/libpgmodeler_ui/src/objectsdiffinfo.h +++ b/libpgmodeler_ui/src/objectsdiffinfo.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -36,11 +36,11 @@ class ObjectsDiffInfo { BaseObject *object, *old_object; public: - static const unsigned CREATE_OBJECT, - DROP_OBJECT, - ALTER_OBJECT, - IGNORE_OBJECT, - NO_DIFFERENCE; + static constexpr unsigned CreateObject=0, + DropObject=1, + AlterObject=2, + IgnoreObject=3, + NoDifference=4; ObjectsDiffInfo(void); ObjectsDiffInfo(unsigned diff_type, BaseObject *ref_object, BaseObject *old_object); diff --git a/libpgmodeler_ui/src/objectselectorwidget.cpp b/libpgmodeler_ui/src/objectselectorwidget.cpp index 1d40df1184..02c3456cff 100644 --- a/libpgmodeler_ui/src/objectselectorwidget.cpp +++ b/libpgmodeler_ui/src/objectselectorwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -27,7 +27,7 @@ ObjectSelectorWidget::ObjectSelectorWidget(ObjectType sel_obj_type, bool install } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -40,7 +40,7 @@ ObjectSelectorWidget::ObjectSelectorWidget(vector sel_obj_types, boo } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -58,7 +58,7 @@ void ObjectSelectorWidget::configureSelector(bool install_highlighter) if(install_highlighter) { obj_name_hl=new SyntaxHighlighter(obj_name_txt, true); - obj_name_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + obj_name_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); } else { @@ -76,7 +76,7 @@ void ObjectSelectorWidget::configureSelector(bool install_highlighter) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -119,7 +119,7 @@ QString ObjectSelectorWidget::getSelectedObjectName(void) void ObjectSelectorWidget::setSelectedObject(BaseObject *object) { - ObjectType obj_type; + ObjectType obj_type = ObjectType::BaseObject; if(object) obj_type=object->getObjectType(); @@ -129,14 +129,20 @@ void ObjectSelectorWidget::setSelectedObject(BaseObject *object) rem_object_tb->setEnabled(object); this->selected_obj=object; - if(object->getObjectType()!=OBJ_CONSTRAINT) - obj_name_txt->setPlainText(selected_obj->getSignature()); + if(obj_type != ObjectType::Constraint) + { + if(obj_type != ObjectType::UserMapping) + obj_name_txt->setPlainText(selected_obj->getSignature()); + else + obj_name_txt->setPlainText(selected_obj->getName()); + } else obj_name_txt->setPlainText(QString("%1.%2") .arg(dynamic_cast(selected_obj)->getParentTable()->getSignature()) .arg(selected_obj->getName(true))); emit s_objectSelected(); + emit s_selectorChanged(true); } else clearSelector(); @@ -155,7 +161,7 @@ void ObjectSelectorWidget::setSelectedObject(const QString &obj_name, ObjectType } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -176,6 +182,7 @@ void ObjectSelectorWidget::clearSelector(void) obj_name_txt->clear(); rem_object_tb->setEnabled(false); emit s_selectorCleared(); + emit s_selectorChanged(false); } void ObjectSelectorWidget::showObjectView(void) diff --git a/libpgmodeler_ui/src/objectselectorwidget.h b/libpgmodeler_ui/src/objectselectorwidget.h index 2ea94b0411..c4283530cb 100644 --- a/libpgmodeler_ui/src/objectselectorwidget.h +++ b/libpgmodeler_ui/src/objectselectorwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -56,8 +56,8 @@ class ObjectSelectorWidget: public QWidget, public Ui::ObjectSelectorWidget { bool eventFilter(QObject *obj, QEvent *evnt); public: - ObjectSelectorWidget(ObjectType sel_obj_type, bool install_highlighter, QWidget * parent = 0); - ObjectSelectorWidget(vector sel_obj_types, bool install_highlighter, QWidget * parent = 0); + ObjectSelectorWidget(ObjectType sel_obj_type, bool install_highlighter, QWidget * parent = nullptr); + ObjectSelectorWidget(vector sel_obj_types, bool install_highlighter, QWidget * parent = nullptr); ~ObjectSelectorWidget(void); //! \brief Enables the creation of new objects from withing the object selector dialog @@ -93,6 +93,10 @@ class ObjectSelectorWidget: public QWidget, public Ui::ObjectSelectorWidget { //! \brief Signal emitted when the user clears the selector void s_selectorCleared(void); + + /*! \brief Signal emitted when the user clears the selector or selects and object + * The boolean param indicates if there's an object selected or not */ + void s_selectorChanged(bool); }; #endif diff --git a/libpgmodeler_ui/src/objectstablewidget.cpp b/libpgmodeler_ui/src/objectstablewidget.cpp index 4b59c4ca88..b89ee381c3 100644 --- a/libpgmodeler_ui/src/objectstablewidget.cpp +++ b/libpgmodeler_ui/src/objectstablewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -41,7 +41,14 @@ ObjectsTableWidget::ObjectsTableWidget(unsigned button_conf, bool conf_exclusion emit s_cellClicked(row, col); }); + connect(resize_cols_tb, &QToolButton::clicked, [&](){ + table_tbw->resizeColumnsToContents(); + table_tbw->resizeRowsToContents(); + table_tbw->horizontalHeader()->setSectionResizeMode(table_tbw->horizontalHeader()->count() - 1, QHeaderView::Stretch); + }); + this->conf_exclusion=conf_exclusion; + cells_editable = false; setButtonConfiguration(button_conf); setColumnCount(1); @@ -63,23 +70,23 @@ void ObjectsTableWidget::setButtonConfiguration(unsigned button_conf) bool move_btn = false; //Checking via bitwise operation the buttons available on the 'button_conf' - move_btn=(button_conf & MOVE_BUTTONS) == MOVE_BUTTONS; + move_btn=(button_conf & MoveButtons) == MoveButtons; move_down_tb->setVisible(move_btn); move_up_tb->setVisible(move_btn); move_first_tb->setVisible(move_btn); move_last_tb->setVisible(move_btn); - edit_tb->setVisible((button_conf & EDIT_BUTTON) == EDIT_BUTTON); - remove_all_tb->setVisible((button_conf & REMOVE_ALL_BUTTON) == REMOVE_ALL_BUTTON); + edit_tb->setVisible((button_conf & EditButton) == EditButton); + remove_all_tb->setVisible((button_conf & RemoveAllButton) == RemoveAllButton); - add_tb->setVisible((button_conf & ADD_BUTTON) == ADD_BUTTON); - remove_tb->setVisible((button_conf & REMOVE_BUTTON) == REMOVE_BUTTON); - update_tb->setVisible((button_conf & UPDATE_BUTTON) == UPDATE_BUTTON); - duplicate_tb->setVisible((button_conf & DUPLICATE_BUTTON) == DUPLICATE_BUTTON); + add_tb->setVisible((button_conf & AddButton) == AddButton); + remove_tb->setVisible((button_conf & RemoveButton) == RemoveButton); + update_tb->setVisible((button_conf & UpdateButton) == UpdateButton); + duplicate_tb->setVisible((button_conf & DuplicateButton) == DuplicateButton); //Disabling the horizontal spacers when no buttons are visible - if(button_conf==NO_BUTTONS) + if(button_conf==NoButtons) { left_spc->changeSize(0,0,QSizePolicy::Ignored,QSizePolicy::Ignored); right_spc->changeSize(0,0,QSizePolicy::Ignored,QSizePolicy::Ignored); @@ -95,10 +102,10 @@ void ObjectsTableWidget::setButtonConfiguration(unsigned button_conf) QTableWidgetItem *ObjectsTableWidget::getItem(unsigned row_idx, unsigned col_idx) { if(row_idx >= static_cast(table_tbw->rowCount())) - throw Exception(ERR_REF_LIN_OBJTAB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefRowObjectTabInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); if(col_idx >= static_cast(table_tbw->columnCount())) - throw Exception(ERR_REF_COL_OBJTAB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefColObjectTabInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(table_tbw->item(row_idx, col_idx)); } @@ -133,18 +140,26 @@ void ObjectsTableWidget::setHeaderLabel(const QString &label, unsigned col_idx) QTableWidgetItem *item=nullptr; if(col_idx >= static_cast(table_tbw->columnCount())) - throw Exception(ERR_REF_COL_OBJTAB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefColObjectTabInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); item=table_tbw->horizontalHeaderItem(col_idx); item->setText(label); } +void ObjectsTableWidget::setHeaderVisible(unsigned col_idx, bool visible) +{ + if(col_idx >= static_cast(table_tbw->columnCount())) + throw Exception(ErrorCode::RefColObjectTabInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + table_tbw->horizontalHeader()->setSectionHidden(col_idx, !visible); +} + void ObjectsTableWidget::setHeaderIcon(const QIcon &icon, unsigned col_idx) { QTableWidgetItem *item=nullptr; if(col_idx >= static_cast(table_tbw->columnCount())) - throw Exception(ERR_REF_COL_OBJTAB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefColObjectTabInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); item=table_tbw->horizontalHeaderItem(col_idx); item->setIcon(icon); @@ -168,7 +183,7 @@ void ObjectsTableWidget::clearCellText(unsigned row_idx, unsigned col_idx) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -178,7 +193,7 @@ void ObjectsTableWidget::setRowFont(int row_idx, const QFont &font, const QColor int col_count, i; if(row_idx >= table_tbw->rowCount()) - throw Exception(ERR_REF_LIN_OBJTAB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefRowObjectTabInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); col_count=table_tbw->columnCount(); for(i=0; i < col_count; i++) @@ -195,7 +210,7 @@ void ObjectsTableWidget::setRowData(const QVariant &data, unsigned row_idx) QTableWidgetItem *item=nullptr; if(row_idx >= static_cast(table_tbw->rowCount())) - throw Exception(ERR_REF_LIN_OBJTAB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefRowObjectTabInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Gets the vertical header of the row. This header stores the whole row data. item=table_tbw->verticalHeaderItem(row_idx); @@ -217,7 +232,7 @@ QString ObjectsTableWidget::getHeaderLabel(unsigned col_idx) QTableWidgetItem *item=nullptr; if(col_idx >= static_cast(table_tbw->columnCount())) - throw Exception(ERR_REF_COL_OBJTAB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefColObjectTabInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); item=table_tbw->horizontalHeaderItem(col_idx); return(item->text()); @@ -258,7 +273,7 @@ QVariant ObjectsTableWidget::getRowData(unsigned row_idx) QTableWidgetItem *item=nullptr; if(row_idx >= static_cast(table_tbw->rowCount())) - throw Exception(ERR_REF_LIN_OBJTAB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefRowObjectTabInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); item=table_tbw->verticalHeaderItem(row_idx); return(item->data(Qt::UserRole)); @@ -331,7 +346,7 @@ void ObjectsTableWidget::addRow(unsigned lin_idx) for(col_idx=0; col_idx < col_cont; col_idx++) { - item=new QTableWidgetItem; + item=new QTableWidgetItem; table_tbw->setItem(lin_idx,col_idx,item); } @@ -355,7 +370,7 @@ void ObjectsTableWidget::removeRow(unsigned row_idx) bool conf; if(row_idx >= static_cast(table_tbw->rowCount())) - throw Exception(ERR_REF_LIN_OBJTAB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefRowObjectTabInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Before remove the row, clears the selection table_tbw->clearSelection(); @@ -386,16 +401,20 @@ void ObjectsTableWidget::removeRow(void) { if(conf_exclusion) msg_box.show(trUtf8("Confirmation"),trUtf8("Do you really want to remove the selected item?"), - Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); if(!conf_exclusion || (conf_exclusion && msg_box.result()==QDialog::Accepted)) { setRowData(QVariant::fromValue(nullptr), row_idx); item->setData(Qt::UserRole, QVariant::fromValue(nullptr)); - emit s_rowRemoved(row_idx); + + emit s_rowAboutToRemove(row_idx); + table_tbw->removeRow(row_idx); table_tbw->setCurrentItem(nullptr); setButtonsEnabled(); + + emit s_rowRemoved(row_idx); } } } @@ -435,7 +454,7 @@ void ObjectsTableWidget::removeRows(void) activating the 'remove_all_tb' button */ if(conf_exclusion && sender_obj==remove_all_tb) msg_box.show(trUtf8("Confirmation"),trUtf8("Do you really want to remove all the items?"), - Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); if(!conf_exclusion || (conf_exclusion && sender_obj!=remove_all_tb) || (conf_exclusion && sender_obj==remove_all_tb && msg_box.result()==QDialog::Accepted)) @@ -451,7 +470,7 @@ void ObjectsTableWidget::removeRows(void) void ObjectsTableWidget::removeColumn(unsigned col_idx) { if(col_idx >= static_cast(table_tbw->columnCount())) - throw Exception(ERR_REF_COL_OBJTAB_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefColObjectTabInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); table_tbw->removeColumn(col_idx); table_tbw->clearSelection(); @@ -570,7 +589,7 @@ void ObjectsTableWidget::setButtonsEnabled(unsigned button_conf, bool value) if(item) lin=item->row(); - if((button_conf & MOVE_BUTTONS) == MOVE_BUTTONS) + if((button_conf & MoveButtons) == MoveButtons) { move_up_tb->setEnabled(value && lin > 0); move_down_tb->setEnabled(value && lin >= 0 && lin < table_tbw->rowCount()-1); @@ -578,28 +597,37 @@ void ObjectsTableWidget::setButtonsEnabled(unsigned button_conf, bool value) move_last_tb->setEnabled(value && lin >=0 && lin < table_tbw->rowCount()-1); } - if((button_conf & EDIT_BUTTON) == EDIT_BUTTON) + if((button_conf & EditButton) == EditButton) edit_tb->setEnabled(value && lin >= 0); - if((button_conf & ADD_BUTTON) == ADD_BUTTON) + if((button_conf & AddButton) == AddButton) add_tb->setEnabled(value); - if((button_conf & REMOVE_BUTTON) == REMOVE_BUTTON) + if((button_conf & RemoveButton) == RemoveButton) remove_tb->setEnabled(value && lin >= 0); - if((button_conf & REMOVE_ALL_BUTTON) == REMOVE_ALL_BUTTON) + if((button_conf & RemoveAllButton) == RemoveAllButton) remove_all_tb->setEnabled(value && table_tbw->rowCount() > 0); - if((button_conf & UPDATE_BUTTON) == UPDATE_BUTTON) + if((button_conf & UpdateButton) == UpdateButton) update_tb->setEnabled(value && lin >= 0); - if((button_conf & DUPLICATE_BUTTON) == DUPLICATE_BUTTON) + if((button_conf & DuplicateButton) == DuplicateButton) duplicate_tb->setEnabled(value && lin >= 0); + + if((button_conf & ResizeColsButton) == ResizeColsButton) + resize_cols_tb->setEnabled(value && table_tbw->rowCount() > 0); +} + +void ObjectsTableWidget::setCellsEditable(bool value) +{ + table_tbw->setSelectionBehavior(value ? QAbstractItemView::SelectItems : QAbstractItemView::SelectRows); + table_tbw->setEditTriggers(value ? QAbstractItemView::AllEditTriggers : QAbstractItemView::NoEditTriggers); } void ObjectsTableWidget::setButtonsEnabled(void) { - setButtonsEnabled(ALL_BUTTONS, true); + setButtonsEnabled(AllButtons, true); } void ObjectsTableWidget::emitRowSelected(void) diff --git a/libpgmodeler_ui/src/objectstablewidget.h b/libpgmodeler_ui/src/objectstablewidget.h index a68a0feb0e..545c797ace 100644 --- a/libpgmodeler_ui/src/objectstablewidget.h +++ b/libpgmodeler_ui/src/objectstablewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -40,21 +40,26 @@ class ObjectsTableWidget: public QWidget, public Ui::ObjectsTableWidget { to remove an element from table. By default, the exclusions are made without confirmation */ bool conf_exclusion; + /*! \brief Indicates that cells' texts can be edited by the user. When changing the text of a cell + * the signal s_cellTextChanged(int,int) is emitted */ + bool cells_editable; + QTableWidgetItem *getItem(unsigned row_idx, unsigned col_idx); public: //! \brief Constants used to configure the table buttons - static const unsigned ADD_BUTTON=1, - REMOVE_BUTTON=2, - UPDATE_BUTTON=4, - MOVE_BUTTONS=8, - EDIT_BUTTON=16, - DUPLICATE_BUTTON=32, - REMOVE_ALL_BUTTON=64, - ALL_BUTTONS=127, - NO_BUTTONS=0; - - ObjectsTableWidget(unsigned button_conf=ALL_BUTTONS, bool conf_exclusion=false, QWidget * parent = 0); + static constexpr unsigned AddButton=1, + RemoveButton=2, + UpdateButton=4, + MoveButtons=8, + EditButton=16, + DuplicateButton=32, + RemoveAllButton=64, + ResizeColsButton=128, + AllButtons=255, + NoButtons=0; + + ObjectsTableWidget(unsigned button_conf=AllButtons, bool conf_exclusion=false, QWidget * parent = nullptr); //! \brief Sets the table's column count void setColumnCount(unsigned col_count); @@ -62,6 +67,9 @@ class ObjectsTableWidget: public QWidget, public Ui::ObjectsTableWidget { //! \brief Sets the specified column header label void setHeaderLabel(const QString &label, unsigned col_idx); + //! \brief Sets the specified column header to be visible or not + void setHeaderVisible(unsigned col_idx, bool visible); + //! \brief Sets the specified column header icon void setHeaderIcon(const QIcon &icon, unsigned col_idx); @@ -168,6 +176,8 @@ class ObjectsTableWidget: public QWidget, public Ui::ObjectsTableWidget { //! \brief Controls the enable state of each button void setButtonsEnabled(unsigned button_conf, bool value); + void setCellsEditable(bool value); + signals: //! \brief Signal emitted when a new row is added. The new row index is send with the signal void s_rowAdded(int); @@ -181,6 +191,9 @@ class ObjectsTableWidget: public QWidget, public Ui::ObjectsTableWidget { //! \brief Signal emitted when a single row is removed. The row index is sent together with the signal void s_rowRemoved(int); + //! \brief Signal emitted when a single row is about to be removed. The row index is sent together with the signal + void s_rowAboutToRemove(int); + //! \brief Signal emitted when a row is selected. The row index is sent together with the signal void s_rowSelected(int); @@ -199,8 +212,12 @@ class ObjectsTableWidget: public QWidget, public Ui::ObjectsTableWidget { //! \brief Signal emitted when a column is added. The column index is sent together with the signal void s_columnAdded(int); + //! \brief Signal emitted when a specific cell is clicked. The column and rows indexes are sent together with the signal void s_cellClicked(int, int); + //! \brief Signal emitted when a specific cell has its text changed. The column and rows indexes are sent together with the signal + void s_cellTextChanged(int, int); + protected: void resizeEvent(QResizeEvent *); }; diff --git a/libpgmodeler_ui/src/operationlistwidget.cpp b/libpgmodeler_ui/src/operationlistwidget.cpp index 6cee4a8adb..8e03638a6c 100644 --- a/libpgmodeler_ui/src/operationlistwidget.cpp +++ b/libpgmodeler_ui/src/operationlistwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -72,6 +72,7 @@ void OperationListWidget::updateOperationList(void) QFont font=this->font(); bool value=false; + operations_tw->setUpdatesEnabled(false); op_count_lbl->setText(QString("%1").arg(model_wgt->op_list->getCurrentSize())); current_pos_lbl->setText(QString("%1").arg(model_wgt->op_list->getCurrentIndex())); redo_tb->setEnabled(model_wgt->op_list->isRedoAvailable()); @@ -92,45 +93,45 @@ void OperationListWidget::updateOperationList(void) item=new QTreeWidgetItem; str_aux=QString(BaseObject::getSchemaName(obj_type)); - item->setData(0, Qt::UserRole, QVariant(obj_type)); + item->setData(0, Qt::UserRole, QVariant(enum_cast(obj_type))); - if(obj_type==BASE_RELATIONSHIP) + if(obj_type==ObjectType::BaseRelationship) str_aux+=QString("tv"); - item->setIcon(0,QPixmap(PgModelerUiNS::getIconPath(str_aux))); + item->setIcon(0,QPixmap(PgModelerUiNs::getIconPath(str_aux))); operations_tw->insertTopLevelItem(i,item); item->setFont(0,font); item->setText(0,trUtf8("Object: %1").arg(BaseObject::getTypeName(obj_type))); item2=new QTreeWidgetItem(item); - item2->setIcon(0,QPixmap(PgModelerUiNS::getIconPath("uid"))); + item2->setIcon(0,QPixmap(PgModelerUiNs::getIconPath("uid"))); item2->setFont(0,font); item2->setText(0,trUtf8("Name: %1").arg(obj_name)); - if(op_type==Operation::OBJECT_CREATED) + if(op_type==Operation::ObjectCreated) { op_icon=QString("criado"); op_name=trUtf8("created"); } - else if(op_type==Operation::OBJECT_REMOVED) + else if(op_type==Operation::ObjectRemoved) { op_icon=QString("removido"); op_name=trUtf8("removed"); } - else if(op_type==Operation::OBJECT_MODIFIED) + else if(op_type==Operation::ObjectModified) { op_icon=QString("modificado"); op_name=trUtf8("modified"); } - else if(op_type==Operation::OBJECT_MOVED) + else if(op_type==Operation::ObjectMoved) { op_icon=QString("movimentado"); op_name=trUtf8("moved"); } item1=new QTreeWidgetItem(item); - item1->setIcon(0,QPixmap(PgModelerUiNS::getIconPath(op_icon))); + item1->setIcon(0,QPixmap(PgModelerUiNs::getIconPath(op_icon))); item1->setFont(0,font); item1->setText(0,trUtf8("Operation: %1").arg(op_name)); @@ -139,6 +140,8 @@ void OperationListWidget::updateOperationList(void) if(value) operations_tw->scrollToItem(item1); } + + operations_tw->setUpdatesEnabled(true); } emit s_operationListUpdated(); @@ -166,13 +169,13 @@ void OperationListWidget::undoOperation(void) QApplication::restoreOverrideCursor(); this->updateOperationList(); - if(e.getErrorType()==ERR_UNDO_REDO_OPR_INV_OBJECT) + if(e.getErrorCode()==ErrorCode::UndoRedoOperationInvalidObject) { Messagebox msg_box; - msg_box.show(e, "", Messagebox::ALERT_ICON); + msg_box.show(e, "", Messagebox::AlertIcon); } else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -190,13 +193,13 @@ void OperationListWidget::redoOperation(void) { QApplication::restoreOverrideCursor(); - if(e.getErrorType()==ERR_UNDO_REDO_OPR_INV_OBJECT) + if(e.getErrorCode()==ErrorCode::UndoRedoOperationInvalidObject) { Messagebox msg_box; - msg_box.show(e, "", Messagebox::ALERT_ICON); + msg_box.show(e, "", Messagebox::AlertIcon); } else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -206,8 +209,8 @@ void OperationListWidget::removeOperations(void) msg_box.show(trUtf8("Operation history exclusion"), trUtf8("Delete the executed operations history is an irreversible action, do you want to continue?"), - Messagebox::CONFIRM_ICON, - Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon, + Messagebox::YesNoButtons); if(msg_box.result()==QDialog::Accepted) { diff --git a/libpgmodeler_ui/src/operationlistwidget.h b/libpgmodeler_ui/src/operationlistwidget.h index 1647ed265a..58c40806b1 100644 --- a/libpgmodeler_ui/src/operationlistwidget.h +++ b/libpgmodeler_ui/src/operationlistwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -40,7 +40,7 @@ class OperationListWidget: public QWidget, public Ui::OperationListWidget { void notifyUpdateOnModel(void); public: - OperationListWidget(QWidget * parent = 0); + OperationListWidget(QWidget * parent = nullptr); public slots: void updateOperationList(void); diff --git a/libpgmodeler_ui/src/operatorclasswidget.cpp b/libpgmodeler_ui/src/operatorclasswidget.cpp index 4c4404cba3..65b2abf690 100644 --- a/libpgmodeler_ui/src/operatorclasswidget.cpp +++ b/libpgmodeler_ui/src/operatorclasswidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "operatorclasswidget.h" -OperatorClassWidget::OperatorClassWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_OPCLASS) +OperatorClassWidget::OperatorClassWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::OpClass) { try { @@ -30,24 +30,24 @@ OperatorClassWidget::OperatorClassWidget(QWidget *parent): BaseObjectWidget(pare Ui_OperatorClassWidget::setupUi(this); - family_sel=new ObjectSelectorWidget(OBJ_OPFAMILY, true, this); + family_sel=new ObjectSelectorWidget(ObjectType::OpFamily, true, this); data_type=new PgSQLTypeWidget(this); - operator_sel=new ObjectSelectorWidget(OBJ_OPERATOR, true, this); - elem_family_sel=new ObjectSelectorWidget(OBJ_OPFAMILY, true, this); - function_sel=new ObjectSelectorWidget(OBJ_FUNCTION, true, this); + operator_sel=new ObjectSelectorWidget(ObjectType::Operator, true, this); + elem_family_sel=new ObjectSelectorWidget(ObjectType::OpFamily, true, this); + function_sel=new ObjectSelectorWidget(ObjectType::Function, true, this); storage_type=new PgSQLTypeWidget(this, trUtf8("Storage Type")); - elements_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ ObjectsTableWidget::DUPLICATE_BUTTON, true, this); + elements_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ ObjectsTableWidget::DuplicateButton, true, this); elements_tab->setColumnCount(4); elements_tab->setHeaderLabel(trUtf8("Object"),0); - elements_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("table")),0); + elements_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("table")),0); elements_tab->setHeaderLabel(trUtf8("Type"),1); - elements_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("usertype")),1); + elements_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("usertype")),1); elements_tab->setHeaderLabel(trUtf8("Support/Strategy"),2); elements_tab->setHeaderLabel(trUtf8("Operator Family"),3); - elements_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("opfamily")),3); + elements_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("opfamily")),3); grid=new QGridLayout; grid->setContentsMargins(0,0,0,0); @@ -60,10 +60,10 @@ OperatorClassWidget::OperatorClassWidget(QWidget *parent): BaseObjectWidget(pare grid->addWidget(data_type,4,0,1,5); grid->addWidget(elements_grp,5,0,1,5); this->setLayout(grid); - configureFormLayout(grid, OBJ_OPCLASS); + configureFormLayout(grid, ObjectType::OpClass); - fields_map[BaseObjectWidget::generateVersionsInterval(BaseObjectWidget::AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_95)].push_back(indexing_lbl); - values_map[indexing_lbl].push_back(~IndexingType(IndexingType::brin)); + fields_map[BaseObjectWidget::generateVersionsInterval(BaseObjectWidget::AfterVersion, PgSqlVersions::PgSqlVersion95)].push_back(indexing_lbl); + values_map[indexing_lbl].push_back(~IndexingType(IndexingType::Brin)); frame=BaseObjectWidget::generateVersionWarningFrame(fields_map, &values_map); frame->setParent(this); @@ -94,7 +94,7 @@ OperatorClassWidget::OperatorClassWidget(QWidget *parent): BaseObjectWidget(pare } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -102,17 +102,17 @@ void OperatorClassWidget::selectElementType(int elem_type) { unsigned sel_idx=static_cast(elem_type); - function_lbl->setVisible(sel_idx==OperatorClassElement::FUNCTION_ELEM); - function_sel->setVisible(sel_idx==OperatorClassElement::FUNCTION_ELEM); + function_lbl->setVisible(sel_idx==OperatorClassElement::FunctionElem); + function_sel->setVisible(sel_idx==OperatorClassElement::FunctionElem); - operator_lbl->setVisible(sel_idx==OperatorClassElement::OPERATOR_ELEM); - operator_sel->setVisible(sel_idx==OperatorClassElement::OPERATOR_ELEM); - elem_family_lbl->setVisible(sel_idx==OperatorClassElement::OPERATOR_ELEM); - elem_family_sel->setVisible(sel_idx==OperatorClassElement::OPERATOR_ELEM); + operator_lbl->setVisible(sel_idx==OperatorClassElement::OperatorElem); + operator_sel->setVisible(sel_idx==OperatorClassElement::OperatorElem); + elem_family_lbl->setVisible(sel_idx==OperatorClassElement::OperatorElem); + elem_family_sel->setVisible(sel_idx==OperatorClassElement::OperatorElem); - storage_type->setVisible(sel_idx==OperatorClassElement::STORAGE_ELEM); - stg_num_lbl->setVisible(sel_idx!=OperatorClassElement::STORAGE_ELEM); - stg_num_sb->setVisible(sel_idx!=OperatorClassElement::STORAGE_ELEM); + storage_type->setVisible(sel_idx==OperatorClassElement::StorageElem); + stg_num_lbl->setVisible(sel_idx!=OperatorClassElement::StorageElem); + stg_num_sb->setVisible(sel_idx!=OperatorClassElement::StorageElem); } void OperatorClassWidget::editElement(int lin_idx) @@ -137,12 +137,12 @@ void OperatorClassWidget::showElementData(OperatorClassElement elem, int lin_idx elem_type=elem.getElementType(); - if(elem_type==OperatorClassElement::FUNCTION_ELEM) + if(elem_type==OperatorClassElement::FunctionElem) { elements_tab->setCellText(elem.getFunction()->getSignature(), lin_idx, 0); elements_tab->setCellText(elem.getFunction()->getTypeName(), lin_idx, 1); } - else if(elem_type==OperatorClassElement::OPERATOR_ELEM) + else if(elem_type==OperatorClassElement::OperatorElem) { elements_tab->setCellText(elem.getOperator()->getSignature(), lin_idx, 0); elements_tab->setCellText(elem.getOperator()->getTypeName(), lin_idx, 1); @@ -150,15 +150,15 @@ void OperatorClassWidget::showElementData(OperatorClassElement elem, int lin_idx else { elements_tab->setCellText(*elem.getStorage(), lin_idx, 0); - elements_tab->setCellText(BaseObject::getTypeName(OBJ_TYPE), lin_idx, 1); + elements_tab->setCellText(BaseObject::getTypeName(ObjectType::Type), lin_idx, 1); } - if(elem_type!=OperatorClassElement::STORAGE_ELEM) + if(elem_type!=OperatorClassElement::StorageElem) elements_tab->setCellText(QString("%1").arg(elem.getStrategyNumber()), lin_idx, 2); else elements_tab->setCellText(QString(" "), lin_idx, 2); - if(elem_type==OperatorClassElement::OPERATOR_ELEM && elem.getOperatorFamily()) + if(elem_type==OperatorClassElement::OperatorElem && elem.getOperatorFamily()) elements_tab->setCellText(elem.getOperatorFamily()->getName(true), lin_idx, 3); else elements_tab->clearCellText(lin_idx, 3); @@ -176,9 +176,9 @@ void OperatorClassWidget::handleElement(int lin_idx) try { - if(elem_type==OperatorClassElement::FUNCTION_ELEM) + if(elem_type==OperatorClassElement::FunctionElem) elem.setFunction(dynamic_cast(function_sel->getSelectedObject()), stg_num_sb->value()); - else if(elem_type==OperatorClassElement::OPERATOR_ELEM) + else if(elem_type==OperatorClassElement::OperatorElem) { elem.setOperator(dynamic_cast(operator_sel->getSelectedObject()), stg_num_sb->value()); elem.setOperatorFamily(dynamic_cast(elem_family_sel->getSelectedObject())); @@ -199,13 +199,13 @@ void OperatorClassWidget::handleElement(int lin_idx) if(elements_tab->getCellText(lin_idx, 0).isEmpty()) elements_tab->removeRow(lin_idx); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void OperatorClassWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, OperatorClass *op_class) { - PgSQLType type; + PgSqlType type; unsigned i, count; BaseObjectWidget::setAttributes(model, op_list, op_class, schema); @@ -264,7 +264,7 @@ void OperatorClassWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/operatorclasswidget.h b/libpgmodeler_ui/src/operatorclasswidget.h index 6314db2e3d..03ac0f708b 100644 --- a/libpgmodeler_ui/src/operatorclasswidget.h +++ b/libpgmodeler_ui/src/operatorclasswidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -52,7 +52,7 @@ class OperatorClassWidget: public BaseObjectWidget, public Ui::OperatorClassWidg ObjectsTableWidget *elements_tab; public: - OperatorClassWidget(QWidget * parent = 0); + OperatorClassWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, OperatorClass *op_class); private slots: diff --git a/libpgmodeler_ui/src/operatorfamilywidget.cpp b/libpgmodeler_ui/src/operatorfamilywidget.cpp index 5276008693..5ee0d4ff21 100644 --- a/libpgmodeler_ui/src/operatorfamilywidget.cpp +++ b/libpgmodeler_ui/src/operatorfamilywidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "operatorfamilywidget.h" -OperatorFamilyWidget::OperatorFamilyWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_OPFAMILY) +OperatorFamilyWidget::OperatorFamilyWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::OpFamily) { QStringList types; map > fields_map; @@ -26,14 +26,14 @@ OperatorFamilyWidget::OperatorFamilyWidget(QWidget *parent): BaseObjectWidget(pa QFrame *frame=nullptr; Ui_OperatorFamilyWidget::setupUi(this); - configureFormLayout(opfamily_grid, OBJ_OPFAMILY); + configureFormLayout(opfamily_grid, ObjectType::OpFamily); IndexingType::getTypes(types); indexing_cmb->addItems(types); setRequiredField(indexing_lbl); - fields_map[BaseObjectWidget::generateVersionsInterval(BaseObjectWidget::AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_95)].push_back(indexing_lbl); - values_map[indexing_lbl].push_back(~IndexingType(IndexingType::brin)); + fields_map[BaseObjectWidget::generateVersionsInterval(BaseObjectWidget::AfterVersion, PgSqlVersions::PgSqlVersion95)].push_back(indexing_lbl); + values_map[indexing_lbl].push_back(~IndexingType(IndexingType::Brin)); opfamily_grid->addItem(new QSpacerItem(10,10,QSizePolicy::Minimum,QSizePolicy::Expanding), opfamily_grid->count()+1, 0, 1, 0); @@ -69,7 +69,7 @@ void OperatorFamilyWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/operatorfamilywidget.h b/libpgmodeler_ui/src/operatorfamilywidget.h index f435da9651..48434bc79d 100644 --- a/libpgmodeler_ui/src/operatorfamilywidget.h +++ b/libpgmodeler_ui/src/operatorfamilywidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -33,7 +33,7 @@ class OperatorFamilyWidget: public BaseObjectWidget, public Ui::OperatorFamilyWi Q_OBJECT public: - OperatorFamilyWidget(QWidget * parent = 0); + OperatorFamilyWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, OperatorFamily *op_family); public slots: diff --git a/libpgmodeler_ui/src/operatorwidget.cpp b/libpgmodeler_ui/src/operatorwidget.cpp index c0c8fbb21f..2f21f23107 100644 --- a/libpgmodeler_ui/src/operatorwidget.cpp +++ b/libpgmodeler_ui/src/operatorwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "operatorwidget.h" -OperatorWidget::OperatorWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_OPERATOR) +OperatorWidget::OperatorWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Operator) { try { @@ -47,24 +47,24 @@ OperatorWidget::OperatorWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_OP grid=dynamic_cast(attributes_twg->widget(1)->layout()); - for(i=Operator::FUNC_OPERATOR; i <= Operator::FUNC_RESTRICT; i++) + for(i=Operator::FuncOperator; i <= Operator::FuncRestrict; i++) { functions_sel[i]=nullptr; - functions_sel[i]=new ObjectSelectorWidget(OBJ_FUNCTION, true, this); + functions_sel[i]=new ObjectSelectorWidget(ObjectType::Function, true, this); - if(i!=Operator::FUNC_OPERATOR) + if(i!=Operator::FuncOperator) grid->addWidget(functions_sel[i],i,1,1,1); } - for(i=Operator::OPER_COMMUTATOR, i1=3; i <= Operator::OPER_NEGATOR; i++,i1++) + for(i=Operator::OperCommutator, i1=3; i <= Operator::OperNegator; i++,i1++) { operators_sel[i]=nullptr; - operators_sel[i]=new ObjectSelectorWidget(OBJ_OPERATOR, true, this); + operators_sel[i]=new ObjectSelectorWidget(ObjectType::Operator, true, this); grid->addWidget(operators_sel[i],i1,1,1,1); } operator_grid->addWidget(functions_sel[0],0,1,1,3); - configureFormLayout(operator_grid, OBJ_OPERATOR); + configureFormLayout(operator_grid, ObjectType::Operator); setRequiredField(operator_func_lbl); setRequiredField(functions_sel[0]); @@ -74,21 +74,21 @@ OperatorWidget::OperatorWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_OP } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void OperatorWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, Operator *oper) { unsigned i; - PgSQLType left_type, right_type; + PgSqlType left_type, right_type; BaseObjectWidget::setAttributes(model,op_list, oper, schema); - for(i=Operator::FUNC_OPERATOR; i <= Operator::FUNC_RESTRICT; i++) + for(i=Operator::FuncOperator; i <= Operator::FuncRestrict; i++) functions_sel[i]->setModel(model); - for(i=Operator::OPER_COMMUTATOR; i <= Operator::OPER_NEGATOR; i++) + for(i=Operator::OperCommutator; i <= Operator::OperNegator; i++) operators_sel[i]->setModel(model); if(oper) @@ -96,14 +96,14 @@ void OperatorWidget::setAttributes(DatabaseModel *model, OperationList *op_list, hashes_chk->setChecked(oper->isHashes()); merges_chk->setChecked(oper->isMerges()); - for(i=Operator::FUNC_OPERATOR; i <= Operator::FUNC_RESTRICT; i++) + for(i=Operator::FuncOperator; i <= Operator::FuncRestrict; i++) functions_sel[i]->setSelectedObject(oper->getFunction(i)); - for(i=Operator::OPER_COMMUTATOR; i <= Operator::OPER_NEGATOR; i++) + for(i=Operator::OperCommutator; i <= Operator::OperNegator; i++) operators_sel[i]->setSelectedObject(oper->getOperator(i)); - left_type=oper->getArgumentType(Operator::LEFT_ARG); - right_type=oper->getArgumentType(Operator::RIGHT_ARG); + left_type=oper->getArgumentType(Operator::LeftArg); + right_type=oper->getArgumentType(Operator::RightArg); } arg_types[0]->setAttributes(left_type, model); @@ -125,13 +125,13 @@ void OperatorWidget::applyConfiguration(void) oper->setHashes(hashes_chk->isChecked()); oper->setMerges(merges_chk->isChecked()); - for(i=Operator::LEFT_ARG; i <= Operator::RIGHT_ARG; i++) + for(i=Operator::LeftArg; i <= Operator::RightArg; i++) oper->setArgumentType(arg_types[i]->getPgSQLType(), i); - for(i=Operator::FUNC_OPERATOR; i <= Operator::FUNC_RESTRICT; i++) + for(i=Operator::FuncOperator; i <= Operator::FuncRestrict; i++) oper->setFunction(dynamic_cast(functions_sel[i]->getSelectedObject()), i); - for(i=Operator::OPER_COMMUTATOR; i <= Operator::OPER_NEGATOR; i++) + for(i=Operator::OperCommutator; i <= Operator::OperNegator; i++) oper->setOperator(dynamic_cast(operators_sel[i]->getSelectedObject()), i); finishConfiguration(); @@ -139,7 +139,7 @@ void OperatorWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/operatorwidget.h b/libpgmodeler_ui/src/operatorwidget.h index 706a071e85..f31cb4ce80 100644 --- a/libpgmodeler_ui/src/operatorwidget.h +++ b/libpgmodeler_ui/src/operatorwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -39,7 +39,7 @@ class OperatorWidget: public BaseObjectWidget, public Ui::OperatorWidget { *operators_sel[2]; public: - OperatorWidget(QWidget * parent = 0); + OperatorWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, Operator *oper); diff --git a/libpgmodeler_ui/src/parameterwidget.cpp b/libpgmodeler_ui/src/parameterwidget.cpp index 6da42e3405..9b7e7d7827 100644 --- a/libpgmodeler_ui/src/parameterwidget.cpp +++ b/libpgmodeler_ui/src/parameterwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "parameterwidget.h" -ParameterWidget::ParameterWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_PARAMETER) +ParameterWidget::ParameterWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Parameter) { try { @@ -41,7 +41,7 @@ ParameterWidget::ParameterWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_ parameter_grid->addWidget(data_type,2, 0, 1, 4); parameter_grid->addItem(spacer, parameter_grid->count()+1,0); - configureFormLayout(parameter_grid, OBJ_PARAMETER); + configureFormLayout(parameter_grid, ObjectType::Parameter); connect(param_variadic_chk, SIGNAL(toggled(bool)), param_in_chk, SLOT(setDisabled(bool))); connect(param_variadic_chk, SIGNAL(toggled(bool)), param_out_chk, SLOT(setDisabled(bool))); connect(param_in_chk, SIGNAL(toggled(bool)), this, SLOT(enableVariadic(void))); @@ -51,7 +51,7 @@ ParameterWidget::ParameterWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_ } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -90,7 +90,7 @@ void ParameterWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/parameterwidget.h b/libpgmodeler_ui/src/parameterwidget.h index 24ff1037e7..cb07bfd0e6 100644 --- a/libpgmodeler_ui/src/parameterwidget.h +++ b/libpgmodeler_ui/src/parameterwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -37,7 +37,7 @@ class ParameterWidget: public BaseObjectWidget, public Ui::ParameterWidget { Parameter parameter; public: - ParameterWidget(QWidget * parent = 0); + ParameterWidget(QWidget * parent = nullptr); void setAttributes(Parameter parameter, DatabaseModel *model); Parameter getParameter(void); diff --git a/libpgmodeler_ui/src/permissionwidget.cpp b/libpgmodeler_ui/src/permissionwidget.cpp index 818b9666d2..0c539cad5b 100644 --- a/libpgmodeler_ui/src/permissionwidget.cpp +++ b/libpgmodeler_ui/src/permissionwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,62 +18,58 @@ #include "permissionwidget.h" -PermissionWidget::PermissionWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_PERMISSION) +PermissionWidget::PermissionWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Permission) { QGridLayout *grid=nullptr; QFrame *frame=nullptr; QCheckBox *check=nullptr; unsigned i; - QString privs[]={ ParsersAttributes::SELECT_PRIV, ParsersAttributes::INSERT_PRIV, - ParsersAttributes::UPDATE_PRIV, ParsersAttributes::DELETE_PRIV, - ParsersAttributes::TRUNCATE_PRIV, ParsersAttributes::REFERENCES_PRIV, - ParsersAttributes::TRIGGER_PRIV, ParsersAttributes::CREATE_PRIV, - ParsersAttributes::CONNECT_PRIV, ParsersAttributes::TEMPORARY_PRIV, - ParsersAttributes::EXECUTE_PRIV, ParsersAttributes::USAGE_PRIV }; + QString privs[]={ Attributes::SelectPriv, Attributes::InsertPriv, + Attributes::UpdatePriv, Attributes::DeletePriv, + Attributes::TruncatePriv, Attributes::ReferencesPriv, + Attributes::TriggerPriv, Attributes::CreatePriv, + Attributes::ConnectPriv, Attributes::TemporaryPriv, + Attributes::ExecutPriv, Attributes::UsagePriv }; Ui_PermissionWidget::setupUi(this); code_hl=new SyntaxHighlighter(code_txt); - code_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + code_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); object_selection_wgt=new ModelObjectsWidget(true); permission=nullptr; - configureFormLayout(permission_grid, OBJ_PERMISSION); + configureFormLayout(permission_grid, ObjectType::Permission); - name_edt->setReadOnly(true); - comment_edt->setVisible(false); - comment_lbl->setVisible(false); - - roles_tab=new ObjectsTableWidget(ObjectsTableWidget::ADD_BUTTON | - ObjectsTableWidget::REMOVE_BUTTON | - ObjectsTableWidget::EDIT_BUTTON, false, this); + roles_tab=new ObjectsTableWidget(ObjectsTableWidget::AddButton | + ObjectsTableWidget::RemoveButton | + ObjectsTableWidget::EditButton, false, this); roles_tab->setColumnCount(1); roles_tab->setHeaderLabel(trUtf8("Name"),0); - roles_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("uid")),0); + roles_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")),0); grid=new QGridLayout; grid->addWidget(roles_tab,0,0,1,1); grid->setContentsMargins(2,2,2,2); roles_gb->setLayout(grid); - permissions_tab=new ObjectsTableWidget(ObjectsTableWidget::REMOVE_BUTTON | - ObjectsTableWidget::EDIT_BUTTON | - ObjectsTableWidget::REMOVE_ALL_BUTTON, true, this); + permissions_tab=new ObjectsTableWidget(ObjectsTableWidget::RemoveButton | + ObjectsTableWidget::EditButton | + ObjectsTableWidget::RemoveAllButton, true, this); permissions_tab->setColumnCount(3); permissions_tab->setHeaderLabel(trUtf8("Id"),0); - permissions_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("uid")),0); + permissions_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")),0); permissions_tab->setHeaderLabel(trUtf8("Roles"),1); - permissions_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("role")),1); + permissions_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("role")),1); permissions_tab->setHeaderLabel(trUtf8("Privileges"),2); - permissions_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("grant")),2); + permissions_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("grant")),2); grid=new QGridLayout; grid->addWidget(permissions_tab,0,0,1,1); grid->setContentsMargins(2,2,2,2); permissions_gb->setLayout(grid); - for(i=Permission::PRIV_SELECT; i<=Permission::PRIV_USAGE; i++) + for(i=Permission::PrivSelect; i<=Permission::PrivUsage; i++) { check=new QCheckBox; check->setText(privs[i].toUpper()); @@ -89,7 +85,7 @@ PermissionWidget::PermissionWidget(QWidget *parent): BaseObjectWidget(parent, OB } frame=generateInformationFrame(trUtf8("Leave the Roles grid empty in order to create a %1 applicable to PUBLIC.") - .arg(BaseObject::getTypeName(OBJ_PERMISSION).toLower())); + .arg(BaseObject::getTypeName(ObjectType::Permission).toLower())); permission_grid->addWidget(frame, permission_grid->count()+1, 0, 1, 0); frame->setParent(this); @@ -140,7 +136,7 @@ void PermissionWidget::setAttributes(DatabaseModel *model, BaseObject *parent_ob name_edt->setText(QString("%1 (%2)").arg(object->getSignature()).arg(object->getTypeName())); - for(priv=Permission::PRIV_SELECT; priv<=Permission::PRIV_USAGE; priv++) + for(priv=Permission::PrivSelect; priv<=Permission::PrivUsage; priv++) { //Gets the checkboxes that represents the privilege and the GRANT OPTION chk=dynamic_cast(privileges_tbw->cellWidget(priv,0)); @@ -150,7 +146,7 @@ void PermissionWidget::setAttributes(DatabaseModel *model, BaseObject *parent_ob chk1->setChecked(false); //Enabling the checkboxes using a validation of privilege type against the curret object type. - privileges_tbw->setRowHidden(priv, !Permission::objectAcceptsPermission(object->getObjectType(), priv)); + privileges_tbw->setRowHidden(priv, !Permission::acceptsPermission(object->getObjectType(), priv)); } listPermissions(); @@ -163,7 +159,7 @@ void PermissionWidget::setAttributes(DatabaseModel *model, BaseObject *parent_ob void PermissionWidget::selectRole(void) { - object_selection_wgt->setObjectVisible(OBJ_ROLE, true); + object_selection_wgt->setObjectVisible(ObjectType::Role, true); object_selection_wgt->setModel(this->model); object_selection_wgt->show(); } @@ -180,7 +176,7 @@ void PermissionWidget::disableGrantOptions(void) { QCheckBox *check=nullptr; - for(unsigned i=Permission::PRIV_SELECT; i<=Permission::PRIV_USAGE; i++) + for(unsigned i=Permission::PrivSelect; i<=Permission::PrivUsage; i++) { check=dynamic_cast(privileges_tbw->cellWidget(i,1)); check->setEnabled(roles_tab->getRowCount() > 0); @@ -262,11 +258,11 @@ void PermissionWidget::showSelectedRoleData(void) //Raise an error if the role already exists on selected role table if(role && row_idx >= 0) { - throw Exception(Exception::getErrorMessage(ERR_ASG_DUPL_OBJ_CONTAINER) - .arg(role->getName()) - .arg(role->getTypeName()) - .arg(roles_gb->title()), - ERR_INS_DUPLIC_ROLE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::AsgDuplicatedObjectContainer) + .arg(role->getName()) + .arg(role->getTypeName()) + .arg(roles_gb->title()), + ErrorCode::InsDuplicatedRole,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } } @@ -294,7 +290,7 @@ void PermissionWidget::addPermission(void) } cancelOperation(); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -317,7 +313,7 @@ void PermissionWidget::updatePermission(void) //Checking if the permission already exists on model perm_idx=model->getPermissionIndex(perm, false); - if(perm_idx < 0 || (perm_idx >=0 && model->getObject(perm_idx,OBJ_PERMISSION)==permission)) + if(perm_idx < 0 || (perm_idx >=0 && model->getObject(perm_idx,ObjectType::Permission)==permission)) { (*permission)=(*perm); listPermissions(); @@ -326,10 +322,10 @@ void PermissionWidget::updatePermission(void) else { //Raises an error if the configured permission already exists - throw Exception(Exception::getErrorMessage(ERR_ASG_DUPLIC_PERMISSION) + throw Exception(Exception::getErrorMessage(ErrorCode::AsgDuplicatedPermission) .arg(permission->getObject()->getName()) .arg(permission->getObject()->getTypeName()), - ERR_ASG_DUPLIC_PERMISSION,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::AsgDuplicatedPermission,__PRETTY_FUNCTION__,__FILE__,__LINE__); } delete(perm_bkp); @@ -344,7 +340,7 @@ void PermissionWidget::updatePermission(void) delete(perm_bkp); cancelOperation(); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -375,7 +371,7 @@ void PermissionWidget::editPermission(void) roles_tab->blockSignals(false); - for(priv=Permission::PRIV_SELECT; priv<=Permission::PRIV_USAGE; priv++) + for(priv=Permission::PrivSelect; priv<=Permission::PrivUsage; priv++) { chk=dynamic_cast(privileges_tbw->cellWidget(priv,0)); chk1=dynamic_cast(privileges_tbw->cellWidget(priv,1)); @@ -423,7 +419,7 @@ void PermissionWidget::configurePermission(Permission *perm) for(i=0; i < count; i++) perm->addRole(reinterpret_cast(roles_tab->getRowData(i).value())); - for(priv=Permission::PRIV_SELECT; priv <= Permission::PRIV_USAGE; priv++) + for(priv=Permission::PrivSelect; priv <= Permission::PrivUsage; priv++) { if(!privileges_tbw->isRowHidden(priv)) { @@ -442,7 +438,7 @@ void PermissionWidget::cancelOperation(void) permission=nullptr; - for(priv=Permission::PRIV_SELECT; priv<=Permission::PRIV_USAGE; priv++) + for(priv=Permission::PrivSelect; priv<=Permission::PrivUsage; priv++) { chk=dynamic_cast(privileges_tbw->cellWidget(priv,0)); chk->setChecked(false); @@ -469,7 +465,7 @@ void PermissionWidget::checkPrivilege(void) chk=dynamic_cast(obj_sender); - for(priv=Permission::PRIV_SELECT; priv<=Permission::PRIV_USAGE; priv++) + for(priv=Permission::PrivSelect; priv<=Permission::PrivUsage; priv++) { chk_priv=dynamic_cast(privileges_tbw->cellWidget(priv,0)); chk_gop=dynamic_cast(privileges_tbw->cellWidget(priv,1)); @@ -496,7 +492,7 @@ void PermissionWidget::enableEditButtons(void) unsigned priv; QCheckBox *chk=nullptr, *chk1=nullptr; - for(priv=Permission::PRIV_SELECT; priv<=Permission::PRIV_USAGE && !checked_privs; priv++) + for(priv=Permission::PrivSelect; priv<=Permission::PrivUsage && !checked_privs; priv++) { chk=dynamic_cast(privileges_tbw->cellWidget(priv,0)); chk1=dynamic_cast(privileges_tbw->cellWidget(priv,1)); @@ -520,7 +516,7 @@ void PermissionWidget::updateCodePreview(void) cnt=perms.size(); for(i=0; i < cnt; i++) - code+=perms[i]->getCodeDefinition(SchemaParser::SQL_DEFINITION); + code+=perms[i]->getCodeDefinition(SchemaParser::SqlDefinition); if(code.isEmpty()) code=trUtf8("-- No permissions defined for the specified object!"); diff --git a/libpgmodeler_ui/src/permissionwidget.h b/libpgmodeler_ui/src/permissionwidget.h index deea3720c4..034da53bff 100644 --- a/libpgmodeler_ui/src/permissionwidget.h +++ b/libpgmodeler_ui/src/permissionwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -53,7 +53,7 @@ class PermissionWidget: public BaseObjectWidget, public Ui::PermissionWidget { bool perms_changed; public: - PermissionWidget(QWidget * parent = 0); + PermissionWidget(QWidget * parent = nullptr); ~PermissionWidget(void); void setAttributes(DatabaseModel *model, BaseObject *objeto_pai, BaseObject *object); diff --git a/libpgmodeler_ui/src/pgmodelerplugin.cpp b/libpgmodeler_ui/src/pgmodelerplugin.cpp index 8bc3eefadf..8fc0b096b8 100644 --- a/libpgmodeler_ui/src/pgmodelerplugin.cpp +++ b/libpgmodeler_ui/src/pgmodelerplugin.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -25,6 +25,7 @@ PgModelerPlugin::PgModelerPlugin(void) QFont font; QWidget *widget=nullptr; + main_window = nullptr; plugin_info_frm=new BaseForm; gridLayout=new QGridLayout; @@ -90,3 +91,8 @@ void PgModelerPlugin::configurePluginInfo(const QString &title, const QString &v ico.load(ico_filename); icon_lbl->setPixmap(ico); } + +void PgModelerPlugin::setMainWindow(QMainWindow *main_window) +{ + this->main_window = main_window; +} diff --git a/libpgmodeler_ui/src/pgmodelerplugin.h b/libpgmodeler_ui/src/pgmodelerplugin.h index 0467cc71f7..eb7e3ae2fd 100644 --- a/libpgmodeler_ui/src/pgmodelerplugin.h +++ b/libpgmodeler_ui/src/pgmodelerplugin.h @@ -1,7 +1,7 @@ /* # Projeto: Modelador de Banco de Dados PostgreSQL (pgsqlDBM) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -51,6 +51,8 @@ class PgModelerPlugin { protected: BaseForm *plugin_info_frm; + QMainWindow *main_window; + private: QLabel *icon_lbl, *title_lbl, @@ -86,7 +88,11 @@ class PgModelerPlugin { //! \brief Sets the plugin's all attributes at once. void configurePluginInfo(const QString &title, const QString &version, const QString &author, - const QString &description, const QString &ico_filename); + const QString &description, const QString &ico_filename); + + /*! \brief Sets the main window of the application so it can perform advanced operations like + * add custom widget, access the models, and much more */ + virtual void setMainWindow(QMainWindow *main_window); }; /* Declares the class PgModelerPlugin as interface, this means that the class is a base diff --git a/libpgmodeler_ui/src/pgmodeleruins.cpp b/libpgmodeler_ui/src/pgmodeleruins.cpp index e5447f1f06..1c206f9cc4 100644 --- a/libpgmodeler_ui/src/pgmodeleruins.cpp +++ b/libpgmodeler_ui/src/pgmodeleruins.cpp @@ -2,11 +2,14 @@ #include "messagebox.h" #include "databasemodel.h" #include +#include #include "numberedtexteditor.h" #include #include +#include "baseform.h" +#include "bulkdataeditwidget.h" -namespace PgModelerUiNS { +namespace PgModelerUiNs { NumberedTextEditor *createNumberedTextEditor(QWidget *parent, bool handle_ext_files) { @@ -25,7 +28,7 @@ namespace PgModelerUiNS { QTreeWidgetItem *createOutputTreeItem(QTreeWidget *output_trw, const QString &text, const QPixmap &ico, QTreeWidgetItem *parent, bool expand_item, bool word_wrap) { if(!output_trw) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); QTreeWidgetItem *item=nullptr; @@ -40,12 +43,16 @@ namespace PgModelerUiNS { else { QLabel *label=new QLabel; + label->setUpdatesEnabled(false); label->setTextFormat(Qt::AutoText); label->setText(text); label->setWordWrap(true); label->setTextInteractionFlags(Qt::TextSelectableByMouse); + label->setUpdatesEnabled(true); label->setMinimumHeight(output_trw->iconSize().height() * 1.5); label->setMaximumHeight(label->heightForWidth(label->width())); + + item->setSizeHint(0, QSize(label->width(), label->minimumHeight())); output_trw->setItemWidget(item, 0, label); } @@ -60,9 +67,10 @@ namespace PgModelerUiNS { void createOutputListItem(QListWidget *output_lst, const QString &text, const QPixmap &ico, bool is_formated) { if(!output_lst) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); QListWidgetItem *item=new QListWidgetItem; + item->setIcon(ico); output_lst->addItem(item); @@ -70,51 +78,72 @@ namespace PgModelerUiNS { item->setText(text); else { - QLabel *label=new QLabel(text); + QLabel *label=new QLabel; + int txt_height = 0; + + txt_height = output_lst->fontMetrics().height() * text.count(QString("
")); + + if(txt_height == 0) + txt_height = output_lst->fontMetrics().height() * 1.25; + else + txt_height *= 1.05; + + label->setUpdatesEnabled(false); + label->setTextFormat(Qt::AutoText); + label->setText(text); + label->setWordWrap(true); + label->setTextInteractionFlags(Qt::TextSelectableByMouse); + label->setUpdatesEnabled(true); + + item->setSizeHint(QSize(output_lst->width(), txt_height)); output_lst->setItemWidget(item, label); } } void disableObjectSQL(BaseObject *object, bool disable) { - if(object && object->getObjectType()!=BASE_RELATIONSHIP) + if(object && object->getObjectType()!=ObjectType::BaseRelationship) { Messagebox msgbox; ObjectType obj_type=object->getObjectType(); bool curr_val=object->isSQLDisabled(); + TableObject *tab_obj = dynamic_cast(object); if(object->isSystemObject()) - throw Exception(Exception::getErrorMessage(ERR_OPR_RESERVED_OBJECT) + throw Exception(Exception::getErrorMessage(ErrorCode::OprReservedObject) .arg(object->getName(true)) .arg(object->getTypeName()), - ERR_OPR_RESERVED_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::OprReservedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); object->setSQLDisabled(disable); - if(obj_type!=OBJ_DATABASE && curr_val!=disable) + if(tab_obj && tab_obj->getParentTable()) + tab_obj->getParentTable()->setModified(true); + + if(obj_type!=ObjectType::Database && curr_val!=disable) { msgbox.show(QString(QT_TR_NOOP("Do you want to apply the SQL %1 status to the object's references too? This will avoid problems when exporting or validating the model.")).arg(disable ? QT_TR_NOOP("disabling") : QT_TR_NOOP("enabling")), - Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); if(msgbox.result()==QDialog::Accepted) disableReferencesSQL(object); } /* Special case for tables. When disable the code there is the need to disable constraints - codes when the code of parent table is disabled too in order to avoid export errors */ - if(object->getObjectType()==OBJ_TABLE) + * codes when the code of parent table is disabled too in order to avoid export errors */ + if(object->getObjectType()==ObjectType::Table) { Constraint *constr = nullptr; - vector *objects=dynamic_cast
(object)->getObjectList(OBJ_CONSTRAINT); + vector *objects=dynamic_cast
(object)->getObjectList(ObjectType::Constraint); for(auto &obj : (*objects)) { constr=dynamic_cast(obj); /* If the constraint is not FK but is declared outside table via alter (ALTER TABLE...ADD CONSTRAINT...) or - The constraint is FK and the reference table is disabled the FK will not be enabled */ - if((constr->getConstraintType()!=ConstraintType::foreign_key && !constr->isDeclaredInTable()) || - (constr->getConstraintType()==ConstraintType::foreign_key && + * The constraint is FK and the reference table is disabled the FK will not be enabled */ + if((constr->getConstraintType()!=ConstraintType::ForeignKey && !constr->isDeclaredInTable()) || + (constr->getConstraintType()==ConstraintType::ForeignKey && (disable || (!disable && !constr->getReferencedTable()->isSQLDisabled())))) constr->setSQLDisabled(disable); } @@ -137,7 +166,7 @@ namespace PgModelerUiNS { tab_obj=dynamic_cast(refs.back()); //If the object is a relationship added does not do anything since the relationship itself will be disabled - if(refs.back()->getObjectType()!=BASE_RELATIONSHIP && + if(refs.back()->getObjectType()!=ObjectType::BaseRelationship && (!tab_obj || (tab_obj && !tab_obj->isAddedByRelationship()))) { refs.back()->setSQLDisabled(object->isSQLDisabled()); @@ -194,29 +223,29 @@ namespace PgModelerUiNS { void configureWidgetFont(QWidget *widget, unsigned factor_id) { - float factor = 1; + double factor = 1; switch(factor_id) { - case SMALL_FONT_FACTOR: - factor=0.85f; + case SmallFontFactor: + factor=0.80; break; - case MEDIUM_FONT_FACTOR: - factor=0.90f; + case MediumFontFactor: + factor=0.90; break; - case BIG_FONT_FACTOR: - factor=1.10f; + case BigFontFactor: + factor=1.10; break; - case HUGE_FONT_FACTOR: + case HugeFontFactor: default: - factor=1.40f; + factor=1.40; break; } - configureWidgetFont(widget, factor); + __configureWidgetFont(widget, factor); } - void configureWidgetFont(QWidget *widget, float factor) + void __configureWidgetFont(QWidget *widget, double factor) { if(!widget) return; @@ -246,7 +275,7 @@ namespace PgModelerUiNS { text=QString("%1 (%2)").arg(ex.getFile()).arg(ex.getLine()); createOutputTreeItem(exceptions_trw, text, QPixmap(getIconPath("codigofonte")), item, false, true); - text=QString("%1 (%2)").arg(Exception::getErrorCode(ex.getErrorType())).arg(ex.getErrorType()); + text=QString("%1 (%2)").arg(Exception::getErrorCode(ex.getErrorCode())).arg(enum_cast(ex.getErrorCode())); createOutputTreeItem(exceptions_trw, text, QPixmap(getIconPath("msgbox_alerta")), item, false, true); child_item=createOutputTreeItem(exceptions_trw, ex.getErrorMessage(), QPixmap(getIconPath("msgbox_erro")), item, false, true); @@ -278,12 +307,14 @@ namespace PgModelerUiNS { int max_h = 0, curr_w =0, curr_h = 0, screen_id = qApp->desktop()->screenNumber(qApp->activeWindow()); QScreen *screen=qApp->screens().at(screen_id); - float dpi_factor = 0; + double dpi_factor = 0; + double pixel_ratio = 0; - dpi_factor = screen->logicalDotsPerInch() / 96.0f; + dpi_factor = screen->logicalDotsPerInch() / 96.0; + pixel_ratio = screen->devicePixelRatio(); //If the dpi_factor is unchanged (1) we keep the dialog original dimension - if(dpi_factor <= 1.01f) + if(dpi_factor <= 1.01) return; max_h = screen->size().height() * 0.70; @@ -307,8 +338,8 @@ namespace PgModelerUiNS { else if(min_size.height() >= max_h) curr_h = max_h; - curr_w *= dpi_factor; - curr_h *= dpi_factor; + curr_w *= dpi_factor * pixel_ratio; + curr_h *= dpi_factor * pixel_ratio; if(curr_w > screen->size().width()) curr_w = screen->size().width() * 0.80; @@ -318,5 +349,46 @@ namespace PgModelerUiNS { widget->setMinimumSize(widget->minimumSize()); widget->resize(curr_w, curr_h); + widget->adjustSize(); + } + + void bulkDataEdit(QTableWidget *results_tbw) + { + if(!results_tbw) + return; + + BaseForm base_frm; + BulkDataEditWidget *bulkedit_wgt = new BulkDataEditWidget; + + base_frm.setMainWidget(bulkedit_wgt); + base_frm.setButtonConfiguration(Messagebox::OkCancelButtons); + + if(base_frm.exec() == QDialog::Accepted) + { + QList sel_ranges=results_tbw->selectedRanges(); + + for(auto range : sel_ranges) + { + for(int row = range.topRow(); row <= range.bottomRow(); row++) + { + for(int col = range.leftColumn(); col <= range.rightColumn(); col++) + { + results_tbw->item(row, col)->setText(bulkedit_wgt->value_edt->toPlainText()); + } + } + } + } + } + + void createDropShadow(QToolButton *btn, int x_offset, int y_offset, int radius) + { + QGraphicsDropShadowEffect *shadow=nullptr; + + shadow=new QGraphicsDropShadowEffect(btn); + shadow->setXOffset(x_offset); + shadow->setYOffset(y_offset); + shadow->setBlurRadius(radius); + shadow->setColor(QColor(0,0,0, 100)); + btn->setGraphicsEffect(shadow); } } diff --git a/libpgmodeler_ui/src/pgmodeleruins.h b/libpgmodeler_ui/src/pgmodeleruins.h index 523b738e0b..559ec0d854 100644 --- a/libpgmodeler_ui/src/pgmodeleruins.h +++ b/libpgmodeler_ui/src/pgmodeleruins.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -27,18 +27,19 @@ #include #include +#include #include #include "baseobject.h" #include "numberedtexteditor.h" -namespace PgModelerUiNS { - static const unsigned SMALL_FONT_FACTOR = 0, - MEDIUM_FONT_FACTOR = 1, - BIG_FONT_FACTOR = 2, - HUGE_FONT_FACTOR = 3; +namespace PgModelerUiNs { + static constexpr unsigned SmallFontFactor = 0, + MediumFontFactor = 1, + BigFontFactor = 2, + HugeFontFactor = 3; extern void configureWidgetFont(QWidget *widget, unsigned factor_id); - extern void configureWidgetFont(QWidget *widget, float factor); + extern void __configureWidgetFont(QWidget *widget, double factor); /*! \brief Creates a NumberedTextEditor instance automatically assigning it to 'parent'. This method will create a layout if 'parent' doesn't has one. If parent has a layout @@ -77,6 +78,12 @@ namespace PgModelerUiNS { //! \brief Resizes the provided dialog considering font dpi changes as well screen size extern void resizeDialog(QDialog *dialog); + + //! brief Changes the values of the grid selection at once + extern void bulkDataEdit(QTableWidget *results_tbw); + + //! \brief Creates drop shadown on a tool button that represents an QAction + extern void createDropShadow(QToolButton *btn, int x_offset = 2, int y_offset = 2, int radius = 5); } #endif diff --git a/libpgmodeler_ui/src/pgsqltypewidget.cpp b/libpgmodeler_ui/src/pgsqltypewidget.cpp index 6bd122972f..d92d981eb9 100644 --- a/libpgmodeler_ui/src/pgsqltypewidget.cpp +++ b/libpgmodeler_ui/src/pgsqltypewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "pgsqltypewidget.h" -const QString PgSQLTypeWidget::INVALID_TYPE = QString("invalid_type"); +const QString PgSQLTypeWidget::InvalidType = QString("invalid_type"); PgSQLTypeWidget::PgSQLTypeWidget(QWidget *parent, const QString &label) : QWidget(parent) { @@ -35,7 +35,7 @@ PgSQLTypeWidget::PgSQLTypeWidget(QWidget *parent, const QString &label) : QWidge format_hl=nullptr; format_hl=new SyntaxHighlighter(format_txt, true); - format_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + format_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); this->adjustSize(); IntervalType::getTypes(interval_lst); @@ -62,7 +62,7 @@ PgSQLTypeWidget::PgSQLTypeWidget(QWidget *parent, const QString &label) : QWidge } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -76,7 +76,7 @@ bool PgSQLTypeWidget::eventFilter(QObject *object, QEvent *event) } catch(Exception &) { - format_txt->setPlainText(INVALID_TYPE); + format_txt->setPlainText(InvalidType); } } @@ -121,11 +121,11 @@ void PgSQLTypeWidget::updateTypeFormat(void) spatial_tp=SpatialType(spatial_cmb->currentText(), srid_spb->value()); if(var_z_chk->isChecked() && var_m_chk->isChecked()) - spatial_tp.setVariation(SpatialType::var_zm); + spatial_tp.setVariation(SpatialType::VarZm); else if(var_m_chk->isChecked()) - spatial_tp.setVariation(SpatialType::var_m); + spatial_tp.setVariation(SpatialType::VarM); else if(var_z_chk->isChecked()) - spatial_tp.setVariation(SpatialType::var_z); + spatial_tp.setVariation(SpatialType::VarZ); type.setSpatialType(spatial_tp); } @@ -140,7 +140,7 @@ void PgSQLTypeWidget::updateTypeFormat(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -154,21 +154,21 @@ void PgSQLTypeWidget::listPgSQLTypes(QComboBox *combo, DatabaseModel *model, uns combo->clear(); //Getting the user defined type adding them into the combo - PgSQLType::getUserTypes(types,model, user_type_conf); + PgSqlType::getUserTypes(types,model, user_type_conf); types.sort(); count=types.size(); for(idx=0; idx < count; idx++) - combo->addItem(types[idx], QVariant(PgSQLType::getUserTypeIndex(types[idx],nullptr,model))); + combo->addItem(types[idx], QVariant(PgSqlType::getUserTypeIndex(types[idx],nullptr,model))); //Getting the built-in type adding them into the combo - PgSQLType::getTypes(types, oid_types, pseudo_types); + PgSqlType::getTypes(types, oid_types, pseudo_types); types.sort(); combo->addItems(types); } } -void PgSQLTypeWidget::setAttributes(PgSQLType type, DatabaseModel *model, unsigned usr_type_conf, bool oid_types, bool pseudo_types) +void PgSQLTypeWidget::setAttributes(PgSqlType type, DatabaseModel *model, unsigned usr_type_conf, bool oid_types, bool pseudo_types) { try { @@ -206,14 +206,14 @@ void PgSQLTypeWidget::setAttributes(PgSQLType type, DatabaseModel *model, unsig } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } -PgSQLType PgSQLTypeWidget::getPgSQLType(void) +PgSqlType PgSQLTypeWidget::getPgSQLType(void) { - if(format_txt->toPlainText() == INVALID_TYPE) - throw Exception(ERR_ASG_INV_TYPE_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(format_txt->toPlainText() == InvalidType) + throw Exception(ErrorCode::AsgInvalidTypeObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); return(type); } diff --git a/libpgmodeler_ui/src/pgsqltypewidget.h b/libpgmodeler_ui/src/pgsqltypewidget.h index f8933195d4..57ce845d5d 100644 --- a/libpgmodeler_ui/src/pgsqltypewidget.h +++ b/libpgmodeler_ui/src/pgsqltypewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -37,35 +37,35 @@ class PgSQLTypeWidget: public QWidget, public Ui::PgSQLTypeWidget { Q_OBJECT //! \brief Stores the PostgreSQL type configured on the form - PgSQLType type; + PgSqlType type; //! \brief Syntax highlighter used on the format field SyntaxHighlighter *format_hl; bool eventFilter(QObject *watched, QEvent *event); - static const QString INVALID_TYPE; + static const QString InvalidType; public: - PgSQLTypeWidget(QWidget * parent = 0, const QString &label=QString()); + PgSQLTypeWidget(QWidget * parent = nullptr, const QString &label=QString()); /*! \brief Lists the PostgreSQL types on the specified combo. The user can configure which types must be shown using the last tree parameters. The DatabaseModel parameter is used to gather the user-defined types of the specified model. */ static void listPgSQLTypes(QComboBox *combo, DatabaseModel *model, - unsigned user_type_conf=UserTypeConfig::ALL_USER_TYPES, + unsigned user_type_conf=UserTypeConfig::AllUserTypes, bool oid_types=true, bool pseudo_types=true); private slots: void updateTypeFormat(void); public slots: - void setAttributes(PgSQLType type, DatabaseModel *model, - unsigned usr_type_conf=UserTypeConfig::ALL_USER_TYPES, + void setAttributes(PgSqlType type, DatabaseModel *model, + unsigned usr_type_conf=UserTypeConfig::AllUserTypes, bool oid_types=true, bool pseudo_types=true); //! \brief Returns the PostgreSQL type configured via form - PgSQLType getPgSQLType(void); + PgSqlType getPgSQLType(void); }; #endif diff --git a/libpgmodeler_ui/src/plaintextitemdelegate.cpp b/libpgmodeler_ui/src/plaintextitemdelegate.cpp index 63376a8265..2d98f44c92 100644 --- a/libpgmodeler_ui/src/plaintextitemdelegate.cpp +++ b/libpgmodeler_ui/src/plaintextitemdelegate.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libpgmodeler_ui/src/plaintextitemdelegate.h b/libpgmodeler_ui/src/plaintextitemdelegate.h index ddb50f7a9a..fa23a5f98c 100644 --- a/libpgmodeler_ui/src/plaintextitemdelegate.h +++ b/libpgmodeler_ui/src/plaintextitemdelegate.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/libpgmodeler_ui/src/pluginsconfigwidget.cpp b/libpgmodeler_ui/src/pluginsconfigwidget.cpp index 1288a10a5e..2912e428ec 100644 --- a/libpgmodeler_ui/src/pluginsconfigwidget.cpp +++ b/libpgmodeler_ui/src/pluginsconfigwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -23,14 +23,14 @@ PluginsConfigWidget::PluginsConfigWidget(QWidget *parent) : BaseConfigWidget(par setupUi(this); QGridLayout *grid=new QGridLayout(loaded_plugins_gb); - QDir dir=QDir(GlobalAttributes::PLUGINS_DIR); + QDir dir=QDir(GlobalAttributes::PluginsDir); root_dir_edt->setText(dir.absolutePath()); - plugins_tab=new ObjectsTableWidget(ObjectsTableWidget::EDIT_BUTTON, false, this); + plugins_tab=new ObjectsTableWidget(ObjectsTableWidget::EditButton, false, this); plugins_tab->setColumnCount(3); plugins_tab->setHeaderLabel(trUtf8("Plugin"),0); - plugins_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("plugins")),0); + plugins_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("plugins")),0); plugins_tab->setHeaderLabel(trUtf8("Version"),1); plugins_tab->setHeaderLabel(trUtf8("Library"),2); @@ -65,8 +65,8 @@ void PluginsConfigWidget::loadConfiguration(void) { vector errors; QString lib, plugin_name, - dir_plugins=GlobalAttributes::PLUGINS_DIR + - GlobalAttributes::DIR_SEPARATOR; + dir_plugins=GlobalAttributes::PluginsDir + + GlobalAttributes::DirSeparator; QPluginLoader plugin_loader; QStringList dir_list; PgModelerPlugin *plugin=nullptr; @@ -90,16 +90,16 @@ void PluginsConfigWidget::loadConfiguration(void) [PLUGINS ROOT DIR]/[PLUGIN NAME]/lib[PLUGIN NAME].[EXTENSION] */ #ifdef Q_OS_WIN lib=dir_plugins + plugin_name + - GlobalAttributes::DIR_SEPARATOR + + GlobalAttributes::DirSeparator + plugin_name + QString(".dll"); #else #ifdef Q_OS_MAC lib=dir_plugins + plugin_name + - GlobalAttributes::DIR_SEPARATOR + + GlobalAttributes::DirSeparator + QString("lib") + plugin_name + QString(".dylib"); #else lib=dir_plugins + plugin_name + - GlobalAttributes::DIR_SEPARATOR + + GlobalAttributes::DirSeparator + QString("lib") + plugin_name + QString(".so"); #endif #endif @@ -121,7 +121,7 @@ void PluginsConfigWidget::loadConfiguration(void) plugin_action->setShortcut(plugin->getPluginShortcut()); icon.load(dir_plugins + plugin_name + - GlobalAttributes::DIR_SEPARATOR + + GlobalAttributes::DirSeparator + plugin_name + QString(".png")); plugin_action->setIcon(icon); @@ -133,25 +133,26 @@ void PluginsConfigWidget::loadConfiguration(void) } else { - errors.push_back(Exception(Exception::getErrorMessage(ERR_PLUGIN_NOT_LOADED) - .arg(dir_list.front()) - .arg(lib) - .arg(plugin_loader.errorString()), - ERR_PLUGIN_NOT_LOADED, __PRETTY_FUNCTION__,__FILE__,__LINE__)); + errors.push_back(Exception(Exception::getErrorMessage(ErrorCode::PluginNotLoaded) + .arg(dir_list.front()) + .arg(lib) + .arg(plugin_loader.errorString()), + ErrorCode::PluginNotLoaded, __PRETTY_FUNCTION__,__FILE__,__LINE__)); } dir_list.pop_front(); plugins_tab->clearSelection(); } if(!errors.empty()) - throw Exception(ERR_PLUGINS_NOT_LOADED,__PRETTY_FUNCTION__,__FILE__,__LINE__, errors); + throw Exception(ErrorCode::PluginsNotLoaded,__PRETTY_FUNCTION__,__FILE__,__LINE__, errors); } -void PluginsConfigWidget::installPluginsActions(QToolBar *toolbar, QMenu *menu, QObject *recv, const char *slot) +void PluginsConfigWidget::installPluginsActions(QToolBar *toolbar, QMenu *menu, QObject *recv, const char *slot, QMainWindow *main_window) { if((toolbar || menu) && slot) { vector::iterator itr=plugins_actions.begin(); + PgModelerPlugin *plugin = nullptr; while(itr!=plugins_actions.end()) { @@ -161,6 +162,13 @@ void PluginsConfigWidget::installPluginsActions(QToolBar *toolbar, QMenu *menu, if(menu) menu->addAction(*itr); + // Exposing the main window instance to the plugin + if(main_window) + { + plugin =reinterpret_cast((*itr)->data().value()); + plugin->setMainWindow(main_window); + } + connect(*itr, SIGNAL(triggered(void)), recv, slot); itr++; } diff --git a/libpgmodeler_ui/src/pluginsconfigwidget.h b/libpgmodeler_ui/src/pluginsconfigwidget.h index 47982b2752..dda2673abd 100644 --- a/libpgmodeler_ui/src/pluginsconfigwidget.h +++ b/libpgmodeler_ui/src/pluginsconfigwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -50,7 +50,7 @@ class PluginsConfigWidget: public BaseConfigWidget, public Ui::PluginsConfigWidg void addConfigurationParam(const QString &, const attribs_map &){} public: - PluginsConfigWidget(QWidget *parent = 0); + PluginsConfigWidget(QWidget *parent = nullptr); ~PluginsConfigWidget(void); //! \brief Since plugins has its own configurations this method load all plugins instead @@ -58,7 +58,7 @@ class PluginsConfigWidget: public BaseConfigWidget, public Ui::PluginsConfigWidg /*! \brief Install the created actions on menu and toolbars. Additionally the user must specify the receiver object and slot executed when the actions is activated */ - void installPluginsActions(QToolBar *toolbar, QMenu *menu, QObject *recv, const char *slot); + void installPluginsActions(QToolBar *toolbar, QMenu *menu, QObject *recv, const char *slot, QMainWindow *main_window); private slots: void showPluginInfo(int idx); diff --git a/libpgmodeler_ui/src/policywidget.cpp b/libpgmodeler_ui/src/policywidget.cpp index 201bd48b14..5c04f825f5 100644 --- a/libpgmodeler_ui/src/policywidget.cpp +++ b/libpgmodeler_ui/src/policywidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,36 +18,38 @@ #include "policywidget.h" -PolicyWidget::PolicyWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_POLICY) +PolicyWidget::PolicyWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Policy) { try { Ui_PolicyWidget::setupUi(this); model_objs_wgt = new ModelObjectsWidget(true, this); - model_objs_wgt->setObjectVisible(OBJ_ROLE, true); + model_objs_wgt->setObjectVisible(ObjectType::Role, true); - check_edt = PgModelerUiNS::createNumberedTextEditor(check_wgt); - check_hl = new SyntaxHighlighter(check_edt); - check_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); - - using_edt = PgModelerUiNS::createNumberedTextEditor(using_wgt); + using_edt = PgModelerUiNs::createNumberedTextEditor(using_wgt); + using_edt->setTabChangesFocus(true); using_hl = new SyntaxHighlighter(using_edt); - using_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + using_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); + + check_edt = PgModelerUiNs::createNumberedTextEditor(check_wgt); + check_edt->setTabChangesFocus(true); + check_hl = new SyntaxHighlighter(check_edt); + check_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); - roles_tab = new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ - (ObjectsTableWidget::DUPLICATE_BUTTON | - ObjectsTableWidget::UPDATE_BUTTON | - ObjectsTableWidget::EDIT_BUTTON), true, this); + roles_tab = new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + (ObjectsTableWidget::DuplicateButton | + ObjectsTableWidget::UpdateButton | + ObjectsTableWidget::EditButton), true, this); roles_tab->setColumnCount(1); roles_tab->setHeaderLabel(trUtf8("Name"), 0); - roles_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("uid")), 0); + roles_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")), 0); QVBoxLayout *vbox = new QVBoxLayout; vbox->addWidget(roles_tab); QFrame *frame=generateInformationFrame(trUtf8("Leave the Roles grid empty in order to create a %1 applicable to PUBLIC.") - .arg(BaseObject::getTypeName(OBJ_POLICY).toLower())); + .arg(BaseObject::getTypeName(ObjectType::Policy).toLower())); vbox->addWidget(frame); frame->setParent(this); vbox->setContentsMargins(4,4,4,4); @@ -57,21 +59,22 @@ PolicyWidget::PolicyWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_POLICY PolicyCmdType::getTypes(cmds); command_cmb->addItems(cmds); - configureFormLayout(policy_grid, OBJ_POLICY); + configureFormLayout(policy_grid, ObjectType::Policy); + configureTabOrder({ basics_grp, attribs_tbw }); connect(roles_tab, SIGNAL(s_rowAdded(int)), model_objs_wgt, SLOT(show())); connect(model_objs_wgt, SIGNAL(s_visibilityChanged(BaseObject*, bool)), this, SLOT(selectRole(BaseObject*, bool))); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void PolicyWidget::setAttributes(DatabaseModel *model, OperationList *op_list, BaseObject *parent_obj, Policy *policy) { if(!parent_obj) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); BaseObjectWidget::setAttributes(model, op_list, policy, parent_obj); model_objs_wgt->setModel(model); @@ -137,6 +140,6 @@ void PolicyWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/policywidget.h b/libpgmodeler_ui/src/policywidget.h index b007a7476b..f289060c81 100644 --- a/libpgmodeler_ui/src/policywidget.h +++ b/libpgmodeler_ui/src/policywidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -39,7 +39,7 @@ class PolicyWidget : public BaseObjectWidget, Ui::PolicyWidget { NumberedTextEditor *using_edt, *check_edt; public: - PolicyWidget(QWidget *parent = 0); + PolicyWidget(QWidget *parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, BaseObject *parent_obj, Policy *policy); diff --git a/libpgmodeler_ui/src/referencewidget.cpp b/libpgmodeler_ui/src/referencewidget.cpp new file mode 100644 index 0000000000..f4af6d1ffd --- /dev/null +++ b/libpgmodeler_ui/src/referencewidget.cpp @@ -0,0 +1,343 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "referencewidget.h" +#include "baseobjectwidget.h" + +ReferenceWidget::ReferenceWidget(QWidget *parent) : QWidget(parent) +{ + setupUi(this); + + model = nullptr; + + ref_flags = 0; + ref_alias_ht=new HintTextWidget(ref_alias_hint, this); + ref_alias_ht->setText(ref_alias_edt->statusTip()); + + used_in_ht=new HintTextWidget(used_in_hint, this); + used_in_ht->setText(select_from_chk->statusTip()); + + ref_object_ht=new HintTextWidget(ref_object_hint, this); + ref_object_ht->setText(trUtf8("To reference all columns of a table select only a table in the object selector, this is the same as write [schema].[table].*. In order to reference a only a single column of a table select a column object in the selector.")); + + alias_ht=new HintTextWidget(alias_hint, this); + alias_ht->setText(alias_edt->statusTip()); + + expression_txt=new NumberedTextEditor(this, true); + expression_hl=new SyntaxHighlighter(expression_txt, false, true); + expression_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); + + ref_object_sel=new ObjectSelectorWidget({ ObjectType::Table, ObjectType::Column }, true, this); + ref_object_sel->enableObjectCreation(false); + expression_cp=new CodeCompletionWidget(expression_txt, true); + + QGridLayout *grid = dynamic_cast(properties_tbw->widget(0)->layout()); + grid->addWidget(ref_object_sel, 2, 1, 1, 3); + grid->addWidget(expression_txt, 4, 1, 1, 4); + + properties_tbw->setTabEnabled(1, false); + properties_tbw->setTabEnabled(2, false); + + pgsqltype_wgt = new PgSQLTypeWidget(this); + + columns_tab = new ObjectsTableWidget(ObjectsTableWidget::AllButtons, true, this); + columns_tab->setColumnCount(3); + columns_tab->setHeaderLabel(trUtf8("Name"), 0); + columns_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")),0); + columns_tab->setHeaderLabel(trUtf8("Type"), 1); + columns_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("usertype")),1); + columns_tab->setHeaderLabel(trUtf8("Alias"), 2); + + QFrame *info_frm=BaseObjectWidget::generateInformationFrame(trUtf8("This tab can be used to inform the columns that the view owns. This is just a convenience to make the visualization of this kind of object more intuitive. If no column is specified here the columns of the view displayed in the canvas will be a fragment of the expression defined in the previous tab.")); + QVBoxLayout *vbox = dynamic_cast(properties_tbw->widget(1)->layout()); + + vbox->addWidget(pgsqltype_wgt); + vbox->addWidget(columns_tab); + + info_frm->setParent(this); + vbox->addWidget(info_frm); + + ref_tables_tab = new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ (ObjectsTableWidget::UpdateButton | + ObjectsTableWidget::DuplicateButton| + ObjectsTableWidget::EditButton), true, this); + ref_tables_tab->setColumnCount(3); + ref_tables_tab->setHeaderLabel(trUtf8("Name"), 0); + ref_tables_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")),0); + ref_tables_tab->setHeaderLabel(trUtf8("Schema"), 1); + ref_tables_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("schema")),1); + + ref_table_sel=new ObjectSelectorWidget(ObjectType::Table, true, this); + ref_table_sel->enableObjectCreation(false); + + QHBoxLayout *hbox = new QHBoxLayout; + hbox->addWidget(ref_table_lbl); + hbox->addWidget(ref_table_sel); + + info_frm=BaseObjectWidget::generateInformationFrame(trUtf8("This tab can be used to inform the tables that the view references. This is just a convenience to make the visualization of this kind of object more intuitive. If no table is specified here no relationship will be displayed in the canvas. Note that no validation will be done to check if the provided tables are really referenced by the view.")); + vbox = new QVBoxLayout; + vbox->setContentsMargins(4,4,4,4); + vbox->addLayout(hbox); + vbox->addWidget(ref_tables_tab); + vbox->addWidget(info_frm); + properties_tbw->widget(2)->setLayout(vbox); + + selectReferenceType(); + setMinimumSize(640, 480); + + connect(columns_tab, SIGNAL(s_rowAdded(int)), this, SLOT(addColumn(int))); + connect(columns_tab, SIGNAL(s_rowUpdated(int)), this, SLOT(updateColumn(int))); + connect(columns_tab, SIGNAL(s_rowEdited(int)), this, SLOT(editColumn(int))); + connect(columns_tab, SIGNAL(s_rowDuplicated(int,int)), this, SLOT(duplicateColumn(int,int))); + + connect(ref_tables_tab, SIGNAL(s_rowAdded(int)), this, SLOT(addRefTable(int))); + + connect(view_def_chk, SIGNAL(toggled(bool)), select_from_chk, SLOT(setDisabled(bool))); + connect(view_def_chk, SIGNAL(toggled(bool)), from_where_chk, SLOT(setDisabled(bool))); + connect(view_def_chk, SIGNAL(toggled(bool)), after_where_chk, SLOT(setDisabled(bool))); + connect(view_def_chk, SIGNAL(toggled(bool)), end_expr_chk, SLOT(setDisabled(bool))); + + connect(view_def_chk, &QCheckBox::toggled, [&](bool checked){ + properties_tbw->setTabEnabled(1, checked); + properties_tbw->setTabEnabled(2, checked); + }); + + connect(ref_type_cmb, SIGNAL(currentIndexChanged(int)), this, SLOT(selectReferenceType(void))); + + connect(ref_object_sel, &ObjectSelectorWidget::s_objectSelected, [&](){ + col_alias_edt->setEnabled(dynamic_cast(ref_object_sel->getSelectedObject())); + }); + + connect(ref_object_sel, &ObjectSelectorWidget::s_selectorCleared, [&](){ + col_alias_edt->setEnabled(false); + }); + + connect(ref_table_sel, &ObjectSelectorWidget::s_selectorChanged, [&](bool selected){ + ref_tables_tab->setButtonsEnabled(ObjectsTableWidget::AddButton, selected); + }); + +} + +void ReferenceWidget::setAttributes(Reference ref, unsigned ref_flags, DatabaseModel *model) +{ + this->ref_flags = ref_flags; + this->reference = ref; + this->model = model; + + pgsqltype_wgt->setAttributes(PgSqlType(), model, + UserTypeConfig::AllUserTypes ^ UserTypeConfig::SequenceType, true, false); + + expression_cp->configureCompletion(model, expression_hl); + ref_object_sel->setModel(model); + ref_table_sel->setModel(model); + + ref_type_cmb->setCurrentIndex(ref.getReferenceType()); + ref_alias_edt->setText(ref.getReferenceAlias()); + + if(ref.getReferenceType()==Reference::ReferColumn) + { + if(ref.getColumn()) + ref_object_sel->setSelectedObject(ref.getColumn()); + else + ref_object_sel->setSelectedObject(ref.getTable()); + + tab_alias_edt->setText(ref.getAlias()); + col_alias_edt->setText(ref.getColumnAlias()); + } + else + { + expression_txt->setPlainText(ref.getExpression()); + expr_alias_edt->setText(ref.getAlias()); + } + + if(ref_flags == Reference::SqlViewDefinition) + { + int row = 0; + view_def_chk->setChecked(true); + columns_tab->blockSignals(true); + + for(auto &col : ref.getColumns()) + { + columns_tab->addRow(); + columns_tab->setCellText(col.name, row, 0); + columns_tab->setCellText(col.type, row, 1); + columns_tab->setCellText(col.alias, row, 2); + columns_tab->setRowData(QVariant::fromValue(PgSqlType::parseString(col.type)), row); + row++; + } + + columns_tab->blockSignals(false); + + ref_tables_tab->blockSignals(true); + row = 0; + for(auto &tab : ref.getReferencedTables()) + { + ref_tables_tab->addRow(); + ref_tables_tab->setCellText(tab->getName(), row, 0); + ref_tables_tab->setCellText(tab->getSchema()->getName(), row, 1); + ref_tables_tab->setRowData(QVariant::fromValue(reinterpret_cast(tab)), row); + row++; + } + + ref_tables_tab->blockSignals(false); + columns_tab->clearSelection(); + ref_tables_tab->clearSelection(); + } + else + { + select_from_chk->setChecked((ref_flags & Reference::SqlReferSelect) == Reference::SqlReferSelect); + from_where_chk->setChecked((ref_flags & Reference::SqlReferFrom) == Reference::SqlReferFrom); + after_where_chk->setChecked((ref_flags & Reference::SqlReferWhere) == Reference::SqlReferWhere); + end_expr_chk->setChecked((ref_flags & Reference::SqlReferEndExpr) == Reference::SqlReferEndExpr); + } + + ref_tables_tab->setButtonsEnabled(ObjectsTableWidget::AddButton, false); +} + +Reference ReferenceWidget::getReference(void) +{ + return(reference); +} + +unsigned ReferenceWidget::getReferenceFlags(void) +{ + return(ref_flags); +} + +void ReferenceWidget::applyConfiguration(void) +{ + try + { + //Creating a reference to a column + if(static_cast(ref_type_cmb->currentIndex())==Reference::ReferColumn) + { + Column *column = dynamic_cast(ref_object_sel->getSelectedObject()); + Table *table = (column ? dynamic_cast
(column->getParentTable()) : + dynamic_cast
(ref_object_sel->getSelectedObject())); + reference = Reference(table, column, tab_alias_edt->text(), col_alias_edt->text()); + } + //Creating a reference to an expression + else + reference = Reference(expression_txt->toPlainText(), expr_alias_edt->text().toUtf8()); + + reference.setReferenceAlias(ref_alias_edt->text()); + + /* The reference must have an SQL application (be between SELECT-FROM, FROM-WHERE or after WHERE), + if the user do not check some of these attributes raises an error */ + if(!select_from_chk->isChecked() && !from_where_chk->isChecked() && + !after_where_chk->isChecked() && !end_expr_chk->isChecked() && + !view_def_chk->isChecked()) + throw Exception(ErrorCode::InvSQLScopeViewReference,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + ref_flags = 0; + + if(view_def_chk->isChecked()) + { + ref_flags = Reference::SqlViewDefinition; + reference.removeColumns(); + + for(unsigned row = 0; row < columns_tab->getRowCount(); row++) + reference.addColumn(columns_tab->getCellText(row, 0), + columns_tab->getRowData(row).value(), + columns_tab->getCellText(row, 2)); + + for(unsigned row = 0; row < ref_tables_tab->getRowCount(); row++) + reference.addReferencedTable(reinterpret_cast
(ref_tables_tab->getRowData(row).value())); + } + + if(select_from_chk->isChecked()) + ref_flags |= Reference::SqlReferSelect; + + if(from_where_chk->isChecked()) + ref_flags |= Reference::SqlReferFrom; + + if(after_where_chk->isChecked()) + ref_flags |= Reference::SqlReferWhere; + + if(end_expr_chk->isChecked()) + ref_flags |= Reference::SqlReferEndExpr; + + + emit s_closeRequested(); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +void ReferenceWidget::handleColumn(int row) +{ + PgSqlType type = pgsqltype_wgt->getPgSQLType(); + columns_tab->setCellText(name_edt->text(), row, 0); + columns_tab->setCellText(*type, row, 1); + columns_tab->setCellText(alias_edt->text(), row, 2); + columns_tab->setRowData(QVariant::fromValue(type), row); + name_edt->clear(); + alias_edt->clear(); + name_edt->setFocus(); +} + +void ReferenceWidget::addColumn(int row) +{ + if(!name_edt->text().isEmpty()) + handleColumn(row); + else + columns_tab->removeRow(row); +} + +void ReferenceWidget::addRefTable(int row) +{ + Table *table = dynamic_cast
(ref_table_sel->getSelectedObject()); + ref_tables_tab->setRowData(QVariant::fromValue(reinterpret_cast(table)), row); + ref_tables_tab->setCellText(table->getName(), row, 0); + ref_tables_tab->setCellText(table->getSchema()->getName(), row, 1); + ref_table_sel->clearSelector(); +} + +void ReferenceWidget::updateColumn(int row) +{ + if(!name_edt->text().isEmpty()) + handleColumn(row); +} + +void ReferenceWidget::editColumn(int row) +{ + name_edt->setText(columns_tab->getCellText(row, 0)); + alias_edt->setText(columns_tab->getCellText(row, 2)); + pgsqltype_wgt->setAttributes(columns_tab->getRowData(row).value(), model, + UserTypeConfig::AllUserTypes ^ UserTypeConfig::SequenceType, true, false); +} + +void ReferenceWidget::duplicateColumn(int src_row, int new_row) +{ + columns_tab->setRowData(columns_tab->getRowData(src_row), new_row); +} + +void ReferenceWidget::selectReferenceType(void) +{ + //Marks if the select reference type treats a reference to an object + bool ref_obj=(ref_type_cmb->currentIndex()==static_cast(Reference::ReferColumn)); + ref_object_sel->setEnabled(ref_obj); + tab_alias_edt->setEnabled(ref_obj); + col_alias_edt->setEnabled(ref_obj); + view_def_chk->setChecked(false); + expression_txt->setEnabled(!ref_obj); + expr_alias_edt->setEnabled(!ref_obj); + view_def_chk->setVisible(!ref_obj); + properties_tbw->setTabEnabled(1, !ref_obj && view_def_chk->isChecked()); +} diff --git a/libpgmodeler_ui/src/referencewidget.h b/libpgmodeler_ui/src/referencewidget.h new file mode 100644 index 0000000000..59824548a7 --- /dev/null +++ b/libpgmodeler_ui/src/referencewidget.h @@ -0,0 +1,80 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#ifndef REFERENCE_WIDGET_H +#define REFERENCE_WIDGET_H + +#include +#include "ui_referencewidget.h" +#include "numberedtexteditor.h" +#include "syntaxhighlighter.h" +#include "codecompletionwidget.h" +#include "objectselectorwidget.h" +#include "hinttextwidget.h" +#include "pgsqltypewidget.h" +#include "objectstablewidget.h" + +class ReferenceWidget : public QWidget, Ui::ReferenceWidget { + private: + Q_OBJECT + + HintTextWidget *ref_alias_ht, *used_in_ht, *ref_object_ht, *alias_ht; + + NumberedTextEditor *expression_txt; + + SyntaxHighlighter *expression_hl; + + CodeCompletionWidget *expression_cp; + + ObjectSelectorWidget *ref_object_sel, *ref_table_sel; + + PgSQLTypeWidget *pgsqltype_wgt; + + ObjectsTableWidget *columns_tab, *ref_tables_tab; + + unsigned ref_flags; + + Reference reference; + + DatabaseModel *model; + + void handleColumn(int row); + + public: + explicit ReferenceWidget(QWidget *parent = nullptr); + + void setAttributes(Reference ref, unsigned ref_flags, DatabaseModel *model); + Reference getReference(void); + unsigned getReferenceFlags(void); + + public slots: + void applyConfiguration(void); + + private slots: + void selectReferenceType(void); + void addColumn(int row); + void addRefTable(int row); + void updateColumn(int row); + void editColumn(int row); + void duplicateColumn(int src_row, int new_row); + + signals: + void s_closeRequested(void); +}; + +#endif diff --git a/libpgmodeler_ui/src/relationshipconfigwidget.cpp b/libpgmodeler_ui/src/relationshipconfigwidget.cpp index 8703e73d1e..36c22e6504 100644 --- a/libpgmodeler_ui/src/relationshipconfigwidget.cpp +++ b/libpgmodeler_ui/src/relationshipconfigwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -22,9 +22,12 @@ map RelationshipConfigWidget::config_params; RelationshipConfigWidget::RelationshipConfigWidget(QWidget * parent) : BaseConfigWidget(parent) { - QStringList list, rel_types={ ParsersAttributes::RELATIONSHIP_11, ParsersAttributes::RELATIONSHIP_1N, - ParsersAttributes::RELATIONSHIP_NN, ParsersAttributes::RELATIONSHIP_GEN, - ParsersAttributes::RELATIONSHIP_DEP }; + QStringList list, rel_types={ Attributes::Relationship11, Attributes::Relationship1n, + Attributes::RelationshipNn, Attributes::RelationshipGen, + Attributes::RelationshipDep, Attributes::RelationshipPart }; + unsigned rel_types_id[]={ BaseRelationship::Relationship11, BaseRelationship::Relationship1n, + BaseRelationship::RelationshipNn, BaseRelationship::RelationshipGen, + BaseRelationship::RelationshipDep, BaseRelationship::RelationshipPart}; Ui_RelationshipConfigWidget::setupUi(this); @@ -36,10 +39,10 @@ RelationshipConfigWidget::RelationshipConfigWidget(QWidget * parent) : BaseConfi for(int i=0; i < pattern_fields.size(); i++) { pattern_hl=new SyntaxHighlighter(pattern_fields[i], true); - pattern_hl->loadConfiguration(GlobalAttributes::CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::PATTERN_HIGHLIGHT_CONF + - GlobalAttributes::CONFIGURATION_EXT); + pattern_hl->loadConfiguration(GlobalAttributes::ConfigurationsDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::PatternHighlightConf + + GlobalAttributes::ConfigurationExt); connect(pattern_fields[i], SIGNAL(textChanged()), this, SLOT(updatePattern())); } @@ -65,7 +68,7 @@ RelationshipConfigWidget::RelationshipConfigWidget(QWidget * parent) : BaseConfi upd_action_cmb->addItems(list); for(int i=0; i < rel_types.size(); i++) - rel_type_cmb->setItemData(i, rel_types[i]); + rel_type_cmb->addItem(BaseRelationship::getRelationshipTypeName(rel_types_id[i]), rel_types[i]); connect(crows_foot_rb, SIGNAL(toggled(bool)), this, SLOT(enableConnModePreview(void))); connect(fk_to_pk_rb, SIGNAL(toggled(bool)), this, SLOT(enableConnModePreview(void))); @@ -92,35 +95,36 @@ void RelationshipConfigWidget::loadConfiguration(void) try { int idx; - vector key_attribs={ParsersAttributes::TYPE}; - BaseConfigWidget::loadConfiguration(GlobalAttributes::RELATIONSHIPS_CONF, config_params, key_attribs); + vector key_attribs={Attributes::Type}; + BaseConfigWidget::loadConfiguration(GlobalAttributes::RelationshipsConf, config_params, key_attribs); - fk_to_pk_rb->setChecked(config_params[ParsersAttributes::CONNECTION][ParsersAttributes::MODE]==ParsersAttributes::CONNECT_FK_TO_PK); - center_pnts_rb->setChecked(config_params[ParsersAttributes::CONNECTION][ParsersAttributes::MODE]==ParsersAttributes::CONNECT_CENTER_PNTS); - tab_edges_rb->setChecked(config_params[ParsersAttributes::CONNECTION][ParsersAttributes::MODE]==ParsersAttributes::CONNECT_TABLE_EDGES); - crows_foot_rb->setChecked(config_params[ParsersAttributes::CONNECTION][ParsersAttributes::MODE]==ParsersAttributes::CROWS_FOOT); + fk_to_pk_rb->setChecked(config_params[Attributes::Connection][Attributes::Mode]==Attributes::ConnectFkToPk); + center_pnts_rb->setChecked(config_params[Attributes::Connection][Attributes::Mode]==Attributes::ConnectCenterPnts); + tab_edges_rb->setChecked(config_params[Attributes::Connection][Attributes::Mode]==Attributes::ConnectTableEdges); + crows_foot_rb->setChecked(config_params[Attributes::Connection][Attributes::Mode]==Attributes::CrowsFoot); - deferrable_chk->setChecked(config_params[ParsersAttributes::FOREIGN_KEYS][ParsersAttributes::DEFERRABLE]==ParsersAttributes::_TRUE_); - deferral_cmb->setCurrentText(config_params[ParsersAttributes::FOREIGN_KEYS][ParsersAttributes::DEFER_TYPE]); + deferrable_chk->setChecked(config_params[Attributes::ForeignKeys][Attributes::Deferrable]==Attributes::True); + deferral_cmb->setCurrentText(config_params[Attributes::ForeignKeys][Attributes::DeferType]); - idx=upd_action_cmb->findText(config_params[ParsersAttributes::FOREIGN_KEYS][ParsersAttributes::UPD_ACTION]); + idx=upd_action_cmb->findText(config_params[Attributes::ForeignKeys][Attributes::UpdAction]); upd_action_cmb->setCurrentIndex(idx < 0 ? 0 : idx); - idx=del_action_cmb->findText(config_params[ParsersAttributes::FOREIGN_KEYS][ParsersAttributes::DEL_ACTION]); + idx=del_action_cmb->findText(config_params[Attributes::ForeignKeys][Attributes::DelAction]); del_action_cmb->setCurrentIndex(idx < 0 ? 0 : idx); - patterns[ParsersAttributes::RELATIONSHIP_11]=config_params[ParsersAttributes::RELATIONSHIP_11]; - patterns[ParsersAttributes::RELATIONSHIP_1N]=config_params[ParsersAttributes::RELATIONSHIP_1N]; - patterns[ParsersAttributes::RELATIONSHIP_NN]=config_params[ParsersAttributes::RELATIONSHIP_NN]; - patterns[ParsersAttributes::RELATIONSHIP_GEN]=config_params[ParsersAttributes::RELATIONSHIP_GEN]; - patterns[ParsersAttributes::RELATIONSHIP_DEP]=config_params[ParsersAttributes::RELATIONSHIP_DEP]; + patterns[Attributes::Relationship11]=config_params[Attributes::Relationship11]; + patterns[Attributes::Relationship1n]=config_params[Attributes::Relationship1n]; + patterns[Attributes::RelationshipNn]=config_params[Attributes::RelationshipNn]; + patterns[Attributes::RelationshipGen]=config_params[Attributes::RelationshipGen]; + patterns[Attributes::RelationshipDep]=config_params[Attributes::RelationshipDep]; + patterns[Attributes::RelationshipPart]=config_params[Attributes::RelationshipPart]; fillNamePatterns(); this->applyConfiguration(); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo()); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo()); } } @@ -130,45 +134,45 @@ void RelationshipConfigWidget::saveConfiguration(void) { QString patterns_sch, root_dir; - root_dir=GlobalAttributes::TMPL_CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR; + root_dir=GlobalAttributes::TmplConfigurationDir + + GlobalAttributes::DirSeparator; patterns_sch=root_dir + - GlobalAttributes::SCHEMAS_DIR + - GlobalAttributes::DIR_SEPARATOR + - ParsersAttributes::PATTERNS + - GlobalAttributes::SCHEMA_EXT; + GlobalAttributes::SchemasDir + + GlobalAttributes::DirSeparator + + Attributes::Patterns + + GlobalAttributes::SchemaExt; if(crows_foot_rb->isChecked()) - config_params[ParsersAttributes::CONNECTION][ParsersAttributes::MODE]=ParsersAttributes::CROWS_FOOT; + config_params[Attributes::Connection][Attributes::Mode]=Attributes::CrowsFoot; else if(fk_to_pk_rb->isChecked()) - config_params[ParsersAttributes::CONNECTION][ParsersAttributes::MODE]=ParsersAttributes::CONNECT_FK_TO_PK; + config_params[Attributes::Connection][Attributes::Mode]=Attributes::ConnectFkToPk; else if(tab_edges_rb->isChecked()) - config_params[ParsersAttributes::CONNECTION][ParsersAttributes::MODE]=ParsersAttributes::CONNECT_TABLE_EDGES; + config_params[Attributes::Connection][Attributes::Mode]=Attributes::ConnectTableEdges; else - config_params[ParsersAttributes::CONNECTION][ParsersAttributes::MODE]=ParsersAttributes::CONNECT_CENTER_PNTS; + config_params[Attributes::Connection][Attributes::Mode]=Attributes::ConnectCenterPnts; - config_params[ParsersAttributes::FOREIGN_KEYS][ParsersAttributes::DEFERRABLE]=(deferrable_chk->isChecked() ? ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_); - config_params[ParsersAttributes::FOREIGN_KEYS][ParsersAttributes::DEFER_TYPE]=deferral_cmb->currentText(); - config_params[ParsersAttributes::FOREIGN_KEYS][ParsersAttributes::UPD_ACTION]=(upd_action_cmb->currentIndex() > 0 ? upd_action_cmb->currentText() : QString()); - config_params[ParsersAttributes::FOREIGN_KEYS][ParsersAttributes::DEL_ACTION]=(del_action_cmb->currentIndex() > 0 ? del_action_cmb->currentText() : QString()); + config_params[Attributes::ForeignKeys][Attributes::Deferrable]=(deferrable_chk->isChecked() ? Attributes::True : Attributes::False); + config_params[Attributes::ForeignKeys][Attributes::DeferType]=deferral_cmb->currentText(); + config_params[Attributes::ForeignKeys][Attributes::UpdAction]=(upd_action_cmb->currentIndex() > 0 ? upd_action_cmb->currentText() : QString()); + config_params[Attributes::ForeignKeys][Attributes::DelAction]=(del_action_cmb->currentIndex() > 0 ? del_action_cmb->currentText() : QString()); - config_params[ParsersAttributes::NAME_PATTERNS][ParsersAttributes::PATTERNS]=QString(); + config_params[Attributes::NamePatterns][Attributes::Patterns]=QString(); for(auto &itr : patterns) { schparser.ignoreUnkownAttributes(true); schparser.ignoreEmptyAttributes(true); config_params[itr.first]=itr.second; - config_params[ParsersAttributes::NAME_PATTERNS][ParsersAttributes::PATTERNS]+=schparser.getCodeDefinition(patterns_sch, itr.second); + config_params[Attributes::NamePatterns][Attributes::Patterns]+=schparser.getCodeDefinition(patterns_sch, itr.second); } - BaseConfigWidget::saveConfiguration(GlobalAttributes::RELATIONSHIPS_CONF, config_params); + BaseConfigWidget::saveConfiguration(GlobalAttributes::RelationshipsConf, config_params); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -179,11 +183,11 @@ void RelationshipConfigWidget::applyConfiguration(void) if(!crows_foot_rb->isChecked()) { if(fk_to_pk_rb->isChecked()) - RelationshipView::setLineConnectionMode(RelationshipView::CONNECT_FK_TO_PK); + RelationshipView::setLineConnectionMode(RelationshipView::ConnectFkToPk); else if(tab_edges_rb->isChecked()) - RelationshipView::setLineConnectionMode(RelationshipView::CONNECT_TABLE_EGDES); + RelationshipView::setLineConnectionMode(RelationshipView::ConnectTableEdges); else - RelationshipView::setLineConnectionMode(RelationshipView::CONNECT_CENTER_PNTS); + RelationshipView::setLineConnectionMode(RelationshipView::ConnectCenterPoints); } } @@ -191,13 +195,13 @@ void RelationshipConfigWidget::restoreDefaults(void) { try { - BaseConfigWidget::restoreDefaults(GlobalAttributes::RELATIONSHIPS_CONF); + BaseConfigWidget::restoreDefaults(GlobalAttributes::RelationshipsConf, false); this->loadConfiguration(); setConfigurationChanged(true); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -209,14 +213,14 @@ void RelationshipConfigWidget::fillNamePatterns(void) dst_col_pattern_txt, src_fk_pattern_txt, dst_fk_pattern_txt, pk_col_pattern_txt }; - QList pattern_ids={ ParsersAttributes::PK_PATTERN, ParsersAttributes::UQ_PATTERN, - ParsersAttributes::SRC_COL_PATTERN, ParsersAttributes::DST_COL_PATTERN, - ParsersAttributes::SRC_FK_PATTERN, ParsersAttributes::DST_FK_PATTERN, - ParsersAttributes::PK_COL_PATTERN }; + QList pattern_ids={ Attributes::PkPattern, Attributes::UqPattern, + Attributes::SrcColPattern, Attributes::DstColPattern, + Attributes::SrcFkPattern, Attributes::DstFkPattern, + Attributes::PkColPattern }; - relnn=(rel_type==ParsersAttributes::RELATIONSHIP_NN); - reldep=(rel_type==ParsersAttributes::RELATIONSHIP_DEP); - relgen=(rel_type==ParsersAttributes::RELATIONSHIP_GEN); + relnn=(rel_type==Attributes::RelationshipNn); + reldep=(rel_type==Attributes::RelationshipDep || rel_type==Attributes::RelationshipPart); + relgen=(rel_type==Attributes::RelationshipGen); dst_col_pattern_txt->setEnabled(relnn); dst_fk_pattern_txt->setEnabled(relnn); @@ -248,14 +252,13 @@ void RelationshipConfigWidget::updatePattern(void) { QPlainTextEdit *input=qobject_cast(sender()); QString rel_type=rel_type_cmb->currentData().toString(); - map inputs_map={ { pk_pattern_txt, ParsersAttributes::PK_PATTERN }, - { uq_pattern_txt, ParsersAttributes::UQ_PATTERN }, - { src_col_pattern_txt, ParsersAttributes::SRC_COL_PATTERN }, - { dst_col_pattern_txt, ParsersAttributes::DST_COL_PATTERN }, - { src_fk_pattern_txt, ParsersAttributes::SRC_FK_PATTERN }, - { dst_fk_pattern_txt, ParsersAttributes::DST_FK_PATTERN }, - { pk_col_pattern_txt, ParsersAttributes::PK_COL_PATTERN } }; - + map inputs_map={ { pk_pattern_txt, Attributes::PkPattern }, + { uq_pattern_txt, Attributes::UqPattern }, + { src_col_pattern_txt, Attributes::SrcColPattern }, + { dst_col_pattern_txt, Attributes::DstColPattern }, + { src_fk_pattern_txt, Attributes::SrcFkPattern }, + { dst_fk_pattern_txt, Attributes::DstFkPattern }, + { pk_col_pattern_txt, Attributes::PkColPattern } }; setConfigurationChanged(true); patterns[rel_type][inputs_map[input]]=input->toPlainText(); diff --git a/libpgmodeler_ui/src/relationshipconfigwidget.h b/libpgmodeler_ui/src/relationshipconfigwidget.h index cd87c9bac7..dfa8b86f16 100644 --- a/libpgmodeler_ui/src/relationshipconfigwidget.h +++ b/libpgmodeler_ui/src/relationshipconfigwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -45,7 +45,7 @@ class RelationshipConfigWidget: public BaseConfigWidget, public Ui::Relationshi void hideEvent(QHideEvent *); public: - RelationshipConfigWidget(QWidget * parent=0); + RelationshipConfigWidget(QWidget * parent = nullptr); void saveConfiguration(void); void loadConfiguration(void); diff --git a/libpgmodeler_ui/src/relationshipwidget.cpp b/libpgmodeler_ui/src/relationshipwidget.cpp index f96962eb41..e911a101c6 100644 --- a/libpgmodeler_ui/src/relationshipwidget.cpp +++ b/libpgmodeler_ui/src/relationshipwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,9 +20,11 @@ #include "constraintwidget.h" #include "columnwidget.h" #include "tablewidget.h" -#include "configurationform.h" +#include "baseform.h" +#include "relationshipconfigwidget.h" +#include "generalconfigwidget.h" -RelationshipWidget::RelationshipWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_RELATIONSHIP) +RelationshipWidget::RelationshipWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Relationship) { try { @@ -48,68 +50,71 @@ RelationshipWidget::RelationshipWidget(QWidget *parent): BaseObjectWidget(parent single_pk_ht=new HintTextWidget(single_pk_hint, this); single_pk_ht->setText(single_pk_chk->statusTip()); + default_part_ht=new HintTextWidget(default_part_hint, this); + default_part_ht->setText(default_part_chk->statusTip()); + table1_hl=nullptr; table1_hl=new SyntaxHighlighter(ref_table_txt, true); - table1_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + table1_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); table2_hl=nullptr; table2_hl=new SyntaxHighlighter(recv_table_txt, true); - table2_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + table2_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); for(int i=0; i < pattern_fields.size(); i++) { patterns_hl[i]=new SyntaxHighlighter(qobject_cast(pattern_fields[i]), true); - patterns_hl[i]->loadConfiguration(GlobalAttributes::CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::PATTERN_HIGHLIGHT_CONF + - GlobalAttributes::CONFIGURATION_EXT); + patterns_hl[i]->loadConfiguration(GlobalAttributes::ConfigurationsDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::PatternHighlightConf + + GlobalAttributes::ConfigurationExt); } - attributes_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ - (ObjectsTableWidget::UPDATE_BUTTON | - ObjectsTableWidget::MOVE_BUTTONS), true, this); + attributes_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + (ObjectsTableWidget::UpdateButton | + ObjectsTableWidget::MoveButtons), true, this); - constraints_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ - (ObjectsTableWidget::UPDATE_BUTTON | - ObjectsTableWidget::MOVE_BUTTONS), true, this); + constraints_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + (ObjectsTableWidget::UpdateButton | + ObjectsTableWidget::MoveButtons), true, this); - advanced_objs_tab=new ObjectsTableWidget(ObjectsTableWidget::EDIT_BUTTON, true, this); + advanced_objs_tab=new ObjectsTableWidget(ObjectsTableWidget::EditButton, true, this); attributes_tab->setColumnCount(2); attributes_tab->setHeaderLabel(trUtf8("Attribute"), 0); - attributes_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("column")),0); + attributes_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("column")),0); attributes_tab->setHeaderLabel(trUtf8("Type"), 1); - attributes_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("usertype")),1); + attributes_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("usertype")),1); constraints_tab->setColumnCount(2); constraints_tab->setHeaderLabel(trUtf8("Constraint"), 0); - constraints_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("constraint")),0); + constraints_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("constraint")),0); constraints_tab->setHeaderLabel(trUtf8("Type"), 1); - constraints_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("usertype")),1); + constraints_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("usertype")),1); advanced_objs_tab->setColumnCount(2); advanced_objs_tab->setHeaderLabel(trUtf8("Name"), 0); - advanced_objs_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("column")),0); + advanced_objs_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("column")),0); advanced_objs_tab->setHeaderLabel(trUtf8("Type"), 1); - advanced_objs_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("usertype")),1); + advanced_objs_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("usertype")),1); connect(advanced_objs_tab, SIGNAL(s_rowEdited(int)), this, SLOT(showAdvancedObject(int))); grid=new QGridLayout; grid->addWidget(attributes_tab, 0,0,1,1); grid->setContentsMargins(4,4,4,4); - rel_attribs_tbw->widget(1)->setLayout(grid); + rel_attribs_tbw->widget(AttributesTab)->setLayout(grid); grid=new QGridLayout; grid->addWidget(constraints_tab, 0,0,1,1); grid->setContentsMargins(4,4,4,4); - rel_attribs_tbw->widget(2)->setLayout(grid); + rel_attribs_tbw->widget(ConstraintsTab)->setLayout(grid); - grid=dynamic_cast(rel_attribs_tbw->widget(3)->layout()); + grid=dynamic_cast(rel_attribs_tbw->widget(SpecialPkTab)->layout()); frame=generateInformationFrame(trUtf8("Use the special primary key if you want to include a primary key containing generated columns to the receiver table. Important: if this is a new relationship there is a need to finish its creation and reopen this dialog to create the special primary key.")); grid->addWidget(frame, 1, 0, 1, 1); - frame->setParent(rel_attribs_tbw->widget(3)); + frame->setParent(rel_attribs_tbw->widget(SpecialPkTab)); grid=new QGridLayout; grid->setContentsMargins(4,4,4,4); @@ -119,14 +124,14 @@ RelationshipWidget::RelationshipWidget(QWidget *parent): BaseObjectWidget(parent frame=generateInformationFrame(trUtf8("This advanced tab shows the objects (columns or table) auto created by the relationship's connection as well the foreign keys that represents the link between the participant tables.")); grid->addWidget(frame, 1, 0, 1, 1); - rel_attribs_tbw->widget(4)->setLayout(grid); + rel_attribs_tbw->widget(AdvancedTab)->setLayout(grid); color_picker=new ColorPickerWidget(1,this); color_picker->setEnabled(false); - grid=dynamic_cast(rel_attribs_tbw->widget(0)->layout()); + grid=dynamic_cast(rel_attribs_tbw->widget(GeneralTab)->layout()); grid->addWidget(color_picker, 0, 1); - configureFormLayout(relationship_grid, OBJ_RELATIONSHIP); + configureFormLayout(relationship_grid, ObjectType::Relationship); DeferralType::getTypes(list); deferral_cmb->addItems(list); @@ -136,10 +141,10 @@ RelationshipWidget::RelationshipWidget(QWidget *parent): BaseObjectWidget(parent %2 = Reference (source) table name.
\ %3 = Receiver (destination) table name.
\ %4 = Generated table name. (Only for n:n relationships)") - .arg(Relationship::SRC_COL_TOKEN) - .arg(Relationship::SRC_TAB_TOKEN) - .arg(Relationship::DST_TAB_TOKEN) - .arg(Relationship::GEN_TAB_TOKEN)); + .arg(Relationship::SrcColToken) + .arg(Relationship::SrcTabToken) + .arg(Relationship::DstTabToken) + .arg(Relationship::GenTabToken)); vlayout=dynamic_cast(name_patterns_grp->layout()); vlayout->addWidget(frame); @@ -148,17 +153,28 @@ RelationshipWidget::RelationshipWidget(QWidget *parent): BaseObjectWidget(parent del_action_cmb->addItems(list); upd_action_cmb->addItems(list); - tabs={ nullptr, rel_attribs_tbw->widget(ATTRIBUTES_TAB), rel_attribs_tbw->widget(CONSTRAINTS_TAB), - rel_attribs_tbw->widget(SPECIAL_PK_TAB), rel_attribs_tbw->widget(ADVANCED_TAB) }; + tabs={ nullptr, rel_attribs_tbw->widget(SettingsTab), + rel_attribs_tbw->widget(AttributesTab), rel_attribs_tbw->widget(ConstraintsTab), + rel_attribs_tbw->widget(SpecialPkTab), rel_attribs_tbw->widget(AdvancedTab) }; + + tab_labels=QStringList{ QString(), rel_attribs_tbw->tabText(SettingsTab), + rel_attribs_tbw->tabText(AttributesTab), rel_attribs_tbw->tabText(ConstraintsTab), + rel_attribs_tbw->tabText(SpecialPkTab), rel_attribs_tbw->tabText(AdvancedTab)}; - tab_labels=QStringList{ QString(), rel_attribs_tbw->tabText(ATTRIBUTES_TAB), rel_attribs_tbw->tabText(CONSTRAINTS_TAB), - rel_attribs_tbw->tabText(SPECIAL_PK_TAB), rel_attribs_tbw->tabText(ADVANCED_TAB)}; + part_bound_expr_txt=new NumberedTextEditor(this, true); + part_bound_expr_hl=new SyntaxHighlighter(part_bound_expr_txt); + part_bound_expr_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); + dynamic_cast(part_bound_expr_gb->layout())->addWidget(part_bound_expr_txt, 1, 0); connect(deferrable_chk, SIGNAL(toggled(bool)), deferral_cmb, SLOT(setEnabled(bool))); connect(deferrable_chk, SIGNAL(toggled(bool)), deferral_lbl, SLOT(setEnabled(bool))); - connect(identifier_chk, SIGNAL(toggled(bool)), table1_mand_chk, SLOT(setDisabled(bool))); - connect(identifier_chk, SIGNAL(toggled(bool)), table2_mand_chk, SLOT(setDisabled(bool))); + connect(identifier_chk, &QCheckBox::toggled, [&](){ + table1_mand_chk->setDisabled(identifier_chk->isChecked()); + table2_mand_chk->setEnabled(!identifier_chk->isChecked() && + this->object && + dynamic_cast(this->object)->getRelationshipType() != BaseRelationship::Relationship1n); + }); connect(attributes_tab, SIGNAL(s_rowsRemoved(void)), this, SLOT(removeObjects(void))); connect(attributes_tab, SIGNAL(s_rowAdded(int)), this, SLOT(addObject(void))); @@ -187,12 +203,14 @@ RelationshipWidget::RelationshipWidget(QWidget *parent): BaseObjectWidget(parent connect(fk_gconf_chk, SIGNAL(toggled(bool)), this, SLOT(useFKGlobalSettings(bool))); connect(patterns_gconf_chk, SIGNAL(toggled(bool)), this, SLOT(usePatternGlobalSettings(bool))); + connect(gen_bound_expr_tb, SIGNAL(clicked(bool)), this, SLOT(generateBoundingExpr())); + connect(default_part_chk, SIGNAL(toggled(bool)), part_bound_expr_txt, SLOT(setDisabled(bool))); - setMinimumSize(620, 670); + setMinimumSize(600, 380); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -215,7 +233,7 @@ void RelationshipWidget::setAttributes(DatabaseModel *model, OperationList *op_l } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -226,7 +244,7 @@ void RelationshipWidget::setAttributes(DatabaseModel *model, OperationList *op_l bool rel1n=false, relnn=false, relgen_dep=false, use_name_patterns=false; if(!base_rel) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); BaseObjectWidget::setAttributes(model, op_list, base_rel); @@ -237,21 +255,14 @@ void RelationshipWidget::setAttributes(DatabaseModel *model, OperationList *op_l } rel_type=base_rel->getRelationshipType(); - switch(rel_type) - { - case BaseRelationship::RELATIONSHIP_11: rel_11_rb->setChecked(true); break; - case BaseRelationship::RELATIONSHIP_1N: rel_1n_rb->setChecked(true); break; - case BaseRelationship::RELATIONSHIP_NN: rel_nn_rb->setChecked(true); break; - case BaseRelationship::RELATIONSHIP_GEN: rel_gen_rb->setChecked(true); break; - case BaseRelationship::RELATIONSHIP_FK: rel_fk_rb->setChecked(true); break; - case BaseRelationship::RELATIONSHIP_DEP: rel_dep_rb->setChecked(true); break; - } + rel_type_name_lbl->setText(base_rel->getRelationshipTypeName()); + rel_icon_lbl->setPixmap(PgModelerUiNs::getIconPath(base_rel->getRelTypeAttribute().replace("rel", "relationship"))); aux_rel=dynamic_cast(base_rel); - if(base_rel->getObjectType()==BASE_RELATIONSHIP) + if(base_rel->getObjectType()==ObjectType::BaseRelationship) { - if(base_rel->getRelationshipType()!=BaseRelationship::RELATIONSHIP_FK) + if(base_rel->getRelationshipType()!=BaseRelationship::RelationshipFk) { ref_table_lbl->setText(trUtf8("Referer View:")); ref_table_ht->setText(trUtf8("Referer view references one or more columns of a table to construct it's own columns.")); @@ -266,12 +277,23 @@ void RelationshipWidget::setAttributes(DatabaseModel *model, OperationList *op_l recv_table_lbl->setText(trUtf8("Referenced Table:")); - ref_table_txt->setPlainText(base_rel->getTable(BaseRelationship::SRC_TABLE)->getName(true)); - recv_table_txt->setPlainText(base_rel->getTable(BaseRelationship::DST_TABLE)->getName(true)); + ref_table_txt->setPlainText(base_rel->getTable(BaseRelationship::SrcTable)->getName(true)); + recv_table_txt->setPlainText(base_rel->getTable(BaseRelationship::DstTable)->getName(true)); } else if(aux_rel) { - if(rel_type!=BaseRelationship::RELATIONSHIP_NN) + if(rel_type == BaseRelationship::RelationshipPart) + { + ref_table_lbl->setText(trUtf8("Partitioned Table:")); + ref_table_ht->setText(trUtf8("Partitioned table is the one which is splitted into smaller pieces (partitions). This table is where the partitioning strategy or type is defined.")); + + recv_table_lbl->setText(trUtf8("Partition Table:")); + recv_table_ht->setText(trUtf8("Partition table is the one attached to a partitioned table in which operations over data will be routed (according to the paritionig rule) when trying to handle the partitioned table.")); + + ref_table_txt->setPlainText(aux_rel->getReferenceTable()->getName(true)); + recv_table_txt->setPlainText(aux_rel->getReceiverTable()->getName(true)); + } + else if(rel_type!=BaseRelationship::RelationshipNn) { ref_table_lbl->setText(trUtf8("Reference Table:")); ref_table_ht->setText(trUtf8("Reference table has the columns from its primary key will copied to the receiver table in order to represent the linking between them. This is the (1) side of relationship.")); @@ -288,62 +310,78 @@ void RelationshipWidget::setAttributes(DatabaseModel *model, OperationList *op_l ref_table_ht->setText(trUtf8("In many-to-many relationships both tables are used as reference to generate the table that represents the linking. Columns from both tables are copied to the resultant table and two foreign keys are created as well in order to reference each participant table.")); recv_table_lbl->setText(trUtf8("Reference Table:")); recv_table_ht->setText(ref_table_ht->getText()); - ref_table_txt->setPlainText(base_rel->getTable(BaseRelationship::SRC_TABLE)->getName(true)); - recv_table_txt->setPlainText(base_rel->getTable(BaseRelationship::DST_TABLE)->getName(true)); + ref_table_txt->setPlainText(base_rel->getTable(BaseRelationship::SrcTable)->getName(true)); + recv_table_txt->setPlainText(base_rel->getTable(BaseRelationship::DstTable)->getName(true)); + } + + if(rel_type == BaseRelationship::RelationshipPart) + { + part_type_lbl->setText(~aux_rel->getReferenceTable()->getPartitioningType()); + default_part_chk->setChecked(aux_rel->getPartitionBoundingExpr().isEmpty()); } } - disable_sql_chk->setVisible(base_rel->getObjectType()==OBJ_RELATIONSHIP); - table1_mand_chk->setText(base_rel->getTable(BaseRelationship::SRC_TABLE)->getName() + trUtf8(" is required")); - table2_mand_chk->setText(base_rel->getTable(BaseRelationship::DST_TABLE)->getName() + trUtf8(" is required")); + disable_sql_chk->setVisible(base_rel->getObjectType()==ObjectType::Relationship); + table1_mand_chk->setText(base_rel->getTable(BaseRelationship::SrcTable)->getName() + trUtf8(" is required")); + table2_mand_chk->setText(base_rel->getTable(BaseRelationship::DstTable)->getName() + trUtf8(" is required")); if(aux_rel) { single_pk_chk->setChecked(aux_rel->isSiglePKColumn()); - table1_mand_chk->setChecked(aux_rel->isTableMandatory(BaseRelationship::SRC_TABLE)); - table2_mand_chk->setChecked(aux_rel->isTableMandatory(BaseRelationship::DST_TABLE)); + table1_mand_chk->setChecked(aux_rel->isTableMandatory(BaseRelationship::SrcTable)); + table2_mand_chk->setChecked(aux_rel->isTableMandatory(BaseRelationship::DstTable)); identifier_chk->setChecked(aux_rel->isIdentifier()); relnn_tab_name_edt->setText(aux_rel->getTableNameRelNN()); - attributes_tab->setButtonsEnabled(ObjectsTableWidget::ALL_BUTTONS, !aux_rel->isProtected()); - constraints_tab->setButtonsEnabled(ObjectsTableWidget::ALL_BUTTONS, !aux_rel->isProtected()); + attributes_tab->setButtonsEnabled(ObjectsTableWidget::AllButtons, !aux_rel->isProtected()); + constraints_tab->setButtonsEnabled(ObjectsTableWidget::AllButtons, !aux_rel->isProtected()); //Lists the relationship attributes - listObjects(OBJ_COLUMN); + listObjects(ObjectType::Column); //Lists the relationship constraints - listObjects(OBJ_CONSTRAINT); + listObjects(ObjectType::Constraint); listSpecialPkColumns(); - if(rel_type!=BaseRelationship::RELATIONSHIP_NN) + if(rel_type!=BaseRelationship::RelationshipNn) { - if(rel_type==BaseRelationship::RELATIONSHIP_DEP) + if(rel_type==BaseRelationship::RelationshipDep) { CopyOptions copy_op=aux_rel->getCopyOptions(); including_rb->setChecked(copy_op.isIncluding()); excluding_rb->setChecked(copy_op.isExcluding()); - all_chk->setChecked(copy_op.isOptionSet(CopyOptions::ALL)); - defaults_chk->setChecked(!all_chk->isChecked() && copy_op.isOptionSet(CopyOptions::DEFAULTS)); - constraints_chk->setChecked(!all_chk->isChecked() && copy_op.isOptionSet(CopyOptions::CONSTRAINTS)); - storage_chk->setChecked(!all_chk->isChecked() && copy_op.isOptionSet(CopyOptions::STORAGE)); - comments_chk->setChecked(!all_chk->isChecked() && copy_op.isOptionSet(CopyOptions::COMMENTS)); - indexes_chk->setChecked(!all_chk->isChecked() && copy_op.isOptionSet(CopyOptions::INDEXES)); + all_chk->setChecked(copy_op.isOptionSet(CopyOptions::All)); + defaults_chk->setChecked(!all_chk->isChecked() && copy_op.isOptionSet(CopyOptions::Defaults)); + constraints_chk->setChecked(!all_chk->isChecked() && copy_op.isOptionSet(CopyOptions::Constraints)); + storage_chk->setChecked(!all_chk->isChecked() && copy_op.isOptionSet(CopyOptions::Storage)); + comments_chk->setChecked(!all_chk->isChecked() && copy_op.isOptionSet(CopyOptions::Comments)); + indexes_chk->setChecked(!all_chk->isChecked() && copy_op.isOptionSet(CopyOptions::Indexes)); + identity_chk->setChecked(!all_chk->isChecked() && copy_op.isOptionSet(CopyOptions::Identity)); + statistics_chk->setChecked(!all_chk->isChecked() && copy_op.isOptionSet(CopyOptions::Statistics)); + } + else if(rel_type == BaseRelationship::RelationshipPart) + { + if(this->new_object) + generateBoundingExpr(); + else + part_bound_expr_txt->setPlainText(aux_rel->getPartitionBoundingExpr()); } } } - rel1n=(rel_type==BaseRelationship::RELATIONSHIP_11 || - rel_type==BaseRelationship::RELATIONSHIP_1N); + rel1n=(rel_type==BaseRelationship::Relationship11 || + rel_type==BaseRelationship::Relationship1n); - relnn=(rel_type==BaseRelationship::RELATIONSHIP_NN); + relnn=(rel_type==BaseRelationship::RelationshipNn); - relgen_dep=(rel_type==BaseRelationship::RELATIONSHIP_DEP || - rel_type==BaseRelationship::RELATIONSHIP_GEN || - rel_type==BaseRelationship::RELATIONSHIP_FK); + relgen_dep=(rel_type==BaseRelationship::RelationshipDep || + rel_type==BaseRelationship::RelationshipGen || + rel_type==BaseRelationship::RelationshipPart || + rel_type==BaseRelationship::RelationshipFk); use_name_patterns=(rel1n || relnn || - (relgen_dep && base_rel->getObjectType()==OBJ_RELATIONSHIP)); + (relgen_dep && base_rel->getObjectType()==ObjectType::Relationship)); name_patterns_grp->setVisible(use_name_patterns); @@ -364,7 +402,7 @@ void RelationshipWidget::setAttributes(DatabaseModel *model, OperationList *op_l card_lbl->setVisible(rel1n); table1_mand_chk->setEnabled(rel1n); table1_mand_chk->setVisible(rel1n); - table2_mand_chk->setEnabled(rel_type==BaseRelationship::RELATIONSHIP_11); + table2_mand_chk->setEnabled(rel_type==BaseRelationship::Relationship11); table2_mand_chk->setVisible(rel1n); identifier_wgt->setVisible(rel1n && !base_rel->isSelfRelationship()); @@ -375,24 +413,26 @@ void RelationshipWidget::setAttributes(DatabaseModel *model, OperationList *op_l relnn_tab_name_edt->setVisible(relnn); gen_tab_name_hint->setVisible(relnn); - for(i=ATTRIBUTES_TAB; i <= ADVANCED_TAB; i++) + part_bound_expr_gb->setVisible(rel_type==BaseRelationship::RelationshipPart); + + for(i=SettingsTab; i <= AdvancedTab; i++) rel_attribs_tbw->removeTab(1); if(!relgen_dep) { - for(i=ATTRIBUTES_TAB; i <= SPECIAL_PK_TAB; i++) + for(i=SettingsTab; i <= SpecialPkTab; i++) rel_attribs_tbw->addTab(tabs[i], tab_labels[i]); } - else if(relgen_dep && base_rel->getObjectType()==OBJ_RELATIONSHIP) - rel_attribs_tbw->addTab(tabs[SPECIAL_PK_TAB], tab_labels[SPECIAL_PK_TAB]); + else if(relgen_dep && base_rel->getObjectType()==ObjectType::Relationship) + rel_attribs_tbw->addTab(tabs[SpecialPkTab], tab_labels[SpecialPkTab]); - if(base_rel->getObjectType()==OBJ_RELATIONSHIP || - (base_rel->getObjectType()==BASE_RELATIONSHIP && - base_rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_FK)) - rel_attribs_tbw->addTab(tabs[ADVANCED_TAB], tab_labels[ADVANCED_TAB]); + if(base_rel->getObjectType()==ObjectType::Relationship || + (base_rel->getObjectType()==ObjectType::BaseRelationship && + base_rel->getRelationshipType()==BaseRelationship::RelationshipFk)) + rel_attribs_tbw->addTab(tabs[AdvancedTab], tab_labels[AdvancedTab]); - copy_options_grp->setVisible(base_rel->getObjectType()==OBJ_RELATIONSHIP && - base_rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_DEP); + copy_options_grp->setVisible(base_rel->getObjectType()==ObjectType::Relationship && + base_rel->getRelationshipType()==BaseRelationship::RelationshipDep); custom_color_chk->setChecked(base_rel->getCustomColor()!=Qt::transparent); color_picker->setColor(0, base_rel->getCustomColor()); @@ -417,10 +457,15 @@ void RelationshipWidget::setAttributes(DatabaseModel *model, OperationList *op_l QSize RelationshipWidget::getIdealSize(void) { - if(rel_fk_rb->isChecked() || - (rel_dep_rb->isChecked() && this->object && this->object->getObjectType()==BASE_RELATIONSHIP)) + unsigned rel_type = 0; + + if(this->object) + rel_type = dynamic_cast(this->object)->getRelationshipType(); + + if(rel_type == BaseRelationship::RelationshipFk || + (BaseRelationship::RelationshipDep && this->object && this->object->getObjectType()==ObjectType::BaseRelationship)) return(QSize(640, 320)); - else if(rel_gen_rb->isChecked()) + else if(BaseRelationship::RelationshipGen) return(QSize(640, 520)); else return(QSize(640, 680)); @@ -433,10 +478,10 @@ void RelationshipWidget::useFKGlobalSettings(bool value) if(value) { map confs=RelationshipConfigWidget::getConfigurationParams(); - deferrable_chk->setChecked(confs[ParsersAttributes::FOREIGN_KEYS][ParsersAttributes::DEFERRABLE]==ParsersAttributes::_TRUE_); - deferral_cmb->setCurrentText(confs[ParsersAttributes::FOREIGN_KEYS][ParsersAttributes::DEFER_TYPE]); - upd_action_cmb->setCurrentText(confs[ParsersAttributes::FOREIGN_KEYS][ParsersAttributes::UPD_ACTION]); - del_action_cmb->setCurrentText(confs[ParsersAttributes::FOREIGN_KEYS][ParsersAttributes::DEL_ACTION]); + deferrable_chk->setChecked(confs[Attributes::ForeignKeys][Attributes::Deferrable]==Attributes::True); + deferral_cmb->setCurrentText(confs[Attributes::ForeignKeys][Attributes::DeferType]); + upd_action_cmb->setCurrentText(confs[Attributes::ForeignKeys][Attributes::UpdAction]); + del_action_cmb->setCurrentText(confs[Attributes::ForeignKeys][Attributes::DelAction]); } else { @@ -450,10 +495,10 @@ void RelationshipWidget::useFKGlobalSettings(bool value) idx=deferral_cmb->findText(~rel->getDeferralType()); deferral_cmb->setCurrentIndex(idx < 0 ? 0 : idx); - idx=del_action_cmb->findText(~rel->getActionType(Constraint::DELETE_ACTION)); + idx=del_action_cmb->findText(~rel->getActionType(Constraint::DeleteAction)); del_action_cmb->setCurrentIndex(idx < 0 ? 0 : idx); - idx=upd_action_cmb->findText(~rel->getActionType(Constraint::UPDATE_ACTION)); + idx=upd_action_cmb->findText(~rel->getActionType(Constraint::UpdateAction)); upd_action_cmb->setCurrentIndex(idx < 0 ? 0 : idx); } } @@ -472,28 +517,45 @@ void RelationshipWidget::usePatternGlobalSettings(bool value) QString rel_type=rel->getRelTypeAttribute(); //Using the global settings - pk_pattern_txt->setPlainText(confs[rel_type][ParsersAttributes::PK_PATTERN]); - src_fk_pattern_txt->setPlainText(confs[rel_type][ParsersAttributes::SRC_FK_PATTERN]); - dst_fk_pattern_txt->setPlainText(confs[rel_type][ParsersAttributes::DST_FK_PATTERN]); - uq_pattern_txt->setPlainText(confs[rel_type][ParsersAttributes::UQ_PATTERN]); - src_col_pattern_txt->setPlainText(confs[rel_type][ParsersAttributes::SRC_COL_PATTERN]); - dst_col_pattern_txt->setPlainText(confs[rel_type][ParsersAttributes::DST_COL_PATTERN]); - pk_col_pattern_txt->setPlainText(confs[rel_type][ParsersAttributes::PK_COL_PATTERN]); + pk_pattern_txt->setPlainText(confs[rel_type][Attributes::PkPattern]); + src_fk_pattern_txt->setPlainText(confs[rel_type][Attributes::SrcFkPattern]); + dst_fk_pattern_txt->setPlainText(confs[rel_type][Attributes::DstFkPattern]); + uq_pattern_txt->setPlainText(confs[rel_type][Attributes::UqPattern]); + src_col_pattern_txt->setPlainText(confs[rel_type][Attributes::SrcColPattern]); + dst_col_pattern_txt->setPlainText(confs[rel_type][Attributes::DstColPattern]); + pk_col_pattern_txt->setPlainText(confs[rel_type][Attributes::PkColPattern]); } else { //Using the settings of the relatinship itself - pk_pattern_txt->setPlainText(rel->getNamePattern(Relationship::PK_PATTERN)); - src_fk_pattern_txt->setPlainText(rel->getNamePattern(Relationship::SRC_FK_PATTERN)); - dst_fk_pattern_txt->setPlainText(rel->getNamePattern(Relationship::DST_FK_PATTERN)); - uq_pattern_txt->setPlainText(rel->getNamePattern(Relationship::UQ_PATTERN)); - src_col_pattern_txt->setPlainText(rel->getNamePattern(Relationship::SRC_COL_PATTERN)); - dst_col_pattern_txt->setPlainText(rel->getNamePattern(Relationship::DST_COL_PATTERN)); - pk_col_pattern_txt->setPlainText(rel->getNamePattern(Relationship::PK_COL_PATTERN)); + pk_pattern_txt->setPlainText(rel->getNamePattern(Relationship::PkPattern)); + src_fk_pattern_txt->setPlainText(rel->getNamePattern(Relationship::SrcFkPattern)); + dst_fk_pattern_txt->setPlainText(rel->getNamePattern(Relationship::DstFkPattern)); + uq_pattern_txt->setPlainText(rel->getNamePattern(Relationship::UqPattern)); + src_col_pattern_txt->setPlainText(rel->getNamePattern(Relationship::SrcColPattern)); + dst_col_pattern_txt->setPlainText(rel->getNamePattern(Relationship::DstColPattern)); + pk_col_pattern_txt->setPlainText(rel->getNamePattern(Relationship::PkColPattern)); } } } +void RelationshipWidget::generateBoundingExpr(void) +{ + PartitioningType part_type = part_type_lbl->text(); + QString tmpl; + + if(part_type == PartitioningType::List) + tmpl = QString("IN (value)"); + else if(part_type == PartitioningType::Range) + tmpl = QString("FROM (value) TO (value)"); + else + tmpl = QString("WITH (MODULUS m, REMAINDER r)"); + + part_bound_expr_txt->setPlainText(QString()); + part_bound_expr_txt->setPlainText(tmpl); + default_part_chk->setChecked(false); +} + void RelationshipWidget::listObjects(ObjectType obj_type) { ObjectsTableWidget *tab=nullptr; @@ -502,7 +564,7 @@ void RelationshipWidget::listObjects(ObjectType obj_type) try { - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) tab=attributes_tab; else tab=constraints_tab; @@ -521,12 +583,12 @@ void RelationshipWidget::listObjects(ObjectType obj_type) tab->clearSelection(); tab->blockSignals(false); - constraints_tab->setButtonsEnabled(ObjectsTableWidget::ADD_BUTTON, + constraints_tab->setButtonsEnabled(ObjectsTableWidget::AddButton, attributes_tab->getRowCount() > 0); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -549,7 +611,7 @@ void RelationshipWidget::listAdvancedObjects(void) if(rel) { - if(rel->getRelationshipType()!=BaseRelationship::RELATIONSHIP_NN) + if(rel->getRelationshipType()!=BaseRelationship::RelationshipNn) { cols=rel->getGeneratedColumns(); count=cols.size(); @@ -585,7 +647,7 @@ void RelationshipWidget::listAdvancedObjects(void) } } } - else if(base_rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_FK) + else if(base_rel->getRelationshipType()==BaseRelationship::RelationshipFk) { Constraint *fk = base_rel->getReferenceForeignKey(); @@ -608,7 +670,7 @@ void RelationshipWidget::listAdvancedObjects(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -621,13 +683,13 @@ void RelationshipWidget::showAdvancedObject(int row) ObjectType obj_type=object->getObjectType(); bool is_protected = false; - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) { col=dynamic_cast(object); is_protected = col->isProtected(); openEditingForm(col, col->getParentTable()); } - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) { constr=dynamic_cast(object); @@ -654,7 +716,11 @@ void RelationshipWidget::showAdvancedObject(int row) tab, tab->getPosition().x(), tab->getPosition().y()); editing_form.setMainWidget(table_wgt); + + GeneralConfigWidget::restoreWidgetGeometry(&editing_form, table_wgt->metaObject()->className()); editing_form.exec(); + GeneralConfigWidget::saveWidgetGeometry(&editing_form, table_wgt->metaObject()->className()); + tab->setProtected(false); } } @@ -664,31 +730,42 @@ int RelationshipWidget::openEditingForm(TableObject *object, BaseObject *parent) { BaseForm editing_form(this); WidgetClass *object_wgt=new WidgetClass; + BaseObject *parent_aux = nullptr; + int res = 0; - object_wgt->setAttributes(this->model, this->op_list, (!parent ? this->object : parent), dynamic_cast(object)); + if(this->object->getObjectType() == ObjectType::BaseRelationship) + parent_aux = dynamic_cast(this->object)->getTable(BaseRelationship::SrcTable); + else + parent_aux = !parent ? this->object : parent; + + object_wgt->setAttributes(this->model, this->op_list, parent_aux, dynamic_cast(object)); editing_form.setMainWidget(object_wgt); - return(editing_form.exec()); + GeneralConfigWidget::restoreWidgetGeometry(&editing_form, object_wgt->metaObject()->className()); + res = editing_form.exec(); + GeneralConfigWidget::saveWidgetGeometry(&editing_form, object_wgt->metaObject()->className()); + + return(res); } void RelationshipWidget::addObject(void) { - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; try { if(sender()==attributes_tab) { - obj_type=OBJ_COLUMN; + obj_type=ObjectType::Column; tab=attributes_tab; } else { - obj_type=OBJ_CONSTRAINT; + obj_type=ObjectType::Constraint; tab=constraints_tab; } - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) openEditingForm(nullptr); else openEditingForm(nullptr); @@ -698,13 +775,13 @@ void RelationshipWidget::addObject(void) catch(Exception &e) { listObjects(obj_type); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void RelationshipWidget::duplicateObject(int curr_row, int new_row) { - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; BaseObject *object = nullptr, *dup_object = nullptr; Relationship *rel = dynamic_cast(this->object); vector obj_list; @@ -718,13 +795,13 @@ void RelationshipWidget::duplicateObject(int curr_row, int new_row) { if(sender()==attributes_tab) { - obj_type=OBJ_COLUMN; + obj_type=ObjectType::Column; tab=attributes_tab; obj_list = rel->getAttributes(); } else { - obj_type=OBJ_CONSTRAINT; + obj_type=ObjectType::Constraint; tab=constraints_tab; obj_list = rel->getConstraints(); } @@ -733,10 +810,10 @@ void RelationshipWidget::duplicateObject(int curr_row, int new_row) if(curr_row >= 0) object = reinterpret_cast(tab->getRowData(curr_row).value()); - PgModelerNS::copyObject(&dup_object, object, obj_type); - dup_object->setName(PgModelerNS::generateUniqueName(dup_object, obj_list, false, QString("_cp"))); + PgModelerNs::copyObject(&dup_object, object, obj_type); + dup_object->setName(PgModelerNs::generateUniqueName(dup_object, obj_list, false, QString("_cp"))); - op_id=op_list->registerObject(dup_object, Operation::OBJECT_CREATED, new_row, rel); + op_id=op_list->registerObject(dup_object, Operation::ObjectCreated, new_row, rel); rel->addObject(dynamic_cast(dup_object)); listObjects(obj_type); @@ -752,13 +829,13 @@ void RelationshipWidget::duplicateObject(int curr_row, int new_row) } listObjects(obj_type); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void RelationshipWidget::editObject(int row) { - ObjectType obj_type=OBJ_COLUMN; + ObjectType obj_type=ObjectType::Column; TableObject *tab_obj=nullptr; try @@ -767,13 +844,13 @@ void RelationshipWidget::editObject(int row) if(sender()==attributes_tab) { - obj_type=OBJ_COLUMN; + obj_type=ObjectType::Column; tab_obj=reinterpret_cast(attributes_tab->getRowData(row).value()); openEditingForm(tab_obj); } else { - obj_type=OBJ_CONSTRAINT; + obj_type=ObjectType::Constraint; tab_obj=reinterpret_cast(constraints_tab->getRowData(row).value()); openEditingForm(tab_obj); } @@ -785,7 +862,7 @@ void RelationshipWidget::editObject(int row) { listObjects(obj_type); op_list->ignoreOperationChain(false); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -793,7 +870,7 @@ void RelationshipWidget::showObjectData(TableObject *object, int row) { ObjectsTableWidget *tab=nullptr; - if(object->getObjectType()==OBJ_COLUMN) + if(object->getObjectType()==ObjectType::Column) { tab=attributes_tab; attributes_tab->setCellText(*dynamic_cast(object)->getType(),row,1); @@ -811,7 +888,7 @@ void RelationshipWidget::showObjectData(TableObject *object, int row) void RelationshipWidget::removeObjects(void) { Relationship *rel=nullptr; - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; unsigned count, op_count=0, i; TableObject *object=nullptr; @@ -821,12 +898,12 @@ void RelationshipWidget::removeObjects(void) if(sender()==attributes_tab) { - obj_type=OBJ_COLUMN; + obj_type=ObjectType::Column; count=rel->getAttributeCount(); } else { - obj_type=OBJ_CONSTRAINT; + obj_type=ObjectType::Constraint; count=rel->getConstraintCount(); } @@ -836,11 +913,11 @@ void RelationshipWidget::removeObjects(void) for(i=0; i < count; i++) { object=rel->getObject(0, obj_type); - op_list->registerObject(object, Operation::OBJECT_REMOVED, 0, rel); + op_list->registerObject(object, Operation::ObjectRemoved, 0, rel); rel->removeObject(object); } - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) listSpecialPkColumns(); } catch(Exception &e) @@ -860,14 +937,14 @@ void RelationshipWidget::removeObjects(void) } listObjects(obj_type); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void RelationshipWidget::removeObject(int row) { Relationship *rel=nullptr; - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; TableObject *object=nullptr; int op_id=-1; @@ -876,15 +953,15 @@ void RelationshipWidget::removeObject(int row) rel=dynamic_cast(this->object); if(sender()==attributes_tab) - obj_type=OBJ_COLUMN; + obj_type=ObjectType::Column; else - obj_type=OBJ_CONSTRAINT; + obj_type=ObjectType::Constraint; object=rel->getObject(row, obj_type); - op_id=op_list->registerObject(object, Operation::OBJECT_REMOVED, 0, rel); + op_id=op_list->registerObject(object, Operation::ObjectRemoved, 0, rel); rel->removeObject(object); - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) listSpecialPkColumns(); } catch(Exception &e) @@ -898,7 +975,7 @@ void RelationshipWidget::removeObject(int row) } listObjects(obj_type); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -911,6 +988,8 @@ void RelationshipWidget::selectCopyOptions(void) storage_chk->setEnabled(!all_chk->isChecked() && !defaults_rb->isChecked()); comments_chk->setEnabled(!all_chk->isChecked() && !defaults_rb->isChecked()); indexes_chk->setEnabled(!all_chk->isChecked() && !defaults_rb->isChecked()); + identity_chk->setEnabled(!all_chk->isChecked() && !defaults_rb->isChecked()); + statistics_chk->setEnabled(!all_chk->isChecked() && !defaults_rb->isChecked()); if(all_chk->isChecked() || defaults_rb->isChecked()) { @@ -922,6 +1001,8 @@ void RelationshipWidget::selectCopyOptions(void) storage_chk->setChecked(false); comments_chk->setChecked(false); indexes_chk->setChecked(false); + identity_chk->setChecked(false); + statistics_chk->setChecked(false); } } @@ -938,7 +1019,7 @@ void RelationshipWidget::listSpecialPkColumns(void) rel_columns_lst->clear(); - if(aux_rel->getRelationshipType()!=BaseRelationship::RELATIONSHIP_NN) + if(aux_rel->getRelationshipType()!=BaseRelationship::RelationshipNn) cols=aux_rel->getGeneratedColumns(); for(auto &attrib : aux_rel->getAttributes()) @@ -977,14 +1058,14 @@ void RelationshipWidget::applyConfiguration(void) /* Due to the complexity of the Relationship class and the strong link between all the relationships on the model is necessary to store the XML of the special objects and disconnect all relationships, edit the relationshi and revalidate all the relationships again */ - if(this->object->getObjectType()==OBJ_RELATIONSHIP) + if(this->object->getObjectType()==ObjectType::Relationship) { model->storeSpecialObjectsXML(); model->disconnectRelationships(); } - if(!this->new_object && this->object->getObjectType()==OBJ_RELATIONSHIP) - op_list->registerObject(this->object, Operation::OBJECT_MODIFIED); + if(!this->new_object && this->object->getObjectType()==ObjectType::Relationship) + op_list->registerObject(this->object, Operation::ObjectModified); else registerNewObject(); @@ -995,14 +1076,14 @@ void RelationshipWidget::applyConfiguration(void) else base_rel->setCustomColor(Qt::transparent); - if(this->object->getObjectType()==OBJ_RELATIONSHIP) + if(this->object->getObjectType()==ObjectType::Relationship) { QPlainTextEdit *pattern_fields[]={ src_col_pattern_txt, dst_col_pattern_txt, - src_fk_pattern_txt, dst_fk_pattern_txt, - pk_pattern_txt, uq_pattern_txt, pk_col_pattern_txt }; - unsigned pattern_ids[]= { Relationship::SRC_COL_PATTERN, Relationship::DST_COL_PATTERN, - Relationship::SRC_FK_PATTERN, Relationship::DST_FK_PATTERN, - Relationship::PK_PATTERN, Relationship::UQ_PATTERN, Relationship::PK_COL_PATTERN }; + src_fk_pattern_txt, dst_fk_pattern_txt, + pk_pattern_txt, uq_pattern_txt, pk_col_pattern_txt }; + unsigned pattern_ids[]= { Relationship::SrcColPattern, Relationship::DstColPattern, + Relationship::SrcFkPattern, Relationship::DstFkPattern, + Relationship::PkPattern, Relationship::UqPattern, Relationship::PkColPattern }; rel=dynamic_cast(base_rel); @@ -1016,47 +1097,51 @@ void RelationshipWidget::applyConfiguration(void) rel_type=rel->getRelationshipType(); rel->blockSignals(true); + rel->setPartitionBoundingExpr(default_part_chk->isChecked() ? QString() : part_bound_expr_txt->toPlainText()); + if(!defaults_rb->isChecked()) { if(including_rb->isChecked()) - copy_mode=CopyOptions::INCLUDING; + copy_mode=CopyOptions::Including; else - copy_mode=CopyOptions::EXCLUDING; - - copy_ops+=(all_chk->isChecked() ? CopyOptions::ALL : 0); - copy_ops+=(defaults_chk->isChecked() ? CopyOptions::DEFAULTS : 0); - copy_ops+=(constraints_chk->isChecked() ? CopyOptions::CONSTRAINTS : 0); - copy_ops+=(comments_chk->isChecked() ? CopyOptions::COMMENTS : 0); - copy_ops+=(indexes_chk->isChecked() ? CopyOptions::INDEXES : 0); - copy_ops+=(storage_chk->isChecked() ? CopyOptions::STORAGE : 0); + copy_mode=CopyOptions::Excluding; + + copy_ops+=(all_chk->isChecked() ? CopyOptions::All : 0); + copy_ops+=(defaults_chk->isChecked() ? CopyOptions::Defaults : 0); + copy_ops+=(constraints_chk->isChecked() ? CopyOptions::Constraints : 0); + copy_ops+=(comments_chk->isChecked() ? CopyOptions::Comments : 0); + copy_ops+=(indexes_chk->isChecked() ? CopyOptions::Indexes : 0); + copy_ops+=(storage_chk->isChecked() ? CopyOptions::Storage : 0); + copy_ops+=(identity_chk->isChecked() ? CopyOptions::Identity : 0); + copy_ops+=(statistics_chk->isChecked() ? CopyOptions::Statistics : 0); } rel->setCopyOptions(CopyOptions(copy_mode, copy_ops)); - rel->setMandatoryTable(BaseRelationship::SRC_TABLE, false); - rel->setMandatoryTable(BaseRelationship::DST_TABLE, false); + rel->setMandatoryTable(BaseRelationship::SrcTable, false); + rel->setMandatoryTable(BaseRelationship::DstTable, false); if(table1_mand_chk->isEnabled()) - rel->setMandatoryTable(BaseRelationship::SRC_TABLE, table1_mand_chk->isChecked()); + rel->setMandatoryTable(BaseRelationship::SrcTable, table1_mand_chk->isChecked()); if(table2_mand_chk->isEnabled()) - rel->setMandatoryTable(BaseRelationship::DST_TABLE, table2_mand_chk->isChecked()); + rel->setMandatoryTable(BaseRelationship::DstTable, table2_mand_chk->isChecked()); - if(rel_type==BaseRelationship::RELATIONSHIP_1N || - rel_type==BaseRelationship::RELATIONSHIP_11) + if(rel_type==BaseRelationship::Relationship1n || + rel_type==BaseRelationship::Relationship11) rel->setIdentifier(identifier_chk->isChecked()); - else if(rel_type==BaseRelationship::RELATIONSHIP_NN) + else if(rel_type==BaseRelationship::RelationshipNn) rel->setTableNameRelNN(relnn_tab_name_edt->text()); - if(rel_type==BaseRelationship::RELATIONSHIP_1N || - rel_type==BaseRelationship::RELATIONSHIP_11 || - rel_type==BaseRelationship::RELATIONSHIP_NN) + if(rel_type==BaseRelationship::Relationship1n || + rel_type==BaseRelationship::Relationship11 || + rel_type==BaseRelationship::RelationshipNn) { rel->setDeferrable(deferrable_chk->isChecked()); rel->setDeferralType(DeferralType(deferral_cmb->currentText())); - rel->setActionType((del_action_cmb->currentIndex()!=0 ? ActionType(del_action_cmb->currentText()) : ActionType::null), Constraint::DELETE_ACTION); - rel->setActionType((upd_action_cmb->currentIndex()!=0 ? ActionType(upd_action_cmb->currentText()) : ActionType::null), Constraint::UPDATE_ACTION); + rel->setActionType((del_action_cmb->currentIndex()!=0 ? ActionType(del_action_cmb->currentText()) : ActionType::Null), Constraint::DeleteAction); + rel->setActionType((upd_action_cmb->currentIndex()!=0 ? ActionType(upd_action_cmb->currentText()) : ActionType::Null), Constraint::UpdateAction); - if(rel_type==BaseRelationship::RELATIONSHIP_NN) + if(rel_type==BaseRelationship::RelationshipNn) rel->setSiglePKColumn(single_pk_chk->isChecked()); } @@ -1072,12 +1157,13 @@ void RelationshipWidget::applyConfiguration(void) try { //Checking if there is relationship redundancy - if(rel_type==BaseRelationship::RELATIONSHIP_DEP || - rel_type==BaseRelationship::RELATIONSHIP_GEN || + if(rel_type==BaseRelationship::RelationshipDep || + rel_type==BaseRelationship::RelationshipGen || + rel_type==BaseRelationship::RelationshipPart || rel->isIdentifier()) model->checkRelationshipRedundancy(rel); - if(rel_type!=BaseRelationship::RELATIONSHIP_FK) + if(rel_type!=BaseRelationship::RelationshipFk) model->validateRelationships(); rel->blockSignals(false); @@ -1086,10 +1172,10 @@ void RelationshipWidget::applyConfiguration(void) { Messagebox msg_box; - if(e.getErrorType()==ERR_INVALIDATED_OBJECTS) + if(e.getErrorCode()==ErrorCode::RemInvalidatedObjects) msg_box.show(e); else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -1099,7 +1185,7 @@ void RelationshipWidget::applyConfiguration(void) catch(Exception &e) { model->validateRelationships(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/relationshipwidget.h b/libpgmodeler_ui/src/relationshipwidget.h index e0ff0b0be5..bf24ffe2ce 100644 --- a/libpgmodeler_ui/src/relationshipwidget.h +++ b/libpgmodeler_ui/src/relationshipwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -35,16 +35,20 @@ class RelationshipWidget: public BaseObjectWidget, public Ui::RelationshipWidget private: Q_OBJECT - static const unsigned GENERAL_TAB=0, - ATTRIBUTES_TAB=1, - CONSTRAINTS_TAB=2, - SPECIAL_PK_TAB=3, - ADVANCED_TAB=4; + static constexpr unsigned GeneralTab=0, + SettingsTab=1, + AttributesTab=2, + ConstraintsTab=3, + SpecialPkTab=4, + AdvancedTab=5; - HintTextWidget *gen_tab_name_ht, *ref_table_ht, *recv_table_ht, *identifier_ht, *single_pk_ht; + HintTextWidget *gen_tab_name_ht, *ref_table_ht, *recv_table_ht, + *identifier_ht, *single_pk_ht, *default_part_ht; ColorPickerWidget *color_picker; + NumberedTextEditor *part_bound_expr_txt; + //! \brief Stores the tab objects to change the configuration of the form depending on the type of the relationship QWidgetList tabs; @@ -53,7 +57,8 @@ class RelationshipWidget: public BaseObjectWidget, public Ui::RelationshipWidget SyntaxHighlighter *table1_hl, *table2_hl, - *patterns_hl[7]; + *patterns_hl[7], + *part_bound_expr_hl; //! \brief Table widgets that stores the attributes, constraint and advanced objects of relationship ObjectsTableWidget *attributes_tab, @@ -79,7 +84,7 @@ class RelationshipWidget: public BaseObjectWidget, public Ui::RelationshipWidget void setAttributes(DatabaseModel *model, OperationList *op_list, Table *src_tab, Table *dst_tab, unsigned rel_type); public: - RelationshipWidget(QWidget * parent = 0); + RelationshipWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, BaseRelationship *base_rel); QSize getIdealSize(void); @@ -93,9 +98,9 @@ class RelationshipWidget: public BaseObjectWidget, public Ui::RelationshipWidget void selectCopyOptions(void); void listSpecialPkColumns(void); void duplicateObject(int curr_row, int new_row); - void useFKGlobalSettings(bool value); void usePatternGlobalSettings(bool value); + void generateBoundingExpr(void); public slots: void applyConfiguration(void); diff --git a/libpgmodeler_ui/src/resultsetmodel.cpp b/libpgmodeler_ui/src/resultsetmodel.cpp new file mode 100644 index 0000000000..5e0ff3dcf2 --- /dev/null +++ b/libpgmodeler_ui/src/resultsetmodel.cpp @@ -0,0 +1,179 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "resultsetmodel.h" + +ResultSetModel::ResultSetModel(ResultSet &res, Catalog &catalog, QObject *parent) : QAbstractTableModel(parent) +{ + try + { + Catalog aux_cat = catalog; + vector type_ids; + vector::iterator end; + vector types; + map type_names; + int col = 0; + + col_count = res.getColumnCount(); + row_count = res.getTupleCount(); + insertColumns(0, col_count); + insertRows(0, row_count); + + for(col=0; col < col_count; col++) + { + header_data.push_back(res.getColumnName(col)); + type_ids.push_back(res.getColumnTypeId(col)); + } + + if(res.accessTuple(ResultSet::FirstTuple)) + { + do + { + //Fills the current row with the values of current tuple + for(int col=0; col < col_count; col++) + { + if(res.isColumnBinaryFormat(col)) + item_data.push_back(trUtf8("[binary data]")); + else + item_data.push_back(res.getColumnValue(col)); + } + } + while(res.accessTuple(ResultSet::NextTuple)); + } + + aux_cat.setFilter(Catalog::ListAllObjects); + std::sort(type_ids.begin(), type_ids.end()); + end=std::unique(type_ids.begin(), type_ids.end()); + type_ids.erase(end, type_ids.end()); + + types = aux_cat.getObjectsAttributes(ObjectType::Type, QString(), QString(), type_ids); + col = 0; + + for(auto &tp : types) + type_names[tp[Attributes::Oid].toInt()]=tp[Attributes::Name]; + + for(col=0; col < col_count; col++) + tooltip_data.push_back(type_names[res.getColumnTypeId(col)]); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +int ResultSetModel::rowCount(const QModelIndex &) const +{ + return(row_count); +} + +int ResultSetModel::columnCount(const QModelIndex &) const +{ + return(col_count); +} + +QModelIndex ResultSetModel::index(int row, int column, const QModelIndex &parent) const +{ + return(QAbstractTableModel::index(row, column, parent)); +} + +QModelIndex ResultSetModel::parent(const QModelIndex &) const +{ + return(QModelIndex()); +} + +QVariant ResultSetModel::data(const QModelIndex &index, int role) const +{ + if(index.row() < row_count && index.column() < col_count) + { + if(role == Qt::DisplayRole) + return(item_data.at(index.row() * col_count + index.column())); + + if(role == Qt::TextAlignmentRole) + return(QVariant(Qt::AlignLeft | Qt::AlignVCenter)); + } + + return(QVariant(QVariant::Invalid)); +} + +QVariant ResultSetModel::headerData(int section, Qt::Orientation orientation, int role) const +{ + if(orientation == Qt::Horizontal) + { + if(section >= col_count) + return(QVariant(QVariant::Invalid)); + + if(role == Qt::DisplayRole) + return(header_data.at(section)); + + if(role == Qt::ToolTipRole) + return(tooltip_data.at(section)); + + if(role == Qt::TextAlignmentRole) + return(QVariant(Qt::AlignLeft | Qt::AlignVCenter)); + } + + return(QAbstractTableModel::headerData(section, orientation, role)); +} + +Qt::ItemFlags ResultSetModel::flags(const QModelIndex &) const +{ + return(Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled ); +} + +void ResultSetModel::append(ResultSet &res) +{ + try + { + if(res.isValid() && !res.isEmpty()) + { + if(res.accessTuple(ResultSet::FirstTuple)) + { + do + { + for(int col=0; col < col_count; col++) + { + if(col < res.getColumnCount()) + { + if(res.isColumnBinaryFormat(col)) + item_data.push_back(trUtf8("[binary data]")); + else + item_data.push_back(res.getColumnValue(col)); + } + else + { + item_data.push_back(QString()); + } + } + } + while(res.accessTuple(ResultSet::NextTuple)); + } + + row_count += res.getTupleCount(); + } + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +bool ResultSetModel::isEmpty(void) +{ + return(row_count <= 0); +} + diff --git a/libpgmodeler_ui/src/resultsetmodel.h b/libpgmodeler_ui/src/resultsetmodel.h new file mode 100644 index 0000000000..6d97c64e4b --- /dev/null +++ b/libpgmodeler_ui/src/resultsetmodel.h @@ -0,0 +1,55 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +/** +\ingroup libpgmodeler_ui +\class ResultSetModel +\brief Implements a model representation of ResultSet class which can be used to show large amount of data in instances of QTableView. +*/ + +#ifndef RESULT_SET_MODEL_H +#define RESULT_SET_MODEL_H + +#include +#include "resultset.h" +#include "catalog.h" + +class ResultSetModel: public QAbstractTableModel { + private: + Q_OBJECT + + int col_count, row_count; + QStringList item_data, header_data, tooltip_data; + + void insertColumn(int, const QModelIndex &){} + void insertRow(int, const QModelIndex &){} + + public: + ResultSetModel(ResultSet &res, Catalog &catalog, QObject *parent = 0); + virtual int rowCount(const QModelIndex & = QModelIndex()) const; + virtual int columnCount(const QModelIndex &) const; + virtual QModelIndex index(int row, int column, const QModelIndex &parent) const; + virtual QModelIndex parent(const QModelIndex &) const; + virtual QVariant data(const QModelIndex &index, int role) const; + virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const; + virtual Qt::ItemFlags flags(const QModelIndex &) const; + void append(ResultSet &res); + bool isEmpty(void); +}; + +#endif diff --git a/libpgmodeler_ui/src/rolewidget.cpp b/libpgmodeler_ui/src/rolewidget.cpp index 2e4c40128d..a3b3a5b335 100644 --- a/libpgmodeler_ui/src/rolewidget.cpp +++ b/libpgmodeler_ui/src/rolewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -19,7 +19,7 @@ #include "rolewidget.h" #include "modelobjectswidget.h" -RoleWidget::RoleWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_ROLE) +RoleWidget::RoleWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Role) { ObjectsTableWidget *obj_tab=nullptr; QGridLayout *grid=nullptr; @@ -28,7 +28,7 @@ RoleWidget::RoleWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_ROLE) unsigned i; Ui_RoleWidget::setupUi(this); - configureFormLayout(role_grid, OBJ_ROLE); + configureFormLayout(role_grid, ObjectType::Role); object_selection_wgt=new ModelObjectsWidget(true); @@ -38,8 +38,8 @@ RoleWidget::RoleWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_ROLE) role_grid->addWidget(frame, role_grid->count()+1, 0, 1, 4); frame->setParent(this); - fields_map[generateVersionsInterval(AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_91)].push_back(can_replicate_chk); - fields_map[generateVersionsInterval(AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_95)].push_back(bypass_rls_chk); + fields_map[generateVersionsInterval(AfterVersion, PgSqlVersions::PgSqlVersion91)].push_back(can_replicate_chk); + fields_map[generateVersionsInterval(AfterVersion, PgSqlVersions::PgSqlVersion95)].push_back(bypass_rls_chk); frame=generateVersionWarningFrame(fields_map); role_grid->addWidget(frame, role_grid->count()+1, 0, 1, 0); frame->setParent(this); @@ -50,26 +50,26 @@ RoleWidget::RoleWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_ROLE) //Alocation of the member role tables for(i=0; i < 3; i++) { - obj_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ - (ObjectsTableWidget::UPDATE_BUTTON | ObjectsTableWidget::DUPLICATE_BUTTON), true, this); + obj_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + (ObjectsTableWidget::UpdateButton | ObjectsTableWidget::DuplicateButton), true, this); members_tab[i]=obj_tab; obj_tab->setColumnCount(5); obj_tab->setHeaderLabel(trUtf8("Role"),0); - obj_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("role")),0); + obj_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("role")),0); obj_tab->setHeaderLabel(trUtf8("Validity"),1); - obj_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("validade")),1); + obj_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("validade")),1); obj_tab->setHeaderLabel(trUtf8("Member of"),2); - obj_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("role")),2); + obj_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("role")),2); obj_tab->setHeaderLabel(trUtf8("Members"),3); - obj_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("role")),3); + obj_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("role")),3); obj_tab->setHeaderLabel(trUtf8("Members (Admin.)"),4); - obj_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("role")),4); + obj_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("role")),4); grid=new QGridLayout; grid->addWidget(obj_tab,0,0,1,1); @@ -93,7 +93,7 @@ void RoleWidget::configureRoleSelection(void) //Disconnects all signals from the member role tables for(i=0; i < 3; i++) - disconnect(members_tab[i],0,this,0); + disconnect(members_tab[i], nullptr,this, nullptr); //Connects the signal/slots only on the current table connect(members_tab[members_twg->currentIndex()], SIGNAL(s_rowAdded(int)), this, SLOT(selectMemberRole(void))); @@ -102,7 +102,7 @@ void RoleWidget::configureRoleSelection(void) void RoleWidget::selectMemberRole(void) { - object_selection_wgt->setObjectVisible(OBJ_ROLE, true); + object_selection_wgt->setObjectVisible(ObjectType::Role, true); object_selection_wgt->setModel(this->model); object_selection_wgt->show(); } @@ -117,14 +117,14 @@ void RoleWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Rol validity_chk->setChecked(!role->getValidity().isEmpty()); validity_dte->setDateTime(QDateTime::fromString(role->getValidity(), QString("yyyy-MM-dd hh:mm:ss"))); - superusr_chk->setChecked(role->getOption(Role::OP_SUPERUSER)); - create_db_chk->setChecked(role->getOption(Role::OP_CREATEDB)); - create_role_chk->setChecked(role->getOption(Role::OP_CREATEROLE)); - encrypt_pass_chk->setChecked(role->getOption(Role::OP_ENCRYPTED)); - inh_perm_chk->setChecked(role->getOption(Role::OP_INHERIT)); - can_login_chk->setChecked(role->getOption(Role::OP_LOGIN)); - can_replicate_chk->setChecked(role->getOption(Role::OP_REPLICATION)); - bypass_rls_chk->setChecked(role->getOption(Role::OP_BYPASSRLS)); + superusr_chk->setChecked(role->getOption(Role::OpSuperuser)); + create_db_chk->setChecked(role->getOption(Role::OpCreateDb)); + create_role_chk->setChecked(role->getOption(Role::OpCreateRole)); + encrypt_pass_chk->setChecked(role->getOption(Role::OpEncrypted)); + inh_perm_chk->setChecked(role->getOption(Role::OpInherit)); + can_login_chk->setChecked(role->getOption(Role::OpLogin)); + can_replicate_chk->setChecked(role->getOption(Role::OpReplication)); + bypass_rls_chk->setChecked(role->getOption(Role::OpBypassRls)); } BaseObjectWidget::setAttributes(model, op_list, role); @@ -140,10 +140,10 @@ void RoleWidget::showRoleData(Role *role, unsigned table_id, unsigned row) QString str_aux; Role *aux_role=nullptr; unsigned count, i, type_id, - role_types[3]={ Role::REF_ROLE, Role::MEMBER_ROLE, Role::ADMIN_ROLE }; + role_types[3]={ Role::RefRole, Role::MemberRole, Role::AdminRole }; if(table_id > 3) - throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::RefObjectInvalidIndex,__PRETTY_FUNCTION__,__FILE__,__LINE__); members_tab[table_id]->setRowData(QVariant::fromValue(reinterpret_cast(role)), row); members_tab[table_id]->setCellText(role->getName(), row, 0); @@ -172,7 +172,7 @@ void RoleWidget::fillMembersTable(void) { Role *aux_role=nullptr, *role=nullptr; unsigned count, i, type_id, - role_types[3]={ Role::REF_ROLE, Role::MEMBER_ROLE, Role::ADMIN_ROLE }; + role_types[3]={ Role::RefRole, Role::MemberRole, Role::AdminRole }; role=dynamic_cast(this->object); @@ -219,10 +219,10 @@ void RoleWidget::showSelectedRoleData(void) if(!members_tab[idx_tab]->getRowData(lin).value()) members_tab[idx_tab]->removeRow(lin); - msg_box.show(Exception(Exception::getErrorMessage(ERR_ROLE_REF_REDUNDANCY) - .arg(obj_sel->getName()) - .arg(name_edt->text()), - ERR_ROLE_REF_REDUNDANCY,__PRETTY_FUNCTION__,__FILE__,__LINE__)); + msg_box.show(Exception(Exception::getErrorMessage(ErrorCode::AsgRoleReferenceRedundancy) + .arg(obj_sel->getName()) + .arg(name_edt->text()), + ErrorCode::AsgRoleReferenceRedundancy,__PRETTY_FUNCTION__,__FILE__,__LINE__)); } //If the role does not exist on table, show its data else if(obj_sel && idx_lin < 0) @@ -237,10 +237,10 @@ void RoleWidget::showSelectedRoleData(void) //Raises an error if the role already is in the table if(obj_sel && idx_lin >= 0) { - msg_box.show( Exception(Exception::getErrorMessage(ERR_INS_DUPLIC_ROLE) - .arg(obj_sel->getName()) - .arg(name_edt->text()), - ERR_INS_DUPLIC_ROLE,__PRETTY_FUNCTION__,__FILE__,__LINE__)); + msg_box.show( Exception(Exception::getErrorMessage(ErrorCode::InsDuplicatedRole) + .arg(obj_sel->getName()) + .arg(name_edt->text()), + ErrorCode::InsDuplicatedRole,__PRETTY_FUNCTION__,__FILE__,__LINE__)); } } } @@ -249,7 +249,7 @@ void RoleWidget::applyConfiguration(void) { Role *role=nullptr, *aux_role=nullptr; unsigned count, i, type_id, - role_types[3]={ Role::REF_ROLE, Role::MEMBER_ROLE, Role::ADMIN_ROLE }; + role_types[3]={ Role::RefRole, Role::MemberRole, Role::AdminRole }; try { @@ -264,14 +264,14 @@ void RoleWidget::applyConfiguration(void) else role->setValidity(QString()); - role->setOption(Role::OP_SUPERUSER, superusr_chk->isChecked()); - role->setOption(Role::OP_CREATEDB, create_db_chk->isChecked()); - role->setOption(Role::OP_CREATEROLE, create_role_chk->isChecked()); - role->setOption(Role::OP_ENCRYPTED, encrypt_pass_chk->isChecked()); - role->setOption(Role::OP_INHERIT, inh_perm_chk->isChecked()); - role->setOption(Role::OP_LOGIN, can_login_chk->isChecked()); - role->setOption(Role::OP_REPLICATION, can_replicate_chk->isChecked()); - role->setOption(Role::OP_BYPASSRLS, bypass_rls_chk->isChecked()); + role->setOption(Role::OpSuperuser, superusr_chk->isChecked()); + role->setOption(Role::OpCreateDb, create_db_chk->isChecked()); + role->setOption(Role::OpCreateRole, create_role_chk->isChecked()); + role->setOption(Role::OpEncrypted, encrypt_pass_chk->isChecked()); + role->setOption(Role::OpInherit, inh_perm_chk->isChecked()); + role->setOption(Role::OpLogin, can_login_chk->isChecked()); + role->setOption(Role::OpReplication, can_replicate_chk->isChecked()); + role->setOption(Role::OpBypassRls, bypass_rls_chk->isChecked()); for(type_id=0; type_id < 3; type_id++) { @@ -291,6 +291,6 @@ void RoleWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/rolewidget.h b/libpgmodeler_ui/src/rolewidget.h index 1007af38a9..4bc09e082c 100644 --- a/libpgmodeler_ui/src/rolewidget.h +++ b/libpgmodeler_ui/src/rolewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -46,7 +46,7 @@ class RoleWidget: public BaseObjectWidget, public Ui::RoleWidget { void showRoleData(Role *role, unsigned table_id, unsigned row); public: - RoleWidget(QWidget * parent = 0); + RoleWidget(QWidget * parent = nullptr); ~RoleWidget(void); void setAttributes(DatabaseModel *model, OperationList *op_list, Role *role); diff --git a/libpgmodeler_ui/src/rulewidget.cpp b/libpgmodeler_ui/src/rulewidget.cpp index 788ebdc9d2..f2fbc17fc5 100644 --- a/libpgmodeler_ui/src/rulewidget.cpp +++ b/libpgmodeler_ui/src/rulewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "rulewidget.h" -RuleWidget::RuleWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_RULE) +RuleWidget::RuleWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Rule) { try { @@ -28,22 +28,22 @@ RuleWidget::RuleWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_RULE) Ui_RuleWidget::setupUi(this); cond_expr_hl=new SyntaxHighlighter(cond_expr_txt, false, true); - cond_expr_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + cond_expr_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); command_hl=new SyntaxHighlighter(comando_txt, false, true); - command_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + command_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); command_cp=new CodeCompletionWidget(comando_txt); - commands_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ ObjectsTableWidget::DUPLICATE_BUTTON, true, this); + commands_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ ObjectsTableWidget::DuplicateButton, true, this); commands_tab->setHeaderLabel(trUtf8("SQL command"),0); - commands_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("codigosql")),0); + commands_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("codigosql")),0); dynamic_cast(commands_gb->layout())->addWidget(commands_tab, 1, 0, 1, 2); frame=generateInformationFrame(trUtf8("To create a rule that does not perform any action (DO NOTHING) simply do not specify commands in the SQL commands table.")); rule_grid->addWidget(frame, rule_grid->count()+1, 0, 1, 0); frame->setParent(this); - configureFormLayout(rule_grid, OBJ_RULE); + configureFormLayout(rule_grid, ObjectType::Rule); EventType::getTypes(list); event_cmb->addItems(list); @@ -62,7 +62,7 @@ RuleWidget::RuleWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_RULE) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -87,7 +87,7 @@ void RuleWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Bas unsigned qtd, i; if(!parent_tab) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); BaseObjectWidget::setAttributes(model, op_list, rule, parent_tab); @@ -136,7 +136,7 @@ void RuleWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/rulewidget.h b/libpgmodeler_ui/src/rulewidget.h index 925e8398f0..934da3a086 100644 --- a/libpgmodeler_ui/src/rulewidget.h +++ b/libpgmodeler_ui/src/rulewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -42,7 +42,7 @@ class RuleWidget: public BaseObjectWidget, public Ui::RuleWidget { ObjectsTableWidget *commands_tab; public: - RuleWidget(QWidget * parent = 0); + RuleWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, BaseTable *parent_tab, Rule *rule); private slots: diff --git a/libpgmodeler_ui/src/sceneinfowidget.cpp b/libpgmodeler_ui/src/sceneinfowidget.cpp index 487fd382a1..bbb9b83fdd 100644 --- a/libpgmodeler_ui/src/sceneinfowidget.cpp +++ b/libpgmodeler_ui/src/sceneinfowidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -38,7 +38,7 @@ void SceneInfoWidget::updateSelectedObject(BaseObjectView *object) { if(!object) { - obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("fechar1"))); + obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("fechar1"))); obj_name_lbl->setText(trUtf8("No selection")); obj_pos_info_lbl->setText(trUtf8("N/A")); } @@ -51,13 +51,13 @@ void SceneInfoWidget::updateSelectedObject(BaseObjectView *object) object->boundingRect().width(), object->boundingRect().height()); - obj_icon_lbl->setPixmap(PgModelerUiNS::getIconPath(object->getSourceObject()->getSchemaName())); - obj_name_lbl->setText(QString("%1 (%2)").arg(object->getSourceObject()->getSignature()).arg(object->getSourceObject()->getTypeName())); + obj_icon_lbl->setPixmap(PgModelerUiNs::getIconPath(object->getUnderlyingObject()->getSchemaName())); + obj_name_lbl->setText(QString("%1 (%2)").arg(object->getUnderlyingObject()->getSignature()).arg(object->getUnderlyingObject()->getTypeName())); obj_pos_info_lbl->setText(QString("(%1, %2) [w: %3, h: %4]") - .arg(roundf(rect.left())) - .arg(roundf(rect.top())) - .arg(roundf(rect.width())) - .arg(roundf(rect.height()))); + .arg(round(rect.left())) + .arg(round(rect.top())) + .arg(round(rect.width())) + .arg(round(rect.height()))); } } @@ -65,7 +65,10 @@ void SceneInfoWidget::updateSelectedObjects(int obj_count, const QRectF &objs_re { QRect rect = objs_rect.toRect(); - obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath("seltodos"))); + if(!rect.isValid()) + rect = QRect(0,0,0,0); + + obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath("seltodos"))); obj_name_lbl->setText(trUtf8("Sel. objects: %1").arg(obj_count)); obj_pos_info_lbl->setText(QString("(%1, %2) [w: %3, h: %4]") .arg(rect.left()) @@ -76,7 +79,7 @@ void SceneInfoWidget::updateSelectedObjects(int obj_count, const QRectF &objs_re void SceneInfoWidget::updateMousePosition(const QPointF &mouse_pos) { - mouse_pos_info_lbl->setText(QString("%1, %2").arg(roundf(mouse_pos.x())).arg(roundf(mouse_pos.y()))); + mouse_pos_info_lbl->setText(QString("%1, %2").arg(round(mouse_pos.x())).arg(round(mouse_pos.y()))); } void SceneInfoWidget::updateSceneZoom(double zoom) diff --git a/libpgmodeler_ui/src/sceneinfowidget.h b/libpgmodeler_ui/src/sceneinfowidget.h index 33b4d2c9b6..8350e28d76 100644 --- a/libpgmodeler_ui/src/sceneinfowidget.h +++ b/libpgmodeler_ui/src/sceneinfowidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -33,7 +33,7 @@ class SceneInfoWidget: public QWidget, public Ui::SceneInfoWidget { Q_OBJECT public: - SceneInfoWidget(QWidget * parent = 0); + SceneInfoWidget(QWidget * parent = nullptr); public slots: void updateSelectedObject(BaseObjectView *object); diff --git a/libpgmodeler_ui/src/schemawidget.cpp b/libpgmodeler_ui/src/schemawidget.cpp index 7ddac2b952..2b410bc584 100644 --- a/libpgmodeler_ui/src/schemawidget.cpp +++ b/libpgmodeler_ui/src/schemawidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,12 +18,12 @@ #include "schemawidget.h" -SchemaWidget::SchemaWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_SCHEMA) +SchemaWidget::SchemaWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Schema) { Ui_SchemaWidget::setupUi(this); QHBoxLayout *hbox=nullptr; - configureFormLayout(nullptr, OBJ_SCHEMA); + configureFormLayout(nullptr, ObjectType::Schema); color_picker=new ColorPickerWidget(1, this); @@ -86,7 +86,7 @@ void SchemaWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/schemawidget.h b/libpgmodeler_ui/src/schemawidget.h index 8808e8a393..4396bf6ede 100644 --- a/libpgmodeler_ui/src/schemawidget.h +++ b/libpgmodeler_ui/src/schemawidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -36,7 +36,7 @@ class SchemaWidget: public BaseObjectWidget, public Ui::SchemaWidget { ColorPickerWidget *color_picker; public: - SchemaWidget(QWidget * parent = 0); + SchemaWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema); public slots: diff --git a/libpgmodeler_ui/src/sequencewidget.cpp b/libpgmodeler_ui/src/sequencewidget.cpp index d736855f9e..40ddc7a22c 100644 --- a/libpgmodeler_ui/src/sequencewidget.cpp +++ b/libpgmodeler_ui/src/sequencewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,29 +18,59 @@ #include "sequencewidget.h" -SequenceWidget::SequenceWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_SEQUENCE) +SequenceWidget::SequenceWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Sequence) { try { Ui_SequenceWidget::setupUi(this); column_sel=nullptr; - column_sel=new ObjectSelectorWidget(OBJ_COLUMN, true, this); - sequence_grid->addWidget(column_sel,3,1,1,3); + column_sel=new ObjectSelectorWidget(ObjectType::Column, true, this); + sequence_grid->addWidget(column_sel, 4, 1, 1, 3); - configureFormLayout(sequence_grid, OBJ_SEQUENCE); + configureFormLayout(sequence_grid, ObjectType::Sequence); sequence_grid->addItem(new QSpacerItem(10,0,QSizePolicy::Minimum,QSizePolicy::Expanding), sequence_grid->count(), 0); configureTabOrder(); - setMinimumSize(520, 320); + def_values_cmb->addItem(trUtf8("User defined")); + def_values_cmb->addItem(QString("smallserial")); + def_values_cmb->addItem(QString("serial")); + def_values_cmb->addItem(QString("bigserial")); + setMinimumSize(520, 350); + + connect(def_values_cmb, SIGNAL(currentIndexChanged(int)), this, SLOT(setDefaultValues())); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } +void SequenceWidget::setAttributesReadonly(DatabaseModel *model, OperationList *op_list, Schema *schema, Sequence *sequence, Column *column) +{ + setAttributes(model, sequence); + BaseObjectWidget::setAttributes(model, op_list, sequence, schema, DNaN, DNaN, false); + + name_edt->setReadOnly(true); + comment_edt->setEnabled(false); + schema_sel->setEnabled(false); + append_sql_tb->setEnabled(false); + edt_perms_tb->setEnabled(false); + column_sel->setSelectedObject(column); + column_sel->setEnabled(false); + disable_sql_chk->setEnabled(false); + owner_sel->setSelectedObject(column && column->getParentTable() ? + column->getParentTable()->getOwner() : nullptr); + owner_sel->setEnabled(false); +} + void SequenceWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, Sequence *sequence) +{ + setAttributes(model, sequence); + BaseObjectWidget::setAttributes(model, op_list, sequence, schema); +} + +void SequenceWidget::setAttributes(DatabaseModel *model, Sequence *sequence) { column_sel->setModel(model); @@ -58,13 +88,11 @@ void SequenceWidget::setAttributes(DatabaseModel *model, OperationList *op_list, { cyclic_chk->setChecked(false); start_edt->setText(QString("1")); - maximum_edt->setText(Sequence::MAX_POSITIVE_VALUE); + maximum_edt->setText(Sequence::MaxPositiveValue); minimum_edt->setText(QString("0")); cache_edt->setText(QString("1")); increment_edt->setText(QString("1")); } - - BaseObjectWidget::setAttributes(model,op_list,sequence,schema); } void SequenceWidget::applyConfiguration(void) @@ -87,7 +115,36 @@ void SequenceWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +void SequenceWidget::setDefaultValues(void) +{ + Sequence *seq = dynamic_cast(this->object); + + if(seq && def_values_cmb->currentIndex() == 0) + { + start_edt->setText(seq->getStart()); + cache_edt->setText(seq->getCache()); + minimum_edt->setText(seq->getMinValue()); + maximum_edt->setText(seq->getMaxValue()); + increment_edt->setText(seq->getIncrement()); + } + else + { + QString min = "0", max = Sequence::MaxPositiveValue; + + if(def_values_cmb->currentText() == "smallserial") + max = Sequence::MaxSmallPositiveValue; + else if(def_values_cmb->currentText() == "bigserial") + max = Sequence::MaxBigPositiveValue; + + start_edt->setText("1"); + cache_edt->setText("1"); + increment_edt->setText("1"); + minimum_edt->setText(min); + maximum_edt->setText(max); } } diff --git a/libpgmodeler_ui/src/sequencewidget.h b/libpgmodeler_ui/src/sequencewidget.h index 8b055c633a..d7a12aada8 100644 --- a/libpgmodeler_ui/src/sequencewidget.h +++ b/libpgmodeler_ui/src/sequencewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -34,13 +34,25 @@ class SequenceWidget: public BaseObjectWidget, public Ui::SequenceWidget { ObjectSelectorWidget *column_sel; - public: - SequenceWidget(QWidget * parent = 0); + protected: + void setAttributes(DatabaseModel *model, Sequence *sequence); + + /*! \brief This auxiliary method is used in ColumnWidget to enable the user to edit the underlying sequence's attributes + * when handling an indentity column. This method disable almost all fields in the form letting only the ones related to + * sequence's values configuration enabled */ + void setAttributesReadonly(DatabaseModel *model, OperationList *op_list, Schema *schema, Sequence *sequence, Column *column); + public: + SequenceWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, Sequence *sequence); public slots: void applyConfiguration(void); + + private slots: + void setDefaultValues(void); + + friend class ColumnWidget; }; #endif diff --git a/libpgmodeler_ui/src/snippetsconfigwidget.cpp b/libpgmodeler_ui/src/snippetsconfigwidget.cpp index c270999116..7479c8e489 100644 --- a/libpgmodeler_ui/src/snippetsconfigwidget.cpp +++ b/libpgmodeler_ui/src/snippetsconfigwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -23,15 +23,15 @@ map SnippetsConfigWidget::config_params; -const QRegExp SnippetsConfigWidget::ID_FORMAT_REGEXP=QRegExp(QString("^([a-z])([a-z]*|(\\d)*|(_)*)+"), Qt::CaseInsensitive); +const QRegExp SnippetsConfigWidget::IdFormatRegExp=QRegExp(QString("^([a-z])([a-z]*|(\\d)*|(_)*)+"), Qt::CaseInsensitive); SnippetsConfigWidget::SnippetsConfigWidget(QWidget * parent) : BaseConfigWidget(parent) { QPixmap ico; QString gen_purpose=trUtf8("General purpose"); map types_map; - vector types=BaseObject::getObjectTypes(true, {OBJ_RELATIONSHIP, OBJ_TAG, OBJ_TEXTBOX, - OBJ_PERMISSION, BASE_RELATIONSHIP }); + vector types=BaseObject::getObjectTypes(true, {ObjectType::Relationship, ObjectType::Tag, ObjectType::Textbox, + ObjectType::Permission, ObjectType::BaseRelationship }); setupUi(this); @@ -41,15 +41,15 @@ SnippetsConfigWidget::SnippetsConfigWidget(QWidget * parent) : BaseConfigWidget( //Creates a combo with the accepted object type for(auto &itr : types_map) { - ico.load(PgModelerUiNS::getIconPath(itr.second)); - applies_to_cmb->addItem(ico, itr.first, itr.second); - filter_cmb->addItem(ico, itr.first, itr.second); + ico.load(PgModelerUiNs::getIconPath(itr.second)); + applies_to_cmb->addItem(ico, itr.first, enum_cast(itr.second)); + filter_cmb->addItem(ico, itr.first, enum_cast(itr.second)); } - applies_to_cmb->insertItem(0, gen_purpose, BASE_OBJECT); + applies_to_cmb->insertItem(0, gen_purpose, enum_cast(ObjectType::BaseObject)); applies_to_cmb->setCurrentIndex(0); - filter_cmb->insertItem(0, gen_purpose, BASE_OBJECT); + filter_cmb->insertItem(0, gen_purpose, enum_cast(ObjectType::BaseObject)); filter_cmb->insertItem(0, trUtf8("All snippets")); filter_cmb->setCurrentIndex(0); @@ -59,16 +59,16 @@ SnippetsConfigWidget::SnippetsConfigWidget(QWidget * parent) : BaseConfigWidget( placeholders_ht=new HintTextWidget(placeholders_hint, this); placeholders_ht->setText(placeholders_chk->statusTip()); - snippet_txt=PgModelerUiNS::createNumberedTextEditor(snippet_wgt); + snippet_txt=PgModelerUiNs::createNumberedTextEditor(snippet_wgt); try { snippet_hl=new SyntaxHighlighter(snippet_txt); - snippet_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + snippet_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } enableEditMode(false); @@ -106,13 +106,13 @@ attribs_map SnippetsConfigWidget::getSnippetById(const QString &snip_id) QStringList SnippetsConfigWidget::getSnippetsIdsByObject(ObjectType obj_type) { QStringList ids; - QString type_name=(obj_type==BASE_OBJECT ? - ParsersAttributes::GENERAL : BaseObject::getSchemaName(obj_type)); + QString type_name=(obj_type==ObjectType::BaseObject ? + Attributes::General : BaseObject::getSchemaName(obj_type)); for(auto &snip : config_params) { - if(snip.second[ParsersAttributes::OBJECT]==type_name) - ids.push_back(snip.second[ParsersAttributes::ID]); + if(snip.second[Attributes::Object]==type_name) + ids.push_back(snip.second[Attributes::Id]); } return(ids); @@ -121,12 +121,12 @@ QStringList SnippetsConfigWidget::getSnippetsIdsByObject(ObjectType obj_type) vector SnippetsConfigWidget::getSnippetsByObject(ObjectType obj_type) { vector snippets; - QString type_name=(obj_type==BASE_OBJECT ? - ParsersAttributes::GENERAL : BaseObject::getSchemaName(obj_type)); + QString type_name=(obj_type==ObjectType::BaseObject ? + Attributes::General : BaseObject::getSchemaName(obj_type)); for(auto &snip : config_params) { - if(snip.second[ParsersAttributes::OBJECT]==type_name) + if(snip.second[Attributes::Object]==type_name) snippets.push_back(snip.second); } @@ -160,9 +160,9 @@ QString SnippetsConfigWidget::parseSnippet(attribs_map snippet, attribs_map attr { SchemaParser schparser; QStringList aux_attribs; - QString buf=snippet[ParsersAttributes::CONTENTS]; + QString buf=snippet[Attributes::Contents]; - if(snippet[ParsersAttributes::PARSABLE]!=ParsersAttributes::_TRUE_) + if(snippet[Attributes::Parsable]!=Attributes::True) return(buf); try @@ -170,7 +170,7 @@ QString SnippetsConfigWidget::parseSnippet(attribs_map snippet, attribs_map attr schparser.loadBuffer(buf); //Assigning dummy values for empty attributes - if(snippet[ParsersAttributes::PLACEHOLDERS]==ParsersAttributes::_TRUE_) + if(snippet[Attributes::Placeholders]==Attributes::True) { aux_attribs=schparser.extractAttributes(); for(QString attr : aux_attribs) @@ -187,7 +187,7 @@ QString SnippetsConfigWidget::parseSnippet(attribs_map snippet, attribs_map attr } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -213,24 +213,24 @@ void SnippetsConfigWidget::fillSnippetsCombo(map &config) snippets_cmb->clear(); for(auto &cfg : config) - snippets_cmb->addItem(QString("[%1] %2").arg(cfg.first, cfg.second.at(ParsersAttributes::LABEL)), cfg.first); + snippets_cmb->addItem(QString("[%1] %2").arg(cfg.first, cfg.second.at(Attributes::Label)), cfg.first); } bool SnippetsConfigWidget::isSnippetValid(attribs_map &attribs, const QString &orig_id) { Messagebox msg_box; - QString snip_id=attribs.at(ParsersAttributes::ID), + QString snip_id=attribs.at(Attributes::Id), err_msg; if(!orig_id.isEmpty() && snip_id!=orig_id && config_params.count(snip_id)!=0) err_msg=trUtf8("Duplicated snippet id %1 detected. Please, specify a different one!").arg(snip_id); - else if(!ID_FORMAT_REGEXP.exactMatch(snip_id)) + else if(!IdFormatRegExp.exactMatch(snip_id)) err_msg=trUtf8("Invalid ID pattern detected %1. This one must start with at leat one letter and be composed by letters, numbers and/or underscore!").arg(snip_id); - else if(attribs[ParsersAttributes::LABEL].isEmpty()) + else if(attribs[Attributes::Label].isEmpty()) err_msg=trUtf8("Empty label for snippet %1. Please, specify a value for it!").arg(snip_id); - else if(attribs[ParsersAttributes::CONTENTS].isEmpty()) + else if(attribs[Attributes::Contents].isEmpty()) err_msg=trUtf8("Empty code for snippet %1. Please, specify a value for it!").arg(snip_id); - else if(attribs[ParsersAttributes::PARSABLE]==ParsersAttributes::_TRUE_) + else if(attribs[Attributes::Parsable]==Attributes::True) { try { @@ -251,7 +251,7 @@ bool SnippetsConfigWidget::isSnippetValid(attribs_map &attribs, const QString &o if(!err_msg.isEmpty()) { - msg_box.show(err_msg, Messagebox::ERROR_ICON, Messagebox::OK_BUTTON); + msg_box.show(err_msg, Messagebox::ErrorIcon, Messagebox::OkButton); return(false); } else @@ -270,7 +270,7 @@ void SnippetsConfigWidget::loadConfiguration(void) QStringList inv_snippets; this->resetForm(); - BaseConfigWidget::loadConfiguration(GlobalAttributes::SNIPPETS_CONF, config_params, { ParsersAttributes::ID }); + BaseConfigWidget::loadConfiguration(GlobalAttributes::SnippetsConf, config_params, { Attributes::Id }); //Check if there are invalid snippets loaded for(auto &snip : config_params) @@ -287,7 +287,7 @@ void SnippetsConfigWidget::loadConfiguration(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo()); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e, e.getExtraInfo()); } } @@ -306,28 +306,28 @@ attribs_map SnippetsConfigWidget::getSnippetAttributes(void) QString object_id=BaseObject::getSchemaName(static_cast(applies_to_cmb->currentData().toUInt())); if(object_id.isEmpty()) - object_id=ParsersAttributes::GENERAL; - - return(attribs_map{ {ParsersAttributes::ID, id_edt->text()}, - {ParsersAttributes::LABEL, label_edt->text()}, - {ParsersAttributes::OBJECT, object_id}, - {ParsersAttributes::PARSABLE, (parsable_chk->isChecked() ? ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_)}, - {ParsersAttributes::PLACEHOLDERS, (parsable_chk->isChecked() && placeholders_chk->isChecked() ? - ParsersAttributes::_TRUE_ : ParsersAttributes::_FALSE_)}, - {ParsersAttributes::CONTENTS, snippet_txt->toPlainText()} }); + object_id=Attributes::General; + + return(attribs_map{ {Attributes::Id, id_edt->text()}, + {Attributes::Label, label_edt->text()}, + {Attributes::Object, object_id}, + {Attributes::Parsable, (parsable_chk->isChecked() ? Attributes::True : Attributes::False)}, + {Attributes::Placeholders, (parsable_chk->isChecked() && placeholders_chk->isChecked() ? + Attributes::True : Attributes::False)}, + {Attributes::Contents, snippet_txt->toPlainText()} }); } void SnippetsConfigWidget::editSnippet(void) { QString snip_id=snippets_cmb->currentData().toString(); - ObjectType obj_type=BaseObject::getObjectType(config_params[snip_id].at(ParsersAttributes::OBJECT)); + ObjectType obj_type=BaseObject::getObjectType(config_params[snip_id].at(Attributes::Object)); enableEditMode(true); - snippet_txt->setPlainText(config_params[snip_id].at(ParsersAttributes::CONTENTS)); + snippet_txt->setPlainText(config_params[snip_id].at(Attributes::Contents)); id_edt->setText(snip_id); - label_edt->setText(config_params[snip_id].at(ParsersAttributes::LABEL)); - parsable_chk->setChecked(config_params[snip_id].at(ParsersAttributes::PARSABLE)==ParsersAttributes::_TRUE_); - placeholders_chk->setChecked(config_params[snip_id].at(ParsersAttributes::PLACEHOLDERS)==ParsersAttributes::_TRUE_); + label_edt->setText(config_params[snip_id].at(Attributes::Label)); + parsable_chk->setChecked(config_params[snip_id].at(Attributes::Parsable)==Attributes::True); + placeholders_chk->setChecked(config_params[snip_id].at(Attributes::Placeholders)==Attributes::True); applies_to_cmb->setCurrentText(BaseObject::getTypeName(obj_type)); } @@ -364,7 +364,7 @@ void SnippetsConfigWidget::removeAllSnippets(void) Messagebox msg_box; msg_box.show(trUtf8("Do you really want to remove all snippets?"), - Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); if(msg_box.result()==QDialog::Accepted) { @@ -414,11 +414,11 @@ void SnippetsConfigWidget::filterSnippets(int idx) QString object_id=BaseObject::getSchemaName(obj_type); if(object_id.isEmpty()) - object_id=ParsersAttributes::GENERAL; + object_id=Attributes::General; for(auto &cfg : config_params) { - if(cfg.second.at(ParsersAttributes::OBJECT)==object_id) + if(cfg.second.at(Attributes::Object)==object_id) flt_snippets[cfg.first]=cfg.second; } @@ -433,7 +433,7 @@ void SnippetsConfigWidget::parseSnippet(void) try { parseSnippet(getSnippetAttributes(), attribs_map()); - msg_box.show(trUtf8("No syntax errors found in the snippet."), Messagebox::INFO_ICON); + msg_box.show(trUtf8("No syntax errors found in the snippet."), Messagebox::InfoIcon); } catch(Exception &e) { @@ -445,14 +445,14 @@ void SnippetsConfigWidget::saveConfiguration(void) { try { - QString root_dir=GlobalAttributes::TMPL_CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR, + QString root_dir=GlobalAttributes::TmplConfigurationDir + + GlobalAttributes::DirSeparator, snippet_sch=root_dir + - GlobalAttributes::SCHEMAS_DIR + - GlobalAttributes::DIR_SEPARATOR + - ParsersAttributes::SNIPPET + - GlobalAttributes::SCHEMA_EXT; + GlobalAttributes::SchemasDir + + GlobalAttributes::DirSeparator + + Attributes::Snippet + + GlobalAttributes::SchemaExt; attribs_map attribs; ObjectType obj_type; @@ -466,17 +466,17 @@ void SnippetsConfigWidget::saveConfiguration(void) for(auto &snip : snippets) { - attribs[ParsersAttributes::SNIPPET]+= + attribs[Attributes::Snippet]+= schparser.convertCharsToXMLEntities(schparser.getCodeDefinition(snippet_sch, snip)); } } - config_params[GlobalAttributes::SNIPPETS_CONF]=attribs; - BaseConfigWidget::saveConfiguration(GlobalAttributes::SNIPPETS_CONF, config_params); + config_params[GlobalAttributes::SnippetsConf]=attribs; + BaseConfigWidget::saveConfiguration(GlobalAttributes::SnippetsConf, config_params); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -484,13 +484,13 @@ void SnippetsConfigWidget::restoreDefaults(void) { try { - BaseConfigWidget::restoreDefaults(GlobalAttributes::SNIPPETS_CONF); + BaseConfigWidget::restoreDefaults(GlobalAttributes::SnippetsConf, false); this->loadConfiguration(); setConfigurationChanged(true); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -520,8 +520,8 @@ void SnippetsConfigWidget::configureSnippetsMenu(QMenu *snip_menu, vectorsetIcon(ico); @@ -543,19 +543,28 @@ void SnippetsConfigWidget::configureSnippetsMenu(QMenu *snip_menu, vectoraddMenu(menu); } //Creating the action for the current snippet - act=new QAction(QPixmap(PgModelerUiNS::getIconPath("codesnippet")), snip_id, submenus[object]); - act->setToolTip(snip[ParsersAttributes::LABEL]); + act=new QAction(QPixmap(PgModelerUiNs::getIconPath("codesnippet")), snip_id, submenus[object]); + act->setToolTip(snip[Attributes::Label]); submenus[object]->addAction(act); } //Include the "general" submenu at the end of snippet menu - if(submenus.count(ParsersAttributes::GENERAL)!=0) - snip_menu->addMenu(submenus[ParsersAttributes::GENERAL]); + if(submenus.count(Attributes::General)!=0) + { + if(snip_menu->isEmpty()) + snip_menu->addMenu(submenus[Attributes::General]); + else + { + //Inserting the "general" submenu at the top of snippets actions + snip_menu->insertMenu(snip_menu->actions().at(0), submenus[Attributes::General]); + snip_menu->insertSeparator(snip_menu->actions().at(1)); + } + } } bool SnippetsConfigWidget::isSnippetExists(const QString &snip_id) diff --git a/libpgmodeler_ui/src/snippetsconfigwidget.h b/libpgmodeler_ui/src/snippetsconfigwidget.h index b3d9f7dd84..5e9099e935 100644 --- a/libpgmodeler_ui/src/snippetsconfigwidget.h +++ b/libpgmodeler_ui/src/snippetsconfigwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -40,7 +40,7 @@ class SnippetsConfigWidget: public BaseConfigWidget, public Ui::SnippetsConfigWi static map config_params; //! \brief The regular expression the defines a valid id for a snippet - static const QRegExp ID_FORMAT_REGEXP; + static const QRegExp IdFormatRegExp; NumberedTextEditor *snippet_txt; @@ -66,7 +66,7 @@ class SnippetsConfigWidget: public BaseConfigWidget, public Ui::SnippetsConfigWi attribs_map getSnippetAttributes(void); public: - SnippetsConfigWidget(QWidget * parent=0); + SnippetsConfigWidget(QWidget * parent = nullptr); void saveConfiguration(void); void loadConfiguration(void); @@ -79,7 +79,7 @@ class SnippetsConfigWidget: public BaseConfigWidget, public Ui::SnippetsConfigWi static QStringList getSnippetsIdsByObject(ObjectType obj_type); /*! \brief Returns a vector of snippets' attributes filtering by the object type in which they apply. - There's a special group for general purpose snippets that can be retrieved using BASE_OBJECT type. + There's a special group for general purpose snippets that can be retrieved using ObjectType::ObjBaseObject type. If there is no snippets related to the type an empty vector is returned. */ static vector getSnippetsByObject(ObjectType obj_type); diff --git a/libpgmodeler_ui/src/sourcecodewidget.cpp b/libpgmodeler_ui/src/sourcecodewidget.cpp index 02c9d73241..d04d5072ec 100644 --- a/libpgmodeler_ui/src/sourcecodewidget.cpp +++ b/libpgmodeler_ui/src/sourcecodewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -25,21 +25,21 @@ SourceCodeWidget::SourceCodeWidget(QWidget *parent): BaseObjectWidget(parent) try { Ui_SourceCodeWidget::setupUi(this); - configureFormLayout(codigofonte_grid, BASE_OBJECT); + configureFormLayout(codigofonte_grid, ObjectType::BaseObject); comment_lbl->setVisible(false); comment_edt->setVisible(false); hl_sqlcode=nullptr; hl_xmlcode=nullptr; - sqlcode_txt=PgModelerUiNS::createNumberedTextEditor(sqlcode_wgt); + sqlcode_txt=PgModelerUiNs::createNumberedTextEditor(sqlcode_wgt); sqlcode_txt->setReadOnly(true); - xmlcode_txt=PgModelerUiNS::createNumberedTextEditor(xmlcode_wgt); + xmlcode_txt=PgModelerUiNs::createNumberedTextEditor(xmlcode_wgt); xmlcode_txt->setReadOnly(true); name_edt->setReadOnly(true); - version_cmb->addItems(PgSQLVersions::ALL_VERSIONS); + version_cmb->addItems(PgSqlVersions::AllVersions); code_options_ht=new HintTextWidget(code_options_hint, this); code_options_ht->setText( @@ -59,7 +59,7 @@ SourceCodeWidget::SourceCodeWidget(QWidget *parent): BaseObjectWidget(parent) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -76,11 +76,11 @@ void SourceCodeWidget::setSourceCodeTab(int) code_icon=QString("codigoxml"); enabled=(sourcecode_twg->currentIndex()==0 && - ((obj_type==BASE_RELATIONSHIP && - dynamic_cast(object)->getRelationshipType()==BaseRelationship::RELATIONSHIP_FK) - || (obj_type!=BASE_RELATIONSHIP && obj_type!=OBJ_TEXTBOX))); + ((obj_type==ObjectType::BaseRelationship && + dynamic_cast(object)->getRelationshipType()==BaseRelationship::RelationshipFk) + || (obj_type!=ObjectType::BaseRelationship && obj_type!=ObjectType::Textbox))); - icone=QPixmap(PgModelerUiNS::getIconPath(code_icon)); + icone=QPixmap(PgModelerUiNs::getIconPath(code_icon)); icon_lbl->setPixmap(icone); version_cmb->setEnabled(enabled); pgsql_lbl->setEnabled(enabled); @@ -109,8 +109,8 @@ void SourceCodeWidget::saveSQLCode(void) out.setFileName(file_dlg.selectedFiles().at(0)); if(!out.open(QFile::WriteOnly)) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(file_dlg.selectedFiles().at(0)), - ERR_FILE_DIR_NOT_WRITTEN,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotWritten).arg(file_dlg.selectedFiles().at(0)), + ErrorCode::FileDirectoryNotWritten,__PRETTY_FUNCTION__,__FILE__,__LINE__); buf.append(sqlcode_txt->toPlainText()); out.write(buf.data(), buf.size()); @@ -130,31 +130,31 @@ void SourceCodeWidget::generateSourceCode(int) xmlcode_txt->clear(); obj_type=object->getObjectType(); - if(obj_type!=OBJ_TEXTBOX || - (obj_type==BASE_RELATIONSHIP && - dynamic_cast(object)->getRelationshipType()==BaseRelationship::RELATIONSHIP_FK)) + if(obj_type!=ObjectType::Textbox || + (obj_type==ObjectType::BaseRelationship && + dynamic_cast(object)->getRelationshipType()==BaseRelationship::RelationshipFk)) { QString aux_def; BaseObject::setPgSQLVersion(version_cmb->currentText()); - if(obj_type==OBJ_DATABASE) + if(obj_type==ObjectType::Database) { task_prog_wgt=new TaskProgressWidget; task_prog_wgt->setWindowTitle(trUtf8("Generating source code...")); task_prog_wgt->show(); connect(this->model, SIGNAL(s_objectLoaded(int,QString,unsigned)), task_prog_wgt, SLOT(updateProgress(int,QString,unsigned))); - sqlcode_txt->setPlainText(object->getCodeDefinition(SchemaParser::SQL_DEFINITION)); + sqlcode_txt->setPlainText(object->getCodeDefinition(SchemaParser::SqlDefinition)); } else { - if(code_options_cmb->currentIndex()==ORIGINAL_SQL) - sqlcode_txt->setPlainText(object->getCodeDefinition(SchemaParser::SQL_DEFINITION)); + if(code_options_cmb->currentIndex()==OriginalSql) + sqlcode_txt->setPlainText(object->getCodeDefinition(SchemaParser::SqlDefinition)); else { - vector objs=model->getCreationOrder(object, code_options_cmb->currentIndex()==CHILDREN_SQL); + vector objs=model->getCreationOrder(object, code_options_cmb->currentIndex()==ChildrenSql); for(BaseObject *obj : objs) - aux_def+=obj->getCodeDefinition(SchemaParser::SQL_DEFINITION); + aux_def+=obj->getCodeDefinition(SchemaParser::SqlDefinition); } if(!aux_def.isEmpty()) @@ -193,7 +193,7 @@ void SourceCodeWidget::generateSourceCode(int) #warning "DEMO VERSION: XML code preview disabled." xmlcode_txt->setPlainText(trUtf8("")); #else - xmlcode_txt->setPlainText(object->getCodeDefinition(SchemaParser::XML_DEFINITION)); + xmlcode_txt->setPlainText(object->getCodeDefinition(SchemaParser::XmlDefinition)); #endif setSourceCodeTab(); @@ -213,7 +213,7 @@ void SourceCodeWidget::generateSourceCode(int) disconnect(this->model, nullptr, task_prog_wgt, nullptr); delete(task_prog_wgt); } - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -229,29 +229,29 @@ void SourceCodeWidget::setAttributes(DatabaseModel *model, BaseObject *object) this->name_edt->setText(QString("%1 (%2)").arg(object->getSignature()).arg(object->getTypeName())); this->protected_obj_frm->setVisible(false); this->obj_id_lbl->setVisible(false); - this->code_options_cmb->setEnabled(obj_type!=OBJ_DATABASE && - obj_type!=OBJ_TEXTBOX && - obj_type!=BASE_RELATIONSHIP && - obj_type!=OBJ_RELATIONSHIP); + this->code_options_cmb->setEnabled(obj_type!=ObjectType::Database && + obj_type!=ObjectType::Textbox && + obj_type!=ObjectType::BaseRelationship && + obj_type!=ObjectType::Relationship); #ifdef DEMO_VERSION #warning "DEMO VERSION: SQL code display options disabled." code_options_cmb->setEnabled(false); #endif - obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath(object->getObjectType()))); + obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath(object->getObjectType()))); if(!hl_sqlcode->isConfigurationLoaded()) - hl_sqlcode->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + hl_sqlcode->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); if(!hl_xmlcode->isConfigurationLoaded()) - hl_xmlcode->loadConfiguration(GlobalAttributes::XML_HIGHLIGHT_CONF_PATH); + hl_xmlcode->loadConfiguration(GlobalAttributes::XMLHighlightConfPath); generateSourceCode(); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } } diff --git a/libpgmodeler_ui/src/sourcecodewidget.h b/libpgmodeler_ui/src/sourcecodewidget.h index 43f0021cc7..b9d285ff40 100644 --- a/libpgmodeler_ui/src/sourcecodewidget.h +++ b/libpgmodeler_ui/src/sourcecodewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -34,9 +34,9 @@ class SourceCodeWidget: public BaseObjectWidget, public Ui::SourceCodeWidget { private: Q_OBJECT - static const int ORIGINAL_SQL=0, - DEPENDENCIES_SQL=1, - CHILDREN_SQL=2; + static constexpr int OriginalSql=0, + DependenciesSql=1, + ChildrenSql=2; NumberedTextEditor *sqlcode_txt, *xmlcode_txt; @@ -47,7 +47,7 @@ class SourceCodeWidget: public BaseObjectWidget, public Ui::SourceCodeWidget { HintTextWidget *code_options_ht; public: - SourceCodeWidget(QWidget * parent = 0); + SourceCodeWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, BaseObject *object=nullptr); diff --git a/libpgmodeler_ui/src/sqlexecutionhelper.cpp b/libpgmodeler_ui/src/sqlexecutionhelper.cpp new file mode 100644 index 0000000000..7bf20ac842 --- /dev/null +++ b/libpgmodeler_ui/src/sqlexecutionhelper.cpp @@ -0,0 +1,95 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "sqlexecutionhelper.h" + +SQLExecutionHelper::SQLExecutionHelper(void) : QObject(nullptr) +{ + cancelled = false; + result_model = nullptr; +} + +void SQLExecutionHelper::setConnection(Connection conn) +{ + connection = conn; +} + +void SQLExecutionHelper::setCommand(const QString &cmd) +{ + command = cmd; +} + +ResultSetModel *SQLExecutionHelper::getResultSetModel(void) +{ + return(result_model); +} + +bool SQLExecutionHelper::isCancelled(void) +{ + return(cancelled); +} + +QStringList SQLExecutionHelper::getNotices(void) +{ + return(notices); +} + +void SQLExecutionHelper::executeCommand(void) +{ + try + { + ResultSet res; + Catalog catalog; + Connection aux_conn = Connection(connection.getConnectionParams()); + + catalog.setConnection(aux_conn); + result_model = nullptr; + cancelled = false; + + if(!connection.isStablished()) + { + connection.setNoticeEnabled(true); + connection.connect(); + + //The connection will break the execution if it keeps idle for one hour or more + connection.setSQLExecutionTimout(3600); + } + + connection.executeDMLCommand(command, res); + notices = connection.getNotices(); + + if(!res.isEmpty()) + result_model = new ResultSetModel(res, catalog); + + emit s_executionFinished(res.getTupleCount()); + } + catch(Exception &e) + { + connection.close(); + emit s_executionAborted(e); + } +} + +void SQLExecutionHelper::cancelCommand(void) +{ + if(connection.isStablished()) + { + connection.requestCancel(); + cancelled = true; + } +} diff --git a/libpgmodeler_ui/src/sqlexecutionhelper.h b/libpgmodeler_ui/src/sqlexecutionhelper.h new file mode 100644 index 0000000000..a9d4b8d698 --- /dev/null +++ b/libpgmodeler_ui/src/sqlexecutionhelper.h @@ -0,0 +1,73 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +/** +\ingroup libpgmodeler_ui +\class SQLExecutionHelper +\brief Implements a command execution helper that permit the execution of SQL commands in a thread +*/ + +#ifndef SQL_EXECUTION_HELPER_H +#define SQL_EXECUTION_HELPER_H + +#include +#include +#include "connection.h" +#include "resultsetmodel.h" + +class SQLExecutionHelper : public QObject { + private: + Q_OBJECT + + Connection connection; + + QString command; + + ResultSetModel *result_model; + + bool cancelled; + + int affected_rows; + + QStringList notices; + + public: + SQLExecutionHelper(void); + + void setConnection(Connection conn); + + void setCommand(const QString &cmd); + + //! \brief Returns the result set model created in the execution. This object is not deleted after the execution. + ResultSetModel *getResultSetModel(void); + + bool isCancelled(void); + + //! \brief Returns the notices generated by the execution + QStringList getNotices(void); + + public slots: + void executeCommand(void); + void cancelCommand(void); + + signals: + void s_executionFinished(int rows_affected); + void s_executionAborted(Exception e); +}; + +#endif diff --git a/libpgmodeler_ui/src/sqlexecutionwidget.cpp b/libpgmodeler_ui/src/sqlexecutionwidget.cpp index 18d8acf839..6ac3a57064 100644 --- a/libpgmodeler_ui/src/sqlexecutionwidget.cpp +++ b/libpgmodeler_ui/src/sqlexecutionwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -27,15 +27,14 @@ map SQLExecutionWidget::cmd_history; int SQLExecutionWidget::cmd_history_max_len = 1000; -int SQLExecutionWidget::max_result_rows = 20000; -const QString SQLExecutionWidget::COLUMN_NULL_VALUE = QString("␀"); +const QString SQLExecutionWidget::ColumnNullValue = QString("␀"); SQLExecutionWidget::SQLExecutionWidget(QWidget * parent) : QWidget(parent) { setupUi(this); - sql_cmd_txt=PgModelerUiNS::createNumberedTextEditor(sql_cmd_wgt); - cmd_history_txt=PgModelerUiNS::createNumberedTextEditor(cmd_history_parent); + sql_cmd_txt=PgModelerUiNs::createNumberedTextEditor(sql_cmd_wgt); + cmd_history_txt=PgModelerUiNs::createNumberedTextEditor(cmd_history_parent); cmd_history_txt->setCustomContextMenuEnabled(false); cmd_history_txt->setTabStopWidth(sql_cmd_txt->getTabWidth()); @@ -51,12 +50,13 @@ SQLExecutionWidget::SQLExecutionWidget(QWidget * parent) : QWidget(parent) layout->addWidget(find_history_wgt); find_history_parent->setLayout(layout); find_history_parent->setVisible(false); + connect(find_history_wgt->hide_tb, SIGNAL(clicked(bool)), find_history_parent, SLOT(hide())); sql_cmd_hl=new SyntaxHighlighter(sql_cmd_txt, false); - sql_cmd_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + sql_cmd_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); cmd_history_hl=new SyntaxHighlighter(cmd_history_txt, false); - cmd_history_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + cmd_history_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); results_parent->setVisible(false); output_tbw->setTabEnabled(0, false); @@ -74,24 +74,53 @@ SQLExecutionWidget::SQLExecutionWidget(QWidget * parent) : QWidget(parent) hbox->setContentsMargins(0,0,0,0); hbox->addWidget(find_replace_wgt); find_wgt_parent->setVisible(false); + connect(find_replace_wgt->hide_tb, SIGNAL(clicked(bool)), find_tb, SLOT(toggle())); run_sql_tb->setToolTip(run_sql_tb->toolTip() + QString(" (%1)").arg(run_sql_tb->shortcut().toString())); + stop_tb->setToolTip(stop_tb->toolTip() + QString(" (%1)").arg(stop_tb->shortcut().toString())); export_tb->setToolTip(export_tb->toolTip() + QString(" (%1)").arg(export_tb->shortcut().toString())); file_tb->setToolTip(file_tb->toolTip() + QString(" (%1)").arg(file_tb->shortcut().toString())); output_tb->setToolTip(output_tb->toolTip() + QString(" (%1)").arg(output_tb->shortcut().toString())); find_tb->setToolTip(find_tb->toolTip() + QString(" (%1)").arg(find_tb->shortcut().toString())); + filter_tb->setToolTip(filter_tb->toolTip() + QString(" (%1)").arg(filter_tb->shortcut().toString())); results_tbw->setItemDelegate(new PlainTextItemDelegate(this, true)); - action_load=new QAction(QIcon(PgModelerUiNS::getIconPath("abrir")), trUtf8("Load"), this); - action_save=new QAction(QIcon(PgModelerUiNS::getIconPath("salvar")), trUtf8("Save"), this); - action_save_as=new QAction(QIcon(PgModelerUiNS::getIconPath("salvar_como")), trUtf8("Save as"), this); + action_load=new QAction(QIcon(PgModelerUiNs::getIconPath("abrir")), trUtf8("Load"), this); + action_save=new QAction(QIcon(PgModelerUiNs::getIconPath("salvar")), trUtf8("Save"), this); + action_save_as=new QAction(QIcon(PgModelerUiNs::getIconPath("salvar_como")), trUtf8("Save as"), this); file_menu.addAction(action_load); file_menu.addAction(action_save); file_menu.addAction(action_save_as); file_tb->setMenu(&file_menu); + filter_wgt->setVisible(false); + + connect(columns_cmb, SIGNAL(currentIndexChanged(int)), this, SLOT(filterResults())); + connect(filter_edt, SIGNAL(textChanged(QString)), this, SLOT(filterResults())); + connect(hide_tb, SIGNAL(clicked(bool)), filter_tb, SLOT(click())); + + connect(filter_tb, &QToolButton::toggled, [&](bool checked){ + filter_wgt->setVisible(checked); + + if(checked) + filter_edt->setFocus(); + else + sql_cmd_txt->setFocus(); + }); + + connect(exact_chk, SIGNAL(toggled(bool)), this, SLOT(filterResults())); + connect(exact_chk, &QCheckBox::toggled, [&](bool checked){ + regexp_chk->setChecked(false); + regexp_chk->setEnabled(!checked); + case_sensitive_chk->setChecked(false); + case_sensitive_chk->setEnabled(!checked); + }); + + connect(regexp_chk, SIGNAL(toggled(bool)), this, SLOT(filterResults())); + connect(case_sensitive_chk, SIGNAL(toggled(bool)), this, SLOT(filterResults())); + connect(action_load, SIGNAL(triggered(bool)), this, SLOT(loadCommands())); connect(action_save, SIGNAL(triggered(bool)), this, SLOT(saveCommands())); connect(action_save_as, SIGNAL(triggered(bool)), this, SLOT(saveCommands())); @@ -103,7 +132,7 @@ SQLExecutionWidget::SQLExecutionWidget(QWidget * parent) : QWidget(parent) connect(output_tb, SIGNAL(toggled(bool)), this, SLOT(toggleOutputPane(bool))); //Signal handling with C++11 lambdas Slots - connect(results_tbw, &QTableWidget::itemPressed, + connect(results_tbw, &QTableView::pressed, [&](){ SQLExecutionWidget::copySelection(results_tbw); }); connect(export_tb, &QToolButton::clicked, @@ -125,6 +154,27 @@ SQLExecutionWidget::SQLExecutionWidget(QWidget * parent) : QWidget(parent) toggleOutputPane(false); filename_wgt->setVisible(false); v_splitter->handle(1)->installEventFilter(this); + + stop_tb->setVisible(false); + sql_exec_hlp.moveToThread(&sql_exec_thread); + + connect(&sql_exec_thread, SIGNAL(started()), &sql_exec_hlp, SLOT(executeCommand())); + connect(&sql_exec_hlp, SIGNAL(s_executionFinished(int)), this, SLOT(finishExecution(int))); + connect(&sql_exec_hlp, SIGNAL(s_executionAborted(Exception)), &sql_exec_thread, SLOT(quit())); + connect(&sql_exec_hlp, SIGNAL(s_executionAborted(Exception)), this, SLOT(handleExecutionAborted(Exception))); + connect(stop_tb, SIGNAL(clicked(bool)), &sql_exec_hlp, SLOT(cancelCommand()), Qt::DirectConnection); +} + +SQLExecutionWidget::~SQLExecutionWidget(void) +{ + if(sql_exec_thread.isRunning()) + { + sql_exec_hlp.cancelCommand(); + sql_exec_thread.quit(); + sql_exec_thread.wait(); + } + + destroyResultModel(); } bool SQLExecutionWidget::eventFilter(QObject *object, QEvent *event) @@ -160,12 +210,20 @@ bool SQLExecutionWidget::eventFilter(QObject *object, QEvent *event) void SQLExecutionWidget::setConnection(Connection conn) { - sql_cmd_conn=conn; + sql_exec_hlp.setConnection(conn); + sql_cmd_conn = conn; + db_name_lbl->setText(QString("%1@%2:%3") - .arg(conn.getConnectionParam(Connection::PARAM_DB_NAME)) - .arg(conn.getConnectionParam(Connection::PARAM_SERVER_IP).isEmpty() ? - conn.getConnectionParam(Connection::PARAM_SERVER_FQDN) : conn.getConnectionParam(Connection::PARAM_SERVER_IP)) - .arg(conn.getConnectionParam(Connection::PARAM_PORT))); + .arg(conn.getConnectionParam(Connection::ParamDbName)) + .arg(conn.getConnectionParam(Connection::ParamServerIp).isEmpty() ? + conn.getConnectionParam(Connection::ParamServerFqdn) : conn.getConnectionParam(Connection::ParamServerIp)) + .arg(conn.getConnectionParam(Connection::ParamPort))); +} + +void SQLExecutionWidget::setSQLCommand(const QString &sql) +{ + sql_cmd_txt->clear(); + sql_cmd_txt->setPlainText(sql); } void SQLExecutionWidget::enableCommandButtons(void) @@ -175,24 +233,6 @@ void SQLExecutionWidget::enableCommandButtons(void) clear_btn->setEnabled(run_sql_tb->isEnabled()); } -void SQLExecutionWidget::fillResultsTable(ResultSet &res) -{ - try - { - Catalog catalog; - Connection aux_conn; - - aux_conn.setConnectionParams(sql_cmd_conn.getConnectionParams()); - export_tb->setEnabled(res.getTupleCount() > 0); - catalog.setConnection(aux_conn); - fillResultsTable(catalog, res, results_tbw); - } - catch(Exception &e) - { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); - } -} - void SQLExecutionWidget::showEvent(QShowEvent *) { sql_cmd_txt->setFocus(); @@ -215,13 +255,15 @@ void SQLExecutionWidget::resizeEvent(QResizeEvent *event) snippets_tb->setToolButtonStyle(style); export_tb->setToolButtonStyle(style); output_tb->setToolButtonStyle(style); + stop_tb->setToolButtonStyle(style); + filter_tb->setToolButtonStyle(style); } } void SQLExecutionWidget::fillResultsTable(Catalog &catalog, ResultSet &res, QTableWidget *results_tbw, bool store_data) { if(!results_tbw) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject ,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { @@ -250,15 +292,15 @@ void SQLExecutionWidget::fillResultsTable(Catalog &catalog, ResultSet &res, QTab } //Retrieving the data type names for each column - catalog.setFilter(Catalog::LIST_ALL_OBJS); + catalog.setFilter(Catalog::ListAllObjects); std::sort(type_ids.begin(), type_ids.end()); end=std::unique(type_ids.begin(), type_ids.end()); type_ids.erase(end, type_ids.end()); - types=catalog.getObjectsAttributes(OBJ_TYPE, QString(), QString(), type_ids); + types=catalog.getObjectsAttributes(ObjectType::Type, QString(), QString(), type_ids); for(auto &tp : types) - type_names[tp[ParsersAttributes::OID].toUInt()]=tp[ParsersAttributes::NAME]; + type_names[tp[Attributes::Oid].toUInt()]=tp[Attributes::Name]; catalog.setFilter(orig_filter); @@ -266,16 +308,13 @@ void SQLExecutionWidget::fillResultsTable(Catalog &catalog, ResultSet &res, QTab for(col=0; col < col_cnt; col++) { item=results_tbw->horizontalHeaderItem(col); - item->setToolTip(res.getColumnName(col) + QString(" [%1]").arg(type_names[res.getColumnTypeId(col)])); + item->setToolTip(type_names[res.getColumnTypeId(col)]); item->setData(Qt::UserRole, type_names[res.getColumnTypeId(col)]); } - if(res.accessTuple(ResultSet::FIRST_TUPLE)) + if(res.accessTuple(ResultSet::FirstTuple)) { - if(max_result_rows != 0 && res.getTupleCount() > max_result_rows) - results_tbw->setRowCount(max_result_rows); - else - results_tbw->setRowCount(res.getTupleCount()); + results_tbw->setRowCount(res.getTupleCount()); do { @@ -297,7 +336,7 @@ void SQLExecutionWidget::fillResultsTable(Catalog &catalog, ResultSet &res, QTab /* When storing column values in the QTableWidget items we need distinguish empty from null values * Since it may affect the generation of SQL like delete when the field value is used somehow (see DataManipulationForm::getDMLCommand) */ if(store_data) - item->setData(Qt::UserRole, res.isColumnValueNull(col) ? COLUMN_NULL_VALUE : item->text()); + item->setData(Qt::UserRole, res.isColumnValueNull(col) ? ColumnNullValue : item->text()); } results_tbw->setItem(row, col, item); @@ -307,7 +346,7 @@ void SQLExecutionWidget::fillResultsTable(Catalog &catalog, ResultSet &res, QTab results_tbw->setVerticalHeaderItem(row, new QTableWidgetItem(QString::number(row + 1))); row++; } - while(res.accessTuple(ResultSet::NEXT_TUPLE)); + while(res.accessTuple(ResultSet::NextTuple)); } results_tbw->setUpdatesEnabled(true); @@ -317,36 +356,155 @@ void SQLExecutionWidget::fillResultsTable(Catalog &catalog, ResultSet &res, QTab } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } -void SQLExecutionWidget::showError(Exception &e) +void SQLExecutionWidget::handleExecutionAborted(Exception e) { QString time_str=QString("[%1]:").arg(QTime::currentTime().toString(QString("hh:mm:ss.zzz"))); + switchToExecutionMode(false); msgoutput_lst->clear(); - PgModelerUiNS::createOutputListItem(msgoutput_lst, - QString("%1 %2").arg(time_str).arg(e.getErrorMessage()), - QPixmap(PgModelerUiNS::getIconPath("msgbox_erro")), false); + PgModelerUiNs::createOutputListItem(msgoutput_lst, + PgModelerUiNs::formatMessage(QString("%1 %2").arg(time_str).arg(e.getErrorMessage())), + QPixmap(PgModelerUiNs::getIconPath("msgbox_erro"))); - if(e.getErrorType()==ERR_CONNECTION_TIMEOUT || - e.getErrorType()==ERR_CONNECTION_BROKEN) + if(e.getErrorCode()==ErrorCode::ConnectionTimeout || + e.getErrorCode()==ErrorCode::ConnectionBroken) { - PgModelerUiNS::createOutputListItem(msgoutput_lst, - QString("%1 %2").arg(time_str).arg(trUtf8("No results retrieved or changes done due to the error above.")), - QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta")), false); + PgModelerUiNs::createOutputListItem(msgoutput_lst, + QString("%1 %2").arg(time_str).arg(trUtf8("No results retrieved or changes done due to the error above! Run the command again.")), + QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta")), false); } msgoutput_lst->setVisible(true); results_parent->setVisible(false); export_tb->setEnabled(false); + filter_tb->setEnabled(false); + filter_tb->setChecked(false); output_tbw->setTabText(0, trUtf8("Results")); output_tbw->setTabText(1, trUtf8("Messages (%1)").arg(msgoutput_lst->count())); output_tbw->setCurrentIndex(1); output_tbw->setTabEnabled(0, false); + + addToSQLHistory(sql_cmd_txt->toPlainText(), 0, e.getErrorMessage()); +} + +void SQLExecutionWidget::finishExecution(int rows_affected) +{ + if(sql_exec_hlp.isCancelled()) + destroyResultModel(); + else + { + bool empty = false; + ResultSetModel *res_model = sql_exec_hlp.getResultSetModel(); + + results_tbw->setSortingEnabled(false); + results_tbw->blockSignals(true); + results_tbw->setUpdatesEnabled(false); + + destroyResultModel(); + + results_tbw->setModel(res_model); + results_tbw->resizeColumnsToContents(); + results_tbw->setUpdatesEnabled(true); + results_tbw->blockSignals(false); + + filter_edt->blockSignals(true); + filter_edt->clear(); + filter_edt->blockSignals(false); + + columns_cmb->blockSignals(true); + columns_cmb->clear(); + + for(int col = 0; res_model && col < res_model->columnCount(QModelIndex()); col++) + columns_cmb->addItem(res_model->headerData(col, Qt::Horizontal, Qt::DisplayRole).toString()); + + columns_cmb->blockSignals(false); + + end_exec=QDateTime::currentDateTime().toMSecsSinceEpoch(); + total_exec = end_exec - start_exec; + + addToSQLHistory(sql_cmd_txt->toPlainText(), rows_affected); + + empty = (!res_model || res_model->rowCount() == 0); + output_tbw->setTabEnabled(0, !empty); + results_parent->setVisible(!empty); + export_tb->setEnabled(!empty); + filter_tb->setEnabled(!empty); + + if(!empty) + { + output_tbw->setTabText(0, trUtf8("Results (%1)").arg(res_model->rowCount())); + output_tbw->setCurrentIndex(0); + } + else + { + output_tbw->setTabText(0, trUtf8("Results")); + output_tbw->setCurrentIndex(1); + } + + msgoutput_lst->clear(); + + for(QString notice : sql_exec_hlp.getNotices()) + { + PgModelerUiNs::createOutputListItem(msgoutput_lst, + QString("[%1]: %2").arg(QTime::currentTime().toString(QString("hh:mm:ss.zzz"))).arg(notice.trimmed()), + QPixmap(PgModelerUiNs::getIconPath("msgbox_alerta")), false); + } + + PgModelerUiNs::createOutputListItem(msgoutput_lst, + PgModelerUiNs::formatMessage(trUtf8("[%1]: SQL command successfully executed in %2. %3 %4") + .arg(QTime::currentTime().toString(QString("hh:mm:ss.zzz"))) + .arg(total_exec >= 1000 ? QString("%1 s").arg(total_exec/1000) : QString("%1 ms").arg(total_exec)) + .arg(!res_model ? trUtf8("Rows affected") : trUtf8("Rows retrieved")) + .arg(rows_affected)), + QPixmap(PgModelerUiNs::getIconPath("msgbox_info"))); + + output_tbw->setTabText(1, trUtf8("Messages (%1)").arg(msgoutput_lst->count())); + } + + switchToExecutionMode(false); + sql_exec_thread.quit(); +} + +void SQLExecutionWidget::filterResults(void) +{ + QModelIndexList list; + Qt::MatchFlags flags = Qt::MatchStartsWith; + int rows_cnt = results_tbw->model()->rowCount(); + + if(exact_chk->isChecked()) + flags = Qt::MatchExactly; + else if(regexp_chk->isChecked()) + flags = Qt::MatchRegExp; + else + flags = Qt::MatchContains; + + if(case_sensitive_chk->isChecked()) + flags |= Qt::MatchCaseSensitive; + + list = results_tbw->model()->match(results_tbw->model()->index(0, columns_cmb->currentIndex()), + Qt::DisplayRole, filter_edt->text(), -1, flags); + + results_tbw->blockSignals(true); + results_tbw->setUpdatesEnabled(false); + + for(int row = 0; row < rows_cnt; row++) + results_tbw->hideRow(row); + + if(!list.isEmpty()) + { + for(auto &idx : list) + results_tbw->showRow(idx.row()); + } + + results_tbw->blockSignals(false); + results_tbw->setUpdatesEnabled(true); + results_tbw->update(); } void SQLExecutionWidget::addToSQLHistory(const QString &cmd, unsigned rows, const QString &error) @@ -358,20 +516,22 @@ void SQLExecutionWidget::addToSQLHistory(const QString &cmd, unsigned rows, cons if(!cmd_history_txt->toPlainText().isEmpty()) fmt_cmd += QString("\n"); - fmt_cmd += QString("-- Executed at [%1] -- \n").arg(QDateTime::currentDateTime().toString(QString("yyyy-MM-dd hh:mm:ss.zzz"))); + fmt_cmd += QString("-- %1 [%2] -- \n") + .arg(trUtf8("Executed at")) + .arg(QDateTime::currentDateTime().toString(QString("yyyy-MM-dd hh:mm:ss.zzz"))); fmt_cmd += cmd; fmt_cmd += QChar('\n'); if(!error.isEmpty()) { - fmt_cmd += QString("-- Query failed --\n"); + fmt_cmd += QString("-- %1 --\n").arg(trUtf8("Command failed")); fmt_cmd += QString("/*\n%1\n*/\n").arg(error); } else - fmt_cmd += QString("-- Rows retrieved: %1\n").arg(rows); + fmt_cmd += QString("-- %1 %2\n").arg(trUtf8("Rows:")).arg(rows); - if(!fmt_cmd.trimmed().endsWith(ParsersAttributes::DDL_END_TOKEN)) - fmt_cmd += ParsersAttributes::DDL_END_TOKEN + QChar('\n'); + if(!fmt_cmd.trimmed().endsWith(Attributes::DdlEndToken)) + fmt_cmd += Attributes::DdlEndToken + QChar('\n'); SQLExecutionWidget::validateSQLHistoryLength(sql_cmd_conn.getConnectionId(true,true), fmt_cmd, cmd_history_txt); } @@ -390,7 +550,7 @@ void SQLExecutionWidget::validateSQLHistoryLength(const QString &conn_id, const { QStringList buffer = cmds.split(QChar('\n')); cmds = buffer.mid(buffer.size()/2).join(QChar('\n')); - cmds = cmds.mid(cmds.indexOf(ParsersAttributes::DDL_END_TOKEN) + ParsersAttributes::DDL_END_TOKEN.length()); + cmds = cmds.mid(cmds.indexOf(Attributes::DdlEndToken) + Attributes::DdlEndToken.length()); cmd_history[conn_id] = cmds.trimmed(); if(cmd_history_txt) @@ -406,90 +566,71 @@ void SQLExecutionWidget::validateSQLHistoryLength(const QString &conn_id, const cmd_history_txt->appendPlainText(fmt_cmd); } -void SQLExecutionWidget::runSQLCommand(void) +void SQLExecutionWidget::switchToExecutionMode(bool value) { - QString cmd=sql_cmd_txt->textCursor().selectedText(); - - try + run_sql_tb->setVisible(!value); + stop_tb->setVisible(value); + file_tb->setEnabled(!value); + find_tb->setEnabled(!value); + clear_btn->setEnabled(!value); + snippets_tb->setEnabled(!value); + export_tb->setEnabled(!value); + output_tb->setEnabled(!value); + sql_cmd_txt->setEnabled(!value); + cmd_history_parent->setEnabled(!value); + find_history_parent->setEnabled(!value); + filter_tb->setEnabled(!value); + + if(value) { - ResultSet res; - QStringList conn_notices; - - output_tb->setChecked(true); - - if(cmd.isEmpty()) - cmd=sql_cmd_txt->toPlainText(); - else - cmd.replace(QChar::ParagraphSeparator, '\n'); - - msgoutput_lst->clear(); - - if(!sql_cmd_conn.isStablished()) - { - sql_cmd_conn.setNoticeEnabled(true); - sql_cmd_conn.connect(); - - //The connection will break the execution if it keeps idle for one hour or more - sql_cmd_conn.setSQLExecutionTimout(3600); - } - - QApplication::setOverrideCursor(Qt::WaitCursor); - sql_cmd_conn.executeDMLCommand(cmd, res); - conn_notices=sql_cmd_conn.getNotices(); - - addToSQLHistory(cmd, res.getTupleCount()); - - output_tbw->setTabEnabled(0, !res.isEmpty()); - results_parent->setVisible(!res.isEmpty()); - export_tb->setEnabled(!res.isEmpty()); - - if(!res.isEmpty()) - { - fillResultsTable(res); - output_tbw->setTabText(0, trUtf8("Results (%1)").arg(results_tbw->rowCount())); + this->setCursor(Qt::WaitCursor); + sql_cmd_txt->setCursor(Qt::WaitCursor); + sql_cmd_txt->clearFocus(); + } + else + { + this->setCursor(Qt::ArrowCursor); + sql_cmd_txt->setCursor(Qt::ArrowCursor); + sql_cmd_txt->setFocus(); + } +} - if(res.getTupleCount() > max_result_rows) - { - conn_notices.append(trUtf8("The number of retrieved rows exceeds the maximum allowed in the results grid! The data was trucated.")); - conn_notices.append(trUtf8("Try to limit the result set by adjusting the query.")); - output_tbw->setCurrentIndex(1); - } - else - output_tbw->setCurrentIndex(0); - } - else - { - output_tbw->setTabText(0, trUtf8("Results")); - output_tbw->setCurrentIndex(1); - } +void SQLExecutionWidget::destroyResultModel(void) +{ + if(results_tbw->model()) + { + ResultSetModel *result_model = dynamic_cast(results_tbw->model()); + results_tbw->blockSignals(true); + results_tbw->setModel(nullptr); + delete(result_model); + results_tbw->blockSignals(false); + } +} - msgoutput_lst->clear(); +void SQLExecutionWidget::runSQLCommand(void) +{ + QString cmd=sql_cmd_txt->textCursor().selectedText(); - for(QString notice : conn_notices) - { - PgModelerUiNS::createOutputListItem(msgoutput_lst, - PgModelerUiNS::formatMessage(QString("[%1]: %2").arg(QTime::currentTime().toString(QString("hh:mm:ss.zzz"))).arg(notice)), - QPixmap(PgModelerUiNS::getIconPath("msgbox_alerta"))); - } + output_tb->setChecked(true); - PgModelerUiNS::createOutputListItem(msgoutput_lst, - PgModelerUiNS::formatMessage(trUtf8("[%1]: SQL command successfully executed. %2 %3") - .arg(QTime::currentTime().toString(QString("hh:mm:ss.zzz"))) - .arg(res.isEmpty() ? trUtf8("Rows affected") : trUtf8("Rows retrieved")) - .arg(res.getTupleCount())), - QPixmap(PgModelerUiNS::getIconPath("msgbox_info"))); + if(cmd.isEmpty()) + cmd=sql_cmd_txt->toPlainText(); + else + cmd.replace(QChar::ParagraphSeparator, '\n'); - output_tbw->setTabText(1, trUtf8("Messages (%1)").arg(msgoutput_lst->count())); + msgoutput_lst->clear(); + sql_exec_hlp.setCommand(cmd); + start_exec=QDateTime::currentDateTime().toMSecsSinceEpoch(); + sql_exec_thread.start(); + switchToExecutionMode(true); - QApplication::restoreOverrideCursor(); - } - catch(Exception &e) - { - addToSQLHistory(cmd, 0, e.getErrorMessage()); - QApplication::restoreOverrideCursor(); - sql_cmd_conn.close(); - showError(e); - } + output_tbw->setTabEnabled(0, false); + output_tbw->setTabText(0, trUtf8("Results")); + output_tbw->setCurrentIndex(1); + PgModelerUiNs::createOutputListItem(msgoutput_lst, + trUtf8("[%1]: SQL command is running...") + .arg(QTime::currentTime().toString(QString("hh:mm:ss.zzz"))), + QPixmap(PgModelerUiNs::getIconPath("msgbox_info")), false); } void SQLExecutionWidget::saveCommands(void) @@ -515,8 +656,8 @@ void SQLExecutionWidget::saveCommands(void) file.setFileName(filename); if(!file.open(QFile::WriteOnly)) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED).arg(filename), - ERR_FILE_DIR_NOT_ACCESSED ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed).arg(filename), + ErrorCode::FileDirectoryNotAccessed ,__PRETTY_FUNCTION__,__FILE__,__LINE__); file.write(sql_cmd_txt->toPlainText().toUtf8()); file.close(); @@ -538,9 +679,9 @@ void SQLExecutionWidget::loadCommands(void) file.setFileName(sql_file_dlg.selectedFiles().at(0)); if(!file.open(QFile::ReadOnly)) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED) - .arg(sql_file_dlg.selectedFiles().at(0)) - ,ERR_FILE_DIR_NOT_ACCESSED ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed) + .arg(sql_file_dlg.selectedFiles().at(0)), + ErrorCode::FileDirectoryNotAccessed ,__PRETTY_FUNCTION__,__FILE__,__LINE__); sql_cmd_txt->clear(); sql_cmd_txt->setPlainText(file.readAll()); @@ -551,10 +692,10 @@ void SQLExecutionWidget::loadCommands(void) } } -void SQLExecutionWidget::exportResults(QTableWidget *results_tbw) +void SQLExecutionWidget::exportResults(QTableView *results_tbw) { if(!results_tbw) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject ,__PRETTY_FUNCTION__,__FILE__,__LINE__); QFileDialog csv_file_dlg; @@ -573,129 +714,127 @@ void SQLExecutionWidget::exportResults(QTableWidget *results_tbw) file.setFileName(csv_file_dlg.selectedFiles().at(0)); if(!file.open(QFile::WriteOnly)) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED) - .arg(csv_file_dlg.selectedFiles().at(0)) - , ERR_FILE_DIR_NOT_ACCESSED ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed) + .arg(csv_file_dlg.selectedFiles().at(0)), + ErrorCode::FileDirectoryNotAccessed ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + + QApplication::setOverrideCursor(Qt::WaitCursor); + results_tbw->setUpdatesEnabled(false); + results_tbw->blockSignals(true); + results_tbw->selectAll(); - file.write(generateCSVBuffer(results_tbw, 0, 0, results_tbw->rowCount(), results_tbw->columnCount())); + file.write(generateCSVBuffer(results_tbw)); file.close(); - } -} -void SQLExecutionWidget::setMaxResultRows(int max_val) -{ - max_result_rows = (max_val < 0 ? 0 : max_val); + results_tbw->clearSelection(); + results_tbw->blockSignals(false); + results_tbw->setUpdatesEnabled(true); + QApplication::restoreOverrideCursor(); + } } -int SQLExecutionWidget::getMaxResultRows(void) +int SQLExecutionWidget::clearAll(void) { - return(max_result_rows); -} + Messagebox msg_box; + int res = 0; -QByteArray SQLExecutionWidget::generateCSVBuffer(QTableWidget *results_tbw, int start_row, int start_col, int row_cnt, int col_cnt) -{ - if(!results_tbw) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + msg_box.show(trUtf8("The SQL input field and the results grid will be cleared! Want to proceed?"), + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); - QByteArray buf; - QStringList line; + res = msg_box.result(); - //If the selection interval is valid - if(start_row >=0 && start_col >=0 && - start_row + row_cnt <= results_tbw->rowCount() && - start_col + col_cnt <= results_tbw->columnCount()) + if(res==QDialog::Accepted) { - int col=0, row=0, - max_col=start_col + col_cnt, - max_row=start_row + row_cnt; - - //Creating the header of csv - for(col=start_col; col < max_col; col++) - line.append(QString("\"%1\"").arg(results_tbw->horizontalHeaderItem(col)->text())); - - buf.append(line.join(';')); - buf.append('\n'); - line.clear(); + sql_cmd_txt->setPlainText(QString()); + msgoutput_lst->clear(); + msgoutput_lst->setVisible(true); + results_parent->setVisible(false); + export_tb->setEnabled(false); + } - //Creating the content - for(row=start_row; row < max_row; row++) - { - for(col=start_col; col < max_col; col++) - line.append(QString("\"%1\"").arg(results_tbw->item(row, col)->text())); + return(res); +} - buf.append(line.join(';')); - line.clear(); - buf.append('\n'); - } - } +QByteArray SQLExecutionWidget::generateCSVBuffer(QTableView *results_tbw) +{ + return(generateBuffer(results_tbw, QChar(';'), true, true)); +} - return(buf); +QByteArray SQLExecutionWidget::generateTextBuffer(QTableView *results_tbw) +{ + return(generateBuffer(results_tbw, QChar('\t'), false, false)); } -QByteArray SQLExecutionWidget::generateTextBuffer(QTableWidget *results_tbw, int start_row, int start_col, int row_cnt, int col_cnt) +QByteArray SQLExecutionWidget::generateBuffer(QTableView *results_tbw, QChar separator, bool incl_col_names, bool use_quotes) { if(!results_tbw) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(!results_tbw->selectionModel()) + return (QByteArray()); + + QAbstractItemModel *model = results_tbw->model(); + QModelIndexList sel_indexes = results_tbw->selectionModel()->selectedIndexes(); QByteArray buf; QStringList line; + QModelIndex index; + QString str_pattern = use_quotes ? QString("\"%1\"") : QString("%1"); + int start_row = -1, start_col = -1, + row_cnt = 0, col_cnt = 0; - //If the selection interval is valid - if(start_row >=0 && start_col >=0 && - start_row + row_cnt <= results_tbw->rowCount() && - start_col + col_cnt <= results_tbw->columnCount()) - { - int col=0, row=0, - max_col=start_col + col_cnt, - max_row=start_row + row_cnt; + start_row = sel_indexes.at(0).row(); + start_col = sel_indexes.at(0).column(); + row_cnt = (sel_indexes.last().row() - start_row) + 1; + col_cnt = (sel_indexes.last().column() - start_col) + 1; + + int col=0, row=0, + max_col=start_col + col_cnt, + max_row=start_row + row_cnt; - //Creating the content - for(row=start_row; row < max_row; row++) + if(incl_col_names) + { + //Creating the header + for(col=start_col; col < max_col; col++) { - for(col=start_col; col < max_col; col++) - { - line.push_back(results_tbw->item(row, col)->text()); - } + if(results_tbw->isColumnHidden(col)) + continue; - buf.append(line.join('\t')); - line.clear(); - buf.append('\n'); + line.append(str_pattern.arg(model->headerData(col, Qt::Horizontal).toString())); } - } - - return(buf); -} -int SQLExecutionWidget::clearAll(void) -{ - Messagebox msg_box; - int res = 0; + buf.append(line.join(separator)); + buf.append('\n'); + line.clear(); + } - msg_box.show(trUtf8("The SQL input field and the results grid will be cleared! Want to proceed?"), - Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + //Creating the content + for(row=start_row; row < max_row; row++) + { + for(col=start_col; col < max_col; col++) + { + if(results_tbw->isColumnHidden(col)) + continue; - res = msg_box.result(); + index = model->index(row, col); + line.append(str_pattern.arg(index.data().toString())); + } - if(res==QDialog::Accepted) - { - sql_cmd_txt->setPlainText(QString()); - msgoutput_lst->clear(); - msgoutput_lst->setVisible(true); - results_parent->setVisible(false); - export_tb->setEnabled(false); + buf.append(line.join(separator)); + line.clear(); + buf.append('\n'); } - return(res); + return(buf); } -void SQLExecutionWidget::copySelection(QTableWidget *results_tbw, bool use_popup, bool csv_is_default) +void SQLExecutionWidget::copySelection(QTableView *results_tbw, bool use_popup, bool csv_is_default) { if(!results_tbw) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject ,__PRETTY_FUNCTION__,__FILE__,__LINE__); - QList sel_ranges=results_tbw->selectedRanges(); + QItemSelectionModel *selection = results_tbw->selectionModel(); - if(sel_ranges.count()==1 && (!use_popup || (use_popup && QApplication::mouseButtons()==Qt::RightButton))) + if(selection && (!use_popup || (use_popup && QApplication::mouseButtons()==Qt::RightButton))) { QMenu copy_menu, copy_mode_menu; QAction *act = nullptr, *act_csv = nullptr, *act_txt = nullptr; @@ -711,25 +850,16 @@ void SQLExecutionWidget::copySelection(QTableWidget *results_tbw, bool use_popup if(!use_popup || act) { - QTableWidgetSelectionRange selection=sel_ranges.at(0); QByteArray buf; if((use_popup && act == act_csv) || (!use_popup && csv_is_default)) { //Generates the csv buffer and assigns it to application's clipboard - buf=generateCSVBuffer(results_tbw, - selection.topRow(), selection.leftColumn(), - selection.rowCount(), selection.columnCount()); - - /* Making DataManipulationForm instances know that the clipboard has csv buffer - * in order to paste the contents properly */ - DataManipulationForm::setHasCsvClipboard(true); + buf=generateCSVBuffer(results_tbw); } else if((use_popup && act == act_txt) || (!use_popup && !csv_is_default)) { - buf=generateTextBuffer(results_tbw, - selection.topRow(), selection.leftColumn(), - selection.rowCount(), selection.columnCount()); + buf=generateTextBuffer(results_tbw); } qApp->clipboard()->setText(buf); @@ -786,44 +916,44 @@ void SQLExecutionWidget::saveSQLHistory(void) for(auto hist : cmd_history) { - attribs[ParsersAttributes::CONNECTION] = hist.first; - attribs[ParsersAttributes::COMMANDS] = hist.second; + attribs[Attributes::Connection] = hist.first; + attribs[Attributes::Commands] = hist.second; schparser.ignoreEmptyAttributes(true); - commands += schparser.getCodeDefinition(GlobalAttributes::TMPL_CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::SCHEMAS_DIR + - GlobalAttributes::DIR_SEPARATOR + - ParsersAttributes::COMMANDS + - GlobalAttributes::SCHEMA_EXT, attribs); + commands += schparser.getCodeDefinition(GlobalAttributes::TmplConfigurationDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::SchemasDir + + GlobalAttributes::DirSeparator + + Attributes::Commands + + GlobalAttributes::SchemaExt, attribs); } - schparser.loadFile(GlobalAttributes::TMPL_CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::SCHEMAS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::SQL_HISTORY_CONF + - GlobalAttributes::SCHEMA_EXT); + schparser.loadFile(GlobalAttributes::TmplConfigurationDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::SchemasDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::SQLHistoryConf + + GlobalAttributes::SchemaExt); attribs.clear(); - attribs[ParsersAttributes::COMMANDS] = commands; + attribs[Attributes::Commands] = commands; buffer.append(schparser.getCodeDefinition(attribs)); - file.setFileName(GlobalAttributes::CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::SQL_HISTORY_CONF + - GlobalAttributes::CONFIGURATION_EXT); + file.setFileName(GlobalAttributes::ConfigurationsDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::SQLHistoryConf + + GlobalAttributes::ConfigurationExt); if(!file.open(QFile::WriteOnly)) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED).arg(file.fileName()), - ERR_FILE_DIR_NOT_ACCESSED, __PRETTY_FUNCTION__, __FILE__ ,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed).arg(file.fileName()), + ErrorCode::FileDirectoryNotAccessed, __PRETTY_FUNCTION__, __FILE__ ,__LINE__); file.write(buffer); file.close(); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -831,45 +961,45 @@ void SQLExecutionWidget::loadSQLHistory(void) { try { - XMLParser xmlparser; + XmlParser xmlparser; attribs_map attribs; - xmlparser.setDTDFile(GlobalAttributes::TMPL_CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::OBJECT_DTD_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::SQL_HISTORY_CONF + - GlobalAttributes::OBJECT_DTD_EXT, - GlobalAttributes::SQL_HISTORY_CONF); + xmlparser.setDTDFile(GlobalAttributes::TmplConfigurationDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::ObjectDTDDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::SQLHistoryConf + + GlobalAttributes::ObjectDTDExt, + GlobalAttributes::SQLHistoryConf); - xmlparser.loadXMLFile(GlobalAttributes::CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::SQL_HISTORY_CONF + - GlobalAttributes::CONFIGURATION_EXT); + xmlparser.loadXMLFile(GlobalAttributes::ConfigurationsDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::SQLHistoryConf + + GlobalAttributes::ConfigurationExt); cmd_history.clear(); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { - if(xmlparser.getElementName() == ParsersAttributes::COMMANDS) + if(xmlparser.getElementName() == Attributes::Commands) { xmlparser.getElementAttributes(attribs); xmlparser.savePosition(); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) - cmd_history[attribs[ParsersAttributes::CONNECTION]].append(xmlparser.getElementContent()); + if(xmlparser.accessElement(XmlParser::ChildElement)) + cmd_history[attribs[Attributes::Connection]].append(xmlparser.getElementContent()); xmlparser.restorePosition(); } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -878,14 +1008,14 @@ void SQLExecutionWidget::destroySQLHistory(void) Messagebox msg_box; msg_box.show(trUtf8("This action will wipe out all the SQL commands history for all connections! Do you really want to proceed?"), - Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); if(msg_box.result() == QDialog::Accepted) { - QFile::remove(GlobalAttributes::CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::SQL_HISTORY_CONF + - GlobalAttributes::CONFIGURATION_EXT); + QFile::remove(GlobalAttributes::ConfigurationsDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::SQLHistoryConf + + GlobalAttributes::ConfigurationExt); SQLExecutionWidget::cmd_history.clear(); } @@ -893,7 +1023,7 @@ void SQLExecutionWidget::destroySQLHistory(void) void SQLExecutionWidget::setSQLHistoryMaxLength(int len) { - if(len < 100 || len > 2000) + if(len < 1000 || len > 20000) len = 1000; SQLExecutionWidget::cmd_history_max_len = len; @@ -917,21 +1047,21 @@ void SQLExecutionWidget::enableSQLExecution(bool enable) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void SQLExecutionWidget::showHistoryContextMenu(void) { QMenu *ctx_menu=cmd_history_txt->createStandardContextMenu(); - QAction *action_clear = new QAction(QPixmap(PgModelerUiNS::getIconPath("limpartexto")), trUtf8("Clear history"), ctx_menu), - *action_save = new QAction(QPixmap(PgModelerUiNS::getIconPath("salvar")), trUtf8("Save history"), ctx_menu), - *action_reload = new QAction(QPixmap(PgModelerUiNS::getIconPath("atualizar")), trUtf8("Reload history"), ctx_menu), + QAction *action_clear = new QAction(QPixmap(PgModelerUiNs::getIconPath("limpartexto")), trUtf8("Clear history"), ctx_menu), + *action_save = new QAction(QPixmap(PgModelerUiNs::getIconPath("salvar")), trUtf8("Save history"), ctx_menu), + *action_reload = new QAction(QPixmap(PgModelerUiNs::getIconPath("atualizar")), trUtf8("Reload history"), ctx_menu), *action_toggle_find = nullptr, *exec_act = nullptr; if(!find_history_parent->isVisible()) - action_toggle_find = new QAction(QPixmap(PgModelerUiNS::getIconPath("buscar")), trUtf8("Find in history"), ctx_menu); + action_toggle_find = new QAction(QPixmap(PgModelerUiNs::getIconPath("buscar")), trUtf8("Find in history"), ctx_menu); else action_toggle_find = new QAction(trUtf8("Hide find tool"), ctx_menu); @@ -949,7 +1079,7 @@ void SQLExecutionWidget::showHistoryContextMenu(void) Messagebox msg_box; msg_box.show(trUtf8("This action will wipe out all the SQL commands history for the current connection! Do you really want to proceed?"), - Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); if(msg_box.result() == QDialog::Accepted) { diff --git a/libpgmodeler_ui/src/sqlexecutionwidget.h b/libpgmodeler_ui/src/sqlexecutionwidget.h index 8257fc1352..d8559b2c95 100644 --- a/libpgmodeler_ui/src/sqlexecutionwidget.h +++ b/libpgmodeler_ui/src/sqlexecutionwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -33,6 +33,8 @@ #include "codecompletionwidget.h" #include "numberedtexteditor.h" #include "findreplacewidget.h" +#include "resultsetmodel.h" +#include "sqlexecutionhelper.h" class SQLExecutionWidget: public QWidget, public Ui::SQLExecutionWidget { private: @@ -42,14 +44,14 @@ class SQLExecutionWidget: public QWidget, public Ui::SQLExecutionWidget { static int cmd_history_max_len; - /*! \brief The maximum amount of rows allowed to the results grid. - * This attribute is used to limit the amount of rows inserted in any QTableWidget instance - * by fillResultsTable() in order to avoid memory exhaustion leading to crash depending on - * the amount of rows stored in a result set */ - static int max_result_rows; + qint64 start_exec, end_exec, total_exec; SchemaParser schparser; + QThread sql_exec_thread; + + SQLExecutionHelper sql_exec_hlp; + //! \brief Syntax highlighter for sql input field SyntaxHighlighter *sql_cmd_hl, @@ -81,13 +83,11 @@ class SQLExecutionWidget: public QWidget, public Ui::SQLExecutionWidget { //! \brief Stores the command on the sql command history void addToSQLHistory(const QString &cmd, unsigned rows=0, const QString &error=QString()); - //! \brief Show the exception message in the output widget - void showError(Exception &e); + static void validateSQLHistoryLength(const QString &conn_id, const QString &fmt_cmd = QString(), NumberedTextEditor *cmd_history_txt = nullptr); - //! \brief Fills the result grid with the specified result set - void fillResultsTable(ResultSet &res); + void switchToExecutionMode(bool value); - static void validateSQLHistoryLength(const QString &conn_id, const QString &fmt_cmd = QString(), NumberedTextEditor *cmd_history_txt = nullptr); + void destroyResultModel(void); protected: //! \brief Widget that serves as SQL commands input @@ -100,35 +100,35 @@ class SQLExecutionWidget: public QWidget, public Ui::SQLExecutionWidget { bool eventFilter(QObject *object, QEvent *event); public: - static const QString COLUMN_NULL_VALUE; + static const QString ColumnNullValue; - SQLExecutionWidget(QWidget * parent = 0); + SQLExecutionWidget(QWidget * parent = nullptr); + ~SQLExecutionWidget(void); //! \brief Configures the connection to query the server void setConnection(Connection conn); + //! \brief Insert the provided sql commands in the input field. This method clears the current commands before adding new content + void setSQLCommand(const QString &sql); + /*! \brief Fills up the results grid based upon the specified result set. The parameter store_data will make each item store the text as its data */ static void fillResultsTable(Catalog &catalog, ResultSet &res, QTableWidget *results_tbw, bool store_data=false); //! \brief Copy to clipboard (in csv format) the current selected items on results grid - static void copySelection(QTableWidget *results_tbw, bool use_popup=true, bool csv_is_default = false); + static void copySelection(QTableView *results_tbw, bool use_popup=true, bool csv_is_default = false); //! \brief Generates a CSV buffer based upon the selection on the results grid - static QByteArray generateCSVBuffer(QTableWidget *results_tbw, int start_row, int start_col, int row_cnt, int col_cnt); + static QByteArray generateCSVBuffer(QTableView *results_tbw); //! \brief Generates a Plain text buffer based upon the selection on the results grid (this method does not include the column names) - static QByteArray generateTextBuffer(QTableWidget *results_tbw, int start_row, int start_col, int row_cnt, int col_cnt); - - //! \brief Exports the results to csv file - static void exportResults(QTableWidget *results_tbw); + static QByteArray generateTextBuffer(QTableView *results_tbw); - static void setMaxResultRows(int max_val); + //! \brief Generates a custom text buffer. User can specify a separator for columns, include column names and quote values + static QByteArray generateBuffer(QTableView *results_tbw, QChar separator, bool incl_col_names, bool use_quotes); - static int getMaxResultRows(void); - - public slots: - void configureSnippets(void); + //! \brief Exports the results to csv file + static void exportResults(QTableView *results_tbw); //! \brief Save the history of all connections open in the SQL Execution to the sql-history.conf static void saveSQLHistory(void); @@ -142,6 +142,12 @@ class SQLExecutionWidget: public QWidget, public Ui::SQLExecutionWidget { static int getSQLHistoryMaxLength(void); + public slots: + void configureSnippets(void); + + //! \brief Show the exception message in the output widget + void handleExecutionAborted(Exception e); + private slots: //! \brief Enables the command buttons when user fills the sql field void enableCommandButtons(void); @@ -164,6 +170,10 @@ class SQLExecutionWidget: public QWidget, public Ui::SQLExecutionWidget { void showHistoryContextMenu(void); + void finishExecution(int rows_affected = 0); + + void filterResults(void); + friend class SQLToolWidget; }; diff --git a/libpgmodeler_ui/src/sqltoolwidget.cpp b/libpgmodeler_ui/src/sqltoolwidget.cpp index 906b9564a8..7c803e7b6d 100644 --- a/libpgmodeler_ui/src/sqltoolwidget.cpp +++ b/libpgmodeler_ui/src/sqltoolwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,10 +18,9 @@ #include "sqltoolwidget.h" #include "taskprogresswidget.h" -#include "databaseexplorerwidget.h" #include "snippetsconfigwidget.h" -#include "sqlexecutionwidget.h" #include "connectionsconfigwidget.h" +#include "pgmodeleruins.h" SQLToolWidget::SQLToolWidget(QWidget * parent) : QWidget(parent) { @@ -29,15 +28,22 @@ SQLToolWidget::SQLToolWidget(QWidget * parent) : QWidget(parent) h_splitter->setSizes({315, 10000}); h_splitter->handle(1)->installEventFilter(this); - v_splitter->setSizes({1000, 400}); + sql_exec_corner_btn = new QToolButton; + sql_exec_corner_btn->setIcon(QPixmap(PgModelerUiNs::getIconPath("newtab"))); + sql_exec_corner_btn->setIconSize(QSize(18, 18)); + sql_exec_corner_btn->setStyleSheet("QToolButton { margin-left: 4px; margin-bottom: 4px; padding: 2px; }"); + sql_exec_corner_btn->setShortcut(QKeySequence("Ctrl+T")); + sql_exec_corner_btn->setToolTip(trUtf8("Add a new execution tab for the current database (%1)").arg(sql_exec_corner_btn->shortcut().toString())); + sql_exec_tbw->setCornerWidget(sql_exec_corner_btn, Qt::TopRightCorner); + QVBoxLayout *vbox=new QVBoxLayout; sourcecode_txt=new NumberedTextEditor(sourcecode_gb); sourcecode_txt->setReadOnly(true); sourcecode_hl=new SyntaxHighlighter(sourcecode_txt); - sourcecode_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + sourcecode_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); vbox->setContentsMargins(4,4,4,4); vbox->addWidget(sourcecode_txt); @@ -50,6 +56,7 @@ SQLToolWidget::SQLToolWidget(QWidget * parent) : QWidget(parent) connect(database_cmb, SIGNAL(activated(int)), this, SLOT(browseDatabase())); connect(disconnect_tb, SIGNAL(clicked()), this, SLOT(disconnectFromDatabases())); connect(source_pane_tb, SIGNAL(toggled(bool)), sourcecode_gb, SLOT(setVisible(bool))); + connect(sql_exec_corner_btn, SIGNAL(clicked(bool)), this, SLOT(addSQLExecutionTab())); connect(databases_tbw, &QTabWidget::currentChanged, [&](){ @@ -60,7 +67,7 @@ SQLToolWidget::SQLToolWidget(QWidget * parent) : QWidget(parent) if(dbexplorer && dbexplorer->objects_trw->currentItem()) sourcecode_txt->setPlainText(dbexplorer->objects_trw->currentItem()-> - data(DatabaseImportForm::OBJECT_SOURCE, Qt::UserRole).toString()); + data(DatabaseImportForm::ObjectSource, Qt::UserRole).toString()); while(itr != sql_exec_wgts.end()) { @@ -72,7 +79,7 @@ SQLToolWidget::SQLToolWidget(QWidget * parent) : QWidget(parent) else { for(auto &wgt : itr.value()) - sql_exec_tbw->addTab(wgt, dbexplorer->getConnection().getConnectionParam(Connection::PARAM_DB_NAME)); + sql_exec_tbw->addTab(wgt, dbexplorer->getConnection().getConnectionParam(Connection::ParamDbName)); } itr++; @@ -163,7 +170,7 @@ void SQLToolWidget::connectToServer(void) if(sender()==connections_cmb && conn->isAutoBrowseDB()) { - database_cmb->setCurrentText(conn->getConnectionParam(Connection::PARAM_DB_NAME)); + database_cmb->setCurrentText(conn->getConnectionParam(Connection::ParamDbName)); browseDatabase(); } } @@ -174,7 +181,7 @@ void SQLToolWidget::connectToServer(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -186,7 +193,7 @@ void SQLToolWidget::disconnectFromDatabases(void) msg_box.show(trUtf8("Warning"), trUtf8("ATTENTION: Disconnect from all databases will close any opened tab in this view! Do you really want to proceed?"), - Messagebox::ALERT_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::AlertIcon, Messagebox::YesNoButtons); if(msg_box.result()==QDialog::Accepted) { @@ -208,7 +215,7 @@ void SQLToolWidget::disconnectFromDatabases(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -230,27 +237,30 @@ void SQLToolWidget::handleDatabaseDropped(const QString &dbname) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } -void SQLToolWidget::browseDatabase(void) +DatabaseExplorerWidget *SQLToolWidget::browseDatabase(void) { try { + DatabaseExplorerWidget *db_explorer_wgt=nullptr; + //If the selected database is already being browse do not create another explorer instance if(database_cmb->currentIndex() > 0) { Connection conn=(*reinterpret_cast(connections_cmb->itemData(connections_cmb->currentIndex()).value())); - QString maintainance_db=conn.getConnectionParam(Connection::PARAM_DB_NAME); - DatabaseExplorerWidget *db_explorer_wgt=new DatabaseExplorerWidget; + QString maintainance_db=conn.getConnectionParam(Connection::ParamDbName); + db_explorer_wgt=new DatabaseExplorerWidget; db_explorer_wgt->setObjectName(database_cmb->currentText()); - conn.setConnectionParam(Connection::PARAM_DB_NAME, database_cmb->currentText()); + conn.setConnectionParam(Connection::ParamDbName, database_cmb->currentText()); db_explorer_wgt->setConnection(conn, maintainance_db); db_explorer_wgt->listObjects(); databases_tbw->addTab(db_explorer_wgt, database_cmb->currentText()); + databases_tbw->setTabToolTip(databases_tbw->count() - 1, db_explorer_wgt->getConnection().getConnectionId(true, true)); databases_tbw->setCurrentWidget(db_explorer_wgt); connect(db_explorer_wgt, SIGNAL(s_databaseDropped(QString)), this, SLOT(handleDatabaseDropped(QString))); @@ -265,40 +275,101 @@ void SQLToolWidget::browseDatabase(void) new tab on the map of sql panes related to the database explorer */ db_explorer_wgt->runsql_tb->click(); } + + return(db_explorer_wgt); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } -void SQLToolWidget::addSQLExecutionTab(void) +SQLExecutionWidget *SQLToolWidget::addSQLExecutionTab(void) { try { SQLExecutionWidget *sql_exec_wgt=new SQLExecutionWidget; - DatabaseExplorerWidget *db_explorer_wgt=dynamic_cast(sender()); - Connection conn=db_explorer_wgt->getConnection(); + DatabaseExplorerWidget *db_explorer_wgt=dynamic_cast(databases_tbw->currentWidget()); + Connection conn; + if(!db_explorer_wgt) + return(nullptr); + + conn = db_explorer_wgt->getConnection(); sql_exec_wgt->setConnection(conn); - sql_exec_tbw->addTab(sql_exec_wgt, conn.getConnectionParam(Connection::PARAM_DB_NAME)); + sql_exec_tbw->addTab(sql_exec_wgt, conn.getConnectionParam(Connection::ParamDbName)); sql_exec_tbw->setCurrentWidget(sql_exec_wgt); sql_exec_tbw->currentWidget()->layout()->setContentsMargins(4,4,4,4); sql_exec_wgts[db_explorer_wgt].push_back(sql_exec_wgt); + + return(sql_exec_wgt); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } +void SQLToolWidget::addSQLExecutionTab(const QString &conn_id, const QString &database, const QString &sql_file) +{ + map conns; + SQLExecutionWidget *sql_exec_wgt = nullptr; + DatabaseExplorerWidget *db_explorer_wgt = nullptr; + QFile file; + + if(!ConnectionsConfigWidget::getConnection(conn_id)) + { + throw Exception(trUtf8("Failed to load the file `%1' in SQL tool because the connection ID `%2' was not found!") + .arg(sql_file).arg(conn_id), + ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + else if(!QFileInfo(sql_file).exists()) + { + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed).arg(sql_file), + ErrorCode::FileDirectoryNotAccessed,__PRETTY_FUNCTION__,__FILE__,__LINE__); + } + + // Connect to the server using the provided connection id + connections_cmb->setCurrentText(conn_id); + connectToServer(); + + // Browse the database and retrive the database explorer instace generated + database_cmb->setCurrentText(database); + db_explorer_wgt = browseDatabase(); + + /* Now we get the sql execution widget created from the previous operation + * in order to load the sql file there */ + sql_exec_wgt = dynamic_cast(sql_exec_wgts[db_explorer_wgt].at(0)); + + file.setFileName(sql_file); + file.open(QFile::ReadOnly); + sql_exec_wgt->setSQLCommand(file.readAll()); + file.close(); +} + void SQLToolWidget::closeDatabaseExplorer(int idx) { DatabaseExplorerWidget *db_explorer=dynamic_cast(databases_tbw->widget(idx)); + /* Display a message box confirming the database explorer tab only if the user + * click the close button on the DatabaseExplorerWidget instance */ + if(sender() == databases_tbw) + { + Messagebox msg_box; + msg_box.show(trUtf8("Warning"), + trUtf8("ATTENTION: Close the database being browsed will close any opened SQL execution pane related to it! Do you really want to proceed?"), + Messagebox::AlertIcon, Messagebox::YesNoButtons); + + if(msg_box.result() != QDialog::Accepted) + return; + } + //Closing sql execution tabs related to the database to be closed for(QWidget *wgt : sql_exec_wgts[db_explorer]) + { sql_exec_tbw->removeTab(sql_exec_tbw->indexOf(wgt)); + delete(wgt); + } sql_exec_wgts.remove(db_explorer); databases_tbw->removeTab(idx); @@ -331,6 +402,7 @@ void SQLToolWidget::closeSQLExecutionTab(int idx) if(sql_exec_wgt) delete(sql_exec_wgt); + } void SQLToolWidget::showSnippet(const QString &snip) @@ -342,9 +414,12 @@ void SQLToolWidget::showSnippet(const QString &snip) sql_exec_wgt=dynamic_cast(sql_exec_tbw->currentWidget()); - QTextCursor cursor=sql_exec_wgt->sql_cmd_txt->textCursor(); - cursor.movePosition(QTextCursor::End); + if(sql_exec_wgt->sql_cmd_txt->isEnabled()) + { + QTextCursor cursor=sql_exec_wgt->sql_cmd_txt->textCursor(); + cursor.movePosition(QTextCursor::End); - sql_exec_wgt->sql_cmd_txt->appendPlainText(snip); - sql_exec_wgt->sql_cmd_txt->setTextCursor(cursor); + sql_exec_wgt->sql_cmd_txt->appendPlainText(snip); + sql_exec_wgt->sql_cmd_txt->setTextCursor(cursor); + } } diff --git a/libpgmodeler_ui/src/sqltoolwidget.h b/libpgmodeler_ui/src/sqltoolwidget.h index f471a4e624..a7a5fb98b0 100644 --- a/libpgmodeler_ui/src/sqltoolwidget.h +++ b/libpgmodeler_ui/src/sqltoolwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -33,11 +33,15 @@ #include "findreplacewidget.h" #include "codecompletionwidget.h" #include "numberedtexteditor.h" +#include "databaseexplorerwidget.h" +#include "sqlexecutionwidget.h" class SQLToolWidget: public QWidget, public Ui::SQLToolWidget { private: Q_OBJECT + QToolButton *sql_exec_corner_btn; + NumberedTextEditor *sourcecode_txt; SyntaxHighlighter *sourcecode_hl; @@ -53,7 +57,7 @@ class SQLToolWidget: public QWidget, public Ui::SQLToolWidget { bool eventFilter(QObject *object, QEvent *event); public: - SQLToolWidget(QWidget * parent = 0); + SQLToolWidget(QWidget * parent = nullptr); ~SQLToolWidget(void); //! \brief Force the update of the sql command input field and the syntax highligter attached to the opened tabs @@ -64,6 +68,10 @@ class SQLToolWidget: public QWidget, public Ui::SQLToolWidget { void clearDatabases(void); + protected slots: + //! \brief Add a tab by browsing a database in the specified connectio, loads the sql file and put its contents on a SQL execution + void addSQLExecutionTab(const QString &conn_id, const QString &database, const QString &sql_file); + private slots: //! \brief Opens a connection to the selected server void connectToServer(void); @@ -75,10 +83,10 @@ class SQLToolWidget: public QWidget, public Ui::SQLToolWidget { void handleDatabaseDropped(const QString &dbname); //! \brief Open the current database in a database explorer instance - void browseDatabase(void); + DatabaseExplorerWidget *browseDatabase(void); //! \brief Add a tab to permit the SQL execution for the current database being browsed - void addSQLExecutionTab(void); + SQLExecutionWidget *addSQLExecutionTab(void); //! \brief Show the selected snippet on the current opened SQL execution tab void showSnippet(const QString &snip); @@ -93,6 +101,8 @@ class SQLToolWidget: public QWidget, public Ui::SQLToolWidget { /*! \brief This signal is emitted whenever the user changes the connections settings within this widget without use the main configurations dialog */ void s_connectionsUpdateRequest(void); + + friend class MainWindow; }; #endif diff --git a/libpgmodeler_ui/src/swapobjectsidswidget.cpp b/libpgmodeler_ui/src/swapobjectsidswidget.cpp index ee97aa35c0..021f4f54ae 100644 --- a/libpgmodeler_ui/src/swapobjectsidswidget.cpp +++ b/libpgmodeler_ui/src/swapobjectsidswidget.cpp @@ -1,18 +1,18 @@ #include "swapobjectsidswidget.h" #include "pgmodeleruins.h" -const QString SwapObjectsIdsWidget::ID_LABEL = QString("ID: %1"); +const QString SwapObjectsIdsWidget::IdLabel = QString("ID: %1"); SwapObjectsIdsWidget::SwapObjectsIdsWidget(QWidget *parent, Qt::WindowFlags f) : QWidget(parent, f) { try { QGridLayout *swap_objs_grid=new QGridLayout(this); - vector types=BaseObject::getObjectTypes(true, {OBJ_PERMISSION, OBJ_ROLE, OBJ_TEXTBOX, - OBJ_COLUMN, OBJ_CONSTRAINT }); + vector types=BaseObject::getObjectTypes(true, {ObjectType::Permission, ObjectType::Role, ObjectType::Textbox, + ObjectType::Column, ObjectType::Constraint }); setupUi(this); - PgModelerUiNS::configureWidgetFont(message_lbl, PgModelerUiNS::MEDIUM_FONT_FACTOR); + PgModelerUiNs::configureWidgetFont(message_lbl, PgModelerUiNs::MediumFontFactor); src_object_sel=nullptr; dst_object_sel=nullptr; @@ -90,7 +90,7 @@ SwapObjectsIdsWidget::SwapObjectsIdsWidget(QWidget *parent, Qt::WindowFlags f) : } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -112,6 +112,12 @@ void SwapObjectsIdsWidget::setModel(DatabaseModel *model) fillCreationOrderGrid(); } +void SwapObjectsIdsWidget::setSelectedObjects(BaseObject *src_object, BaseObject *dst_objct) +{ + src_object_sel->setSelectedObject(src_object); + dst_object_sel->setSelectedObject(dst_objct); +} + void SwapObjectsIdsWidget::fillCreationOrderGrid(void) { objects_tbw->clearContents(); @@ -120,12 +126,12 @@ void SwapObjectsIdsWidget::fillCreationOrderGrid(void) if(!model) return; - map creation_order = model->getCreationOrder(SchemaParser::SQL_DEFINITION); + map creation_order = model->getCreationOrder(SchemaParser::SqlDefinition); vector objects; //Using an stl function to extract all the values (objects) from the map and put them into a list std::for_each(creation_order.begin(), creation_order.end(), [&](const std::pair &itr) { - if(itr.second->getObjectType() != OBJ_CONSTRAINT) { + if(itr.second->getObjectType() != ObjectType::Constraint) { objects.push_back(itr.second); } }); @@ -155,8 +161,8 @@ void SwapObjectsIdsWidget::showObjectId(void) id_lbl->clear(); if(sel_obj) { - id_lbl->setText(ID_LABEL.arg(sel_obj->getObjectId())); - ico_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath(sel_obj->getObjectType()))); + id_lbl->setText(IdLabel.arg(sel_obj->getObjectId())); + ico_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath(sel_obj->getObjectType()))); ico_lbl->setToolTip(sel_obj->getTypeName()); id_lbl->setVisible(true); @@ -183,21 +189,21 @@ void SwapObjectsIdsWidget::swapObjectsIds(void) *graph_dst_obj=dynamic_cast(dst_obj); if(!src_obj && !dst_obj) - throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::OprNotAllocatedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Raise an exception if the user try to swap an id of relationship by other object of different kind - else if((src_obj->getObjectType()==OBJ_RELATIONSHIP || dst_obj->getObjectType()==OBJ_RELATIONSHIP) && + else if((src_obj->getObjectType()==ObjectType::Relationship || dst_obj->getObjectType()==ObjectType::Relationship) && (src_obj->getObjectType() != dst_obj->getObjectType())) - throw Exception(ERR_INV_REL_ID_SWAP,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::InvRelationshipIdSwap,__PRETTY_FUNCTION__,__FILE__,__LINE__); try { BaseObject::swapObjectsIds(src_obj, dst_obj, false); //Special id swap for relationship - if(src_obj->getObjectType()==OBJ_RELATIONSHIP) + if(src_obj->getObjectType()==ObjectType::Relationship) { vector::iterator itr, itr1; - vector *list=model->getObjectList(OBJ_RELATIONSHIP); + vector *list=model->getObjectList(ObjectType::Relationship); //Find the relationships in the list and swap the memory position too itr=std::find(list->begin(), list->end(), src_obj); @@ -219,14 +225,14 @@ void SwapObjectsIdsWidget::swapObjectsIds(void) model->setInvalidated(true); fillCreationOrderGrid(); - src_id_lbl->setText(ID_LABEL.arg(src_object_sel->getSelectedObject()->getObjectId())); - dst_id_lbl->setText(ID_LABEL.arg(dst_object_sel->getSelectedObject()->getObjectId())); + src_id_lbl->setText(IdLabel.arg(src_object_sel->getSelectedObject()->getObjectId())); + dst_id_lbl->setText(IdLabel.arg(dst_object_sel->getSelectedObject()->getObjectId())); emit s_objectsIdsSwapped(); } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/swapobjectsidswidget.h b/libpgmodeler_ui/src/swapobjectsidswidget.h index af414541fb..2435b6b604 100644 --- a/libpgmodeler_ui/src/swapobjectsidswidget.h +++ b/libpgmodeler_ui/src/swapobjectsidswidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -33,7 +33,7 @@ class SwapObjectsIdsWidget: public QWidget, public Ui::SwapObjectsIdsWidget { private: Q_OBJECT - static const QString ID_LABEL; + static const QString IdLabel; //! \brief Reference database model DatabaseModel *model; @@ -44,9 +44,10 @@ class SwapObjectsIdsWidget: public QWidget, public Ui::SwapObjectsIdsWidget { void fillCreationOrderGrid(void); public: - SwapObjectsIdsWidget(QWidget *parent = 0, Qt::WindowFlags f = 0); + SwapObjectsIdsWidget(QWidget *parent = nullptr, Qt::WindowFlags f = Qt::Widget); ~SwapObjectsIdsWidget(void); void setModel(DatabaseModel *model); + void setSelectedObjects(BaseObject *src_object, BaseObject *dst_objct); private slots: void showObjectId(void); diff --git a/libpgmodeler_ui/src/syntaxhighlighter.cpp b/libpgmodeler_ui/src/syntaxhighlighter.cpp index 9537fd8004..4f0e8112f8 100644 --- a/libpgmodeler_ui/src/syntaxhighlighter.cpp +++ b/libpgmodeler_ui/src/syntaxhighlighter.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -24,7 +24,7 @@ QFont SyntaxHighlighter::default_font=QFont(QString("Source Code Pro"), 10); SyntaxHighlighter::SyntaxHighlighter(QPlainTextEdit *parent, bool single_line_mode, bool use_custom_tab_width) : QSyntaxHighlighter(parent) { if(!parent) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->setDocument(parent->document()); this->single_line_mode=single_line_mode; @@ -38,7 +38,7 @@ SyntaxHighlighter::SyntaxHighlighter(QPlainTextEdit *parent, bool single_line_mo if(single_line_mode) { QFontMetrics fm=QFontMetrics(default_font); - int height=fm.height() + (fm.lineSpacing()/static_cast(1.3)); + int height=fm.height() + (fm.lineSpacing()/static_cast(1.3)); parent->setMinimumHeight(height); parent->setMaximumHeight(height); parent->setSizePolicy(parent->sizePolicy().horizontalPolicy(), QSizePolicy::Fixed); @@ -100,18 +100,18 @@ void SyntaxHighlighter::highlightBlock(const QString &txt) //Reset the block's info to permit the rehighlighting info=dynamic_cast(currentBlockUserData()); info->resetBlockInfo(); - setCurrentBlockState(SIMPLE_BLOCK); + setCurrentBlockState(SimpleBlock); } /* If the previous block info is a open multiline expression the current block will inherit this settings to force the same text formatting */ - if(prev_info && currentBlock().previous().userState()==OPEN_EXPR_BLOCK && - currentBlockState() == OPEN_EXPR_BLOCK) + if(prev_info && currentBlock().previous().userState()==OpenExprBlock && + currentBlockState() == OpenExprBlock) { info->group=prev_info->group; info->has_exprs=prev_info->has_exprs; info->is_expr_closed=false; - setCurrentBlockState(OPEN_EXPR_BLOCK); + setCurrentBlockState(OpenExprBlock); } if(!txt.isEmpty()) @@ -220,9 +220,9 @@ void SyntaxHighlighter::highlightBlock(const QString &txt) } if(info->has_exprs && !info->is_expr_closed && hasInitialAndFinalExprs(group)) - setCurrentBlockState(OPEN_EXPR_BLOCK); + setCurrentBlockState(OpenExprBlock); else - setCurrentBlockState(SIMPLE_BLOCK); + setCurrentBlockState(SimpleBlock); aux_len=(match_idx + match_len); if(match_idx >=0 && aux_len != word.length()) @@ -372,17 +372,17 @@ void SyntaxHighlighter::loadConfiguration(const QString &filename) { clearConfiguration(); xmlparser.restartParser(); - xmlparser.setDTDFile(GlobalAttributes::TMPL_CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::OBJECT_DTD_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::CODE_HIGHLIGHT_CONF + - GlobalAttributes::OBJECT_DTD_EXT, - GlobalAttributes::CODE_HIGHLIGHT_CONF); + xmlparser.setDTDFile(GlobalAttributes::TmplConfigurationDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::ObjectDTDDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::CodeHighlightConf + + GlobalAttributes::ObjectDTDExt, + GlobalAttributes::CodeHighlightConf); xmlparser.loadXMLFile(filename); - if(xmlparser.accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser.accessElement(XmlParser::ChildElement)) { do { @@ -390,27 +390,27 @@ void SyntaxHighlighter::loadConfiguration(const QString &filename) { elem=xmlparser.getElementName(); - if(elem==ParsersAttributes::WORD_SEPARATORS) + if(elem==Attributes::WordSeparators) { xmlparser.getElementAttributes(attribs); - word_separators=attribs[ParsersAttributes::VALUE]; + word_separators=attribs[Attributes::Value]; } - else if(elem==ParsersAttributes::WORD_DELIMITERS) + else if(elem==Attributes::WordDelimiters) { xmlparser.getElementAttributes(attribs); - word_delimiters=attribs[ParsersAttributes::VALUE]; + word_delimiters=attribs[Attributes::Value]; } - else if(elem==ParsersAttributes::IGNORED_CHARS) + else if(elem==Attributes::IgnoredChars) { xmlparser.getElementAttributes(attribs); - ignored_chars=attribs[ParsersAttributes::VALUE]; + ignored_chars=attribs[Attributes::Value]; } - else if(elem==ParsersAttributes::COMPLETION_TRIGGER) + else if(elem==Attributes::CompletionTrigger) { xmlparser.getElementAttributes(attribs); - if(attribs[ParsersAttributes::VALUE].size() >= 1) - completion_trigger=attribs[ParsersAttributes::VALUE].at(0); + if(attribs[Attributes::Value].size() >= 1) + completion_trigger=attribs[Attributes::Value].at(0); } /* If the element is what defines the order of application of the groups @@ -418,19 +418,19 @@ void SyntaxHighlighter::loadConfiguration(const QString &filename) the groups used to highlight the source code. ALL groups in this block must be declared before they are built otherwise an error will be triggered. */ - else if(elem==ParsersAttributes::HIGHLIGHT_ORDER) + else if(elem==Attributes::HighlightOrder) { //Marks a flag indication that groups are being declared groups_decl=true; xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); elem=xmlparser.getElementName(); } - if(elem==ParsersAttributes::GROUP) + if(elem==Attributes::Group) { xmlparser.getElementAttributes(attribs); - group=attribs[ParsersAttributes::NAME]; + group=attribs[Attributes::Name]; /* If the parser is on the group declaration block and not in the build block some validations are made. */ @@ -439,15 +439,15 @@ void SyntaxHighlighter::loadConfiguration(const QString &filename) //Raises an error if the group was declared before if(find(groups_order.begin(), groups_order.end(), group)!=groups_order.end()) { - throw Exception(Exception::getErrorMessage(ERR_REDECL_HL_GROUP).arg(group), - ERR_REDECL_HL_GROUP,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::InvRedeclarationGroup).arg(group), + ErrorCode::InvRedeclarationGroup,__PRETTY_FUNCTION__,__FILE__,__LINE__); } //Raises an error if the group is being declared and build at the declaration statment (not permitted) - else if(attribs.size() > 1 || xmlparser.hasElement(XMLParser::CHILD_ELEMENT)) + else if(attribs.size() > 1 || xmlparser.hasElement(XmlParser::ChildElement)) { - throw Exception(Exception::getErrorMessage(ERR_DEF_INV_GROUP_DECL) - .arg(group).arg(ParsersAttributes::HIGHLIGHT_ORDER), - ERR_REDECL_HL_GROUP,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::InvGroupDeclaration) + .arg(group).arg(Attributes::HighlightOrder), + ErrorCode::InvRedeclarationGroup,__PRETTY_FUNCTION__,__FILE__,__LINE__); } groups_order.push_back(group); @@ -458,38 +458,38 @@ void SyntaxHighlighter::loadConfiguration(const QString &filename) //Raises an error if the group is being constructed by a second time if(initial_exprs.count(group)!=0) { - throw Exception(Exception::getErrorMessage(ERR_DEF_DUPLIC_GROUP).arg(group), - ERR_DEF_DUPLIC_GROUP,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::DefDuplicatedGroup).arg(group), + ErrorCode::DefDuplicatedGroup,__PRETTY_FUNCTION__,__FILE__,__LINE__); } //Raises an error if the group is being constructed without being declared else if(find(groups_order.begin(), groups_order.end(), group)==groups_order.end()) { - throw Exception(Exception::getErrorMessage(ERR_DEF_NOT_DECL_GROUP) - .arg(group).arg(ParsersAttributes::HIGHLIGHT_ORDER), - ERR_DEF_NOT_DECL_GROUP,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::DefNotDeclaredGroup) + .arg(group).arg(Attributes::HighlightOrder), + ErrorCode::DefNotDeclaredGroup,__PRETTY_FUNCTION__,__FILE__,__LINE__); } //Raises an error if the group does not have children element - else if(!xmlparser.hasElement(XMLParser::CHILD_ELEMENT)) + else if(!xmlparser.hasElement(XmlParser::ChildElement)) { - throw Exception(Exception::getErrorMessage(ERR_DEF_EMPTY_GROUP).arg(group), - ERR_DEF_EMPTY_GROUP,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::DefEmptyGroup).arg(group), + ErrorCode::DefEmptyGroup,__PRETTY_FUNCTION__,__FILE__,__LINE__); } - chr_sensitive=(attribs[ParsersAttributes::CASE_SENSITIVE]==ParsersAttributes::_TRUE_); - italic=(attribs[ParsersAttributes::ITALIC]==ParsersAttributes::_TRUE_); - bold=(attribs[ParsersAttributes::BOLD]==ParsersAttributes::_TRUE_); - underline=(attribs[ParsersAttributes::UNDERLINE]==ParsersAttributes::_TRUE_); - partial_match=(attribs[ParsersAttributes::PARTIAL_MATCH]==ParsersAttributes::_TRUE_); - fg_color.setNamedColor(attribs[ParsersAttributes::FOREGROUND_COLOR]); + chr_sensitive=(attribs[Attributes::CaseSensitive]==Attributes::True); + italic=(attribs[Attributes::Italic]==Attributes::True); + bold=(attribs[Attributes::Bold]==Attributes::True); + underline=(attribs[Attributes::Underline]==Attributes::True); + partial_match=(attribs[Attributes::PartialMatch]==Attributes::True); + fg_color.setNamedColor(attribs[Attributes::ForegroundColor]); //If the attribute isn't defined the bg color will be transparent - if(attribs[ParsersAttributes::BACKGROUND_COLOR].isEmpty()) + if(attribs[Attributes::BackgroundColor].isEmpty()) bg_color.setRgb(0,0,0,0); else - bg_color.setNamedColor(attribs[ParsersAttributes::BACKGROUND_COLOR]); + bg_color.setNamedColor(attribs[Attributes::BackgroundColor]); - if(!attribs[ParsersAttributes::LOOKAHEAD_CHAR].isEmpty()) - lookahead_char[group]=attribs[ParsersAttributes::LOOKAHEAD_CHAR][0]; + if(!attribs[Attributes::LookaheadChar].isEmpty()) + lookahead_char[group]=attribs[Attributes::LookaheadChar][0]; format.setFontFamily(default_font.family()); format.setFontPointSize(default_font.pointSizeF()); @@ -507,7 +507,7 @@ void SyntaxHighlighter::loadConfiguration(const QString &filename) xmlparser.savePosition(); - xmlparser.accessElement(XMLParser::CHILD_ELEMENT); + xmlparser.accessElement(XmlParser::ChildElement); if(chr_sensitive) regexp.setCaseSensitivity(Qt::CaseSensitive); @@ -521,25 +521,25 @@ void SyntaxHighlighter::loadConfiguration(const QString &filename) if(xmlparser.getElementType()==XML_ELEMENT_NODE) { xmlparser.getElementAttributes(attribs); - expr_type=attribs[ParsersAttributes::TYPE]; - regexp.setPattern(attribs[ParsersAttributes::VALUE]); + expr_type=attribs[Attributes::Type]; + regexp.setPattern(attribs[Attributes::Value]); - if(attribs[ParsersAttributes::REGULAR_EXP]==ParsersAttributes::_TRUE_) + if(attribs[Attributes::RegularExp]==Attributes::True) regexp.setPatternSyntax(QRegExp::RegExp2); - else if(attribs[ParsersAttributes::WILDCARD]==ParsersAttributes::_TRUE_) + else if(attribs[Attributes::Wildcard]==Attributes::True) regexp.setPatternSyntax(QRegExp::Wildcard); else regexp.setPatternSyntax(QRegExp::FixedString); if(expr_type.isEmpty() || - expr_type==ParsersAttributes::SIMPLE_EXP || - expr_type==ParsersAttributes::INITIAL_EXP) + expr_type==Attributes::SimpleExp || + expr_type==Attributes::InitialExp) initial_exprs[group].push_back(regexp); else final_exprs[group].push_back(regexp); } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); xmlparser.restorePosition(); } } @@ -547,14 +547,14 @@ void SyntaxHighlighter::loadConfiguration(const QString &filename) /* Check if there are some other groups to be declared, if not, continues to reading to the other part of configuration */ - if(groups_decl && !xmlparser.hasElement(XMLParser::NEXT_ELEMENT)) + if(groups_decl && !xmlparser.hasElement(XmlParser::NextElement)) { groups_decl=false; xmlparser.restorePosition(); } } - while(xmlparser.accessElement(XMLParser::NEXT_ELEMENT)); + while(xmlparser.accessElement(XmlParser::NextElement)); } itr=groups_order.begin(); @@ -568,8 +568,8 @@ void SyntaxHighlighter::loadConfiguration(const QString &filename) if(initial_exprs[group].size()==0) { //Raises an error if the group was declared but not constructed - throw Exception(Exception::getErrorMessage(ERR_GROUP_DECL_NOT_DEFINED).arg(group), - ERR_GROUP_DECL_NOT_DEFINED,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::InvGroupDeclarationNotDefined).arg(group), + ErrorCode::InvGroupDeclarationNotDefined,__PRETTY_FUNCTION__,__FILE__,__LINE__); } } @@ -577,7 +577,7 @@ void SyntaxHighlighter::loadConfiguration(const QString &filename) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } } diff --git a/libpgmodeler_ui/src/syntaxhighlighter.h b/libpgmodeler_ui/src/syntaxhighlighter.h index 67e949f09b..08f6c21f83 100644 --- a/libpgmodeler_ui/src/syntaxhighlighter.h +++ b/libpgmodeler_ui/src/syntaxhighlighter.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -31,7 +31,7 @@ #include "exception.h" #include "xmlparser.h" #include "globalattributes.h" -#include "parsersattributes.h" +#include "attributes.h" #include class SyntaxHighlighter: public QSyntaxHighlighter { @@ -58,18 +58,18 @@ class SyntaxHighlighter: public QSyntaxHighlighter { }; //! \brief XML parser used to parse configuration files - XMLParser xmlparser; + XmlParser xmlparser; //! \brief Default font configuratoin for all instances os syntax highlighter static QFont default_font; //! \brief Indicates that the current block has no special meaning - static const int SIMPLE_BLOCK=-1, + static constexpr int SimpleBlock=-1, /*! \brief Indicates that the current block has an open (but still to close) expression (e.g. multline comments) When the highlighter finds this const it'll do special operation like highlight next blocks with the same configuration as the current one */ - OPEN_EXPR_BLOCK=0; + OpenExprBlock=0; /*! \brief Stores the regexp used to identify keywords, identifiers, strings, numbers. Also stores initial regexps used to identify a multiline group */ diff --git a/libpgmodeler_ui/src/tabledatawidget.cpp b/libpgmodeler_ui/src/tabledatawidget.cpp index 74bb0add73..36e26652b5 100644 --- a/libpgmodeler_ui/src/tabledatawidget.cpp +++ b/libpgmodeler_ui/src/tabledatawidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,15 +18,17 @@ #include "tabledatawidget.h" #include "htmlitemdelegate.h" +#include "bulkdataeditwidget.h" +#include "sqlexecutionwidget.h" -const QString TableDataWidget::PLACEHOLDER_COLUMN=QString("$placeholder$"); +const QString TableDataWidget::PlaceholderColumn=QString("$placeholder$"); -TableDataWidget::TableDataWidget(QWidget *parent): BaseObjectWidget(parent, BASE_OBJECT) +TableDataWidget::TableDataWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::BaseObject) { Ui_TableDataWidget::setupUi(this); - configureFormLayout(tabledata_grid, BASE_OBJECT); + configureFormLayout(tabledata_grid, ObjectType::BaseObject); - obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNS::getIconPath(OBJ_TABLE))); + obj_icon_lbl->setPixmap(QPixmap(PgModelerUiNs::getIconPath(ObjectType::Table))); comment_lbl->setVisible(false); comment_edt->setVisible(false); @@ -71,8 +73,52 @@ TableDataWidget::TableDataWidget(QWidget *parent): BaseObjectWidget(parent, BASE connect(csv_load_tb, SIGNAL(toggled(bool)), csv_load_parent, SLOT(setVisible(bool))); connect(csv_load_wgt, &CsvLoadWidget::s_csvFileLoaded, [&](){ - populateDataGrid(csv_load_wgt->getCsvBuffer(Table::DATA_SEPARATOR, Table::DATA_LINE_BREAK)); + populateDataGrid(csv_load_wgt->getCsvBuffer(Table::DataSeparator, Table::DataLineBreak)); }); + + connect(paste_tb, &QToolButton::clicked, [&](){ + csv_load_wgt->loadCsvBuffer(qApp->clipboard()->text(), QString(";"), QString("\""), true); + populateDataGrid(csv_load_wgt->getCsvBuffer(Table::DataSeparator, Table::DataLineBreak)); + qApp->clipboard()->clear(); + paste_tb->setEnabled(false); + }); + + connect(bulkedit_tb, &QToolButton::clicked, [&](){ + PgModelerUiNs::bulkDataEdit(data_tbw); + }); + + connect(copy_tb, &QToolButton::clicked, [&](){ + SQLExecutionWidget::copySelection(data_tbw, false, true); + paste_tb->setEnabled(true); + }); + + connect(data_tbw, &QTableWidget::itemPressed, + [&](){ + if(QApplication::mouseButtons()==Qt::RightButton) + { + QMenu item_menu; + QAction *act = nullptr; + QList btns = { add_row_tb, add_col_tb, dup_rows_tb, nullptr, + del_rows_tb, del_cols_tb, nullptr, + clear_rows_tb, clear_cols_tb, nullptr, + copy_tb, paste_tb }; + + for(auto &btn : btns) + { + if(!btn) + { + item_menu.addSeparator(); + continue; + } + + act = item_menu.addAction(btn->icon(), btn->text(), btn, SLOT(click()), btn->shortcut()); + act->setEnabled(btn->isEnabled()); + act->setMenu(btn->menu()); + } + + item_menu.exec(QCursor::pos()); + } + }); } void TableDataWidget::insertRowOnTabPress(int curr_row, int curr_col, int prev_row, int prev_col) @@ -127,7 +173,7 @@ void TableDataWidget::deleteColumns(void) Messagebox msg_box; msg_box.show(trUtf8("Delete columns is an irreversible action! Do you really want to proceed?"), - Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); if(msg_box.result()==QDialog::Accepted) { @@ -162,7 +208,7 @@ void TableDataWidget::clearRows(bool confirm) if(confirm) msg_box.show(trUtf8("Remove all rows is an irreversible action! Do you really want to proceed?"), - Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); if(!confirm || msg_box.result()==QDialog::Accepted) { @@ -177,7 +223,7 @@ void TableDataWidget::clearColumns(void) Messagebox msg_box; msg_box.show(trUtf8("Remove all columns is an irreversible action! Do you really want to proceed?"), - Messagebox::CONFIRM_ICON, Messagebox::YES_NO_BUTTONS); + Messagebox::ConfirmIcon, Messagebox::YesNoButtons); if(msg_box.result()==QDialog::Accepted) { @@ -209,7 +255,7 @@ void TableDataWidget::changeColumnName(int col_idx) item->setText(col_name); - if(act->text()==PLACEHOLDER_COLUMN) + if(act->text()==PlaceholderColumn) { item->setFlags(Qt::NoItemFlags); item->setForeground(QColor(Qt::red)); @@ -228,7 +274,7 @@ void TableDataWidget::changeColumnName(int col_idx) { item=data_tbw->item(row, col_idx); - if(col_name==PLACEHOLDER_COLUMN) + if(col_name==PlaceholderColumn) setItemInvalid(item); else { @@ -262,6 +308,8 @@ void TableDataWidget::enableButtons(void) add_row_tb->setEnabled(data_tbw->columnCount() > 0); del_cols_tb->setEnabled(rows_selected); dup_rows_tb->setEnabled(cols_selected); + bulkedit_tb->setEnabled(!sel_ranges.isEmpty()); + copy_tb->setEnabled(!sel_ranges.isEmpty()); } void TableDataWidget::setAttributes(DatabaseModel *model, Table *table) @@ -295,20 +343,19 @@ void TableDataWidget::populateDataGrid(const QString &data) else ini_data=table->getInitialData(); - /* If the initial data buffer is preset the columns there have priority over the current table's columns */ if(!ini_data.isEmpty()) { - buffer=ini_data.split(Table::DATA_LINE_BREAK); + buffer=ini_data.split(Table::DataLineBreak); - //The first line of the buffer always have the column names + //The first line of the buffer always has the column names if(!buffer.isEmpty() && !buffer[0].isEmpty()) - columns.append(buffer[0].split(Table::DATA_SEPARATOR)); + columns.append(buffer[0].split(Table::DataSeparator)); } else { - for(auto object : *table->getObjectList(OBJ_COLUMN)) + for(auto object : *table->getObjectList(ObjectType::Column)) columns.push_back(object->getName()); } @@ -345,7 +392,7 @@ void TableDataWidget::populateDataGrid(const QString &data) for(QString buf_row : buffer) { addRow(); - values = buf_row.split(Table::DATA_SEPARATOR); + values = buf_row.split(Table::DataSeparator); col = 0; for(QString val : values) @@ -387,7 +434,7 @@ void TableDataWidget::configureColumnNamesMenu(void) col_names_menu.clear(); - for(auto object : *table->getObjectList(OBJ_COLUMN)) + for(auto object : *table->getObjectList(ObjectType::Column)) col_names.push_back(object->getName()); for(int col = 0; col < data_tbw->columnCount(); col++) @@ -402,7 +449,7 @@ void TableDataWidget::configureColumnNamesMenu(void) } col_names_menu.addSeparator(); - col_names_menu.addAction(PLACEHOLDER_COLUMN); + col_names_menu.addAction(PlaceholderColumn); } void TableDataWidget::toggleWarningFrame(void) @@ -435,7 +482,7 @@ QString TableDataWidget::generateDataBuffer(void) col_names.push_back(data_tbw->horizontalHeaderItem(col)->text()); //The first line of the buffer consists in the column names - buffer.push_back(col_names.join(Table::DATA_SEPARATOR)); + buffer.push_back(col_names.join(Table::DataSeparator)); for(int row = 0; row < data_tbw->rowCount(); row++) { @@ -444,24 +491,34 @@ QString TableDataWidget::generateDataBuffer(void) value = data_tbw->item(row, col)->text(); //Checking if the value is a malformed unescaped value, e.g., {value, value}, {value\} - if((value.startsWith(PgModelerNS::UNESC_VALUE_START) && value.endsWith(QString("\\") + PgModelerNS::UNESC_VALUE_END)) || - (value.startsWith(PgModelerNS::UNESC_VALUE_START) && !value.endsWith(PgModelerNS::UNESC_VALUE_END)) || - (!value.startsWith(PgModelerNS::UNESC_VALUE_START) && !value.endsWith(QString("\\") + PgModelerNS::UNESC_VALUE_END) && value.endsWith(PgModelerNS::UNESC_VALUE_END))) - throw Exception(Exception::getErrorMessage(ERR_MALFORMED_UNESCAPED_VALUE) - .arg(row + 1).arg(col_names[col]), - ERR_MALFORMED_UNESCAPED_VALUE,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if((value.startsWith(PgModelerNs::UnescValueStart) && value.endsWith(QString("\\") + PgModelerNs::UnescValueEnd)) || + (value.startsWith(PgModelerNs::UnescValueStart) && !value.endsWith(PgModelerNs::UnescValueEnd)) || + (!value.startsWith(PgModelerNs::UnescValueStart) && !value.endsWith(QString("\\") + PgModelerNs::UnescValueEnd) && value.endsWith(PgModelerNs::UnescValueEnd))) + throw Exception(Exception::getErrorMessage(ErrorCode::MalformedUnescapedValue) + .arg(row + 1).arg(col_names[col]), + ErrorCode::MalformedUnescapedValue,__PRETTY_FUNCTION__,__FILE__,__LINE__); val_list.push_back(value); } - buffer.push_back(val_list.join(Table::DATA_SEPARATOR)); + buffer.push_back(val_list.join(Table::DataSeparator)); val_list.clear(); } if(buffer.size() <= 1) return(QString()); - return(buffer.join(Table::DATA_LINE_BREAK)); + return(buffer.join(Table::DataLineBreak)); +} + +void TableDataWidget::enterEvent(QEvent *) +{ + paste_tb->setEnabled(!qApp->clipboard()->text().isEmpty()); +} + +void TableDataWidget::showEvent(QShowEvent *) +{ + paste_tb->setEnabled(!qApp->clipboard()->text().isEmpty()); } void TableDataWidget::addRow(void) @@ -532,7 +589,7 @@ void TableDataWidget::applyConfiguration(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/tabledatawidget.h b/libpgmodeler_ui/src/tabledatawidget.h index 564eeb9b36..fe723d35d8 100644 --- a/libpgmodeler_ui/src/tabledatawidget.h +++ b/libpgmodeler_ui/src/tabledatawidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -54,10 +54,14 @@ class TableDataWidget: public BaseObjectWidget, public Ui::TableDataWidget { //! brief Generated the CSV-like buffer to be used as initial data in the table object QString generateDataBuffer(void); + void showEvent(QShowEvent *); + + void enterEvent(QEvent *); + public: - static const QString PLACEHOLDER_COLUMN; + static const QString PlaceholderColumn; - TableDataWidget(QWidget * parent = 0); + TableDataWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, Table *table); diff --git a/libpgmodeler_ui/src/tablespacewidget.cpp b/libpgmodeler_ui/src/tablespacewidget.cpp index 4933de221b..8260b19c27 100644 --- a/libpgmodeler_ui/src/tablespacewidget.cpp +++ b/libpgmodeler_ui/src/tablespacewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,10 +18,10 @@ #include "tablespacewidget.h" -TablespaceWidget::TablespaceWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_TABLESPACE) +TablespaceWidget::TablespaceWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Tablespace) { Ui_TablespaceWidget::setupUi(this); - configureFormLayout(tablespace_grid, OBJ_TABLESPACE); + configureFormLayout(tablespace_grid, ObjectType::Tablespace); tablespace_grid->addItem(new QSpacerItem(10,0,QSizePolicy::Minimum,QSizePolicy::Expanding), tablespace_grid->count(), 0); @@ -58,7 +58,7 @@ void TablespaceWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/tablespacewidget.h b/libpgmodeler_ui/src/tablespacewidget.h index 2d2590fe11..0798f1e34f 100644 --- a/libpgmodeler_ui/src/tablespacewidget.h +++ b/libpgmodeler_ui/src/tablespacewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -33,7 +33,7 @@ class TablespaceWidget: public BaseObjectWidget, public Ui::TablespaceWidget { Q_OBJECT public: - TablespaceWidget(QWidget * parent = 0); + TablespaceWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Tablespace *tablespc); public slots: diff --git a/libpgmodeler_ui/src/tablewidget.cpp b/libpgmodeler_ui/src/tablewidget.cpp index 8099d124a4..69273c3f76 100644 --- a/libpgmodeler_ui/src/tablewidget.cpp +++ b/libpgmodeler_ui/src/tablewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -25,59 +25,64 @@ #include "baseform.h" #include "tabledatawidget.h" #include "policywidget.h" +#include "generalconfigwidget.h" -TableWidget::TableWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_TABLE) +TableWidget::TableWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Table) { QGridLayout *grid=nullptr; + QVBoxLayout *vbox=nullptr; ObjectsTableWidget *tab=nullptr; - ObjectType types[]={ OBJ_COLUMN, OBJ_CONSTRAINT, OBJ_TRIGGER, OBJ_RULE, OBJ_INDEX, OBJ_POLICY }; + ObjectType types[]={ ObjectType::Column, ObjectType::Constraint, ObjectType::Trigger, ObjectType::Rule, ObjectType::Index, ObjectType::Policy }; map > fields_map; QFrame *frame=nullptr; - QToolButton *edt_data_tb=nullptr; + QPushButton *edt_data_tb=nullptr; + QStringList part_types; Ui_TableWidget::setupUi(this); - edt_data_tb=new QToolButton(this); - QPixmap icon=QPixmap(PgModelerUiNS::getIconPath("editdata")); + edt_data_tb=new QPushButton(this); + QPixmap icon=QPixmap(PgModelerUiNs::getIconPath("editdata")); edt_data_tb->setMinimumSize(edt_perms_tb->minimumSize()); edt_data_tb->setText(trUtf8("Edit data")); edt_data_tb->setToolTip(trUtf8("Define initial data for the table")); edt_data_tb->setIcon(icon); edt_data_tb->setIconSize(edt_perms_tb->iconSize()); - edt_data_tb->setToolButtonStyle(edt_perms_tb->toolButtonStyle()); connect(edt_data_tb, SIGNAL(clicked(bool)), this, SLOT(editData())); misc_btns_lt->insertWidget(1, edt_data_tb); - fields_map[generateVersionsInterval(AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_91)].push_back(unlogged_chk); - fields_map[generateVersionsInterval(AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_95)].push_back(enable_rls_chk); - fields_map[generateVersionsInterval(AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_95)].push_back(force_rls_chk); + fields_map[generateVersionsInterval(AfterVersion, PgSqlVersions::PgSqlVersion91)].push_back(unlogged_chk); + fields_map[generateVersionsInterval(AfterVersion, PgSqlVersions::PgSqlVersion95)].push_back(enable_rls_chk); + fields_map[generateVersionsInterval(AfterVersion, PgSqlVersions::PgSqlVersion95)].push_back(force_rls_chk); + fields_map[generateVersionsInterval(AfterVersion, PgSqlVersions::PgSqlVersion100)].push_back(partitioning_type_lbl); frame=generateVersionWarningFrame(fields_map); table_grid->addWidget(frame, table_grid->count()+1, 0, 1, 2); frame->setParent(this); - parent_tables = new ObjectsTableWidget(ObjectsTableWidget::NO_BUTTONS, true, this); + parent_tables = new ObjectsTableWidget(ObjectsTableWidget::NoButtons, true, this); parent_tables->setColumnCount(3); parent_tables->setHeaderLabel(trUtf8("Name"), 0); - parent_tables->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("uid")),0); + parent_tables->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")),0); parent_tables->setHeaderLabel(trUtf8("Schema"), 1); - parent_tables->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("schema")),1); + parent_tables->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("schema")),1); parent_tables->setHeaderLabel(trUtf8("Type"), 2); - parent_tables->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("usertype")),2); + parent_tables->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("usertype")),2); - tag_sel=new ObjectSelectorWidget(OBJ_TAG, false, this); - dynamic_cast(options_gb->layout())->addWidget(tag_sel, 0, 1,1,3); + tag_sel = new ObjectSelectorWidget(ObjectType::Tag, false, this); + vbox = new QVBoxLayout(tag_sel_parent); + vbox->addWidget(tag_sel); + vbox->setContentsMargins(0,0,0,0); grid=new QGridLayout; grid->addWidget(parent_tables, 0,0,1,1); grid->setContentsMargins(4,4,4,4); - attributes_tbw->widget(6)->setLayout(grid); + attributes_tbw->widget(7)->setLayout(grid); //Configuring the table objects that stores the columns, triggers, constraints, rules and indexes for(unsigned i=0; i <= 5; i++) { - tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ - (ObjectsTableWidget::UPDATE_BUTTON), true, this); + tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + (ObjectsTableWidget::UpdateButton), true, this); objects_tab_map[types[i]]=tab; @@ -94,73 +99,97 @@ TableWidget::TableWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_TABLE) connect(tab, SIGNAL(s_rowsMoved(int,int)), this, SLOT(swapObjects(int,int))); } - objects_tab_map[OBJ_COLUMN]->setColumnCount(5); - objects_tab_map[OBJ_COLUMN]->setHeaderLabel(trUtf8("PK"), 0); - objects_tab_map[OBJ_COLUMN]->setHeaderLabel(trUtf8("Name"), 1); - objects_tab_map[OBJ_COLUMN]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("uid")),1); - objects_tab_map[OBJ_COLUMN]->setHeaderLabel(trUtf8("Type"), 2); - objects_tab_map[OBJ_COLUMN]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("usertype")),2); - objects_tab_map[OBJ_COLUMN]->setHeaderLabel(trUtf8("Default Value"), 3); - objects_tab_map[OBJ_COLUMN]->setHeaderLabel(trUtf8("Attribute(s)"), 4); - objects_tab_map[OBJ_COLUMN]->adjustColumnToContents(0); - - connect(objects_tab_map[OBJ_COLUMN], &ObjectsTableWidget::s_cellClicked, [&](int row, int col){ - if(col == 0 && objects_tab_map[OBJ_COLUMN]->isCellDisabled(static_cast(row), static_cast(col))) + objects_tab_map[ObjectType::Column]->setColumnCount(7); + objects_tab_map[ObjectType::Column]->setHeaderLabel(trUtf8("PK"), 0); + objects_tab_map[ObjectType::Column]->setHeaderLabel(trUtf8("Name"), 1); + objects_tab_map[ObjectType::Column]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")),1); + objects_tab_map[ObjectType::Column]->setHeaderLabel(trUtf8("Type"), 2); + objects_tab_map[ObjectType::Column]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("usertype")),2); + objects_tab_map[ObjectType::Column]->setHeaderLabel(trUtf8("Default Value"), 3); + objects_tab_map[ObjectType::Column]->setHeaderLabel(trUtf8("Attribute(s)"), 4); + objects_tab_map[ObjectType::Column]->setHeaderLabel(trUtf8("Alias"), 5); + objects_tab_map[ObjectType::Column]->setHeaderLabel(trUtf8("Comment"), 6); + objects_tab_map[ObjectType::Column]->adjustColumnToContents(0); + + connect(objects_tab_map[ObjectType::Column], &ObjectsTableWidget::s_cellClicked, [&](int row, int col){ + if(col == 0 && objects_tab_map[ObjectType::Column]->isCellDisabled(static_cast(row), static_cast(col))) { Messagebox msg_box; Table *table = dynamic_cast
(this->object); Constraint *pk = table->getPrimaryKey(); if(pk && pk->isAddedByRelationship()) - msg_box.show(trUtf8("It is not possible to mark a column as primary key when the table already has a primary key which was created by a relationship! This action should be done in the section Primary key of the relationship's editing form."), Messagebox::ALERT_ICON); + msg_box.show(trUtf8("It is not possible to mark a column as primary key when the table already has a primary key which was created by a relationship! This action should be done in the section Primary key of the relationship's editing form."), Messagebox::AlertIcon); else - msg_box.show(trUtf8("It is not possible to mark a column created by a relationship as primary key! This action should be done in the section Primary key of the relationship's editing form."), Messagebox::ALERT_ICON); + msg_box.show(trUtf8("It is not possible to mark a column created by a relationship as primary key! This action should be done in the section Primary key of the relationship's editing form."), Messagebox::AlertIcon); } }); - objects_tab_map[OBJ_CONSTRAINT]->setColumnCount(4); - objects_tab_map[OBJ_CONSTRAINT]->setHeaderLabel(trUtf8("Name"), 0); - objects_tab_map[OBJ_CONSTRAINT]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("uid")),0); - objects_tab_map[OBJ_CONSTRAINT]->setHeaderLabel(trUtf8("Type"), 1); - objects_tab_map[OBJ_CONSTRAINT]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("usertype")),1); - objects_tab_map[OBJ_CONSTRAINT]->setHeaderLabel(trUtf8("ON DELETE"), 2); - objects_tab_map[OBJ_CONSTRAINT]->setHeaderLabel(trUtf8("ON UPDATE"), 3); - - objects_tab_map[OBJ_TRIGGER]->setColumnCount(4); - objects_tab_map[OBJ_TRIGGER]->setHeaderLabel(trUtf8("Name"), 0); - objects_tab_map[OBJ_TRIGGER]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("uid")),0); - objects_tab_map[OBJ_TRIGGER]->setHeaderLabel(trUtf8("Refer. Table"), 1); - objects_tab_map[OBJ_TRIGGER]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("table")),1); - objects_tab_map[OBJ_TRIGGER]->setHeaderLabel(trUtf8("Firing"), 2); - objects_tab_map[OBJ_TRIGGER]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("trigger")),2); - objects_tab_map[OBJ_TRIGGER]->setHeaderLabel(trUtf8("Events"), 3); - - objects_tab_map[OBJ_RULE]->setColumnCount(3); - objects_tab_map[OBJ_RULE]->setHeaderLabel(trUtf8("Name"), 0); - objects_tab_map[OBJ_RULE]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("uid")),0); - objects_tab_map[OBJ_RULE]->setHeaderLabel(trUtf8("Execution"), 1); - objects_tab_map[OBJ_RULE]->setHeaderLabel(trUtf8("Event"), 2); - - objects_tab_map[OBJ_INDEX]->setColumnCount(2); - objects_tab_map[OBJ_INDEX]->setHeaderLabel(trUtf8("Name"), 0); - objects_tab_map[OBJ_INDEX]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("uid")),0); - objects_tab_map[OBJ_INDEX]->setHeaderLabel(trUtf8("Indexing"), 1); - - objects_tab_map[OBJ_POLICY]->setColumnCount(6); - objects_tab_map[OBJ_POLICY]->setHeaderLabel(trUtf8("Name"), 0); - objects_tab_map[OBJ_POLICY]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("uid")),0); - objects_tab_map[OBJ_POLICY]->setHeaderLabel(trUtf8("Command"), 1); - objects_tab_map[OBJ_POLICY]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("keyword")),1); - objects_tab_map[OBJ_POLICY]->setHeaderLabel(trUtf8("Permissive"), 2); - objects_tab_map[OBJ_POLICY]->setHeaderLabel(trUtf8("USING expression"), 3); - objects_tab_map[OBJ_POLICY]->setHeaderLabel(trUtf8("CHECK expression"), 4); - objects_tab_map[OBJ_POLICY]->setHeaderLabel(trUtf8("Roles"), 5); - objects_tab_map[OBJ_POLICY]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("role")),5); - - configureFormLayout(table_grid, OBJ_TABLE); - configureTabOrder({ tag_sel }); + objects_tab_map[ObjectType::Constraint]->setColumnCount(6); + objects_tab_map[ObjectType::Constraint]->setHeaderLabel(trUtf8("Name"), 0); + objects_tab_map[ObjectType::Constraint]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")),0); + objects_tab_map[ObjectType::Constraint]->setHeaderLabel(trUtf8("Type"), 1); + objects_tab_map[ObjectType::Constraint]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("usertype")),1); + objects_tab_map[ObjectType::Constraint]->setHeaderLabel(trUtf8("ON DELETE"), 2); + objects_tab_map[ObjectType::Constraint]->setHeaderLabel(trUtf8("ON UPDATE"), 3); + objects_tab_map[ObjectType::Constraint]->setHeaderLabel(trUtf8("Alias"), 4); + objects_tab_map[ObjectType::Constraint]->setHeaderLabel(trUtf8("Comment"), 5); + + objects_tab_map[ObjectType::Trigger]->setColumnCount(6); + objects_tab_map[ObjectType::Trigger]->setHeaderLabel(trUtf8("Name"), 0); + objects_tab_map[ObjectType::Trigger]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")),0); + objects_tab_map[ObjectType::Trigger]->setHeaderLabel(trUtf8("Refer. Table"), 1); + objects_tab_map[ObjectType::Trigger]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("table")),1); + objects_tab_map[ObjectType::Trigger]->setHeaderLabel(trUtf8("Firing"), 2); + objects_tab_map[ObjectType::Trigger]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("trigger")),2); + objects_tab_map[ObjectType::Trigger]->setHeaderLabel(trUtf8("Events"), 3); + objects_tab_map[ObjectType::Trigger]->setHeaderLabel(trUtf8("Alias"), 4); + objects_tab_map[ObjectType::Trigger]->setHeaderLabel(trUtf8("Comment"), 5); + + objects_tab_map[ObjectType::Rule]->setColumnCount(5); + objects_tab_map[ObjectType::Rule]->setHeaderLabel(trUtf8("Name"), 0); + objects_tab_map[ObjectType::Rule]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")),0); + objects_tab_map[ObjectType::Rule]->setHeaderLabel(trUtf8("Execution"), 1); + objects_tab_map[ObjectType::Rule]->setHeaderLabel(trUtf8("Event"), 2); + objects_tab_map[ObjectType::Rule]->setHeaderLabel(trUtf8("Alias"), 3); + objects_tab_map[ObjectType::Rule]->setHeaderLabel(trUtf8("Comment"), 4); + + objects_tab_map[ObjectType::Index]->setColumnCount(4); + objects_tab_map[ObjectType::Index]->setHeaderLabel(trUtf8("Name"), 0); + objects_tab_map[ObjectType::Index]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")),0); + objects_tab_map[ObjectType::Index]->setHeaderLabel(trUtf8("Indexing"), 1); + objects_tab_map[ObjectType::Index]->setHeaderLabel(trUtf8("Alias"), 2); + objects_tab_map[ObjectType::Index]->setHeaderLabel(trUtf8("Comment"), 3); + + objects_tab_map[ObjectType::Policy]->setColumnCount(8); + objects_tab_map[ObjectType::Policy]->setHeaderLabel(trUtf8("Name"), 0); + objects_tab_map[ObjectType::Policy]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")),0); + objects_tab_map[ObjectType::Policy]->setHeaderLabel(trUtf8("Command"), 1); + objects_tab_map[ObjectType::Policy]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("keyword")),1); + objects_tab_map[ObjectType::Policy]->setHeaderLabel(trUtf8("Permissive"), 2); + objects_tab_map[ObjectType::Policy]->setHeaderLabel(trUtf8("USING expression"), 3); + objects_tab_map[ObjectType::Policy]->setHeaderLabel(trUtf8("CHECK expression"), 4); + objects_tab_map[ObjectType::Policy]->setHeaderLabel(trUtf8("Roles"), 5); + objects_tab_map[ObjectType::Policy]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("role")),5); + objects_tab_map[ObjectType::Policy]->setHeaderLabel(trUtf8("Alias"), 6); + objects_tab_map[ObjectType::Policy]->setHeaderLabel(trUtf8("Comment"), 7); + + partition_keys_tab = new ElementsTableWidget; + partition_keys_tab->setEnabled(false); + grid = dynamic_cast(attributes_tbw->widget(6)->layout()); + grid->addWidget(partition_keys_tab, 1, 0, 1, 2); + + PartitioningType::getTypes(part_types); + part_types.push_front(trUtf8("None")); + partitioning_type_cmb->addItems(part_types); + + connect(partitioning_type_cmb, &QComboBox::currentTextChanged, [&](){ + partition_keys_tab->setEnabled(partitioning_type_cmb->currentIndex() != 0); + }); - setMinimumSize(600, 610); + configureFormLayout(table_grid, ObjectType::Table); + configureTabOrder({ tag_sel }); + setMinimumSize(660, 620); } template @@ -168,10 +197,17 @@ int TableWidget::openEditingForm(TableObject *object) { BaseForm editing_form(this); WidgetClass *object_wgt=new WidgetClass; + int res = 0; + object_wgt->setAttributes(this->model, this->op_list, - dynamic_cast
(this->object), dynamic_cast(object)); + dynamic_cast
(this->object), dynamic_cast(object)); editing_form.setMainWidget(object_wgt); - return(editing_form.exec()); + + GeneralConfigWidget::restoreWidgetGeometry(&editing_form, object_wgt->metaObject()->className()); + res = editing_form.exec(); + GeneralConfigWidget::saveWidgetGeometry(&editing_form, object_wgt->metaObject()->className()); + + return(res); } ObjectsTableWidget *TableWidget::getObjectTable(ObjectType obj_type) @@ -184,7 +220,7 @@ ObjectsTableWidget *TableWidget::getObjectTable(ObjectType obj_type) ObjectType TableWidget::getObjectType(QObject *sender) { - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; if(sender) { @@ -193,7 +229,7 @@ ObjectType TableWidget::getObjectType(QObject *sender) itr=objects_tab_map.begin(); itr_end=objects_tab_map.end(); - while(itr!=itr_end && obj_type==BASE_OBJECT) + while(itr!=itr_end && obj_type==ObjectType::BaseObject) { if(itr->second==sender) obj_type=itr->first; @@ -211,7 +247,8 @@ void TableWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Sc { unsigned i, count; Table *aux_tab=nullptr; - ObjectType types[]={ OBJ_COLUMN, OBJ_CONSTRAINT, OBJ_TRIGGER, OBJ_RULE, OBJ_INDEX, OBJ_POLICY }; + ObjectType types[]={ ObjectType::Column, ObjectType::Constraint, ObjectType::Trigger, ObjectType::Rule, ObjectType::Index, ObjectType::Policy }; + vector part_keys; if(!table) { @@ -235,8 +272,8 @@ void TableWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Sc for(i=0; i < 6; i++) { listObjects(types[i]); - objects_tab_map[types[i]]->setButtonConfiguration(ObjectsTableWidget::ALL_BUTTONS ^ - (ObjectsTableWidget::UPDATE_BUTTON)); + objects_tab_map[types[i]]->setButtonConfiguration(ObjectsTableWidget::AllButtons ^ + (ObjectsTableWidget::UpdateButton)); } //Listing the ancestor tables @@ -253,12 +290,33 @@ void TableWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Sc aux_tab=table->getCopyTable(); if(aux_tab) { + i = parent_tables->getRowCount(); parent_tables->addRow(); parent_tables->setCellText(aux_tab->getName(), i, 0); parent_tables->setCellText(aux_tab->getSchema()->getName(), i, 1); parent_tables->setCellText(trUtf8("Copy"), i, 2); } + aux_tab=table->getPartitionedTable(); + if(aux_tab) + { + i = parent_tables->getRowCount(); + parent_tables->addRow(); + parent_tables->setCellText(aux_tab->getName(), i, 0); + parent_tables->setCellText(aux_tab->getSchema()->getName(), i, 1); + parent_tables->setCellText(trUtf8("Partitioned"), i, 2); + } + + i = parent_tables->getRowCount(); + for(auto &tab : table->getPartionTables()) + { + parent_tables->addRow(); + parent_tables->setCellText(tab->getName(), i, 0); + parent_tables->setCellText(tab->getSchema()->getName(), i, 1); + parent_tables->setCellText(trUtf8("Partition"), i, 2); + i++; + } + parent_tables->clearSelection(); with_oids_chk->setChecked(table->isWithOIDs()); unlogged_chk->setChecked(table->isUnlogged()); @@ -268,10 +326,18 @@ void TableWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Sc tag_sel->setModel(this->model); tag_sel->setSelectedObject(table->getTag()); + + int idx = partitioning_type_cmb->findText(~table->getPartitioningType()); + partitioning_type_cmb->setCurrentIndex(idx < 0 ? 0 : idx); + partition_keys_tab->setAttributes(model, table); + + part_keys = table->getPartitionKeys(); + partition_keys_tab->setAttributes(this->model, table); + partition_keys_tab->setElements(part_keys); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -301,25 +367,25 @@ void TableWidget::listObjects(ObjectType obj_type) tab->blockSignals(false); //Enables the add button on the constraints, triggers and index tab only when there is columns created - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) { - objects_tab_map[OBJ_CONSTRAINT]->setButtonsEnabled(ObjectsTableWidget::ADD_BUTTON, - objects_tab_map[OBJ_COLUMN]->getRowCount() > 0); - objects_tab_map[OBJ_TRIGGER]->setButtonsEnabled(ObjectsTableWidget::ADD_BUTTON, - objects_tab_map[OBJ_COLUMN]->getRowCount() > 0); - objects_tab_map[OBJ_INDEX]->setButtonsEnabled(ObjectsTableWidget::ADD_BUTTON, - objects_tab_map[OBJ_COLUMN]->getRowCount() > 0); + objects_tab_map[ObjectType::Constraint]->setButtonsEnabled(ObjectsTableWidget::AddButton, + objects_tab_map[ObjectType::Column]->getRowCount() > 0); + objects_tab_map[ObjectType::Trigger]->setButtonsEnabled(ObjectsTableWidget::AddButton, + objects_tab_map[ObjectType::Column]->getRowCount() > 0); + objects_tab_map[ObjectType::Index]->setButtonsEnabled(ObjectsTableWidget::AddButton, + objects_tab_map[ObjectType::Column]->getRowCount() > 0); } } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void TableWidget::handleObject(void) { - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; TableObject *object=nullptr; ObjectsTableWidget *obj_table=nullptr; @@ -334,28 +400,28 @@ void TableWidget::handleObject(void) if(obj_table->getSelectedRow()>=0) object=reinterpret_cast(obj_table->getRowData(obj_table->getSelectedRow()).value()); - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) openEditingForm(object); - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) openEditingForm(object); - else if(obj_type==OBJ_TRIGGER) + else if(obj_type==ObjectType::Trigger) openEditingForm(object); - else if(obj_type==OBJ_INDEX) + else if(obj_type==ObjectType::Index) openEditingForm(object); - else if(obj_type==OBJ_RULE) + else if(obj_type==ObjectType::Rule) openEditingForm(object); else openEditingForm(object); listObjects(obj_type); - if(obj_type == OBJ_CONSTRAINT) - listObjects(OBJ_COLUMN); + if(obj_type == ObjectType::Constraint) + listObjects(ObjectType::Column); } catch(Exception &e) { listObjects(obj_type); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -371,31 +437,31 @@ void TableWidget::showObjectData(TableObject *object, int row) ObjectType obj_type; QString str_aux, str_aux1; - QStringList contr_types={ ~ConstraintType(ConstraintType::primary_key), ~ConstraintType(ConstraintType::foreign_key), - ~ConstraintType(ConstraintType::check), ~ConstraintType(ConstraintType::unique), + QStringList contr_types={ ~ConstraintType(ConstraintType::PrimaryKey), ~ConstraintType(ConstraintType::ForeignKey), + ~ConstraintType(ConstraintType::Check), ~ConstraintType(ConstraintType::Unique), QString("NOT NULL") }, - constr_codes={ TableObjectView::TXT_PRIMARY_KEY, - TableObjectView::TXT_FOREIGN_KEY, - TableObjectView::TXT_CHECK, - TableObjectView::TXT_UNIQUE, - TableObjectView::TXT_NOT_NULL}; + constr_codes={ TableObjectView::TextPrimaryKey, + TableObjectView::TextForeignKey, + TableObjectView::TextCheck, + TableObjectView::TextUnique, + TableObjectView::TextNotNull}; QFont font; unsigned i; - EventType events[]={ EventType::on_insert, EventType::on_delete, - EventType::on_truncate, EventType::on_update }; + EventType events[]={ EventType::OnInsert, EventType::OnDelete, + EventType::OnTruncate, EventType::OnUpdate }; obj_type=object->getObjectType(); tab=objects_tab_map[obj_type]; - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) tab->setCellText(object->getName(),row,1); else tab->setCellText(object->getName(),row,0); //For each object type there is a use for the columns from 1 to 3 - if(obj_type==OBJ_COLUMN) + if(obj_type==ObjectType::Column) { Table *table = dynamic_cast
(this->object); Constraint *pk = table->getPrimaryKey(); @@ -407,7 +473,7 @@ void TableWidget::showObjectData(TableObject *object, int row) //Column 3: Column defaul value if(column->getSequence()) str_aux=QString("nextval('%1'::regclass)").arg(column->getSequence()->getName(true).remove('"')); - else if(column->getIdentityType() != BaseType::null) + else if(column->getIdentityType() != BaseType::Null) str_aux=QString("GENERATED %1 AS IDENTITY").arg(~column->getIdentityType()); else str_aux=column->getDefaultValue(); @@ -430,7 +496,7 @@ void TableWidget::showObjectData(TableObject *object, int row) tab->setCellText(str_aux1,row,4); - if(str_aux.indexOf(TableObjectView::TXT_PRIMARY_KEY) >= 0) + if(str_aux.indexOf(TableObjectView::TextPrimaryKey) >= 0) tab->setCellCheckState(row, 0, Qt::Checked); else tab->setCellCheckState(row, 0, Qt::Unchecked); @@ -438,16 +504,17 @@ void TableWidget::showObjectData(TableObject *object, int row) if(column->isAddedByRelationship() || (pk && pk->isAddedByRelationship())) tab->setCellDisabled(row, 0, true); + tab->setCellText(column->getAlias(), row, 5); tab->adjustColumnToContents(0); } - else if(obj_type==OBJ_CONSTRAINT) + else if(obj_type==ObjectType::Constraint) { constr=dynamic_cast(object); //Column 1: Constraint type tab->setCellText(~constr->getConstraintType(),row,1); - if(constr->getConstraintType()==ConstraintType::foreign_key) + if(constr->getConstraintType()==ConstraintType::ForeignKey) { //Column 2: ON DELETE action tab->setCellText(~constr->getActionType(false),row,2); @@ -460,8 +527,10 @@ void TableWidget::showObjectData(TableObject *object, int row) tab->setCellText(QString("-"),row,2); tab->setCellText(QString("-"),row,3); } + + tab->setCellText(constr->getAlias(), row, 4); } - else if(obj_type==OBJ_TRIGGER) + else if(obj_type==ObjectType::Trigger) { trigger=dynamic_cast(object); @@ -480,9 +549,10 @@ void TableWidget::showObjectData(TableObject *object, int row) str_aux+=~events[i] + QString(", "); } str_aux.remove(str_aux.size()-2, 2); - tab->setCellText(str_aux ,row,3); + tab->setCellText(str_aux ,row,3); + tab->setCellText(trigger->getAlias(), row, 4); } - else if(obj_type==OBJ_RULE) + else if(obj_type==ObjectType::Rule) { rule=dynamic_cast(object); @@ -491,15 +561,19 @@ void TableWidget::showObjectData(TableObject *object, int row) //Column 2: Rule event type tab->setCellText(~rule->getEventType(),row,2); + + tab->setCellText(rule->getAlias(), row, 3); } - else if(obj_type==OBJ_INDEX) + else if(obj_type==ObjectType::Index) { index=dynamic_cast(object); //Coluna 1: Indexing type tab->setCellText(~index->getIndexingType(),row,1); + + tab->setCellText(index->getAlias(), row, 2); } - else if(obj_type==OBJ_POLICY) + else if(obj_type==ObjectType::Policy) { QStringList rol_names; @@ -522,6 +596,8 @@ void TableWidget::showObjectData(TableObject *object, int row) //Column 5: Roles tab->setCellText(!rol_names.isEmpty() ? rol_names.join(", ") : QString("PUBLIC"), row, 5); + + tab->setCellText(policy->getAlias(), row, 6); } //Changes the foreground/background color of the table row if the object is protected or added by relationship @@ -531,11 +607,12 @@ void TableWidget::showObjectData(TableObject *object, int row) font.setItalic(true); if(object->isAddedByRelationship()) - tab->setRowFont(row, font, RELINC_LINE_FGCOLOR, RELINC_LINE_BGCOLOR); + tab->setRowFont(row, font, RelAddedRowFgColor, RelAddedRowBgColor); else - tab->setRowFont(row, font, PROT_LINE_FGCOLOR, PROT_LINE_BGCOLOR); + tab->setRowFont(row, font, ProtRowFgColor, ProtRowBgColor); } + tab->setCellText(object->getComment(), row, tab->getColumnCount() - 1); tab->setRowData(QVariant::fromValue(object), row); } @@ -544,7 +621,7 @@ void TableWidget::removeObjects(void) Table *table=nullptr; unsigned count, op_count=0, i; BaseObject *object=nullptr; - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; try { @@ -561,18 +638,18 @@ void TableWidget::removeObjects(void) if(!object->isProtected() && !dynamic_cast(object)->isAddedByRelationship()) { - op_list->registerObject(object, Operation::OBJECT_REMOVED, 0, this->object); + op_list->registerObject(object, Operation::ObjectRemoved, 0, this->object); table->removeObject(object); } else - throw Exception(Exception::getErrorMessage(ERR_REM_PROTECTED_OBJECT) + throw Exception(Exception::getErrorMessage(ErrorCode::RemProtectedObject) .arg(object->getName()) .arg(object->getTypeName()), - ERR_REM_PROTECTED_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::RemProtectedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); } - if(obj_type == OBJ_CONSTRAINT) - listObjects(OBJ_COLUMN); + if(obj_type == ObjectType::Constraint) + listObjects(ObjectType::Column); } catch(Exception &e) { @@ -592,7 +669,7 @@ void TableWidget::removeObjects(void) listObjects(obj_type); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -600,7 +677,7 @@ void TableWidget::removeObject(int row) { Table *table=nullptr; BaseObject *object=nullptr; - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; int op_id=-1; try @@ -613,18 +690,18 @@ void TableWidget::removeObject(int row) if(!object->isProtected() && !dynamic_cast(object)->isAddedByRelationship()) { - op_id=op_list->registerObject(object, Operation::OBJECT_REMOVED, row, this->object); + op_id=op_list->registerObject(object, Operation::ObjectRemoved, row, this->object); table->removeObject(object); table->setModified(true); } else - throw Exception(Exception::getErrorMessage(ERR_REM_PROTECTED_OBJECT) + throw Exception(Exception::getErrorMessage(ErrorCode::RemProtectedObject) .arg(object->getName()) .arg(object->getTypeName()), - ERR_REM_PROTECTED_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::RemProtectedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(obj_type == OBJ_CONSTRAINT) - listObjects(OBJ_COLUMN); + if(obj_type == ObjectType::Constraint) + listObjects(ObjectType::Column); } catch(Exception &e) { @@ -637,13 +714,13 @@ void TableWidget::removeObject(int row) } listObjects(obj_type); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void TableWidget::duplicateObject(int sel_row, int new_row) { - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; BaseObject *object=nullptr, *dup_object=nullptr; ObjectsTableWidget *obj_table=nullptr; Table *table = dynamic_cast
(this->object); @@ -660,10 +737,10 @@ void TableWidget::duplicateObject(int sel_row, int new_row) if(sel_row >= 0) object = reinterpret_cast(obj_table->getRowData(sel_row).value()); - PgModelerNS::copyObject(&dup_object, object, obj_type); - dup_object->setName(PgModelerNS::generateUniqueName(dup_object, *table->getObjectList(obj_type), false, QString("_cp"))); + PgModelerNs::copyObject(&dup_object, object, obj_type); + dup_object->setName(PgModelerNs::generateUniqueName(dup_object, *table->getObjectList(obj_type), false, QString("_cp"))); - op_id=op_list->registerObject(dup_object, Operation::OBJECT_CREATED, new_row, this->object); + op_id=op_list->registerObject(dup_object, Operation::ObjectCreated, new_row, this->object); table->addObject(dup_object); table->setModified(true); @@ -680,13 +757,13 @@ void TableWidget::duplicateObject(int sel_row, int new_row) } listObjects(obj_type); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void TableWidget::TableWidget::swapObjects(int idx1, int idx2) { - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; Table *table=nullptr; int count; @@ -713,7 +790,7 @@ void TableWidget::TableWidget::swapObjects(int idx1, int idx2) catch(Exception &e) { listObjects(obj_type); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -724,8 +801,11 @@ void TableWidget::editData(void) tab_data_wgt->setAttributes(this->model, dynamic_cast
(this->object)); base_form.setMainWidget(tab_data_wgt); - base_form.setButtonConfiguration(Messagebox::OK_CANCEL_BUTTONS); + base_form.setButtonConfiguration(Messagebox::OkCancelButtons); + + GeneralConfigWidget::restoreWidgetGeometry(&base_form, tab_data_wgt->metaObject()->className()); base_form.exec(); + GeneralConfigWidget::saveWidgetGeometry(&base_form, tab_data_wgt->metaObject()->className()); } void TableWidget::applyConfiguration(void) @@ -736,10 +816,12 @@ void TableWidget::applyConfiguration(void) Constraint *pk = nullptr; vector rels; vector pk_cols; - ObjectsTableWidget *col_tab = objects_tab_map[OBJ_COLUMN]; + vector part_keys; + ObjectsTableWidget *col_tab = objects_tab_map[ObjectType::Column]; + PartitioningType part_type; if(!this->new_object) - op_list->registerObject(this->object, Operation::OBJECT_MODIFIED); + op_list->registerObject(this->object, Operation::ObjectModified); else registerNewObject(); @@ -751,6 +833,20 @@ void TableWidget::applyConfiguration(void) table->setUnlogged(unlogged_chk->isChecked()); table->setTag(dynamic_cast(tag_sel->getSelectedObject())); + part_type = partitioning_type_cmb->currentIndex() == 0 ? BaseType::Null : PartitioningType(partitioning_type_cmb->currentText()); + table->setPartitioningType(part_type); + + if(part_type != BaseType::Null) + { + partition_keys_tab->getElements(part_keys); + table->addPartitionKeys(part_keys); + + if(part_keys.empty()) + part_type = BaseType::Null; + } + else + table->removePartitionKeys(); + BaseObjectWidget::applyConfiguration(); //Retrieving all columns marked as primary key @@ -772,28 +868,40 @@ void TableWidget::applyConfiguration(void) pk = new Constraint; pk->setName(pk_name); - pk->setName(PgModelerNS::generateUniqueName(pk, *table->getObjectList(OBJ_CONSTRAINT))); + pk->setName(PgModelerNs::generateUniqueName(pk, *table->getObjectList(ObjectType::Constraint))); for(Column *col : pk_cols) - pk->addColumn(col, Constraint::SOURCE_COLS); + pk->addColumn(col, Constraint::SourceCols); table->addConstraint(pk); - op_list->registerObject(pk, Operation::OBJECT_CREATED, -1, table); + op_list->registerObject(pk, Operation::ObjectCreated, -1, table); } else if(!pk->isAddedByRelationship()) { + vector orig_pk_cols = pk->getColumns(Constraint::SourceCols); + //If the table owns a pk we only update the columns - op_list->registerObject(pk, Operation::OBJECT_MODIFIED, -1, table); + op_list->registerObject(pk, Operation::ObjectModified, -1, table); pk->removeColumns(); + /* Adding the original primary key columns if they also exists in the + * list of columns generated by the selection in the column list */ + for(auto col : orig_pk_cols) + { + if(std::find(pk_cols.begin(), pk_cols.end(), col) != pk_cols.end()) + pk->addColumn(col, Constraint::SourceCols); + } + + /* Adding the other columns selected in the grid as pk columns. + * Duplicated columns are discarded by the method Constraint::addColumn */ for(Column *col : pk_cols) - pk->addColumn(col, Constraint::SOURCE_COLS); + pk->addColumn(col, Constraint::SourceCols); } } else if(pk_cols.empty() && pk && !pk->isAddedByRelationship()) { //Removing the primary key from the table when no column is checked as pk - op_list->registerObject(pk, Operation::OBJECT_REMOVED, -1, table); + op_list->registerObject(pk, Operation::ObjectRemoved, -1, table); table->removeObject(pk); } @@ -805,37 +913,38 @@ void TableWidget::applyConfiguration(void) model->validateRelationships(); model->updateTableFKRelationships(table); + model->updateViewsReferencingTable(table); } catch(Exception &e) { Messagebox msg_box; - if(e.getErrorType()==ERR_INVALIDATED_OBJECTS) + if(e.getErrorCode()==ErrorCode::RemInvalidatedObjects) msg_box.show(e); else - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } op_list->finishOperationChain(); finishConfiguration(); - if(RelationshipView::getLineConnectinMode()==RelationshipView::CONNECT_FK_TO_PK) + if(RelationshipView::getLineConnectinMode()==RelationshipView::ConnectFkToPk) { /* Forcing the update of relationships connected to the table in order to reconfigure the line in case of the relationship is using the CONNECT_FK_TO_PK line mode */ rels=model->getRelationships(table); for(auto &rel : rels) { - if(rel->getRelationshipType()==Relationship::RELATIONSHIP_11 || - rel->getRelationshipType()==Relationship::RELATIONSHIP_1N || - rel->getRelationshipType()==Relationship::RELATIONSHIP_FK) + if(rel->getRelationshipType()==Relationship::Relationship11 || + rel->getRelationshipType()==Relationship::Relationship1n || + rel->getRelationshipType()==Relationship::RelationshipFk) rel->setModified(true); } } } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/tablewidget.h b/libpgmodeler_ui/src/tablewidget.h index 2019e12fa7..53c2174c45 100644 --- a/libpgmodeler_ui/src/tablewidget.h +++ b/libpgmodeler_ui/src/tablewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -29,6 +29,7 @@ #include "ui_tablewidget.h" #include "objectstablewidget.h" #include "tableview.h" +#include "elementstablewidget.h" class TableWidget: public BaseObjectWidget, public Ui::TableWidget { private: @@ -36,6 +37,8 @@ class TableWidget: public BaseObjectWidget, public Ui::TableWidget { ObjectsTableWidget *parent_tables; + ElementsTableWidget *partition_keys_tab; + ObjectSelectorWidget *tag_sel; //! \brief Stores the objects tables used to handle columns, constraints, indexes, rules and triggers @@ -59,7 +62,7 @@ class TableWidget: public BaseObjectWidget, public Ui::TableWidget { int openEditingForm(TableObject *object); public: - TableWidget(QWidget * parent = 0); + TableWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, Table *table, double pos_x, double pos_y); diff --git a/libpgmodeler_ui/src/tagwidget.cpp b/libpgmodeler_ui/src/tagwidget.cpp index dacae2328e..7a87965e0d 100644 --- a/libpgmodeler_ui/src/tagwidget.cpp +++ b/libpgmodeler_ui/src/tagwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,20 +18,20 @@ #include "tagwidget.h" -TagWidget::TagWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_TAG) +TagWidget::TagWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Tag) { Ui_TagWidget::setupUi(this); - configureFormLayout(tag_grid, OBJ_TAG); + configureFormLayout(tag_grid, ObjectType::Tag); - QStringList attribs={ ParsersAttributes::TABLE_NAME, ParsersAttributes::TABLE_SCHEMA_NAME, - ParsersAttributes::TABLE_TITLE, ParsersAttributes::TABLE_BODY, - ParsersAttributes::TABLE_EXT_BODY }; + QStringList attribs={ Attributes::TableName, Attributes::TableSchemaName, + Attributes::TableTitle, Attributes::TableBody, + Attributes::TableExtBody }; unsigned color_count=1; int row=0; for(auto &attr : attribs) { - if(color_count==1 && attr!=ParsersAttributes::TABLE_NAME && attr!=ParsersAttributes::TABLE_SCHEMA_NAME) + if(color_count==1 && attr!=Attributes::TableName && attr!=Attributes::TableSchemaName) color_count=3; color_pickers[attr]=new ColorPickerWidget(color_count, this); @@ -46,15 +46,15 @@ TagWidget::TagWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_TAG) void TagWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Tag *tag) { unsigned color_count=1, i; - QStringList attribs={ ParsersAttributes::TABLE_NAME, ParsersAttributes::TABLE_SCHEMA_NAME, - ParsersAttributes::TABLE_TITLE, ParsersAttributes::TABLE_BODY, - ParsersAttributes::TABLE_EXT_BODY }; + QStringList attribs={ Attributes::TableName, Attributes::TableSchemaName, + Attributes::TableTitle, Attributes::TableBody, + Attributes::TableExtBody }; BaseObjectWidget::setAttributes(model, op_list, tag); for(auto &attr : attribs) { - if(color_count==1 && attr!=ParsersAttributes::TABLE_NAME && attr!=ParsersAttributes::TABLE_SCHEMA_NAME) + if(color_count==1 && attr!=Attributes::TableName && attr!=Attributes::TableSchemaName) color_count=3; for(i=0; i < color_count; i++) @@ -73,24 +73,24 @@ void TagWidget::applyConfiguration(void) { Tag *tag=nullptr; vector tagged_tabs; - QStringList attribs={ ParsersAttributes::TABLE_TITLE, ParsersAttributes::TABLE_BODY, - ParsersAttributes::TABLE_EXT_BODY }; + QStringList attribs={ Attributes::TableTitle, Attributes::TableBody, + Attributes::TableExtBody }; startConfiguration(); tag=dynamic_cast(this->object); BaseObjectWidget::applyConfiguration(); - tag->setElementColor(ParsersAttributes::TABLE_NAME, color_pickers[ParsersAttributes::TABLE_NAME]->getColor(0), Tag::FILL_COLOR1); - tag->setElementColor(ParsersAttributes::TABLE_SCHEMA_NAME, color_pickers[ParsersAttributes::TABLE_SCHEMA_NAME]->getColor(0), Tag::FILL_COLOR1); + tag->setElementColor(Attributes::TableName, color_pickers[Attributes::TableName]->getColor(0), Tag::FillColor1); + tag->setElementColor(Attributes::TableSchemaName, color_pickers[Attributes::TableSchemaName]->getColor(0), Tag::FillColor1); for(auto &attr : attribs) { tag->setElementColors(attr, QString("%1,%2,%3") - .arg(color_pickers[attr]->getColor(Tag::FILL_COLOR1).name()) - .arg(color_pickers[attr]->getColor(Tag::FILL_COLOR2).name()) - .arg(color_pickers[attr]->getColor(Tag::BORDER_COLOR).name())); + .arg(color_pickers[attr]->getColor(Tag::FillColor1).name()) + .arg(color_pickers[attr]->getColor(Tag::FillColor2).name()) + .arg(color_pickers[attr]->getColor(Tag::BorderColor).name())); } model->getObjectReferences(tag, tagged_tabs); @@ -105,7 +105,7 @@ void TagWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/tagwidget.h b/libpgmodeler_ui/src/tagwidget.h index a33cdbcde5..738cb2d6be 100644 --- a/libpgmodeler_ui/src/tagwidget.h +++ b/libpgmodeler_ui/src/tagwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -38,7 +38,7 @@ class TagWidget: public BaseObjectWidget, public Ui::TagWidget { map color_pickers; public: - TagWidget(QWidget * parent = 0); + TagWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Tag *tag); diff --git a/libpgmodeler_ui/src/taskprogresswidget.cpp b/libpgmodeler_ui/src/taskprogresswidget.cpp index 930d7cd739..7afd95da79 100644 --- a/libpgmodeler_ui/src/taskprogresswidget.cpp +++ b/libpgmodeler_ui/src/taskprogresswidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -28,7 +28,7 @@ TaskProgressWidget::TaskProgressWidget(QWidget *parent, Qt::WindowFlags f) : QDi this->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); for(auto &obj_tp : obj_types) - addIcon(obj_tp, QIcon(PgModelerUiNS::getIconPath(obj_tp))); + addIcon(enum_cast(obj_tp), QIcon(PgModelerUiNs::getIconPath(obj_tp))); } void TaskProgressWidget::addIcon(unsigned id, const QIcon &ico) @@ -43,7 +43,7 @@ void TaskProgressWidget::show(void) isn't used the task is not shown properly and sometimes stay only on taskbar not poping up to the user. */ QEventLoop eventLoop; - PgModelerUiNS::resizeDialog(this); + PgModelerUiNs::resizeDialog(this); QDialog::show(); QTimer t; @@ -66,7 +66,7 @@ void TaskProgressWidget::updateProgress(int progress, QString text, unsigned ico progress_pb->setValue(progress); if(!text.isEmpty()) - text_lbl->setText(PgModelerUiNS::formatMessage(text)); + text_lbl->setText(PgModelerUiNs::formatMessage(text)); if(icons.count(icon_id)) icon_lbl->setPixmap(icons[icon_id].pixmap(QSize(32,32))); diff --git a/libpgmodeler_ui/src/taskprogresswidget.h b/libpgmodeler_ui/src/taskprogresswidget.h index 7b9a08294c..e94f67ae9f 100644 --- a/libpgmodeler_ui/src/taskprogresswidget.h +++ b/libpgmodeler_ui/src/taskprogresswidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -40,7 +40,7 @@ class TaskProgressWidget: public QDialog, public Ui::TaskProgressWidget map icons; public: - TaskProgressWidget(QWidget *parent=0, Qt::WindowFlags f=0); + TaskProgressWidget(QWidget *parent = nullptr, Qt::WindowFlags f = Qt::Widget); void addIcon(unsigned id, const QIcon &ico); public slots: diff --git a/libpgmodeler_ui/src/textboxwidget.cpp b/libpgmodeler_ui/src/textboxwidget.cpp index 2adfc67460..ca628ecce7 100644 --- a/libpgmodeler_ui/src/textboxwidget.cpp +++ b/libpgmodeler_ui/src/textboxwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,10 +18,10 @@ #include "textboxwidget.h" -TextboxWidget::TextboxWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_TEXTBOX) +TextboxWidget::TextboxWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Textbox) { Ui_TextboxWidget::setupUi(this); - configureFormLayout(textbox_grid, OBJ_TEXTBOX); + configureFormLayout(textbox_grid, ObjectType::Textbox); text_txt->removeEventFilter(this); connect(color_select_tb, SIGNAL(clicked(void)), this, SLOT(selectTextColor(void))); @@ -38,9 +38,9 @@ void TextboxWidget::setAttributes(DatabaseModel *model, OperationList *op_list, color_select_tb->setPalette(palette); text_txt->setPlainText(txtbox->getComment()); - bold_chk->setChecked(txtbox->getTextAttribute(Textbox::BOLD_TXT)); - italic_chk->setChecked(txtbox->getTextAttribute(Textbox::ITALIC_TXT)); - underline_chk->setChecked(txtbox->getTextAttribute(Textbox::UNDERLINE_TXT)); + bold_chk->setChecked(txtbox->getTextAttribute(Textbox::BoldText)); + italic_chk->setChecked(txtbox->getTextAttribute(Textbox::ItalicText)); + underline_chk->setChecked(txtbox->getTextAttribute(Textbox::UnderlineText)); font_size_sb->setValue(txtbox->getFontSize()); } @@ -73,9 +73,9 @@ void TextboxWidget::applyConfiguration(void) txtbox=dynamic_cast(this->object); txtbox->setComment(text_txt->toPlainText().toUtf8()); - txtbox->setTextAttribute(Textbox::ITALIC_TXT, italic_chk->isChecked()); - txtbox->setTextAttribute(Textbox::BOLD_TXT, bold_chk->isChecked()); - txtbox->setTextAttribute(Textbox::UNDERLINE_TXT, underline_chk->isChecked()); + txtbox->setTextAttribute(Textbox::ItalicText, italic_chk->isChecked()); + txtbox->setTextAttribute(Textbox::BoldText, bold_chk->isChecked()); + txtbox->setTextAttribute(Textbox::UnderlineText, underline_chk->isChecked()); txtbox->setTextColor(color_select_tb->palette().color(QPalette::Button)); txtbox->setFontSize(font_size_sb->value()); @@ -85,7 +85,7 @@ void TextboxWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/textboxwidget.h b/libpgmodeler_ui/src/textboxwidget.h index 2b79912227..c83da289ed 100644 --- a/libpgmodeler_ui/src/textboxwidget.h +++ b/libpgmodeler_ui/src/textboxwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -33,9 +33,9 @@ class TextboxWidget: public BaseObjectWidget, public Ui::TextboxWidget { Q_OBJECT public: - TextboxWidget(QWidget * parent = 0); + TextboxWidget(QWidget * parent = nullptr); - void setAttributes(DatabaseModel *model, OperationList *op_list, Textbox *txtbox=nullptr, double obj_px=NAN, double obj_py=NAN); + void setAttributes(DatabaseModel *model, OperationList *op_list, Textbox *txtbox=nullptr, double obj_px=DNaN, double obj_py=DNaN); private slots: void selectTextColor(void); diff --git a/libpgmodeler_ui/src/triggerwidget.cpp b/libpgmodeler_ui/src/triggerwidget.cpp index d619ad9466..ec3f07ff68 100644 --- a/libpgmodeler_ui/src/triggerwidget.cpp +++ b/libpgmodeler_ui/src/triggerwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "triggerwidget.h" -TriggerWidget::TriggerWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_TRIGGER) +TriggerWidget::TriggerWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Trigger) { try { @@ -27,30 +27,30 @@ TriggerWidget::TriggerWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_TRIG Ui_TriggerWidget::setupUi(this); cond_expr_hl=new SyntaxHighlighter(cond_expr_txt, false, true); - cond_expr_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + cond_expr_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); - columns_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ - (ObjectsTableWidget::EDIT_BUTTON | - ObjectsTableWidget::UPDATE_BUTTON | - ObjectsTableWidget::DUPLICATE_BUTTON), true, this); + columns_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + (ObjectsTableWidget::EditButton | + ObjectsTableWidget::UpdateButton | + ObjectsTableWidget::DuplicateButton), true, this); - arguments_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ ObjectsTableWidget::DUPLICATE_BUTTON, true, this); + arguments_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ ObjectsTableWidget::DuplicateButton, true, this); - ref_table_sel=new ObjectSelectorWidget(OBJ_TABLE, true, this); - function_sel=new ObjectSelectorWidget(OBJ_FUNCTION, true, this); + ref_table_sel=new ObjectSelectorWidget(ObjectType::Table, true, this); + function_sel=new ObjectSelectorWidget(ObjectType::Function, true, this); ref_table_sel->setEnabled(false); - trigger_grid->addWidget(function_sel, 2, 2, 1, 1); - trigger_grid->addWidget(ref_table_sel, 6, 2, 1, 1); + trigger_grid->addWidget(function_sel, 3, 1, 1, 5); columns_tab->setColumnCount(2); columns_tab->setHeaderLabel(trUtf8("Column"), 0); - columns_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("column")),0); + columns_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("column")),0); columns_tab->setHeaderLabel(trUtf8("Type"), 1); - columns_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("usertype")),1); + columns_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("usertype")),1); dynamic_cast(arg_cols_tbw->widget(1)->layout())->addWidget(columns_tab, 1,0,1,3); dynamic_cast(arg_cols_tbw->widget(0)->layout())->addWidget(arguments_tab, 1,0,1,3); + dynamic_cast(arg_cols_tbw->widget(2)->layout())->addWidget(ref_table_sel, 1, 1, 1, 1); DeferralType::getTypes(list); deferral_type_cmb->addItems(list); @@ -58,7 +58,7 @@ TriggerWidget::TriggerWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_TRIG FiringType::getTypes(list); firing_mode_cmb->addItems(list); - configureFormLayout(trigger_grid, OBJ_TRIGGER); + configureFormLayout(trigger_grid, ObjectType::Trigger); connect(deferrable_chk, SIGNAL(toggled(bool)), deferral_type_cmb, SLOT(setEnabled(bool))); connect(columns_tab, SIGNAL(s_rowAdded(int)), this, SLOT(addColumn(int))); @@ -67,19 +67,25 @@ TriggerWidget::TriggerWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_TRIG connect(arguments_tab, SIGNAL(s_rowAdded(int)), this, SLOT(handleArgument(int))); connect(arguments_tab, SIGNAL(s_rowUpdated(int)), this, SLOT(handleArgument(int))); connect(arguments_tab, SIGNAL(s_rowEdited(int)), this, SLOT(editArgument(int))); - connect(constr_trig_chk, SIGNAL(toggled(bool)), this, SLOT(setConstraintTrigger(bool))); + connect(constraint_rb, SIGNAL(toggled(bool)), this, SLOT(setConstraintTrigger(bool))); connect(update_chk, SIGNAL(toggled(bool)), this, SLOT(selectUpdateEvent(void))); + connect(insert_chk, SIGNAL(toggled(bool)), this, SLOT(enableTransitionTableNames())); + connect(delete_chk, SIGNAL(toggled(bool)), this, SLOT(enableTransitionTableNames())); + connect(update_chk, SIGNAL(toggled(bool)), this, SLOT(enableTransitionTableNames())); + connect(truncate_chk, SIGNAL(toggled(bool)), this, SLOT(enableTransitionTableNames())); + connect(firing_mode_cmb, SIGNAL(currentIndexChanged(int)), this, SLOT(enableTransitionTableNames())); + setRequiredField(event_lbl); setRequiredField(firing_mode_lbl); setRequiredField(function_lbl); setRequiredField(function_sel); - setMinimumSize(580, 580); + setMinimumSize(580, 500); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -91,7 +97,7 @@ void TriggerWidget::selectUpdateEvent(void) /* Disable the columns tab when the trigger belongs to a view. pgModeler does not support triggers reference view columns (yet) */ arg_cols_tbw->widget(1)->setEnabled(update_chk->isChecked() && - table->getObjectType()==OBJ_TABLE); + table->getObjectType()==ObjectType::Table); } void TriggerWidget::setConstraintTrigger(bool value) @@ -109,7 +115,27 @@ void TriggerWidget::setConstraintTrigger(bool value) deferrable_chk->setChecked(false); } else - firing_mode_cmb->setCurrentText(~FiringType(FiringType::after)); + firing_mode_cmb->setCurrentText(~FiringType(FiringType::After)); +} + +void TriggerWidget::enableTransitionTableNames(void) +{ + int num_evnts = 0; + QWidget *wgt = nullptr; + QCheckBox *chk = nullptr; + FiringType firing_type = firing_mode_cmb->currentText(); + + for(auto &obj : events_wgt->children()) + { + wgt = qobject_cast(obj); + chk = dynamic_cast(wgt); + + if(chk && chk->isChecked()) + num_evnts++; + } + + old_table_edt->setEnabled(firing_type == FiringType::After && num_evnts == 1 && (update_chk->isChecked() || delete_chk->isChecked())); + new_table_edt->setEnabled(firing_type == FiringType::After && num_evnts == 1 && (update_chk->isChecked() || insert_chk->isChecked())); } void TriggerWidget::addColumn(int lin_idx) @@ -121,12 +147,12 @@ void TriggerWidget::addColumn(int lin_idx) column=reinterpret_cast(column_cmb->itemData(column_cmb->currentIndex(),Qt::UserRole).value()); column_cmb->removeItem(column_cmb->currentIndex()); addColumn(column, lin_idx); - columns_tab->setButtonsEnabled(ObjectsTableWidget::ADD_BUTTON, (column_cmb->count()!=0)); + columns_tab->setButtonsEnabled(ObjectsTableWidget::AddButton, (column_cmb->count()!=0)); } catch(Exception &e) { columns_tab->removeRow(lin_idx); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -147,14 +173,14 @@ void TriggerWidget::updateColumnsCombo(void) try { - if(this->table->getObjectType()==OBJ_TABLE) + if(this->table->getObjectType()==ObjectType::Table) { - col_count=table->getObjectCount(OBJ_COLUMN); + col_count=table->getObjectCount(ObjectType::Column); column_cmb->clear(); for(i=0; i < col_count; i++) { - column=dynamic_cast(table->getObject(i, OBJ_COLUMN)); + column=dynamic_cast(table->getObject(i, ObjectType::Column)); if(columns_tab->getRowIndex(QVariant::fromValue(column)) < 0) { @@ -164,12 +190,12 @@ void TriggerWidget::updateColumnsCombo(void) } } - columns_tab->setButtonsEnabled(ObjectsTableWidget::ADD_BUTTON, (column_cmb->count()!=0)); + columns_tab->setButtonsEnabled(ObjectsTableWidget::AddButton, (column_cmb->count()!=0)); } } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -195,7 +221,7 @@ void TriggerWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Column *column=nullptr; if(!parent_table) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); BaseObjectWidget::setAttributes(model, op_list, trigger, parent_table); ref_table_sel->setModel(model); @@ -203,7 +229,7 @@ void TriggerWidget::setAttributes(DatabaseModel *model, OperationList *op_list, if(trigger) { - constr_trig_chk->setChecked(trigger->isConstraint()); + constraint_rb->setChecked(trigger->isConstraint()); exec_per_row_chk->setChecked(trigger->isExecutePerRow()); cond_expr_txt->setPlainText(trigger->getCondition()); @@ -211,10 +237,10 @@ void TriggerWidget::setAttributes(DatabaseModel *model, OperationList *op_list, deferral_type_cmb->setCurrentIndex(deferral_type_cmb->findText(~trigger->getDeferralType())); firing_mode_cmb->setCurrentIndex(firing_mode_cmb->findText(~trigger->getFiringType())); - insert_chk->setChecked(trigger->isExecuteOnEvent(EventType::on_insert)); - delete_chk->setChecked(trigger->isExecuteOnEvent(EventType::on_delete)); - update_chk->setChecked(trigger->isExecuteOnEvent(EventType::on_update)); - truncate_chk->setChecked(trigger->isExecuteOnEvent(EventType::on_truncate)); + insert_chk->setChecked(trigger->isExecuteOnEvent(EventType::OnInsert)); + delete_chk->setChecked(trigger->isExecuteOnEvent(EventType::OnDelete)); + update_chk->setChecked(trigger->isExecuteOnEvent(EventType::OnUpdate)); + truncate_chk->setChecked(trigger->isExecuteOnEvent(EventType::OnTruncate)); ref_table_sel->setSelectedObject(trigger->getReferencedTable()); function_sel->setSelectedObject(trigger->getFunction()); @@ -236,9 +262,12 @@ void TriggerWidget::setAttributes(DatabaseModel *model, OperationList *op_list, arguments_tab->setCellText(trigger->getArgument(i), i, 0); } - columns_tab->setButtonsEnabled(ObjectsTableWidget::ADD_BUTTON, (column_cmb->count()!=0)); + columns_tab->setButtonsEnabled(ObjectsTableWidget::AddButton, (column_cmb->count()!=0)); arguments_tab->blockSignals(false); columns_tab->blockSignals(false); + + old_table_edt->setText(trigger->getTransitionTableName(Trigger::OldTableName)); + new_table_edt->setText(trigger->getTransitionTableName(Trigger::NewTableName)); } updateColumnsCombo(); @@ -255,7 +284,7 @@ void TriggerWidget::applyConfiguration(void) startConfiguration(); trigger=dynamic_cast(this->object); - trigger->setConstraint(constr_trig_chk->isChecked()); + trigger->setConstraint(constraint_rb->isChecked()); trigger->setFiringType(FiringType(firing_mode_cmb->currentText())); trigger->setExecutePerRow(exec_per_row_chk->isChecked()); trigger->setDeferrable(deferrable_chk->isChecked()); @@ -263,10 +292,12 @@ void TriggerWidget::applyConfiguration(void) trigger->setCondition(cond_expr_txt->toPlainText()); trigger->setFunction(dynamic_cast(function_sel->getSelectedObject())); trigger->setReferecendTable(dynamic_cast
(ref_table_sel->getSelectedObject())); - trigger->setEvent(EventType::on_insert, insert_chk->isChecked()); - trigger->setEvent(EventType::on_update, update_chk->isChecked()); - trigger->setEvent(EventType::on_delete, delete_chk->isChecked()); - trigger->setEvent(EventType::on_truncate, truncate_chk->isChecked()); + trigger->setEvent(EventType::OnInsert, insert_chk->isChecked()); + trigger->setEvent(EventType::OnUpdate, update_chk->isChecked()); + trigger->setEvent(EventType::OnDelete, delete_chk->isChecked()); + trigger->setEvent(EventType::OnTruncate, truncate_chk->isChecked()); + trigger->setTransitionTableName(Trigger::OldTableName, old_table_edt->isEnabled() ? old_table_edt->text() : QString()); + trigger->setTransitionTableName(Trigger::NewTableName, new_table_edt->isEnabled() ? new_table_edt->text() : QString()); trigger->removeArguments(); trigger->removeColumns(); @@ -290,7 +321,7 @@ void TriggerWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/triggerwidget.h b/libpgmodeler_ui/src/triggerwidget.h index 1b80954709..7fd1184458 100644 --- a/libpgmodeler_ui/src/triggerwidget.h +++ b/libpgmodeler_ui/src/triggerwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -48,7 +48,7 @@ class TriggerWidget: public BaseObjectWidget, public Ui::TriggerWidget { void addColumn(Column *column, int row); public: - TriggerWidget(QWidget * parent = 0); + TriggerWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, BaseTable *parent_table, Trigger *trigger); @@ -59,6 +59,7 @@ class TriggerWidget: public BaseObjectWidget, public Ui::TriggerWidget { void editArgument(int lin_idx); void updateColumnsCombo(void); void setConstraintTrigger(bool value); + void enableTransitionTableNames(void); public slots: void applyConfiguration(void); diff --git a/libpgmodeler_ui/src/typewidget.cpp b/libpgmodeler_ui/src/typewidget.cpp index 08a03f3a51..b20da59116 100644 --- a/libpgmodeler_ui/src/typewidget.cpp +++ b/libpgmodeler_ui/src/typewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ #include "typewidget.h" -TypeWidget::TypeWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_TYPE) +TypeWidget::TypeWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::Type) { try { @@ -28,7 +28,7 @@ TypeWidget::TypeWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_TYPE) unsigned i,i1; Ui_TypeWidget::setupUi(this); - configureFormLayout(type_grid, OBJ_TYPE); + configureFormLayout(type_grid, ObjectType::Type); like_type=new PgSQLTypeWidget(this, trUtf8("Like Type")); element_type=new PgSQLTypeWidget(this, trUtf8("Element Type")); @@ -40,31 +40,31 @@ TypeWidget::TypeWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_TYPE) grid->addItem(new QSpacerItem(20, 1, QSizePolicy::Minimum, QSizePolicy::Expanding),8,0); grid=dynamic_cast(base_attribs_twg->widget(0)->layout()); - for(i=Type::INPUT_FUNC; i <= Type::ANALYZE_FUNC; i++) + for(i=Type::InputFunc; i <= Type::AnalyzeFunc; i++) { functions_sel[i]=nullptr; - functions_sel[i]=new ObjectSelectorWidget(OBJ_FUNCTION, true, this); + functions_sel[i]=new ObjectSelectorWidget(ObjectType::Function, true, this); grid->addWidget(functions_sel[i],i,1,1,1); } - enumerations_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ - (ObjectsTableWidget::EDIT_BUTTON | ObjectsTableWidget::DUPLICATE_BUTTON), true, this); + enumerations_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + (ObjectsTableWidget::EditButton | ObjectsTableWidget::DuplicateButton), true, this); grid=dynamic_cast(enumerations_gb->layout()); grid->addWidget(enumerations_tab,1,0,1,2); enumerations_gb->setVisible(false); - attributes_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ ObjectsTableWidget::DUPLICATE_BUTTON, true, this); + attributes_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ ObjectsTableWidget::DuplicateButton, true, this); attributes_tab->setColumnCount(3); attributes_tab->setHeaderLabel(trUtf8("Name"),0); - attributes_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("uid")),0); + attributes_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")),0); attributes_tab->setHeaderLabel(trUtf8("Type"),1); - attributes_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("usertype")),1); + attributes_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("usertype")),1); attributes_tab->setHeaderLabel(trUtf8("Collation"),2); - attributes_tab->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("collation")),2); + attributes_tab->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("collation")),2); grid=dynamic_cast(attributes_gb->layout()); - attrib_collation_sel=new ObjectSelectorWidget(OBJ_COLLATION, true, this); + attrib_collation_sel=new ObjectSelectorWidget(ObjectType::Collation, true, this); grid->addWidget(attrib_collation_sel, 1,1,1,2); attrib_type_wgt=new PgSQLTypeWidget(this); @@ -81,13 +81,13 @@ TypeWidget::TypeWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_TYPE) frame->setParent(base_attribs_twg->widget(0)); grid=dynamic_cast(range_attribs_gb->layout()); - opclass_sel=new ObjectSelectorWidget(OBJ_OPCLASS, true, this); + opclass_sel=new ObjectSelectorWidget(ObjectType::OpClass, true, this); grid->addWidget(opclass_sel,0,1,1,1); - for(i1=1, i=Type::CANONICAL_FUNC; i <= Type::SUBTYPE_DIFF_FUNC; i++,i1++) + for(i1=1, i=Type::CanonicalFunc; i <= Type::SubtypeDiffFunc; i++,i1++) { functions_sel[i]=nullptr; - functions_sel[i]=new ObjectSelectorWidget(OBJ_FUNCTION, true, this); + functions_sel[i]=new ObjectSelectorWidget(ObjectType::Function, true, this); grid->addWidget(functions_sel[i],i1,1,1,1); } @@ -117,21 +117,21 @@ TypeWidget::TypeWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_TYPE) setRequiredField(range_subtype); setRequiredField(input_lbl); setRequiredField(output_lbl); - setRequiredField(functions_sel[Type::INPUT_FUNC]); - setRequiredField(functions_sel[Type::OUTPUT_FUNC]); + setRequiredField(functions_sel[Type::InputFunc]); + setRequiredField(functions_sel[Type::OutputFunc]); setRequiredField(enumerations_gb); setRequiredField(attributes_gb); configureTabOrder({base_type_rb, enumeration_rb, composite_rb, range_rb, enum_name_edt, attrib_name_edt, attrib_collation_sel, attrib_type_wgt, - opclass_sel, functions_sel[Type::CANONICAL_FUNC], functions_sel[Type::SUBTYPE_DIFF_FUNC], + opclass_sel, functions_sel[Type::CanonicalFunc], functions_sel[Type::SubtypeDiffFunc], base_attribs_twg}); setMinimumSize(620, 750); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -200,31 +200,31 @@ void TypeWidget::handleAttribute(int row) if(attributes_tab->getCellText(row,0).isEmpty()) attributes_tab->removeRow(row); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void TypeWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, Type *type) { - PgSQLType like_tp, elem_tp; + PgSqlType like_tp, elem_tp; unsigned type_conf, i, count; BaseObjectWidget::setAttributes(model, op_list, type, schema); attrib_collation_sel->setModel(model); - attrib_type_wgt->setAttributes(PgSQLType(), model); - range_subtype->setAttributes(PgSQLType(), model); + attrib_type_wgt->setAttributes(PgSqlType(), model); + range_subtype->setAttributes(PgSqlType(), model); opclass_sel->setModel(model); - for(i=Type::INPUT_FUNC; i <= Type::SUBTYPE_DIFF_FUNC; i++) + for(i=Type::InputFunc; i <= Type::SubtypeDiffFunc; i++) functions_sel[i]->setModel(model); if(type) { type_conf=type->getConfiguration(); - if(type_conf==Type::COMPOSITE_TYPE) + if(type_conf==Type::CompositeType) { composite_rb->setChecked(true); attributes_tab->blockSignals(true); @@ -239,7 +239,7 @@ void TypeWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Sch attributes_tab->blockSignals(false); attributes_tab->clearSelection(); } - else if(type_conf==Type::ENUMERATION_TYPE) + else if(type_conf==Type::EnumerationType) { enumeration_rb->setChecked(true); enumerations_tab->blockSignals(true); @@ -254,13 +254,13 @@ void TypeWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Sch enumerations_tab->blockSignals(false); enumerations_tab->clearSelection(); } - else if(type_conf==Type::RANGE_TYPE) + else if(type_conf==Type::RangeType) { range_rb->setChecked(true); opclass_sel->setSelectedObject(type->getSubtypeOpClass()); range_subtype->setAttributes(type->getSubtype(), model); - functions_sel[Type::CANONICAL_FUNC]->setSelectedObject(type->getFunction(Type::CANONICAL_FUNC)); - functions_sel[Type::SUBTYPE_DIFF_FUNC]->setSelectedObject(type->getFunction(Type::SUBTYPE_DIFF_FUNC)); + functions_sel[Type::CanonicalFunc]->setSelectedObject(type->getFunction(Type::CanonicalFunc)); + functions_sel[Type::SubtypeDiffFunc]->setSelectedObject(type->getFunction(Type::SubtypeDiffFunc)); } else { @@ -279,7 +279,7 @@ void TypeWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Sch storage_cmb->setCurrentIndex(storage_cmb->findText(~type->getStorage())); alignment_cmb->setCurrentIndex(alignment_cmb->findText(~type->getAlignment())); - for(i=Type::INPUT_FUNC; i <= Type::ANALYZE_FUNC; i++) + for(i=Type::InputFunc; i <= Type::AnalyzeFunc; i++) functions_sel[i]->setSelectedObject(type->getFunction(i)); } } @@ -305,7 +305,7 @@ void TypeWidget::applyConfiguration(void) //Configuring an enumaration type if(enumeration_rb->isChecked()) { - type->setConfiguration(Type::ENUMERATION_TYPE); + type->setConfiguration(Type::EnumerationType); count=enumerations_tab->getRowCount(); for(i=0; i < count; i++) @@ -314,7 +314,7 @@ void TypeWidget::applyConfiguration(void) //Configuration a composite type else if(composite_rb->isChecked()) { - type->setConfiguration(Type::COMPOSITE_TYPE); + type->setConfiguration(Type::CompositeType); count=attributes_tab->getRowCount(); for(i=0; i < count; i++) @@ -323,17 +323,17 @@ void TypeWidget::applyConfiguration(void) //Configuration a range type else if(range_rb->isChecked()) { - type->setConfiguration(Type::RANGE_TYPE); + type->setConfiguration(Type::RangeType); type->setCollation(collation_sel->getSelectedObject()); type->setSubtype(range_subtype->getPgSQLType()); type->setSubtypeOpClass(dynamic_cast(opclass_sel->getSelectedObject())); - type->setFunction(Type::CANONICAL_FUNC, dynamic_cast(functions_sel[Type::CANONICAL_FUNC]->getSelectedObject())); - type->setFunction(Type::SUBTYPE_DIFF_FUNC, dynamic_cast(functions_sel[Type::SUBTYPE_DIFF_FUNC]->getSelectedObject())); + type->setFunction(Type::CanonicalFunc, dynamic_cast(functions_sel[Type::CanonicalFunc]->getSelectedObject())); + type->setFunction(Type::SubtypeDiffFunc, dynamic_cast(functions_sel[Type::SubtypeDiffFunc]->getSelectedObject())); } //Configuring a base type else { - type->setConfiguration(Type::BASE_TYPE); + type->setConfiguration(Type::BaseType); type->setLikeType(like_type->getPgSQLType()); type->setElement(element_type->getPgSQLType()); type->setInternalLength(internal_len_sb->value()); @@ -346,10 +346,10 @@ void TypeWidget::applyConfiguration(void) type->setDefaultValue(default_value_edt->text()); type->setCategory(CategoryType(category_cmb->currentText())); - type->setAlignment(PgSQLType(alignment_cmb->currentText())); + type->setAlignment(PgSqlType(alignment_cmb->currentText())); type->setStorage(StorageType(storage_cmb->currentText())); - for(i=Type::INPUT_FUNC; i <= Type::ANALYZE_FUNC; i++) + for(i=Type::InputFunc; i <= Type::AnalyzeFunc; i++) type->setFunction(i, dynamic_cast(functions_sel[i]->getSelectedObject())); } @@ -358,7 +358,7 @@ void TypeWidget::applyConfiguration(void) catch(Exception &e) { cancelConfiguration(); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/typewidget.h b/libpgmodeler_ui/src/typewidget.h index b4041a3348..3ae6db0615 100644 --- a/libpgmodeler_ui/src/typewidget.h +++ b/libpgmodeler_ui/src/typewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -61,7 +61,7 @@ class TypeWidget: public BaseObjectWidget, public Ui::TypeWidget { PgSQLTypeWidget *attrib_type_wgt; public: - TypeWidget(QWidget * parent = 0); + TypeWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, Type *type); diff --git a/libpgmodeler_ui/src/updatenotifierwidget.cpp b/libpgmodeler_ui/src/updatenotifierwidget.cpp index e1376cb0be..b8a47b5430 100644 --- a/libpgmodeler_ui/src/updatenotifierwidget.cpp +++ b/libpgmodeler_ui/src/updatenotifierwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -37,8 +37,8 @@ UpdateNotifierWidget::UpdateNotifierWidget(QWidget *parent) : QWidget(parent) connect(&update_chk_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(handleUpdateChecked(QNetworkReply*))); //C++11 lambda slots - connect(get_source_tb, &QToolButton::clicked, this, [&](){ activateLink(GlobalAttributes::PGMODELER_SRC_URL); }); - connect(get_binary_tb, &QToolButton::clicked, this, [&](){ activateLink(GlobalAttributes::PGMODELER_DOWNLOAD_URL); }); + connect(get_source_tb, &QToolButton::clicked, this, [&](){ activateLink(GlobalAttributes::PgModelerSourceURL); }); + connect(get_binary_tb, &QToolButton::clicked, this, [&](){ activateLink(GlobalAttributes::PgModelerDownloadURL); }); connect(hide_tb, &QToolButton::clicked, this, @@ -47,9 +47,9 @@ UpdateNotifierWidget::UpdateNotifierWidget(QWidget *parent) : QWidget(parent) emit s_visibilityChanged(false); }); - PgModelerUiNS::configureWidgetFont(changelog_txt, PgModelerUiNS::MEDIUM_FONT_FACTOR); - PgModelerUiNS::configureWidgetFont(ver_num_lbl, PgModelerUiNS::BIG_FONT_FACTOR); - PgModelerUiNS::configureWidgetFont(title_lbl, PgModelerUiNS::BIG_FONT_FACTOR); + PgModelerUiNs::configureWidgetFont(changelog_txt, PgModelerUiNs::MediumFontFactor); + PgModelerUiNs::configureWidgetFont(ver_num_lbl, PgModelerUiNs::BigFontFactor); + PgModelerUiNs::configureWidgetFont(title_lbl, PgModelerUiNs::BigFontFactor); this->adjustSize(); } @@ -97,7 +97,7 @@ void UpdateNotifierWidget::activateLink(const QString &link) void UpdateNotifierWidget::checkForUpdate(void) { - QUrl url(GlobalAttributes::PGMODELER_UPD_CHECK_URL + GlobalAttributes::PGMODELER_VERSION); + QUrl url(GlobalAttributes::PgModelerUpdateCheckURL + GlobalAttributes::PgModelerVersion); QNetworkRequest req(url); req.setRawHeader("User-Agent", "pgModelerUpdateCheck"); @@ -114,7 +114,7 @@ void UpdateNotifierWidget::handleUpdateChecked(QNetworkReply *reply) { msg_box.show(trUtf8("Failed to check updates"), trUtf8("The update notifier failed to check for new versions! Please, verify your internet connectivity and try again! Connection error returned: %1 - %2.").arg(http_status).arg(reply->errorString()), - Messagebox::ERROR_ICON, Messagebox::OK_BUTTON); + Messagebox::ErrorIcon, Messagebox::OkButton); } else { @@ -124,8 +124,8 @@ void UpdateNotifierWidget::handleUpdateChecked(QNetworkReply *reply) { QString url=reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString(); - if(http_status==302 && !url.startsWith(GlobalAttributes::PGMODELER_SITE)) - url.prepend(GlobalAttributes::PGMODELER_SITE); + if(http_status==302 && !url.startsWith(GlobalAttributes::PgModelerSite)) + url.prepend(GlobalAttributes::PgModelerSite); QNetworkRequest req(url); update_chk_reply=update_chk_manager.get(req); @@ -137,10 +137,10 @@ void UpdateNotifierWidget::handleUpdateChecked(QNetworkReply *reply) { QJsonDocument json_doc=QJsonDocument::fromJson(reply->readAll()); QJsonObject json_obj=json_doc.object(); - QString version=json_obj.value(ParsersAttributes::NEW_VERSION).toString(), - changelog=json_obj.value(ParsersAttributes::CHANGELOG).toString(), - date=json_obj.value(ParsersAttributes::DATE).toString(); - bool upd_found=(!version.isEmpty() && version!=ParsersAttributes::_FALSE_); + QString version=json_obj.value(Attributes::NewVersion).toString(), + changelog=json_obj.value(Attributes::Changelog).toString(), + date=json_obj.value(Attributes::Date).toString(); + bool upd_found=(!version.isEmpty() && version!=Attributes::False); if(upd_found) { @@ -152,7 +152,7 @@ void UpdateNotifierWidget::handleUpdateChecked(QNetworkReply *reply) { msg_box.show(trUtf8("No updates found"), trUtf8("You are running the most recent pgModeler version! No update needed."), - Messagebox::INFO_ICON, Messagebox::OK_BUTTON); + Messagebox::InfoIcon, Messagebox::OkButton); } emit s_updateAvailable(upd_found); @@ -161,7 +161,7 @@ void UpdateNotifierWidget::handleUpdateChecked(QNetworkReply *reply) { msg_box.show(trUtf8("Failed to check updates"), trUtf8("The update notifier failed to check for new versions! A HTTP status code was returned: %1").arg(http_status), - Messagebox::ERROR_ICON, Messagebox::OK_BUTTON); + Messagebox::ErrorIcon, Messagebox::OkButton); } delete(update_chk_reply); diff --git a/libpgmodeler_ui/src/updatenotifierwidget.h b/libpgmodeler_ui/src/updatenotifierwidget.h index b650b28468..701f885ed9 100644 --- a/libpgmodeler_ui/src/updatenotifierwidget.h +++ b/libpgmodeler_ui/src/updatenotifierwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -49,7 +49,7 @@ #include "ui_updatenotifierwidget.h" #include "messagebox.h" #include "globalattributes.h" -#include "parsersattributes.h" +#include "attributes.h" class UpdateNotifierWidget: public QWidget, public Ui::UpdateNotifierWidget { private: @@ -75,7 +75,7 @@ class UpdateNotifierWidget: public QWidget, public Ui::UpdateNotifierWidget { void activateLink(const QString &link); public: - UpdateNotifierWidget(QWidget * parent = 0); + UpdateNotifierWidget(QWidget * parent = nullptr); public slots: void checkForUpdate(void); diff --git a/libpgmodeler_ui/src/usermappingwidget.cpp b/libpgmodeler_ui/src/usermappingwidget.cpp new file mode 100644 index 0000000000..c2bf263cf6 --- /dev/null +++ b/libpgmodeler_ui/src/usermappingwidget.cpp @@ -0,0 +1,109 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include "usermappingwidget.h" + +UserMappingWidget::UserMappingWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::UserMapping) +{ + try + { + QHBoxLayout *hbox = nullptr; + + Ui_UserMappingWidget::setupUi(this); + + server_sel=nullptr; + server_sel=new ObjectSelectorWidget(ObjectType::ForeignServer, true, this); + + hbox = new QHBoxLayout; + hbox->setContentsMargins(0,0,0,0); + hbox->addWidget(server_sel); + server_wgt->setLayout(hbox); + + options_tab = new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + (ObjectsTableWidget::EditButton | ObjectsTableWidget::UpdateButton), true, this); + options_tab->setCellsEditable(true); + options_tab->setColumnCount(2); + options_tab->setHeaderLabel(trUtf8("Option"), 0); + options_tab->setHeaderLabel(trUtf8("Value"), 1); + + hbox = new QHBoxLayout; + hbox->setContentsMargins(4,4,4,4); + hbox->addWidget(options_tab); + options_gb->setLayout(hbox); + + configureFormLayout(server_grid, ObjectType::UserMapping); + + setRequiredField(server_sel); + setRequiredField(server_lbl); + configureTabOrder({ server_sel, options_tab }); + + setMinimumSize(550, 280); + } + catch(Exception &e) + { + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + +void UserMappingWidget::setAttributes(DatabaseModel *model, OperationList *op_list, UserMapping *user_map) +{ + BaseObjectWidget::setAttributes(model, op_list, user_map); + server_sel->setModel(model); + + if(user_map) + { + server_sel->setSelectedObject(user_map->getForeignServer()); + options_tab->blockSignals(true); + + for(auto &itr : user_map->getOptions()) + { + options_tab->addRow(); + options_tab->setCellText(itr.first, options_tab->getRowCount() - 1, 0); + options_tab->setCellText(itr.second, options_tab->getRowCount() - 1, 1); + } + + options_tab->clearSelection(); + options_tab->blockSignals(false); + } +} + +void UserMappingWidget::applyConfiguration(void) +{ + try + { + UserMapping *user_map = nullptr; + + startConfiguration(); + + user_map = dynamic_cast(this->object); + user_map->setForeignServer(dynamic_cast(server_sel->getSelectedObject())); + + user_map->removeOptions(); + for(unsigned row = 0; row < options_tab->getRowCount(); row++) + user_map->setOption(options_tab->getCellText(row, 0), options_tab->getCellText(row, 1)); + + BaseObjectWidget::applyConfiguration(); + finishConfiguration(); + } + catch(Exception &e) + { + cancelConfiguration(); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + } +} + diff --git a/libpgmodeler_ui/src/usermappingwidget.h b/libpgmodeler_ui/src/usermappingwidget.h new file mode 100644 index 0000000000..f646e7fd29 --- /dev/null +++ b/libpgmodeler_ui/src/usermappingwidget.h @@ -0,0 +1,48 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +/** +\ingroup libpgmodeler_ui +\class UserMappingWidget +\brief Implements the operations to create/edit user mappings via form. +*/ + +#ifndef USER_MAPPING_WIDGET_H +#define USER_MAPPING_WIDGET_H + +#include "baseobjectwidget.h" +#include "ui_usermappingwidget.h" +#include "objectstablewidget.h" + +class UserMappingWidget: public BaseObjectWidget, public Ui::UserMappingWidget { + private: + Q_OBJECT + + ObjectSelectorWidget *server_sel; + + ObjectsTableWidget *options_tab; + + public: + UserMappingWidget(QWidget * parent = nullptr); + void setAttributes(DatabaseModel *model, OperationList *op_list, UserMapping *user_map); + + public slots: + void applyConfiguration(void); +}; + +#endif diff --git a/libpgmodeler_ui/src/validationinfo.cpp b/libpgmodeler_ui/src/validationinfo.cpp index b97ce3ee58..10eda993ab 100644 --- a/libpgmodeler_ui/src/validationinfo.cpp +++ b/libpgmodeler_ui/src/validationinfo.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -21,16 +21,16 @@ ValidationInfo::ValidationInfo(void) { object=nullptr; - val_type=VALIDATION_ABORTED; + val_type=ValidationAborted; } ValidationInfo::ValidationInfo(unsigned val_type, BaseObject *object, vector references) { - if(val_type >= SQL_VALIDATION_ERR) - throw Exception(ERR_ASG_INV_TYPE_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); - else if((val_type==NO_UNIQUE_NAME || val_type==BROKEN_REFERENCE) && + if(val_type >= SqlValidationError) + throw Exception(ErrorCode::AsgInvalidTypeObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); + else if((val_type==NoUniqueName || val_type==BrokenReference) && (!object || references.empty())) - throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(ErrorCode::AsgNotAllocattedObject,__PRETTY_FUNCTION__,__FILE__,__LINE__); this->val_type=val_type; this->object=object; @@ -41,7 +41,7 @@ ValidationInfo::ValidationInfo(Exception e) { vector err_list; - val_type=SQL_VALIDATION_ERR; + val_type=SqlValidationError; e.getExceptionsList(err_list); while(!err_list.empty()) @@ -55,7 +55,7 @@ ValidationInfo::ValidationInfo(Exception e) ValidationInfo::ValidationInfo(const QString &msg) { - val_type=VALIDATION_ABORTED; + val_type=ValidationAborted; errors.push_back(msg); } @@ -81,6 +81,6 @@ QStringList ValidationInfo::getErrors(void) bool ValidationInfo::isValid(void) { - return(((val_type==NO_UNIQUE_NAME || val_type==BROKEN_REFERENCE) && object) || - (val_type==SQL_VALIDATION_ERR && !errors.empty())); + return(((val_type==NoUniqueName || val_type==BrokenReference) && object) || + (val_type==SqlValidationError && !errors.empty())); } diff --git a/libpgmodeler_ui/src/validationinfo.h b/libpgmodeler_ui/src/validationinfo.h index 81773c2289..6428528667 100644 --- a/libpgmodeler_ui/src/validationinfo.h +++ b/libpgmodeler_ui/src/validationinfo.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -46,12 +46,13 @@ class ValidationInfo { QStringList errors; public: - static const unsigned NO_UNIQUE_NAME=0, - BROKEN_REFERENCE=1, - SP_OBJ_BROKEN_REFERENCE=2, - BROKEN_REL_CONFIG=3, - SQL_VALIDATION_ERR=4, - VALIDATION_ABORTED=5; + static constexpr unsigned NoUniqueName=0, + BrokenReference=1, + SpObjBrokenReference=2, + BrokenRelConfig=3, + MissingExtension=4, + SqlValidationError=5, + ValidationAborted=6; ValidationInfo(void); ValidationInfo(unsigned val_type, BaseObject *object, vector references); diff --git a/libpgmodeler_ui/src/viewwidget.cpp b/libpgmodeler_ui/src/viewwidget.cpp index 3c5e087860..53bd0eca7a 100644 --- a/libpgmodeler_ui/src/viewwidget.cpp +++ b/libpgmodeler_ui/src/viewwidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -21,13 +21,14 @@ #include "triggerwidget.h" #include "indexwidget.h" #include "baseform.h" +#include "referencewidget.h" -ViewWidget::ViewWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_VIEW) +ViewWidget::ViewWidget(QWidget *parent): BaseObjectWidget(parent, ObjectType::View) { try { ObjectsTableWidget *tab=nullptr; - ObjectType types[]={ OBJ_TRIGGER, OBJ_RULE, OBJ_INDEX }; + ObjectType types[]={ ObjectType::Trigger, ObjectType::Rule, ObjectType::Index }; QGridLayout *grid=nullptr; QVBoxLayout *vbox=nullptr; @@ -36,56 +37,43 @@ ViewWidget::ViewWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_VIEW) Ui_ViewWidget::setupUi(this); - expression_txt=new NumberedTextEditor(this, true); - expression_hl=new SyntaxHighlighter(expression_txt, false, true); - expression_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); - referencias_grid->addWidget(expression_txt, 4, 1, 1, 4); - code_txt=new NumberedTextEditor(this); code_txt->setReadOnly(true); code_hl=new SyntaxHighlighter(code_txt); - code_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + code_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); vbox=new QVBoxLayout(code_prev_tab); vbox->setContentsMargins(4,4,4,4); vbox->addWidget(code_txt); cte_expression_txt=new NumberedTextEditor(this, true); cte_expression_hl=new SyntaxHighlighter(cte_expression_txt); - cte_expression_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + cte_expression_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); vbox=new QVBoxLayout(cte_tab); vbox->setContentsMargins(4,4,4,4); vbox->addWidget(cte_expression_txt); - tag_sel=new ObjectSelectorWidget(OBJ_TAG, false, this); + tag_sel=new ObjectSelectorWidget(ObjectType::Tag, false, this); dynamic_cast(options_gb->layout())->addWidget(tag_sel, 0, 1, 1, 4); - table_sel=new ObjectSelectorWidget(OBJ_TABLE, true, this); - table_sel->enableObjectCreation(false); - column_sel=new ObjectSelectorWidget(OBJ_COLUMN, true, this); - column_sel->enableObjectCreation(false); + references_tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ ObjectsTableWidget::UpdateButton, true, this); + references_tab->setColumnCount(5); + references_tab->setHeaderLabel(trUtf8("Col./Expr."), 0); + references_tab->setHeaderLabel(trUtf8("Table alias"), 1); + references_tab->setHeaderLabel(trUtf8("Column alias"), 2); + references_tab->setHeaderLabel(trUtf8("Flags: SF FW AW EX VD"), 3); + references_tab->setHeaderLabel(trUtf8("Reference alias"), 4); - references_tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS, true, this); - references_tab->setColumnCount(4); - references_tab->setHeaderLabel(trUtf8("Col./Expr."),0); - references_tab->setHeaderLabel(trUtf8("Alias"),1); - references_tab->setHeaderLabel(trUtf8("Alias Col."),2); - references_tab->setHeaderLabel(trUtf8("Flags: SF FW AW EX VD"),3); + vbox=new QVBoxLayout(tabWidget->widget(0)); + vbox->setContentsMargins(4,4,4,4); + vbox->addWidget(references_tab); cte_expression_cp=new CodeCompletionWidget(cte_expression_txt, true); - expression_cp=new CodeCompletionWidget(expression_txt, true); - - frame_info=generateInformationFrame(trUtf8("To reference all columns in a table (*) just do not fill the field Column, this is the same as write [schema].[table].*")); - - referencias_grid->addWidget(table_sel, 2,1,1,2); - referencias_grid->addWidget(column_sel, 3,1,1,2); - referencias_grid->addWidget(frame_info, 6, 0, 1, 0); - referencias_grid->addWidget(references_tab, 7,0,2,0); //Configuring the table objects that stores the triggers and rules for(unsigned i=0, tab_id=1; i < sizeof(types)/sizeof(ObjectType); i++, tab_id++) { - tab=new ObjectsTableWidget(ObjectsTableWidget::ALL_BUTTONS ^ - (ObjectsTableWidget::UPDATE_BUTTON | ObjectsTableWidget::MOVE_BUTTONS), true, this); + tab=new ObjectsTableWidget(ObjectsTableWidget::AllButtons ^ + (ObjectsTableWidget::UpdateButton | ObjectsTableWidget::MoveButtons), true, this); objects_tab_map[types[i]]=tab; @@ -101,51 +89,49 @@ ViewWidget::ViewWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_VIEW) connect(tab, SIGNAL(s_rowDuplicated(int,int)), this, SLOT(duplicateObject(int,int))); } - objects_tab_map[OBJ_TRIGGER]->setColumnCount(4); - objects_tab_map[OBJ_TRIGGER]->setHeaderLabel(trUtf8("Name"), 0); - objects_tab_map[OBJ_TRIGGER]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("uid")),0); - objects_tab_map[OBJ_TRIGGER]->setHeaderLabel(trUtf8("Refer. Table"), 1); - objects_tab_map[OBJ_TRIGGER]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("table")),1); - objects_tab_map[OBJ_TRIGGER]->setHeaderLabel(trUtf8("Firing"), 2); - objects_tab_map[OBJ_TRIGGER]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("trigger")),2); - objects_tab_map[OBJ_TRIGGER]->setHeaderLabel(trUtf8("Events"), 3); - - objects_tab_map[OBJ_INDEX]->setColumnCount(2); - objects_tab_map[OBJ_INDEX]->setHeaderLabel(trUtf8("Name"), 0); - objects_tab_map[OBJ_INDEX]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("uid")),0); - objects_tab_map[OBJ_INDEX]->setHeaderLabel(trUtf8("Indexing"), 1); - - objects_tab_map[OBJ_RULE]->setColumnCount(3); - objects_tab_map[OBJ_RULE]->setHeaderLabel(trUtf8("Name"), 0); - objects_tab_map[OBJ_RULE]->setHeaderIcon(QPixmap(PgModelerUiNS::getIconPath("uid")),0); - objects_tab_map[OBJ_RULE]->setHeaderLabel(trUtf8("Execution"), 1); - objects_tab_map[OBJ_RULE]->setHeaderLabel(trUtf8("Event"), 2); + objects_tab_map[ObjectType::Trigger]->setColumnCount(6); + objects_tab_map[ObjectType::Trigger]->setHeaderLabel(trUtf8("Name"), 0); + objects_tab_map[ObjectType::Trigger]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")),0); + objects_tab_map[ObjectType::Trigger]->setHeaderLabel(trUtf8("Refer. Table"), 1); + objects_tab_map[ObjectType::Trigger]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("table")),1); + objects_tab_map[ObjectType::Trigger]->setHeaderLabel(trUtf8("Firing"), 2); + objects_tab_map[ObjectType::Trigger]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("trigger")),2); + objects_tab_map[ObjectType::Trigger]->setHeaderLabel(trUtf8("Events"), 3); + objects_tab_map[ObjectType::Trigger]->setHeaderLabel(trUtf8("Alias"), 4); + objects_tab_map[ObjectType::Trigger]->setHeaderLabel(trUtf8("Comment"), 5); + + objects_tab_map[ObjectType::Index]->setColumnCount(4); + objects_tab_map[ObjectType::Index]->setHeaderLabel(trUtf8("Name"), 0); + objects_tab_map[ObjectType::Index]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")),0); + objects_tab_map[ObjectType::Index]->setHeaderLabel(trUtf8("Indexing"), 1); + objects_tab_map[ObjectType::Index]->setHeaderLabel(trUtf8("Alias"), 2); + objects_tab_map[ObjectType::Index]->setHeaderLabel(trUtf8("Comment"), 3); + + objects_tab_map[ObjectType::Rule]->setColumnCount(5); + objects_tab_map[ObjectType::Rule]->setHeaderLabel(trUtf8("Name"), 0); + objects_tab_map[ObjectType::Rule]->setHeaderIcon(QPixmap(PgModelerUiNs::getIconPath("uid")),0); + objects_tab_map[ObjectType::Rule]->setHeaderLabel(trUtf8("Execution"), 1); + objects_tab_map[ObjectType::Rule]->setHeaderLabel(trUtf8("Event"), 2); + objects_tab_map[ObjectType::Rule]->setHeaderLabel(trUtf8("Alias"), 3); + objects_tab_map[ObjectType::Rule]->setHeaderLabel(trUtf8("Comment"), 4); + tablespace_sel->setEnabled(false); tablespace_lbl->setEnabled(false); - configureFormLayout(view_grid, OBJ_VIEW); + configureFormLayout(view_grid, ObjectType::View); - fields_map[generateVersionsInterval(AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_93)].push_back(recursive_rb); - fields_map[generateVersionsInterval(AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_93)].push_back(materialized_rb); - fields_map[generateVersionsInterval(AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_93)].push_back(with_no_data_chk); + fields_map[generateVersionsInterval(AfterVersion, PgSqlVersions::PgSqlVersion93)].push_back(recursive_rb); + fields_map[generateVersionsInterval(AfterVersion, PgSqlVersions::PgSqlVersion93)].push_back(materialized_rb); + fields_map[generateVersionsInterval(AfterVersion, PgSqlVersions::PgSqlVersion93)].push_back(with_no_data_chk); frame=generateVersionWarningFrame(fields_map); view_grid->addWidget(frame, view_grid->count()+1, 0, 1,3); frame->setParent(this); - connect(ref_type_cmb, SIGNAL(currentIndexChanged(int)), this, SLOT(selectReferenceType(void))); - connect(column_sel, SIGNAL(s_objectSelected(void)), this, SLOT(showObjectName(void))); - connect(column_sel, SIGNAL(s_selectorCleared(void)), this, SLOT(showObjectName(void))); - connect(table_sel, SIGNAL(s_objectSelected(void)), this, SLOT(showObjectName(void))); - connect(references_tab, SIGNAL(s_rowAdded(int)), this, SLOT(handleReference(int))); - connect(references_tab, SIGNAL(s_rowUpdated(int)), this, SLOT(handleReference(int))); + connect(references_tab, SIGNAL(s_rowAdded(int)), this, SLOT(addReference(int))); connect(references_tab, SIGNAL(s_rowEdited(int)), this, SLOT(editReference(int))); + connect(references_tab, SIGNAL(s_rowDuplicated(int,int)), this, SLOT(duplicateReference(int,int))); connect(tabWidget, SIGNAL(currentChanged(int)), this, SLOT(updateCodePreview(void))); - connect(view_def_chk, SIGNAL(toggled(bool)), select_from_chk, SLOT(setDisabled(bool))); - connect(view_def_chk, SIGNAL(toggled(bool)), from_where_chk, SLOT(setDisabled(bool))); - connect(view_def_chk, SIGNAL(toggled(bool)), after_where_chk, SLOT(setDisabled(bool))); - connect(view_def_chk, SIGNAL(toggled(bool)), expr_alias_edt, SLOT(setDisabled(bool))); - connect(view_def_chk, SIGNAL(toggled(bool)), expr_alias_lbl, SLOT(setDisabled(bool))); connect(materialized_rb, SIGNAL(toggled(bool)), with_no_data_chk, SLOT(setEnabled(bool))); connect(materialized_rb, SIGNAL(toggled(bool)), tablespace_sel, SLOT(setEnabled(bool))); connect(materialized_rb, SIGNAL(toggled(bool)), tablespace_lbl, SLOT(setEnabled(bool))); @@ -158,17 +144,12 @@ ViewWidget::ViewWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_VIEW) connect(schema_sel, SIGNAL(s_objectSelected(void)), this, SLOT(updateCodePreview(void))); connect(schema_sel, SIGNAL(s_selectorCleared(void)), this, SLOT(updateCodePreview(void))); - selectReferenceType(); - - configureTabOrder({ tag_sel, ordinary_rb, recursive_rb, with_no_data_chk, tabWidget, - ref_type_cmb, select_from_chk, from_where_chk, after_where_chk, - table_sel, tab_alias_edt, column_sel, col_alias_edt }); - - setMinimumSize(600, 730); + configureTabOrder({ tag_sel, ordinary_rb, recursive_rb, with_no_data_chk, tabWidget }); + setMinimumSize(660, 650); } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -176,8 +157,8 @@ ObjectsTableWidget *ViewWidget::getObjectTable(ObjectType obj_type) { if(objects_tab_map.count(obj_type) > 0) return(objects_tab_map[obj_type]); - else - return(nullptr); + + return(nullptr); } template @@ -195,7 +176,7 @@ int ViewWidget::openEditingForm(TableObject *object) void ViewWidget::handleObject(void) { - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; TableObject *object=nullptr; ObjectsTableWidget *obj_table=nullptr; @@ -207,9 +188,9 @@ void ViewWidget::handleObject(void) if(obj_table->getSelectedRow()>=0) object=reinterpret_cast(obj_table->getRowData(obj_table->getSelectedRow()).value()); - if(obj_type==OBJ_TRIGGER) + if(obj_type==ObjectType::Trigger) openEditingForm(object); - else if(obj_type==OBJ_INDEX) + else if(obj_type==ObjectType::Index) openEditingForm(object); else openEditingForm(object); @@ -219,13 +200,13 @@ void ViewWidget::handleObject(void) catch(Exception &e) { listObjects(obj_type); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } void ViewWidget::duplicateObject(int curr_row, int new_row) { - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; BaseObject *object=nullptr, *dup_object=nullptr; ObjectsTableWidget *obj_table=nullptr; View *view = dynamic_cast(this->object); @@ -242,10 +223,10 @@ void ViewWidget::duplicateObject(int curr_row, int new_row) if(curr_row >= 0) object = reinterpret_cast(obj_table->getRowData(curr_row).value()); - PgModelerNS::copyObject(&dup_object, object, obj_type); - dup_object->setName(PgModelerNS::generateUniqueName(dup_object, *view->getObjectList(obj_type), false, QString("_cp"))); + PgModelerNs::copyObject(&dup_object, object, obj_type); + dup_object->setName(PgModelerNs::generateUniqueName(dup_object, *view->getObjectList(obj_type), false, QString("_cp"))); - op_id=op_list->registerObject(dup_object, Operation::OBJECT_CREATED, new_row, this->object); + op_id=op_list->registerObject(dup_object, Operation::ObjectCreated, new_row, this->object); view->addObject(dup_object); view->setModified(true); @@ -262,7 +243,7 @@ void ViewWidget::duplicateObject(int curr_row, int new_row) } listObjects(obj_type); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } @@ -282,7 +263,7 @@ void ViewWidget::removeObjects(void) { object=view->getObject(0, obj_type); view->removeObject(object); - op_list->registerObject(object, Operation::OBJECT_REMOVED, 0, this->object); + op_list->registerObject(object, Operation::ObjectRemoved, 0, this->object); } } catch(Exception &e) @@ -302,10 +283,21 @@ void ViewWidget::removeObjects(void) } listObjects(obj_type); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } +void ViewWidget::addReference(int row) +{ + openReferenceForm(Reference(), row, false); +} + +void ViewWidget::duplicateReference(int orig_row, int new_row) +{ + showReferenceData(references_tab->getRowData(orig_row).value(), + getReferenceFlag(orig_row), new_row); +} + void ViewWidget::removeObject(int row) { View *view=nullptr; @@ -317,18 +309,18 @@ void ViewWidget::removeObject(int row) view=dynamic_cast(this->object); object=view->getObject(row, obj_type); view->removeObject(object); - op_list->registerObject(object, Operation::OBJECT_REMOVED, row, this->object); + op_list->registerObject(object, Operation::ObjectRemoved, row, this->object); } catch(Exception &e) { listObjects(obj_type); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } ObjectType ViewWidget::getObjectType(QObject *sender) { - ObjectType obj_type=BASE_OBJECT; + ObjectType obj_type=ObjectType::BaseObject; if(sender) { @@ -337,7 +329,7 @@ ObjectType ViewWidget::getObjectType(QObject *sender) itr=objects_tab_map.begin(); itr_end=objects_tab_map.end(); - while(itr!=itr_end && obj_type==BASE_OBJECT) + while(itr!=itr_end && obj_type==ObjectType::BaseObject) { if(itr->second==sender) obj_type=itr->first; @@ -358,8 +350,8 @@ void ViewWidget::showObjectData(TableObject *object, int row) ObjectType obj_type; QString str_aux; unsigned i; - EventType events[]={ EventType::on_insert, EventType::on_delete, - EventType::on_truncate, EventType::on_update }; + EventType events[]={ EventType::OnInsert, EventType::OnDelete, + EventType::OnTruncate, EventType::OnUpdate }; obj_type=object->getObjectType(); tab=objects_tab_map[obj_type]; @@ -367,7 +359,7 @@ void ViewWidget::showObjectData(TableObject *object, int row) //Column 0: Object name tab->setCellText(object->getName(),row,0); - if(obj_type==OBJ_TRIGGER) + if(obj_type==ObjectType::Trigger) { trigger=dynamic_cast(object); @@ -388,8 +380,9 @@ void ViewWidget::showObjectData(TableObject *object, int row) str_aux.remove(str_aux.size()-2, 2); tab->setCellText(str_aux ,row,3); + tab->setCellText(trigger->getAlias(), row, 4); } - else if(obj_type==OBJ_RULE) + else if(obj_type==ObjectType::Rule) { rule=dynamic_cast(object); @@ -398,6 +391,8 @@ void ViewWidget::showObjectData(TableObject *object, int row) //Column 2: Rule event type tab->setCellText(~rule->getEventType(),row,2); + + tab->setCellText(rule->getAlias(), row, 3); } else { @@ -405,8 +400,10 @@ void ViewWidget::showObjectData(TableObject *object, int row) //Column 1: Indexing type tab->setCellText(~index->getIndexingType(),row,1); + tab->setCellText(index->getAlias(), row, 2); } + tab->setCellText(object->getComment(), row, tab->getColumnCount() - 1); tab->setRowData(QVariant::fromValue(object), row); } @@ -436,164 +433,77 @@ void ViewWidget::listObjects(ObjectType obj_type) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } -void ViewWidget::clearReferenceForm(void) +int ViewWidget::openReferenceForm(Reference ref, int row, bool update) { - column_sel->clearSelector(); - table_sel->clearSelector(); - col_alias_edt->clear(); - expr_alias_edt->clear(); - tab_alias_edt->clear(); - expression_txt->clear(); - select_from_chk->setChecked(false); - from_where_chk->setChecked(false); - after_where_chk->setChecked(false); -} - -void ViewWidget::selectReferenceType(void) -{ - //Marks if the select reference type treats a reference to an object - bool ref_obj=(ref_type_cmb->currentIndex()==static_cast(Reference::REFER_COLUMN)); - - table_lbl->setVisible(ref_obj); - column_lbl->setVisible(ref_obj); - table_sel->setVisible(ref_obj); - column_sel->setVisible(ref_obj); - col_alias_lbl->setVisible(ref_obj); - col_alias_edt->setVisible(ref_obj); - tab_alias_edt->setVisible(ref_obj); - tab_alias_lbl->setVisible(ref_obj); - frame_info->setVisible(ref_obj); - - view_def_chk->setChecked(false); - expression_lbl->setVisible(!ref_obj); - expression_txt->setVisible(!ref_obj); - expr_alias_edt->setVisible(!ref_obj); - expr_alias_lbl->setVisible(!ref_obj); - view_def_chk->setVisible(!ref_obj); -} - -void ViewWidget::handleReference(int ref_idx) -{ - try - { - Reference ref; - - //Creating a reference to a column - if(static_cast(ref_type_cmb->currentIndex())==Reference::REFER_COLUMN) - { - ref=Reference(dynamic_cast
(table_sel->getSelectedObject()), - dynamic_cast(column_sel->getSelectedObject()), - tab_alias_edt->text().toUtf8(), col_alias_edt->text().toUtf8()); - } - //Creating a reference to an expression - else - { - ref=Reference(expression_txt->toPlainText(), expr_alias_edt->text().toUtf8()); - } + BaseForm editing_form(this); + ReferenceWidget *ref_wgt=new ReferenceWidget; + int result = 0; - /* The reference must have an SQL application (be between SELECT-FROM, FROM-WHERE or after WHERE), - if the user do not check some of these attributes raises an error */ - if(!select_from_chk->isChecked() && !from_where_chk->isChecked() && - !after_where_chk->isChecked() && !end_expr_chk->isChecked() && - !view_def_chk->isChecked()) - throw Exception(ERR_SQL_SCOPE_INV_VIEW_REF,__PRETTY_FUNCTION__,__FILE__,__LINE__); + editing_form.setMainWidget(ref_wgt); + editing_form.setButtonConfiguration(Messagebox::OkCancelButtons); - if(view_def_chk->isChecked()) - { - select_from_chk->setChecked(false); - from_where_chk->setChecked(false); - after_where_chk->setChecked(false); - } + disconnect(editing_form.apply_ok_btn, SIGNAL(clicked(bool)), &editing_form, SLOT(accept())); + connect(editing_form.apply_ok_btn, SIGNAL(clicked(bool)), ref_wgt, SLOT(applyConfiguration())); + connect(ref_wgt, SIGNAL(s_closeRequested()), &editing_form, SLOT(accept())); - showReferenceData(ref, select_from_chk->isChecked(), from_where_chk->isChecked(), - after_where_chk->isChecked(), end_expr_chk->isChecked(), view_def_chk->isChecked() ,ref_idx); + ref_wgt->setAttributes(ref, getReferenceFlag(row), model); + result = editing_form.exec(); + disconnect(ref_wgt, nullptr, &editing_form, nullptr); - clearReferenceForm(); - references_tab->clearSelection(); - } - catch(Exception &e) - { - if(references_tab->getCellText(ref_idx, 0).isEmpty()) - references_tab->removeRow(ref_idx); + if(result == QDialog::Accepted) + showReferenceData(ref_wgt->getReference(), ref_wgt->getReferenceFlags(), row); + else if(!update) + references_tab->removeRow(row); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); - } + return(result); } -void ViewWidget::editReference(int ref_idx) +unsigned ViewWidget::getReferenceFlag(int row) { - Reference ref; - QString str_aux; - - //Get the reference at the selected table row - ref=references_tab->getRowData(ref_idx).value(); - ref_type_cmb->setCurrentIndex(ref.getReferenceType()); + QString flags_str = references_tab->getCellText(row, 3); + unsigned ref_flags = 0; - if(ref.getReferenceType()==Reference::REFER_COLUMN) - { - if(ref.getColumn()) - column_sel->setSelectedObject(ref.getColumn()); - else - table_sel->setSelectedObject(ref.getTable()); - - col_alias_edt->setText(ref.getColumnAlias()); - tab_alias_edt->setText(ref.getAlias()); - } + if(flags_str[4] == '1') + ref_flags = Reference::SqlViewDefinition; else { - expression_txt->setPlainText(ref.getExpression()); - expr_alias_edt->setText(ref.getAlias()); - } - - str_aux=references_tab->getCellText(ref_idx,3); - select_from_chk->setChecked(str_aux[0]=='1'); - from_where_chk->setChecked(str_aux[1]=='1'); - after_where_chk->setChecked(str_aux[2]=='1'); - end_expr_chk->setChecked(str_aux[3]=='1'); - view_def_chk->setChecked(str_aux[4]=='1'); -} + if(flags_str[0] == '1') + ref_flags |= Reference::SqlReferSelect; -void ViewWidget::showObjectName(void) -{ - Column *col=nullptr; - QObject *obj_sender=sender(); + if(flags_str[1] == '1') + ref_flags |= Reference::SqlReferFrom; - //If the sender is the table selector means that user want to reference all table columns - if(obj_sender==table_sel) - { - column_sel->blockSignals(true); - //Clears the column selector indicating the situation. (TABLE.*) - column_sel->clearSelector(); + if(flags_str[2] == '1') + ref_flags |= Reference::SqlReferWhere; - column_sel->blockSignals(false); + if(flags_str[3] == '1') + ref_flags |= Reference::SqlReferEndExpr; } - //If the sender is not the table sender the user wants to reference a specific column - else - { - col=dynamic_cast(column_sel->getSelectedObject()); - table_sel->blockSignals(true); - - if(col) - table_sel->setSelectedObject(col->getParentTable()); - else - table_sel->clearSelector(); + return(ref_flags); +} - table_sel->blockSignals(false); - } +void ViewWidget::editReference(int ref_idx) +{ + openReferenceForm(references_tab->getRowData(ref_idx).value(), ref_idx, true); } -void ViewWidget::showReferenceData(Reference refer, bool selec_from, bool from_where, bool after_where, bool end_expr, bool view_def, unsigned row) +void ViewWidget::showReferenceData(Reference refer, unsigned ref_flags, unsigned row) { Table *tab=nullptr; Column *col=nullptr; QString str_aux; + bool selec_from = (ref_flags & Reference::SqlReferSelect) == Reference::SqlReferSelect, + from_where = (ref_flags & Reference::SqlReferFrom) == Reference::SqlReferFrom, + after_where = (ref_flags & Reference::SqlReferWhere) == Reference::SqlReferWhere, + end_expr = (ref_flags & Reference::SqlReferEndExpr) == Reference::SqlReferEndExpr, + view_def = (ref_flags & Reference::SqlViewDefinition) == Reference::SqlViewDefinition; - if(refer.getReferenceType()==Reference::REFER_COLUMN) + if(refer.getReferenceType()==Reference::ReferColumn) { tab=refer.getTable(); col=refer.getColumn(); @@ -614,7 +524,7 @@ void ViewWidget::showReferenceData(Reference refer, bool selec_from, bool from_w } else { - references_tab->setCellText(refer.getExpression(),row,0); + references_tab->setCellText(refer.getExpression().simplified(),row,0); references_tab->setCellText(refer.getAlias(),row,1); } @@ -624,7 +534,9 @@ void ViewWidget::showReferenceData(Reference refer, bool selec_from, bool from_w str_aux+=(after_where ? QString("1") : QString("0")); str_aux+=(end_expr ? QString("1") : QString("0")); str_aux+=(view_def ? QString("1") : QString("0")); - references_tab->setCellText(str_aux,row,3); + references_tab->setCellText(str_aux, row, 3); + + references_tab->setCellText(refer.getReferenceAlias(), row, 4); refer.setDefinitionExpression(view_def); references_tab->setRowData(QVariant::fromValue(refer), row); @@ -642,11 +554,11 @@ void ViewWidget::updateCodePreview(void) TableObject *tab_obj=nullptr; map::iterator itr, itr_end; unsigned i, count, i1, expr_type[]={ - Reference::SQL_REFER_SELECT, - Reference::SQL_REFER_FROM, - Reference::SQL_REFER_WHERE, - Reference::SQL_REFER_END_EXPR, - Reference::SQL_VIEW_DEFINITION}; + Reference::SqlReferSelect, + Reference::SqlReferFrom, + Reference::SqlReferWhere, + Reference::SqlReferEndExpr, + Reference::SqlViewDefinition}; aux_view.BaseObject::setName(name_edt->text().toUtf8()); aux_view.BaseObject::setSchema(schema_sel->getSelectedObject()); @@ -683,7 +595,7 @@ void ViewWidget::updateCodePreview(void) //Make a copy of each view objects (rule/trigger) to the auxiliary view for(i=0; i < count; i++) { - if(itr->first==OBJ_TRIGGER) + if(itr->first==ObjectType::Trigger) { tab_obj=new Trigger; (*dynamic_cast(tab_obj))= @@ -700,7 +612,7 @@ void ViewWidget::updateCodePreview(void) itr++; } - code_txt->setPlainText(aux_view.getCodeDefinition(SchemaParser::SQL_DEFINITION)); + code_txt->setPlainText(aux_view.getCodeDefinition(SchemaParser::SqlDefinition)); } } catch(Exception &e) @@ -715,8 +627,7 @@ void ViewWidget::updateCodePreview(void) void ViewWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, View *view, double px, double py) { - unsigned i, count; - bool sel_from = false, from_where = false, after_where = false, view_def = false, end_expr = false; + unsigned i, count, ref_flags = 0; Reference refer; if(!view) @@ -737,15 +648,11 @@ void ViewWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Sch recursive_rb->setChecked(view->isRecursive()); with_no_data_chk->setChecked(view->isWithNoData()); - expression_cp->configureCompletion(model, expression_hl); cte_expression_cp->configureCompletion(model, cte_expression_hl); op_list->startOperationChain(); operation_count=op_list->getCurrentSize(); - column_sel->setModel(model); - table_sel->setModel(model); - tag_sel->setModel(this->model); tag_sel->setSelectedObject(view->getTag()); @@ -758,22 +665,33 @@ void ViewWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Sch { references_tab->addRow(); + ref_flags = 0; refer=view->getReference(i); - sel_from=(view->getReferenceIndex(refer,Reference::SQL_REFER_SELECT) >= 0); - from_where=(view->getReferenceIndex(refer,Reference::SQL_REFER_FROM) >= 0); - after_where=(view->getReferenceIndex(refer,Reference::SQL_REFER_WHERE)>= 0); - end_expr=(view->getReferenceIndex(refer,Reference::SQL_REFER_END_EXPR)>= 0); - view_def=(view->getReferenceIndex(refer,Reference::SQL_VIEW_DEFINITION)>= 0); - showReferenceData(refer, sel_from, from_where, after_where, end_expr, view_def, i); + if(view->getReferenceIndex(refer, Reference::SqlViewDefinition) >= 0) + ref_flags = Reference::SqlViewDefinition; + + if(view->getReferenceIndex(refer, Reference::SqlReferSelect) >= 0) + ref_flags |= Reference::SqlReferSelect; + + if(view->getReferenceIndex(refer, Reference::SqlReferFrom) >= 0) + ref_flags |= Reference::SqlReferFrom; + + if(view->getReferenceIndex(refer, Reference::SqlReferWhere) >= 0) + ref_flags |= Reference::SqlReferWhere; + + if(view->getReferenceIndex(refer, Reference::SqlReferEndExpr) >= 0) + ref_flags |= Reference::SqlReferEndExpr; + + showReferenceData(refer, ref_flags, i); } references_tab->blockSignals(false); references_tab->clearSelection(); - listObjects(OBJ_TRIGGER); - listObjects(OBJ_RULE); - listObjects(OBJ_INDEX); + listObjects(ObjectType::Trigger); + listObjects(ObjectType::Rule); + listObjects(ObjectType::Index); } void ViewWidget::applyConfiguration(void) @@ -781,17 +699,17 @@ void ViewWidget::applyConfiguration(void) try { View *view=nullptr; - ObjectType types[]={ OBJ_TRIGGER, OBJ_RULE, OBJ_INDEX }; - unsigned expr_type[]={ Reference::SQL_REFER_SELECT, - Reference::SQL_REFER_FROM, - Reference::SQL_REFER_WHERE, - Reference::SQL_REFER_END_EXPR, - Reference::SQL_VIEW_DEFINITION}; + ObjectType types[]={ ObjectType::Trigger, ObjectType::Rule, ObjectType::Index }; + unsigned expr_type[]={ Reference::SqlReferSelect, + Reference::SqlReferFrom, + Reference::SqlReferWhere, + Reference::SqlReferEndExpr, + Reference::SqlViewDefinition}; Reference refer; QString str_aux; if(!this->new_object) - op_list->registerObject(this->object, Operation::OBJECT_MODIFIED); + op_list->registerObject(this->object, Operation::ObjectModified); else registerNewObject(); @@ -811,7 +729,7 @@ void ViewWidget::applyConfiguration(void) refer=references_tab->getRowData(i).value(); //Get the SQL application string for the current reference - str_aux=references_tab->getCellText(i,3); + str_aux=references_tab->getCellText(i, 3); for(unsigned i=0; i < sizeof(expr_type)/sizeof(unsigned); i++) { if(str_aux[i]=='1') @@ -832,7 +750,7 @@ void ViewWidget::applyConfiguration(void) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/libpgmodeler_ui/src/viewwidget.h b/libpgmodeler_ui/src/viewwidget.h index f499437f13..1640b7415c 100644 --- a/libpgmodeler_ui/src/viewwidget.h +++ b/libpgmodeler_ui/src/viewwidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -41,35 +41,25 @@ class ViewWidget: public BaseObjectWidget, public Ui::ViewWidget { private: Q_OBJECT - QFrame *frame_info; - ObjectSelectorWidget *tag_sel; - NumberedTextEditor *cte_expression_txt, *code_txt, *expression_txt; + NumberedTextEditor *cte_expression_txt, *code_txt; //! \brief Stores all the view references ObjectsTableWidget *references_tab; map objects_tab_map; - SyntaxHighlighter *expression_hl, - *code_hl, - *cte_expression_hl; - - CodeCompletionWidget *cte_expression_cp, - *expression_cp; + SyntaxHighlighter *code_hl, *cte_expression_hl; - ObjectSelectorWidget *table_sel, - *column_sel; + CodeCompletionWidget *cte_expression_cp; //! \brief Shows the reference at the reference's table - void showReferenceData(Reference refer, bool selec_from, bool from_where, - bool after_where, bool end_expr, bool view_def, unsigned row); - - void clearReferenceForm(void); + void showReferenceData(Reference refer, unsigned ref_flags, unsigned row); //! \brief Returns the object table according with the child type ObjectsTableWidget *getObjectTable(ObjectType obj_type); + ObjectType getObjectType(QObject *sender); void showObjectData(TableObject *object, int row); @@ -81,24 +71,19 @@ class ViewWidget: public BaseObjectWidget, public Ui::ViewWidget { template int openEditingForm(TableObject *object); + int openReferenceForm(Reference ref, int row, bool update); + + unsigned getReferenceFlag(int row); + public: - ViewWidget(QWidget * parent = 0); + ViewWidget(QWidget * parent = nullptr); void setAttributes(DatabaseModel *model, OperationList *op_list, Schema *schema, View *view, double px, double py); private slots: - //! \brief Shows the field according to the selected reference type - void selectReferenceType(void); - - //! \brief Creates a reference from the values filled on the form - void handleReference(int ref_idx); - //! \brief Edits the selected reference void editReference(int ref_idx); - //! \brief Controls the form which are show the table and column names of the reference - void showObjectName(void); - //! \brief Updates the sql code field of the view form void updateCodePreview(void); @@ -114,6 +99,12 @@ class ViewWidget: public BaseObjectWidget, public Ui::ViewWidget { //! \brief Removes all objects from the table that calls the slot void removeObjects(void); + //! \brief Opens the reference form when a new row is added in the references grid + void addReference(int row); + + //! \brief Duplicate the current selected reference + void duplicateReference(int orig_row, int new_row); + public slots: void applyConfiguration(void); void cancelConfiguration(void); diff --git a/libpgmodeler_ui/src/welcomewidget.cpp b/libpgmodeler_ui/src/welcomewidget.cpp index 13d28a7961..85de550389 100644 --- a/libpgmodeler_ui/src/welcomewidget.cpp +++ b/libpgmodeler_ui/src/welcomewidget.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -17,28 +17,22 @@ */ #include "welcomewidget.h" -#include #include "pgmodeleruins.h" WelcomeWidget::WelcomeWidget(QWidget *parent): QWidget(parent) { setupUi(this); - QList btns= { new_tb, open_tb, recent_tb, last_session_tb, sample_tb }; - QGraphicsDropShadowEffect *shadow=nullptr; + QList btns= { new_tb, open_tb, recent_tb, last_session_tb, sample_tb, support_tb }; for(auto &btn : btns) { - shadow=new QGraphicsDropShadowEffect(this); - shadow->setXOffset(3); - shadow->setYOffset(3); - shadow->setBlurRadius(10); - btn->setGraphicsEffect(shadow); + PgModelerUiNs::createDropShadow(btn, 3, 3, 10); #ifdef Q_OS_LINUX - PgModelerUiNS::configureWidgetFont(btn, 1.20f); + PgModelerUiNs::__configureWidgetFont(btn, 1.30); #else - PgModelerUiNS::configureWidgetFont(btn, 1.50f); + PgModelerUiNs::__configureWidgetFont(btn, 1.50); #endif } } diff --git a/libpgmodeler_ui/src/welcomewidget.h b/libpgmodeler_ui/src/welcomewidget.h index 93bce54e33..9ca1c9745d 100644 --- a/libpgmodeler_ui/src/welcomewidget.h +++ b/libpgmodeler_ui/src/welcomewidget.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -31,7 +31,7 @@ class WelcomeWidget: public QWidget, public Ui::WelcomeWidget { Q_OBJECT public: - WelcomeWidget(QWidget * parent = 0); + WelcomeWidget(QWidget * parent = nullptr); public slots: }; diff --git a/libpgmodeler_ui/ui/aboutwidget.ui b/libpgmodeler_ui/ui/aboutwidget.ui index 2fdb9dcc26..5df306c8fd 100644 --- a/libpgmodeler_ui/ui/aboutwidget.ui +++ b/libpgmodeler_ui/ui/aboutwidget.ui @@ -9,8 +9,8 @@ 0 0 - 575 - 550 + 550 + 530 @@ -21,14 +21,14 @@ - 575 - 550 + 550 + 530 16777215 - 600 + 550 @@ -68,7 +68,7 @@ QFrame::Raised - + 6 @@ -81,32 +81,7 @@ 6 - - 6 - - - - - - 0 - 0 - - - - - 75 - true - - - - PostgreSQL Database Modeler - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - + @@ -116,14 +91,14 @@ - 100 - 100 + 50 + 50 - 100 - 100 + 50 + 50 @@ -137,190 +112,32 @@ - - - - - 0 - 0 - - - - - 0 - 0 - - - - - false - - - - QFrame::NoFrame - - - Open source data modeling tool designed for PostgreSQL. No more DDL commands written by hand, let pgModeler do the job for you! This software reunites the concepts of entity-relationship diagrams and the features that PostgreSQL implements as extensions of SQL standards. - - - Qt::PlainText - - - Qt::AlignJustify|Qt::AlignTop - - - true - - - 0 - - - Qt::TextSelectableByMouse - - - - - - - - 0 - 0 - - - - - 230 - 0 - - - - - 16777215 - 16777215 - - - - - true - - - - Design, configure, deploy - - - - - - - - - - 0 - 0 - - - - <html><head/><body><p><a href="http://pgmodeler.com.br"><span style=" text-decoration: underline; color:#2980b9;">https://pgmodeler.io</span></a></p></body></html> - - - Qt::RichText - - - 5 - - - true - - - - - - - pgModeler is proudly a brazilian software! - - - - - - - - - :/imagens/imagens/brazil_flag.png - - - Qt::AlignHCenter|Qt::AlignTop - - - + + - - - - 0 - 0 - - - - <html><head/><body><p>Copyright 2006-2016 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.io</span></a>&gt;</p></body></html> + + + Qt::Horizontal - - Qt::AutoText - - - 5 - - - true + + + 40 + 20 + - + - - - - - - - 20 - 20 - - - - - 20 - 20 - - - - Hide this widget - - - ... - - - - :/icones/icones/fechar1.png:/icones/icones/fechar1.png - - - true - - - - - - - 6 - - + - + 0 0 - 60 + 0 0 @@ -337,19 +154,15 @@ true + + + - 0.0.0.0 + 0.0.0 - - - - - - 6 - - + @@ -368,20 +181,17 @@ Qt::LeftToRight - Build: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + build: -1 - + - + 0 0 @@ -436,482 +246,258 @@ -1 + + Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 75 + true + + + + PostgreSQL Database Modeler + + + Qt::AlignCenter + + + Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse + - - - - - 0 - 0 - - + + - 0 - 0 + 20 + 20 - - 0 + + + 20 + 20 + + + + Hide this widget + + + ... + + + + :/icones/icones/fechar1.png:/icones/icones/fechar1.png + + + true - - - License - - - - 4 - - - 4 - - - 4 - - - 4 - - - - - - Droid Sans Tamil - - - - QFrame::Sunken - - - QAbstractScrollArea::AdjustToContents - - - false - - - QTextEdit::WidgetWidth - - - true - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'Droid Sans Tamil'; font-size:10pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Courier';">pgModeler - PostgreSQL Database Modeler<br />Copyright 2006-2016 - Raphael Araújo e Silva<br /><br />This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 3.<br /><br />This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.<br /><br />The complete text of GPLv3 is at LICENSE file on pgModeler's source code root directory. Also, you can get the complete GNU General Public License at &lt;</span><a href="http://www.gnu.org/licenses"><span style=" font-family:'Courier'; text-decoration: underline; color:#0000ff;">http://www.gnu.org/licenses</span></a><span style=" font-family:'Courier';">&gt;</span></p></body></html> - - - false - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse - - - - - - - - Contributors - - - - 4 - - - 4 - - - 4 - - - 4 - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - false - - - - QFrame::NoFrame - - - <html><head/><body><p>This page is dedicated to all contributors who gave a bit of their time in make pgModeler a better software somehow. The complete list of people that helped pgModeler can be found at <a href="https://github.com/pgmodeler/pgmodeler/graphs/contributors"><span style=" text-decoration: underline; color:#00a489;">GitHub</span></a>.</p><p>If you have a great idea to improve pgModeler please submit it <a href="http://github.com/pgmodeler/pgmodeler/issues"><span style=" text-decoration: underline; color:#00a489;">here</span></a>. No ideas for now but want to help? Why not donate a few bucks <a href="http://pgmodeler.com.br/#donate"><span style=" text-decoration: underline; color:#00a489;">here</span></a>!?</p></body></html> - - - Qt::RichText - - - Qt::AlignJustify|Qt::AlignTop - - - true - - - 0 - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - 0 - 0 - - - - Qt::ScrollBarAsNeeded - - - Qt::ScrollBarAsNeeded - - - QAbstractItemView::NoEditTriggers - - - false - - - true - - - QAbstractItemView::SingleSelection - - - QAbstractItemView::SelectItems - - - QAbstractItemView::ScrollPerItem - - - true - - - false - - - true - - - true - - - false - - - true - - - false - - - false - - - false - - - - 1 - - - - - 2 - - - - - 3 - - - - - 4 - - - - - 5 - - - - - 6 - - - - - 7 - - - - - 8 - - - - - 9 - - - - - 10 - - - - - Name - - - - - Country - - - - - Contribution - - - - - Damien Degois - - - - - France - - - - :/icones/icones/flag_france.png:/icones/icones/flag_france.png - - - - - French UI translation and several improvements in auxiliary scripts. - - - - - Ji Bin - - - - - China - - - - :/icones/icones/flag_china.png:/icones/icones/flag_china.png - - - - - Chinese UI translation and small fixes. - - - - - Pierre-Samuel LE STANG - - - - - France - - - - :/icones/icones/flag_france.png:/icones/icones/flag_france.png - - - - - French UI translation. - - - - - Lisandro Damián Nicanor - - - - - Argentina - - - - :/icones/icones/flag_argentina.png:/icones/icones/flag_argentina.png - - - - - Improvements on build scripts enabling the custom packaging in Linux distros; Per-user settings; pgModeler's package maintainer in Debian Linux. - - - - - Pavel Alexeev - - - - - Russia - - - - :/icones/icones/flag_russia.png:/icones/icones/flag_russia.png - - - - - Additional work for packaging in Linux distros; pgModeler's package maintainer in Fedora Linux. - - - - - Mariusz Fik - - - - - Poland - - - - :/icones/icones/flag_poland.png:/icones/icones/flag_poland.png - - - - - Custom packaging first ideas. Tester of first version of custom packaging patch. - - - - - Jonathan DUPRE - - - - - France - - - - :/icones/icones/flag_france.png:/icones/icones/flag_france.png - - - - - French UI translation. - - - - - Gilberto Castillo - - - - - Cuba - - - - :/icones/icones/flag_cuba.png:/icones/icones/flag_cuba.png - - - - - Spanish UI translation. - - - - - -Danúbio Viana Nogueira - - - - - Brazil - - - - :/imagens/imagens/brazil_flag.png:/imagens/imagens/brazil_flag.png - - - - - Brazilian Portuguese UI translation. - - - - - Alfredo Marcillo - - - - - Ecuador - - - - :/icones/icones/flag_ecuador.png:/icones/icones/flag_ecuador.png - - - - - Spanish UI translation review. - - - - - - - + Qt::Vertical - QSizePolicy::Expanding + QSizePolicy::Fixed 20 - 10 + 20 + + + + + 0 + 0 + + + + + 0 + 0 + + + + + false + + + + QFrame::NoFrame + + + Open source data modeling tool designed for PostgreSQL. No more DDL commands written by hand, let pgModeler do the job for you! This software reunites the concepts of entity-relationship diagrams and the features that PostgreSQL implements as extensions of SQL standards. + + + Qt::PlainText + + + Qt::AlignJustify|Qt::AlignTop + + + true + + + 0 + + + Qt::TextSelectableByMouse + + + + + + + License + + + + 4 + + + 4 + + + 4 + + + 4 + + + + + QFrame::Sunken + + + QAbstractScrollArea::AdjustToContents + + + false + + + QTextEdit::WidgetWidth + + + true + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Noto Sans'; font-size:10pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Courier';">pgModeler - PostgreSQL Database Modeler<br />Copyright 2006-2018 - Raphael Araújo e Silva<br /><br />This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 3.<br /><br />This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.<br /><br />The complete text of GPLv3 is at LICENSE file on pgModeler's source code root directory. Also, you can get the complete GNU General Public License at &lt;</span><a href="http://www.gnu.org/licenses"><span style=" font-family:'Courier'; text-decoration: underline; color:#0000ff;">http://www.gnu.org/licenses</span></a><span style=" font-family:'Courier';">&gt;</span></p></body></html> + + + false + + + Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse + + + + + + + + + + + + + 0 + 0 + + + + <html><head/><body><p><a href="http://pgmodeler.com.br"><span style=" text-decoration: underline; color:#2980b9;">https://pgmodeler.io</span></a></p></body></html> + + + Qt::RichText + + + 5 + + + true + + + + + + + pgModeler is proudly a brazilian software! + + + + + + + + + :/imagens/imagens/brazil_flag.png + + + Qt::AlignHCenter|Qt::AlignTop + + + + + + + + 0 + 0 + + + + <html><head/><body><p>Copyright 2006-2018 - Raphael Araújo e Silva &lt;<a href="mailto:raphael@pgmodeler.com.br"><span style=" text-decoration: underline; color:#0057ae;">raphael@pgmodeler.io</span></a>&gt;</p></body></html> + + + Qt::AutoText + + + 5 + + + true + + + + + diff --git a/libpgmodeler_ui/ui/appearanceconfigwidget.ui b/libpgmodeler_ui/ui/appearanceconfigwidget.ui index 4c3e082f50..cb62533654 100644 --- a/libpgmodeler_ui/ui/appearanceconfigwidget.ui +++ b/libpgmodeler_ui/ui/appearanceconfigwidget.ui @@ -167,6 +167,16 @@ Constraint: Descriptor + + + Policy: Name + + + + + Policy: Descriptor + + View: Schema name diff --git a/libpgmodeler_ui/ui/baseobjectwidget.ui b/libpgmodeler_ui/ui/baseobjectwidget.ui index c3db5ea209..de3f7deec7 100644 --- a/libpgmodeler_ui/ui/baseobjectwidget.ui +++ b/libpgmodeler_ui/ui/baseobjectwidget.ui @@ -74,9 +74,15 @@ 16777215 + + This is the name of the object in the PostgreSQL database. + + + true + @@ -147,7 +153,7 @@ Schema: - + 318 @@ -193,9 +199,6 @@ 22 - - Qt::ToolButtonTextBesideIcon - @@ -331,7 +334,7 @@ This will disable the code of all child and referrer objects. Collation: - + 197 @@ -377,9 +380,6 @@ This will disable the code of all child and referrer objects. 22 - - Qt::ToolButtonTextBesideIcon - @@ -403,9 +403,9 @@ This will disable the code of all child and referrer objects. - 210 - 90 - 141 + 200 + 80 + 161 31 @@ -428,7 +428,7 @@ This will disable the code of all child and referrer objects. - + 0 0 @@ -507,6 +507,126 @@ This will disable the code of all child and referrer objects. 80 + + true + + + + + + 80 + 120 + 111 + 25 + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + This is a more friendly name for the object. When displaying the model in compact view this is the name shown for the object instead of its real name. If this field is empty the real name will be displayed anyway. + + + + + + true + + + + + + 8 + 120 + 81 + 16 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Alias: + + + + + + 200 + 120 + 31 + 31 + + + + + 0 + 0 + + + + + 6 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + diff --git a/libpgmodeler_ui/ui/bugreportform.ui b/libpgmodeler_ui/ui/bugreportform.ui index bbcc725ce2..99f2929e1d 100644 --- a/libpgmodeler_ui/ui/bugreportform.ui +++ b/libpgmodeler_ui/ui/bugreportform.ui @@ -350,7 +350,11 @@ - + + + true + + diff --git a/libpgmodeler_ui/ui/columnwidget.ui b/libpgmodeler_ui/ui/columnwidget.ui index 7bcc7008d1..4ba331f204 100644 --- a/libpgmodeler_ui/ui/columnwidget.ui +++ b/libpgmodeler_ui/ui/columnwidget.ui @@ -6,8 +6,8 @@ 0 0 - 347 - 171 + 585 + 250 @@ -44,10 +44,23 @@ 4 - - - - false + + + + + 0 + 30 + + + + Edit the underlying sequence's attributes + + + Edit sequence + + + + :/icones/icones/sequence.png:/icones/icones/sequence.png @@ -75,20 +88,7 @@ - - - - - 0 - 0 - - - - &NOT NULL - - - - + @@ -116,6 +116,39 @@ + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + false + + + + + + + + 0 + 0 + + + + &NOT NULL + + + @@ -126,6 +159,8 @@ def_value_txt sequence_rb - + + + diff --git a/libpgmodeler_ui/ui/configurationform.ui b/libpgmodeler_ui/ui/configurationform.ui index c33ee5bf83..e2e72b0462 100644 --- a/libpgmodeler_ui/ui/configurationform.ui +++ b/libpgmodeler_ui/ui/configurationform.ui @@ -117,7 +117,7 @@ false - QAbstractItemView::DragOnly + QAbstractItemView::NoDragDrop Qt::IgnoreAction @@ -205,6 +205,9 @@ :/icones/icones/relationshiptv.png:/icones/icones/relationshiptv.png + + ItemIsSelectable|ItemIsUserCheckable|ItemIsEnabled + @@ -244,6 +247,9 @@ :/icones/icones/codesnippet.png:/icones/icones/codesnippet.png + + ItemIsSelectable|ItemIsUserCheckable|ItemIsEnabled + diff --git a/libpgmodeler_ui/ui/connectionsconfigwidget.ui b/libpgmodeler_ui/ui/connectionsconfigwidget.ui index d1710ec20f..dfa311db35 100644 --- a/libpgmodeler_ui/ui/connectionsconfigwidget.ui +++ b/libpgmodeler_ui/ui/connectionsconfigwidget.ui @@ -7,7 +7,7 @@ 0 0 562 - 442 + 446 @@ -405,6 +405,9 @@ + + true + @@ -450,7 +453,7 @@ - false + true @@ -499,7 +502,7 @@ QLineEdit::Password - false + true @@ -536,6 +539,9 @@ Specify additional connection parameters in the form [param]=[value]. These parameters are described in the <strong>libpq</strong> chapter at PostgreSQL docs. + + true + @@ -597,6 +603,9 @@ + + true + @@ -682,6 +691,9 @@ + + true + @@ -777,6 +789,9 @@ + + true + @@ -842,6 +857,9 @@ + + true + @@ -851,6 +869,9 @@ true + + true + @@ -908,6 +929,9 @@ + + true + @@ -969,6 +993,9 @@ + + true + diff --git a/libpgmodeler_ui/ui/csvloadwidget.ui b/libpgmodeler_ui/ui/csvloadwidget.ui index 51a614e1d9..d8b9384c5b 100644 --- a/libpgmodeler_ui/ui/csvloadwidget.ui +++ b/libpgmodeler_ui/ui/csvloadwidget.ui @@ -6,7 +6,7 @@ 0 0 - 729 + 710 100 @@ -64,7 +64,11 @@ - + + + true + + diff --git a/libpgmodeler_ui/ui/databaseexplorerwidget.ui b/libpgmodeler_ui/ui/databaseexplorerwidget.ui index 82082236c4..0612af7c5a 100644 --- a/libpgmodeler_ui/ui/databaseexplorerwidget.ui +++ b/libpgmodeler_ui/ui/databaseexplorerwidget.ui @@ -34,6 +34,9 @@ + + 4 + @@ -69,6 +72,9 @@ Qt::ToolButtonIconOnly + + true + @@ -109,6 +115,9 @@ Qt::ToolButtonIconOnly + + true + @@ -143,6 +152,9 @@ Qt::ToolButtonIconOnly + + true + @@ -151,7 +163,7 @@ true - Open a new SQL execution pane + Add a new SQL execution tab for the current database ... @@ -169,6 +181,9 @@ Ctrl+F6 + + true + @@ -192,6 +207,9 @@ 22 + + true + @@ -215,6 +233,9 @@ 22 + + true + @@ -593,7 +614,7 @@ false - 25 + 26 false diff --git a/libpgmodeler_ui/ui/databaseimportform.ui b/libpgmodeler_ui/ui/databaseimportform.ui index 39235995fe..db732a9175 100644 --- a/libpgmodeler_ui/ui/databaseimportform.ui +++ b/libpgmodeler_ui/ui/databaseimportform.ui @@ -81,49 +81,7 @@ 4 - - - - - 0 - 0 - - - - - 32 - 32 - - - - - 32 - 32 - - - - - - - :/icones/icones/import.png - - - - - - - - 13 - 75 - true - - - - Import database - - - - + @@ -441,7 +399,7 @@ - pgModeler ignores import errors and will try to create as many as possible objects. By checking this option the import operation will be not aborted but an incomplete model will be constructed. This option generates a log file on pgModeler's temp directory. + pgModeler ignores import errors and will try to create as many as possible objects. By checking this option the import operation will not be aborted but an incomplete model will be constructed. This option generates a log file on pgModeler's temp directory. diff --git a/libpgmodeler_ui/ui/databasewidget.ui b/libpgmodeler_ui/ui/databasewidget.ui index 4bf82b86a7..77097e7df2 100644 --- a/libpgmodeler_ui/ui/databasewidget.ui +++ b/libpgmodeler_ui/ui/databasewidget.ui @@ -78,6 +78,9 @@ 25 + + true + @@ -101,6 +104,9 @@ 25 + + true + diff --git a/libpgmodeler_ui/ui/datamanipulationform.ui b/libpgmodeler_ui/ui/datamanipulationform.ui index 97d2c9f515..5f276b0133 100644 --- a/libpgmodeler_ui/ui/datamanipulationform.ui +++ b/libpgmodeler_ui/ui/datamanipulationform.ui @@ -6,14 +6,20 @@ 0 0 - 800 - 600 + 897 + 650 - 800 - 600 + 700 + 650 + + + + + 1250 + 900 @@ -28,7 +34,7 @@ - 2 + 0 2 @@ -39,117 +45,7 @@ 2 - - - - 2 - - - 2 - - - 2 - - - 2 - - - 6 - - - - - - 0 - 0 - - - - - 127 - 0 - - - - - - - - - - Qt::PlainText - - - :/imagens/imagens/pgmodeler_name.png - - - - - - - - 0 - 0 - - - - - 90 - 32 - - - - - 16777215 - 16777215 - - - - false - - - - - - &Close - - - - :/icones/icones/fechar1.png:/icones/icones/fechar1.png - - - - 20 - 20 - - - - false - - - false - - - false - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - + @@ -176,25 +72,761 @@ 4 - - + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + 0 + 0 + + + + Schema: + + + + + + + + 0 + 0 + + + + 20 + + + QComboBox::InsertAtBottom + + + + 16 + 16 + + + + + + + + + 0 + 0 + + + + Table: + + + + + + + + 0 + 0 + + + + 20 + + + QComboBox::InsertAtBottom + + + QComboBox::AdjustToContentsOnFirstShow + + + + 16 + 16 + + + + + + + + + 0 + 0 + + + + Hide views + + + true + + + + + + + + + 0 + + + + + + 20 + 20 + + + + + 22 + 22 + + + + + + + :/icones/icones/database.png + + + true + + + + + + + + 0 + 0 + + + + + + + 5 + + + + + + + + + - + 0 0 - - - 0 - 30 - - - - QFrame::StyledPanel + + Qt::Horizontal - - QFrame::Raised + + false + + + + true + + + + 0 + 0 + + + + QAbstractItemView::AnyKeyPressed|QAbstractItemView::DoubleClicked + + + true + + + QAbstractItemView::ExtendedSelection + + + QAbstractItemView::SelectItems + + + QAbstractItemView::ScrollPerItem + + + QAbstractItemView::ScrollPerPixel + + + false + + + 0 + + + 0 + + + true + + + 30 + + + false + + + true + + + false + + + false + + + 26 + + + 25 + + + false + + + + + 0 + + + + Filter + + + + 4 + + + 4 + + + 4 + + + 4 + + + + + Qt::Vertical + + + false + + + + Expression + + + + 4 + + + 4 + + + 4 + + + 4 + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + + + + + Order && Limit + + + + 4 + + + 4 + + + 4 + + + 4 + + + + + + 0 + 0 + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Add Item + + + + + + + :/icones/icones/adicionar.png:/icones/icones/adicionar.png + + + + 20 + 20 + + + + Ins + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Remove Item + + + + + + + :/icones/icones/remover.png:/icones/icones/remover.png + + + + 20 + 20 + + + + Del + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Clear the order by columns list + + + + + + + :/icones/icones/limpartexto.png:/icones/icones/limpartexto.png + + + + 20 + 20 + + + + Del + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Move selected item up + + + + + + + :/icones/icones/movercima.png:/icones/icones/movercima.png + + + + 20 + 20 + + + + Del + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Move selected item down + + + + + + + :/icones/icones/moverbaixo.png:/icones/icones/moverbaixo.png + + + + 20 + 20 + + + + Del + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + 0 + 0 + + + + 0 + + + 1000000 + + + 50 + + + 1000 + + + + + + + + 0 + 0 + + + + Column: + + + + + + + + 0 + 0 + + + + results (Use <strong>0</strong> for no limit) + + + + + + + Limit in: + + + + + + + + + + 0 + 0 + + + + QComboBox::InsertAlphabetically + + + + + + + + 0 + 0 + + + + ASC + + + true + + + + + + + + 0 + 0 + + + + DESC + + + + + + + + + + + + + + Columns + + + + 4 + + + 4 + + + 4 + + + 4 + + + + + + + + + + Qt::Horizontal + + + + 58 + 20 + + + + + + + + + 0 + 0 + + + + Select all + + + + + + + + 0 + 0 + + + + Clear all + + + + + + + Qt::Horizontal + + + + 58 + 20 + + + + + + + + + + + + + + + + 0 + 0 + + + + + 0 + 30 + + + + QFrame::StyledPanel + + + QFrame::Raised @@ -265,7 +897,7 @@ - + @@ -310,692 +942,17 @@ - - - - - - - - false - - - - 0 - 0 - - - - - 8 - - - - Refresh listing - - - - :/icones/icones/atualizar.png:/icones/icones/atualizar.png - - - - 22 - 22 - - - - F5 - - - Qt::ToolButtonIconOnly - - - - - - - false - - - - 0 - 0 - - - - - 8 - - - - Save changes - - - - :/icones/icones/salvar.png:/icones/icones/salvar.png - - - - 22 - 22 - - - - Ctrl+S - - - Qt::ToolButtonIconOnly - - - - - - - false - - - - 0 - 0 - - - - - 8 - - - - Copy items on the grid - - - - :/icones/icones/copiar.png:/icones/icones/copiar.png - - - - 22 - 22 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonIconOnly - - - - - - - false - - - - 0 - 0 - - - - - 8 - - - - Paste items on the grid - - - - :/icones/icones/colar.png:/icones/icones/colar.png - - - - 22 - 22 - - - - Ctrl+V - - - QToolButton::InstantPopup - - - Qt::ToolButtonIconOnly - - - - - - - false - - - - 0 - 0 - - - - - 8 - - - - Export results to CSV file - - - - :/icones/icones/exportdata.png:/icones/icones/exportdata.png - - - - 22 - 22 - - - - Ctrl+X - - - Qt::ToolButtonIconOnly - - - - - - - false - - - - 0 - 0 - - - - - 8 - - - - Browse referenced tables - - - - :/icones/icones/browsetable.png:/icones/icones/browsetable.png - - - - 22 - 22 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonIconOnly - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 10 - 20 - - - - - - - - false - - - - 0 - 0 - - - - - 8 - - - - Undo modifications - - - - :/icones/icones/desfazer.png:/icones/icones/desfazer.png - - - - 22 - 22 - - - - Ctrl+Z - - - Qt::ToolButtonIconOnly - - - - - - - false - - - - 0 - 0 - - - - - 8 - - - - Add empty rows - - - - :/icones/icones/addrow.png:/icones/icones/addrow.png - - - - 22 - 22 - - - - Ins - - - Qt::ToolButtonIconOnly - - - - - - - false - - - - 0 - 0 - - - - - 8 - - - - Mark the selected rows to be deleted - - - - :/icones/icones/delrow.png:/icones/icones/delrow.png - - - - 22 - 22 - - - - Del - - - Qt::ToolButtonIconOnly - - - - - - - false - - - - 0 - 0 - - - - - 8 - - - - Change the values of all selected cells at once - - - - :/icones/icones/bulkedit.png:/icones/icones/bulkedit.png - - - - 22 - 22 - - - - Ctrl+E - - - Qt::ToolButtonIconOnly - - - - - - - false - - - - 0 - 0 - - - - - 8 - - - - Duplicate the selected rows - - - - :/icones/icones/duprow.png:/icones/icones/duprow.png - - - - 22 - 22 - - - - Ctrl+D - - - Qt::ToolButtonIconOnly - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 10 - 20 - - - - - - - - true - - - - 0 - 0 - - - - Add new rows from a CSV file - - - - :/icones/icones/loadcsv.png:/icones/icones/loadcsv.png - - - - 22 - 22 - - - - - - - true - - - Qt::ToolButtonIconOnly - - - - - - - false - - - - 0 - 0 - - - - - 8 - - - - Filter the result set - - - - :/icones/icones/filter.png:/icones/icones/filter.png - - - - 22 - 22 - - - - true - - - Qt::ToolButtonIconOnly - - - - - - - - - - 0 - 0 - - - - Table: - - - - - - - - 0 - 0 - - - - Schema: - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - 20 - - - QComboBox::InsertAtBottom - - - QComboBox::AdjustToContentsOnFirstShow - - - - 16 - 16 - - - - - - - - - 0 - 0 - - - - 20 - - - QComboBox::InsertAtBottom - - - - 16 - 16 - - - - - - - - 0 - - - - - - 0 - 0 - - - - in - - - - - - - - 20 - 20 - - - - - 22 - 22 - - - - - - - :/icones/icones/database.png - - - true - - - - - - - - 0 - 0 - - - - - - - 5 - - - - - - - - - - 0 - 0 - - - - Hide views - - - true - - - - + + + + + 0 + 0 + + + - + @@ -1028,34 +985,6 @@ 2 - - - - - 24 - 24 - - - - - 24 - 24 - - - - - - - Qt::AutoText - - - :/icones/icones/msgbox_alerta.png - - - true - - - @@ -1076,490 +1005,937 @@ - - - - - - - - 0 - 0 - - - - Qt::Horizontal - - - false - - - - true - - - QAbstractScrollArea::AdjustToContents - - - QAbstractItemView::AnyKeyPressed|QAbstractItemView::DoubleClicked - - - true - - - QAbstractItemView::ExtendedSelection - - - QAbstractItemView::SelectItems - - - QAbstractItemView::ScrollPerItem - - - QAbstractItemView::ScrollPerPixel - - - false - - - 0 - - - 0 - - - true - - - 30 - - - false - - - true - - - false - - - false - - - 25 - - - 25 - - - false - - - - - Qt::Vertical - - - false - - - - Filter expression - - - - 4 - - - 4 - - - 4 + + + + + 24 + 24 + - - 4 + + + 24 + 24 + - - - - - 0 - 0 - - - - - 0 - 0 - - - - - - - - - Order && Limit - - - - 4 + + - - 4 + + Qt::AutoText - - 4 + + :/icones/icones/msgbox_alerta.png - - 4 + + true - - - - - 0 - 0 - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - false - - - - 0 - 0 - - - - - 0 - 0 - - - - Add Item - - - - - - - :/icones/icones/adicionar.png:/icones/icones/adicionar.png - - - - 20 - 20 - - - - Ins - - - - - - - false - - - - 0 - 0 - - - - - 0 - 0 - - - - Remove Item - - - - - - - :/icones/icones/remover.png:/icones/icones/remover.png - - - - 20 - 20 - - - - Del - - - - - - - false - - - - 0 - 0 - - - - - 0 - 0 - - - - Clear the order by columns list - - - - - - - :/icones/icones/limpartexto.png:/icones/icones/limpartexto.png - - - - 20 - 20 - - - - Del - - - - - - - false - - - - 0 - 0 - - - - - 0 - 0 - - - - Move selected item up - - - - - - - :/icones/icones/movercima.png:/icones/icones/movercima.png - - - - 20 - 20 - - - - Del - - - - - - - false - - - - 0 - 0 - - - - - 0 - 0 - - - - Move selected item down - - - - - - - :/icones/icones/moverbaixo.png:/icones/icones/moverbaixo.png - - - - 20 - 20 - - - - Del - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - 0 - 0 - - - - 0 - - - 999999 - - - 500 - - - - - - - - 0 - 0 - - - - Column: - - - - - - - - 0 - 0 - - - - results (Use <strong>0</strong> for no limit) - - - - - - - Limit in: - - - - - - - - - - 0 - 0 - - - - QComboBox::InsertAlphabetically - - - - - - - - 0 - 0 - - - - ASC - - - true - - - - - - - - 0 - 0 - - - - DESC - - - - - - - - + + + + + + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 0 + + + 3 + + + 0 + + + 3 + + + 4 + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Add empty rows + + + Add + + + + :/icones/icones/addrow.png:/icones/icones/addrow.png + + + + 25 + 25 + + + + Ins + + + Qt::ToolButtonIconOnly + + + true + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Clears the items selected on the grid + + + Clear + + + + :/icones/icones/limpartexto.png:/icones/icones/limpartexto.png + + + + 25 + 25 + + + + Ctrl+R + + + QToolButton::InstantPopup + + + Qt::ToolButtonIconOnly + + + true + + + + + + + Qt::Horizontal + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Change the values of all selected cells at once + + + Edit + + + + :/icones/icones/bulkedit.png:/icones/icones/bulkedit.png + + + + 25 + 25 + + + + Ctrl+E + + + Qt::ToolButtonIconOnly + + + true + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Browse referenced tables + + + Browse + + + + :/icones/icones/browsetable.png:/icones/icones/browsetable.png + + + + 25 + 25 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonIconOnly + + + true + + + + + + + true + + + + 0 + 0 + + + + + 0 + 0 + + + + Add new rows from a CSV file + + + Load CSV + + + + :/icones/icones/loadcsv.png:/icones/icones/loadcsv.png + + + + 25 + 25 + + + + Ctrl+L + + + true + + + Qt::ToolButtonIconOnly + + + true + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Copy items on the grid + + + Copy + + + + :/icones/icones/copiar.png:/icones/icones/copiar.png + + + + 25 + 25 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonIconOnly + + + true + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Duplicate the selected rows + + + Duplicate + + + + :/icones/icones/duprow.png:/icones/icones/duprow.png + + + + 25 + 25 + + + + Ctrl+D + + + Qt::ToolButtonIconOnly + + + true + + + + + + + Qt::Horizontal + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Filter the result set + + + Filter + + + + :/icones/icones/filter.png:/icones/icones/filter.png + + + + 25 + 25 + + + + Ctrl+F + + + true + + + Qt::ToolButtonIconOnly + + + true + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Mark the selected rows to be deleted + + + Delete + + + + :/icones/icones/delrow.png:/icones/icones/delrow.png + + + + 25 + 25 + + + + Del + + + Qt::ToolButtonIconOnly + + + true + + + + + + + Qt::Horizontal + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + true + + + + 0 + 0 + + + + + 0 + 0 + + + + Open a new data manipulation window + + + New + + + + :/icones/icones/novoobjeto.png:/icones/icones/novoobjeto.png + + + + 25 + 25 + + + + Ctrl+N + + + Qt::ToolButtonIconOnly + + + true + + + + + + + Qt::Horizontal + - - + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Paste items on the grid + + + Paste + + + + :/icones/icones/colar.png:/icones/icones/colar.png + + + + 25 + 25 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonIconOnly + + + true + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Save changes + + + Save + + + + :/icones/icones/salvar.png:/icones/icones/salvar.png + + + + 25 + 25 + + + + Ctrl+S + + + Qt::ToolButtonIconOnly + + + true + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Undo modifications + + + Undo + + + + :/icones/icones/desfazer.png:/icones/icones/desfazer.png + + + + 25 + 25 + + + + Ctrl+Z + + + Qt::ToolButtonIconOnly + + + true + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Export results to CSV file + + + Export + + + + :/icones/icones/exportdata.png:/icones/icones/exportdata.png + + + + 25 + 25 + + + + Ctrl+X + + + Qt::ToolButtonIconOnly + + + true + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Refresh listing + + + Refresh + + + + :/icones/icones/atualizar.png:/icones/icones/atualizar.png + + + + 25 + 25 + + + + F5 + + + Qt::ToolButtonIconOnly + + + true + + + + + + + false + + + + 0 + 0 + + 0 0 + + Truncate the browsed table + + + Truncate + + + + :/icones/icones/truncate.png:/icones/icones/truncate.png + + + + 25 + 25 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonIconOnly + + + true + + + + + 2 + + + 2 + + + 2 + + + 2 + + + 6 + + + + + + 0 + 0 + + + + + 127 + 0 + + + + + + + + + + Qt::PlainText + + + :/imagens/imagens/pgmodeler_name.png + + + + + + + + 0 + 0 + + + + + 90 + 32 + + + + + 16777215 + 16777215 + + + + false + + + + + + &Close + + + + :/icones/icones/fechar1.png:/icones/icones/fechar1.png + + + + 20 + 20 + + + + false + + + false + + + false + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + diff --git a/libpgmodeler_ui/ui/domainwidget.ui b/libpgmodeler_ui/ui/domainwidget.ui index 4e40619310..36d8adeb4d 100644 --- a/libpgmodeler_ui/ui/domainwidget.ui +++ b/libpgmodeler_ui/ui/domainwidget.ui @@ -7,7 +7,7 @@ 0 0 487 - 132 + 140 @@ -55,7 +55,11 @@ - + + + true + + @@ -93,7 +97,11 @@ - + + + true + + diff --git a/libpgmodeler_ui/ui/donatewidget.ui b/libpgmodeler_ui/ui/donatewidget.ui index d150e9660d..82b6988a59 100644 --- a/libpgmodeler_ui/ui/donatewidget.ui +++ b/libpgmodeler_ui/ui/donatewidget.ui @@ -166,6 +166,12 @@ + + + 0 + 0 + + 0 @@ -203,7 +209,7 @@ - 40 + 118 20 diff --git a/libpgmodeler_ui/ui/elementswidget.ui b/libpgmodeler_ui/ui/elementwidget.ui similarity index 94% rename from libpgmodeler_ui/ui/elementswidget.ui rename to libpgmodeler_ui/ui/elementwidget.ui index 8fa0ad6028..52222603aa 100644 --- a/libpgmodeler_ui/ui/elementswidget.ui +++ b/libpgmodeler_ui/ui/elementwidget.ui @@ -1,30 +1,36 @@ - ElementsWidget - + ElementWidget + 0 0 - 385 - 210 + 540 + 215 + + + 540 + 215 + + - Form + Element properties - 0 + 4 - 0 + 4 - 0 + 4 - 0 + 4 6 @@ -60,7 +66,7 @@ false - + 0 0 diff --git a/libpgmodeler_ui/ui/eventtriggerwidget.ui b/libpgmodeler_ui/ui/eventtriggerwidget.ui index 7290e2b1b1..402caae30c 100644 --- a/libpgmodeler_ui/ui/eventtriggerwidget.ui +++ b/libpgmodeler_ui/ui/eventtriggerwidget.ui @@ -91,7 +91,11 @@ - + + + true + + diff --git a/libpgmodeler_ui/ui/extensionwidget.ui b/libpgmodeler_ui/ui/extensionwidget.ui index a883670b1e..e310160c04 100644 --- a/libpgmodeler_ui/ui/extensionwidget.ui +++ b/libpgmodeler_ui/ui/extensionwidget.ui @@ -53,6 +53,9 @@ 0 + + true + @@ -82,6 +85,9 @@ 0 + + true + diff --git a/libpgmodeler_ui/ui/findreplacewidget.ui b/libpgmodeler_ui/ui/findreplacewidget.ui index 9bdea1a4c4..f49e77883b 100644 --- a/libpgmodeler_ui/ui/findreplacewidget.ui +++ b/libpgmodeler_ui/ui/findreplacewidget.ui @@ -7,7 +7,7 @@ 0 0 704 - 62 + 68 @@ -46,7 +46,11 @@ - + + + true + + @@ -170,6 +174,35 @@ + + + + + 20 + 20 + + + + + 20 + 20 + + + + Hide this widget + + + ... + + + + :/icones/icones/fechar1.png:/icones/icones/fechar1.png + + + true + + + @@ -186,7 +219,11 @@ - + + + true + + diff --git a/libpgmodeler_ui/ui/foreigndatawrapperwidget.ui b/libpgmodeler_ui/ui/foreigndatawrapperwidget.ui new file mode 100644 index 0000000000..d2fe9ab21f --- /dev/null +++ b/libpgmodeler_ui/ui/foreigndatawrapperwidget.ui @@ -0,0 +1,157 @@ + + + ForeignDataWrapperWidget + + + + 0 + 0 + 337 + 221 + + + + + 0 + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + Validator: + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + Handler: + + + + + + + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + + + + + 0 + 0 + + + + + 0 + 20 + + + + + + + + + 0 + 0 + + + + + 0 + 20 + + + + + + + + Options + + + + + + + + diff --git a/libpgmodeler_ui/ui/foreignserverwidget.ui b/libpgmodeler_ui/ui/foreignserverwidget.ui new file mode 100644 index 0000000000..d7a915f0cd --- /dev/null +++ b/libpgmodeler_ui/ui/foreignserverwidget.ui @@ -0,0 +1,122 @@ + + + ForeignServerWidget + + + + 0 + 0 + 462 + 210 + + + + + 0 + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + Version: + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + FDW: + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + Type: + + + + + + + + + + Options + + + + + + + + 0 + 0 + + + + + 0 + 20 + + + + + + + + + diff --git a/libpgmodeler_ui/ui/functionwidget.ui b/libpgmodeler_ui/ui/functionwidget.ui index bbc468d9c2..6a1e3720dd 100644 --- a/libpgmodeler_ui/ui/functionwidget.ui +++ b/libpgmodeler_ui/ui/functionwidget.ui @@ -544,6 +544,9 @@ 0 + + true + @@ -573,6 +576,9 @@ 0 + + true + diff --git a/libpgmodeler_ui/ui/generalconfigwidget.ui b/libpgmodeler_ui/ui/generalconfigwidget.ui index e68bad1f52..fca73a6de5 100644 --- a/libpgmodeler_ui/ui/generalconfigwidget.ui +++ b/libpgmodeler_ui/ui/generalconfigwidget.ui @@ -6,8 +6,8 @@ 0 0 - 671 - 587 + 795 + 712 @@ -60,6 +60,19 @@ 4 + + + + Qt::Vertical + + + + 20 + 40 + + + + @@ -81,10 +94,10 @@ 10 - - + + - + 0 @@ -93,17 +106,17 @@ - 200 + 210 0 - Minimum object opacity (%): + Attributes per page: - + 0 @@ -117,13 +130,13 @@ - Defines the minimum opacity percentage applied to the objects when using the fade out feature. A zero opacity causes the object to be completely hidden not being possible to interact with it in the canvas area. + These spinners define the minimum amount of attributes visible per page in each section of tables and views when the pagination is enabled on them. The first one controls the amount of columns per page. The second defines the amount of extended attributes (constraints, indexes, trigger, rules, policies) displayed per page. - 0 + 5 - 70 + 100 5 @@ -134,7 +147,54 @@ - + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + + 0 + 0 + + + + + 60 + 0 + + + + Defines the minimum amount of attributes visible per page on tables and view when the pagination is enabled on these objects. + + + 5 + + + 100 + + + 5 + + + 5 + + + + + Qt::Horizontal @@ -147,7 +207,7 @@ - + 0 @@ -170,32 +230,29 @@ - - + + - + - + 0 0 - 200 + 210 0 - - - - Canvas grid size: + Minimum object opacity (%): - + 0 @@ -209,24 +266,24 @@ - Defines the vertical and horizontal grid size. This value affects the spacing of objects when using object grid alignment feature. + Defines the minimum opacity percentage applied to the objects when using the fade out feature. A zero opacity causes the object to be completely hidden not being possible to interact with it in the canvas area. - 10 + 0 - 100 + 70 - 1 + 5 - 20 + 10 - + Qt::Horizontal @@ -239,7 +296,7 @@ - + 0 @@ -262,77 +319,73 @@ - - + + - + - + 0 0 + + + 210 + 0 + + - Start move the canvas when the cursor is on the canvas edges + Defines the period when the opened models will be saved automatically. The temporary models saving period will be defined as the half of the value defined here. If the autosave is disabled the temporary models saving will occur in a period of 5 minutes. - Move canvas by keep mouse on corners - - - false + Autosave interval (minutes): - + - + 0 0 - 22 - 22 + 60 + 0 - - - 22 - 22 - + + 5 + + + 30 + + + 5 - - - - - - - - 0 - 0 - - - - - - - After loading the model the last zoom and position on canvas will be restored + + + Qt::Horizontal - - Save and restore last position and zoom + + + 40 + 20 + - + - + 0 @@ -355,77 +408,67 @@ - - + + - + - + 0 0 - - - - - By default the range selection is triggered with Shift + left click. By checking this option range selection will be activated only with a single click and move. + + + 210 + 0 + - Trigger range selection with a single click - - - false + Operation history size: - + - + 0 0 - 22 - 22 + 60 + 0 - - - 22 - 22 - + + Defines the maximum amount of elements held in the operation history. Once reached the maximum number the history is automatically cleaned. + + + 500 + + + 1000 - - - - - - - - 0 - 0 - - - - - - - Hide the portion of table which represent triggers, indexes and rules + + + Qt::Horizontal - - Hide table extended attributes + + + 40 + 20 + - + - + 0 @@ -448,74 +491,32 @@ - - + + - + - + 0 0 - - + + + 210 + 0 + - Hide the object which represents the tag assigned to the table + - Hide table tags + Canvas grid size: - - - - 0 - 0 - - - - - 22 - 22 - - - - - 22 - 22 - - - - - - - - - - - - - 0 - 0 - - - - - 200 - 0 - - - - Operation history: - - - - - + 0 @@ -529,18 +530,24 @@ - Defines the maximum amount of elements held in the operation history. Once reached the maximum number the history is automatically cleaned. + Defines the vertical and horizontal grid size. This value affects the spacing of objects when using the feature that aligns the objects on the grid. - 500 + 10 - 1000 + 100 + + + 1 + + + 20 - + Qt::Horizontal @@ -553,7 +560,7 @@ - + 0 @@ -576,18 +583,24 @@ - - + + - + + + + 0 + 0 + + - Triggers a dialog asking the user to validate the model before a save, export or diff operation. + Graphical objects (table, views and textboxes) will be created in a single step without the need to click on canvas - Validate before save, export or diff + Simplify the creation of graphical objects false @@ -595,7 +608,7 @@ - + 0 @@ -618,70 +631,74 @@ - - + + - + - + 0 0 - - - 200 - 0 - - - Defines the period when the opened models will be saved automatically. + When enabled this option creates a placeholder object at the previous table's position when starting to move it. This will cause graphical updates on relationship lines to be performed only when the drag & drop action is done improving the performance. Disabling placeholders will cause those updates to be executed every time the table's position changes a single pixel (classical behavior). - Autosave interval (minutes): + Use placeholders when moving tables - + - + 0 0 - 60 - 0 + 22 + 22 - - 1 - - - 30 + + + 22 + 22 + + + + + - - - Qt::Horizontal + + + + 0 + 0 + - - - 40 - 20 - + + - + + After loading the model the last zoom and position on canvas will be restored + + + Save and restore last position and zoom + + - + 0 @@ -704,10 +721,10 @@ - - + + - + 0 @@ -718,15 +735,18 @@ - Disable antialiasing for lines and texts improving performance when handling huge models. + By default the range selection is triggered with Shift + left click. By checking this option range selection will be activated only with a single click and move. - Disable render smoothness + Trigger range selection with a single click + + + false - + 0 @@ -749,10 +769,10 @@ - - + + - + 0 @@ -763,18 +783,15 @@ - Graphical objects (table, views and textboxes) will be created in a single step without the need to click on canvas + Hide the portion of table which represents triggers, indexes and rules. - Simplify creation of graphical objects - - - false + Hide table extended attributes - + 0 @@ -797,10 +814,10 @@ - - + + - + 0 @@ -811,15 +828,15 @@ - Toggles the code completion in all fields that accepts the input of SQL commands. + Hide the object which represents the tag assigned to the table - Enable SQL code completion + Hide table tags - + 0 @@ -842,12 +859,12 @@ - - + + - + - + 0 0 @@ -856,15 +873,15 @@ - When enabled this option creates a placeholder object at the previous table's position when starting to move it. This will cause graphical updates on relationship lines to be performed only when the drag & drop action is done improving the performance. Disabling placeholders will cause those updates to be executed every time the table's position changes a single pixel (classical behavior). + Hide the object that represents the relationship name - Use placeholders when moving tables + Hide relationship name - + 0 @@ -887,12 +904,54 @@ - - + + - + + + + + + Triggers a dialog asking the user to validate the model before a save, export or diff operation. + + + Validate before save, export or diff + + + false + + + + + - + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + + + + + + + + 0 0 @@ -901,15 +960,18 @@ - Hide the object that represents the relationship name + Start move the canvas when the cursor is on the canvas edges - Hide relationship name + Move canvas by keeping the mouse on corners + + + false - + 0 @@ -977,229 +1039,149 @@ - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - General - - - - 4 - - - 4 - - - 4 - - - 4 - - - - - - 0 - 0 - - - - - 22 - 22 - - - - - 22 - 22 - - - - - - + + - + - + 0 0 - - - 60 - 0 - - - - 100 - - - 10000 + + - - 100 + + Toggles the code completion in all fields that accepts the input of SQL commands. - - 1000 + + Enable SQL code completion - + - + 0 0 - 0 - 0 + 22 + 22 - 16777215 - 16777215 + 22 + 22 - - lines - + + + + - - - Qt::Horizontal + + + + 0 + 0 + - - QSizePolicy::Expanding + + - - - 25 - 20 - + + Disable the antialiasing for lines and texts improving performance when handling huge models. - + + Disable render smoothness + + - + - + 0 0 - 0 - 30 + 22 + 22 - - 16777215 - 16777215 - - - - Qt::StrongFocus - - - Clear the entire SQL comand history. - - - Clear history - - - - :/icones/icones/limpartexto.png:/icones/icones/limpartexto.png - - 22 22 - - Qt::ToolButtonTextBesideIcon + + + + + + + + + + + General + + + + 4 + + + 4 + + + 4 + + + 4 + + + + + + + Save/restore dialogs sizes - + Qt::Horizontal + + QSizePolicy::Expanding + - 40 + 25 20 - - - - - - - - 0 - 0 - - - - - 60 - 0 - - - - Maximum number of rows to be displayed in the results grid. This is used as a security measure to avoid application crash due to memory exhaustion when retrieving a huge set of data from the database without using filtering keywords like <strong>LIMIT</strong> or <strong>WHERE</strong>. - - - 5000 - - - 500000 - - - 5000 - - - 20000 + + + false - - - - - + 0 0 @@ -1207,7 +1189,7 @@ 0 - 0 + 30 @@ -1216,44 +1198,41 @@ 16777215 + + Qt::StrongFocus + + + Reset the dialogs sizes and positions to their default values. + - rows + Reset sizes - - - - - - - 0 - 0 - + + + :/icones/icones/atualizar.png:/icones/icones/atualizar.png - + 22 22 - - - 22 - 22 - + + Qt::ToolButtonTextBesideIcon - + Qt::Horizontal - QSizePolicy::Expanding + QSizePolicy::Fixed - 25 + 100 20 @@ -1261,12 +1240,41 @@ - - - - + + + + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + + + + Souce code editor args: + + + + + true + + false @@ -1290,13 +1298,6 @@ - - - - true - - - @@ -1304,15 +1305,15 @@ - - - - Configurations directory: + + + + Overrides the default user interface language defined by the system. Requires restarting the program. <strong>NOTE:</strong> UI translations are third party collaborations thus any typo or mistake should be reported directly to their respective maintainers. - - + + 0 @@ -1332,7 +1333,7 @@ - Browse the source code editor application + Open in file manager @@ -1349,8 +1350,8 @@ - - + + 0 @@ -1370,7 +1371,7 @@ - Open in file manager + Browse the source code editor application @@ -1387,23 +1388,143 @@ - - - - Check if there is a new version on server - - - Check updates at startup - - - false - - + + + + + + + 0 + 0 + + + + + 60 + 0 + + + + 1000 + + + 20000 + + + 500 + + + 1000 + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + lines + + + + + + + Qt::Horizontal + + + QSizePolicy::Expanding + + + + 25 + 20 + + + + + + + + + 0 + 0 + + + + + 0 + 30 + + + + + 16777215 + 16777215 + + + + Qt::StrongFocus + + + Clear the entire SQL comand history. + + + Clear history + + + + :/icones/icones/limpartexto.png:/icones/icones/limpartexto.png + + + + 22 + 22 + + + + Qt::ToolButtonTextBesideIcon + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 100 + 20 + + + + + - - + + - Souce code editor args: + Configurations directory: @@ -1414,33 +1535,94 @@ - - - - Overrides the default user interface language defined by the system. Requires restarting the program. <strong>NOTE:</strong> UI translations are third party collaborations thus any typo or mistake should be reported directly to their respective maintainers. + + + + + + + false + + + true - - + + false + + true + - - + + + + Check if there is a new version on server + - Limit SQL results in: + Check updates at startup - true + false + + + + + + Reduces the verbosity of the export, import and diff process causing only key info messages and errors to be displayed. This option causes less UI operations to be performed when displaying progress messages and, as a consequence, it makes these processes run faster. + + + Low verbosity for the export, import and diff processes + + + + + + + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + diff --git a/libpgmodeler_ui/ui/genericsqlwidget.ui b/libpgmodeler_ui/ui/genericsqlwidget.ui index b2da2e2376..030655f6e7 100644 --- a/libpgmodeler_ui/ui/genericsqlwidget.ui +++ b/libpgmodeler_ui/ui/genericsqlwidget.ui @@ -7,7 +7,7 @@ 0 0 651 - 394 + 418 @@ -27,10 +27,191 @@ 2 - - - SQL code + + + 0 + + + SQL code + + + + + References + + + + 4 + + + 4 + + + 4 + + + 4 + + + + + + + Object: + + + + + + + + 0 + 0 + + + + + 32 + 32 + + + + + 32 + 32 + + + + QFrame::NoFrame + + + QFrame::Plain + + + + + + false + + + Qt::AlignCenter + + + + + + + + + Ref. name: + + + + + + + + + The name of the reference to an object. All occurences of the reference enclosed by <strong>{}</strong> are replaced by the referenced object's name or signature in the generic SQL object's code. + + + + + + + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + + + + Use the referenced object's signature instead of its name. For some objects like functions, casts, operators and some others the signature will include parameters types and some other information. + + + Use signature + + + + + + + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + + + + The referenced object's name or signature will be automatically quoted when special characters are found. Additionally, for schema qualified objects, the name of the parent schema is prepended to the referenced object's name or signature. This will avoid common SQL syntax errors or loss of semantics. + + + Format name + + + + + + + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + + + + + + + Preview + + diff --git a/libpgmodeler_ui/ui/layerswidget.ui b/libpgmodeler_ui/ui/layerswidget.ui new file mode 100644 index 0000000000..b8014d4e80 --- /dev/null +++ b/libpgmodeler_ui/ui/layerswidget.ui @@ -0,0 +1,252 @@ + + + LayersWidget + + + + 0 + 0 + 448 + 165 + + + + Form + + + true + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 165 + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + 4 + + + 4 + + + 4 + + + 4 + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Remove all layers + + + Delete all + + + + :/icones/icones/clearlayers.png:/icones/icones/clearlayers.png + + + + 22 + 22 + + + + Shift+Del + + + Qt::ToolButtonTextBesideIcon + + + false + + + + + + + true + + + + + + + + 20 + 20 + + + + + 20 + 20 + + + + Hide this widget + + + ... + + + + :/icones/icones/fechar1.png:/icones/icones/fechar1.png + + + true + + + + + + + Qt::Horizontal + + + QSizePolicy::Expanding + + + + 20 + 20 + + + + + + + + true + + + + 0 + 0 + + + + + 0 + 0 + + + + Add a new layer + + + Add + + + + :/icones/icones/addlayer.png:/icones/icones/addlayer.png + + + + 22 + 22 + + + + Ins + + + Qt::ToolButtonTextBesideIcon + + + false + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Remove the selected layer + + + Delete + + + + :/icones/icones/dellayer.png:/icones/icones/dellayer.png + + + + 22 + 22 + + + + Shift+Del + + + Qt::ToolButtonTextBesideIcon + + + false + + + + + + + + + + + + + diff --git a/libpgmodeler_ui/ui/mainwindow.ui b/libpgmodeler_ui/ui/mainwindow.ui index fa5ee1db02..8b12fd1600 100644 --- a/libpgmodeler_ui/ui/mainwindow.ui +++ b/libpgmodeler_ui/ui/mainwindow.ui @@ -10,7 +10,7 @@ 0 0 1068 - 673 + 708 @@ -382,83 +382,6 @@ 0 - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - 3 - - - - - Saving temp. models - - - - - - - - 16777215 - 16 - - - - 24 - - - - - - - - @@ -503,6 +426,9 @@ Qt::ToolButtonTextBesideIcon + + false + @@ -517,7 +443,7 @@ Toggle the object finder - Find Object + Find objects @@ -538,11 +464,65 @@ Qt::ToolButtonTextBesideIcon + + false + + + + + + + + 0 + 0 + + + + Toggle the object finder + + + Layers + + + + :/icones/icones/layers.png:/icones/icones/layers.png + + + + 22 + 22 + + + + Ctrl+F + + + true + + + Qt::ToolButtonTextBesideIcon + + + false + - + + + + Qt::Horizontal + + + + 40 + 20 + + + + + 0 @@ -554,7 +534,7 @@ 3 - + 0 @@ -562,14 +542,14 @@ - Toggle the operation history widget + Toggle the model objects widget - &Operations + O&bjects - :/icones/icones/funcao.png:/icones/icones/funcao.png + :/icones/icones/tablespace.png:/icones/icones/tablespace.png @@ -578,7 +558,7 @@ - Alt+O + Alt+B true @@ -586,6 +566,9 @@ Qt::ToolButtonTextBesideIcon + + false + @@ -605,7 +588,7 @@ - + 0 @@ -613,14 +596,14 @@ - Toggle the model objects widget + Toggle the operation history widget - O&bjects + &Operations - :/icones/icones/tablespace.png:/icones/icones/tablespace.png + :/icones/icones/funcao.png:/icones/icones/funcao.png @@ -629,7 +612,7 @@ - Alt+B + Alt+O true @@ -637,12 +620,79 @@ Qt::ToolButtonTextBesideIcon + + false + - - + + + + + 0 + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 3 + + + + + Saving temp. models + + + + + + + + 16777215 + 16 + + + + 24 + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + 20 @@ -678,7 +728,7 @@ 0 0 1068 - 23 + 27 @@ -744,6 +794,8 @@ + + @@ -767,6 +819,12 @@ 0 + + + 50 + false + + General @@ -800,11 +858,11 @@ + - @@ -873,6 +931,7 @@ + @@ -1514,6 +1573,36 @@ Rearrange objects over the canvas + + + true + + + false + + + + :/icones/icones/compactview.png:/icones/icones/compactview.png + + + Compact view + + + Toggle the compact view on the model(s) + + + + + + :/icones/icones/moreactions.png:/icones/icones/moreactions.png + + + More + + + Addition action over the model + + models_tbw diff --git a/libpgmodeler_ui/ui/messagebox.ui b/libpgmodeler_ui/ui/messagebox.ui index 9f1a235117..38e5e05b28 100644 --- a/libpgmodeler_ui/ui/messagebox.ui +++ b/libpgmodeler_ui/ui/messagebox.ui @@ -10,7 +10,7 @@ 0 0 500 - 175 + 244 @@ -105,7 +105,7 @@ 0 - + 0 @@ -118,91 +118,121 @@ 0 - - 0 - - - - 2 + + + + 40 + 40 + - - - - - 40 - 40 - - - - - 40 - 40 - - - - - - - Qt::AlignCenter - - - - - - - true - - - - 0 - 0 - + + + 40 + 40 + + + + + + + Qt::AlignCenter + + + + + + + true + + + + 0 + 0 + + + + + 0 + 90 + + + + + 16777215 + 16777215 + + + + false + + + false + + + + + + msg + + + Qt::RichText + + + true + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + true + + + 4 + + + true + + + Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse + + + + + + + Qt::Vertical + + + + 20 + 84 + + + + + + + + + + Qt::Horizontal - - - 0 - 90 - + + QSizePolicy::Fixed - + - 16777215 - 16777215 + 5 + 20 - - false - - - false - - - - + + + + - msg - - - Qt::RichText - - - true - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - true - - - 4 - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse + @@ -316,86 +346,100 @@ - - - - Qt::Horizontal - - + + + - 414 - 27 + 0 + 0 - - - - - - 4 - - - 4 - - - - - - 0 - 0 - - - - Show raw text errors or information. - - - - - - - :/icones/icones/codigofonte.png:/icones/icones/codigofonte.png - - - - 22 - 22 - - - - true - - - - - - - - 0 - 0 - - - - Show/hide exceptions stack. - - - ... - - - - :/icones/icones/refazer.png:/icones/icones/refazer.png - - - - 22 - 22 - - - - true - - - - + + + 0 + + + 0 + + + 4 + + + 4 + + + + + Qt::Horizontal + + + + 415 + 24 + + + + + + + + + 0 + 0 + + + + Show raw text errors or information. + + + + + + + :/icones/icones/codigofonte.png:/icones/icones/codigofonte.png + + + + 22 + 22 + + + + true + + + + + + + + 0 + 0 + + + + Show/hide exceptions stack. + + + ... + + + + :/icones/icones/refazer.png:/icones/icones/refazer.png + + + + 22 + 22 + + + + true + + + + + diff --git a/libpgmodeler_ui/ui/metadatahandlingform.ui b/libpgmodeler_ui/ui/metadatahandlingform.ui index 6b572f1fdc..38d7828044 100644 --- a/libpgmodeler_ui/ui/metadatahandlingform.ui +++ b/libpgmodeler_ui/ui/metadatahandlingform.ui @@ -6,8 +6,8 @@ 0 0 - 666 - 574 + 727 + 609 @@ -173,52 +173,6 @@ 4 - - - - - - 0 - 0 - - - - - 32 - 32 - - - - - 32 - 32 - - - - - - - :/icones/icones/objmetadata.png - - - - - - - - 13 - 75 - true - - - - Handle objects metadata - - - - - - @@ -344,7 +298,7 @@ - + 0 @@ -367,6 +321,54 @@ 10 + + + + + + + 0 + 0 + + + + + + + Handles the objects' aliases in the metadata file. Only for graphical objects and table's children objects. + + + Objects' aliases + + + true + + + + + + + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + + @@ -415,7 +417,7 @@ - + Qt::Vertical @@ -815,7 +817,7 @@ - + 0 @@ -826,10 +828,10 @@ - Handles the tables' and views' extended attributes display status in the metadata file. + Handles the tables' and views' collapsing mode in the metadata file. - Tables' extended attributes display + Tables and views collpsing mode true @@ -837,7 +839,7 @@ - + 0 @@ -860,7 +862,7 @@ - + @@ -908,6 +910,73 @@ + + + + + 0 + 0 + + + + + 6 + + + 0 + + + 10 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 252 + 20 + + + + + + + + Select all + + + + + + + Clear all + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + @@ -921,7 +990,11 @@ - + + + true + + @@ -1139,6 +1212,9 @@ true + + false + @@ -1290,28 +1366,6 @@ - - - - - 0 - 1 - - - - - 16777215 - 1 - - - - QFrame::StyledPanel - - - QFrame::Sunken - - - diff --git a/libpgmodeler_ui/ui/modeldatabasediffform.ui b/libpgmodeler_ui/ui/modeldatabasediffform.ui index 4fccfe761c..8087ecf11f 100644 --- a/libpgmodeler_ui/ui/modeldatabasediffform.ui +++ b/libpgmodeler_ui/ui/modeldatabasediffform.ui @@ -85,58 +85,6 @@ 4 - - - - - - 0 - 0 - - - - - 32 - 32 - - - - - 32 - 32 - - - - - - - :/icones/icones/diff.png - - - - - - - - 0 - 0 - - - - - 13 - 75 - true - - - - Generate diff code - - - - - - @@ -192,7 +140,7 @@ - Source database + Input false @@ -498,7 +446,7 @@ - Override the PostgreSQL version when generating the diff. The default is to use the same version as the input database. + Override the PostgreSQL version when generating the diff code. The default is to use the same version as the input database (detected automatically). Use PostgreSQL: @@ -702,6 +650,9 @@ false + + true + @@ -866,7 +817,7 @@ - Permissions already set on database objects will be kept.The ones configured on the model will be applied to the database. + Permissions already set on database objects will be kept. The ones configured on the model will be applied to the database. Keep object's permissions @@ -965,7 +916,7 @@ - Froce the generation of DROP commands for columns and constraints that exist in database but not in the model. This is useful when diff a partial model against the complete database and the user needs to drop columns and constraint but preserve the rest of the objects. + Force the generation of DROP commands for columns and constraints that exist in database but not in the model. This is useful when diff a partial model against the complete database and the user needs to drop columns and constraint but preserve the rest of the objects. Drop missing columns and constraints @@ -2171,7 +2122,61 @@ 4 - + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 0 + 30 + + + + + 16777215 + 16777215 + + + + + + + &Apply diff + + + + :/icones/icones/diff.png:/icones/icones/diff.png + + + + 22 + 22 + + + + false + + + + @@ -2181,8 +2186,21 @@ - - + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + 0 @@ -2201,12 +2219,15 @@ 16777215 + + Loads the generated diff code in the destination server for manual applying. + - &Apply diff + Open in SQL Tool - :/icones/icones/diff.png:/icones/icones/diff.png + :/icones/icones/codigosql.png:/icones/icones/codigosql.png @@ -2214,8 +2235,11 @@ 22 + + false + - true + false diff --git a/libpgmodeler_ui/ui/modelexportform.ui b/libpgmodeler_ui/ui/modelexportform.ui index e0003788ae..cf3e35e16d 100644 --- a/libpgmodeler_ui/ui/modelexportform.ui +++ b/libpgmodeler_ui/ui/modelexportform.ui @@ -82,61 +82,6 @@ 4 - - - 2 - - - - - - 0 - 0 - - - - - 32 - 32 - - - - - 32 - 32 - - - - - - - :/icones/icones/exportar.png - - - - - - - - 0 - 0 - - - - - 13 - 75 - true - - - - Export model - - - - - - @@ -544,7 +489,7 @@ - If <strong>DB</strong> is checked pgModeler will destroy the database if already exists on the server. When <strong>Objects</strong> is checked pgModeler will execute the DROP command attached to SQL-enabled objects. <strong>WARNING:</strong> this option leads to data loss so make sure to have a backup first. + If <strong>DB</strong> is checked pgModeler will destroy the database if already exists on the server. When <strong>Objects</strong> is checked pgModeler will execute the DROP command attached to SQL-enabled objects. <strong>WARNING:</strong> this option leads to data loss so make sure to have a backup before exporting. Drop: @@ -738,6 +683,9 @@ true + + false + @@ -1081,6 +1029,9 @@ true + + false + diff --git a/libpgmodeler_ui/ui/modelfixform.ui b/libpgmodeler_ui/ui/modelfixform.ui index 7a25ee3773..d0c6bab739 100644 --- a/libpgmodeler_ui/ui/modelfixform.ui +++ b/libpgmodeler_ui/ui/modelfixform.ui @@ -81,160 +81,8 @@ 4 - - - - - - - 0 - 0 - - - - - 32 - 32 - - - - - 32 - 32 - - - - - - - :/icones/icones/fixobject.png - - - - - - - - 13 - 75 - true - - - - Fix model file - - - - - - - - - - 0 - 1 - - - - - 16777215 - 1 - - - - QFrame::StyledPanel - - - QFrame::Sunken - - - - - - - - 0 - 0 - - - - - 0 - 48 - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - 2 - - - 2 - - - 2 - - - 2 - - - - - - 24 - 24 - - - - - 24 - 24 - - - - - - - Qt::AutoText - - - :/icones/icones/msgbox_alerta.png - - - true - - - - - - - - 50 - false - false - false - false - true - - - - <html><head/><body><p>[pgmodeler-cli not found error]</p></body></html> - - - true - - - - - - - - + + 0 @@ -242,126 +90,41 @@ - pgmodeler-cli: + Input file: - - - - 0 - - - - - - - - true - - - Browse for pgmodeler-cli tool - - - ... - - - - :/icones/icones/abrir.png:/icones/icones/abrir.png + + + + + + 1 - - - 22 - 22 - + + 100 - - - - - - - - - 170 - 0 - 0 - - - - - - - - - 170 - 0 - 0 - - - - - - - - - 128 - 128 - 128 - - - - - - - - - false - + + + + + 0 + 0 + - The specified file is not the pgModeler command line tool (pgmodeler-cli). + Load fixed model when finish + + + true - - - - - 0 - 0 - - - - Input file: - - - - - - - - 0 - 0 - - - - Output file: - - - - - - - Fix tries: - - - - + @@ -475,7 +238,7 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'Monospace'; font-size:10pt; font-weight:400; font-style:normal;"> +</style></head><body style=" font-family:'Monospace'; font-size:11pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:9pt;">Waiting process to start...</span></p></body></html> @@ -486,41 +249,15 @@ p, li { white-space: pre-wrap; } - - + + - - - - - + + true - - Select input file - - - ... - - - - :/icones/icones/abrir.png:/icones/icones/abrir.png - - - - 22 - 22 - - - - - - - - - @@ -546,37 +283,91 @@ p, li { white-space: pre-wrap; } - - - - - - 1 - - - 100 - - - - - - - - 0 - 0 - - - - Load fixed model when finish - - - true - - - - + + + + + 0 + 0 + + + + + 0 + 48 + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + 2 + + + 2 + + + 2 + + + 2 + + + + + + 24 + 24 + + + + + 24 + 24 + + + + + + + Qt::AutoText + + + :/icones/icones/msgbox_alerta.png + + + true + + + + + + + + 50 + false + false + false + false + true + + + + <html><head/><body><p>[pgmodeler-cli not found error]</p></body></html> + + + true + + + + + - + @@ -666,6 +457,159 @@ p, li { white-space: pre-wrap; } + + + + + 0 + 0 + + + + pgmodeler-cli: + + + + + + + 0 + + + + + true + + + + + + + true + + + Browse for pgmodeler-cli tool + + + ... + + + + :/icones/icones/abrir.png:/icones/icones/abrir.png + + + + 22 + 22 + + + + + + + + + + + + + 170 + 0 + 0 + + + + + + + + + 170 + 0 + 0 + + + + + + + + + 128 + 128 + 128 + + + + + + + + + false + + + + The specified file is not the pgModeler command line tool (pgmodeler-cli). + + + + + + + + + + 0 + 0 + + + + Output file: + + + + + + + Fix tries: + + + + + + + + + true + + + + + + + true + + + Select input file + + + ... + + + + :/icones/icones/abrir.png:/icones/icones/abrir.png + + + + 22 + 22 + + + + + + diff --git a/libpgmodeler_ui/ui/modeloverviewwidget.ui b/libpgmodeler_ui/ui/modeloverviewwidget.ui index c00c2c36f3..0ae83805b7 100644 --- a/libpgmodeler_ui/ui/modeloverviewwidget.ui +++ b/libpgmodeler_ui/ui/modeloverviewwidget.ui @@ -53,7 +53,10 @@ border: 1px solid #707070; - + + + 0 + 0 @@ -66,10 +69,7 @@ 0 - - 0 - - + @@ -99,7 +99,7 @@ - QFrame::Box + QFrame::NoFrame QFrame::Plain @@ -156,6 +156,9 @@ + + QFrame::NoFrame + diff --git a/libpgmodeler_ui/ui/modelvalidationwidget.ui b/libpgmodeler_ui/ui/modelvalidationwidget.ui index 6530560647..fdc016a937 100644 --- a/libpgmodeler_ui/ui/modelvalidationwidget.ui +++ b/libpgmodeler_ui/ui/modelvalidationwidget.ui @@ -718,7 +718,7 @@ Try to resolve the reported issues. - Apply Fix + Apply fixes @@ -753,7 +753,7 @@ Change the creation order for two objects by swapping their ids - Swap Ids + Swap ids diff --git a/libpgmodeler_ui/ui/newobjectoverlaywidget.ui b/libpgmodeler_ui/ui/newobjectoverlaywidget.ui index 54d72ddc2d..7d5d85b21d 100644 --- a/libpgmodeler_ui/ui/newobjectoverlaywidget.ui +++ b/libpgmodeler_ui/ui/newobjectoverlaywidget.ui @@ -6,8 +6,8 @@ 0 0 - 408 - 702 + 434 + 911 @@ -83,1652 +83,1925 @@ 4 - - - - 0 - 0 - + + + Database objects - + - 0 + 4 - 0 + 4 - 0 + 4 - 0 + 4 - - 6 - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Schema - - - - :/icones/icones/schema.png:/icones/icones/schema.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Tablespace - - - - :/icones/icones/tablespace.png:/icones/icones/tablespace.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Cast - - - - :/icones/icones/cast.png:/icones/icones/cast.png - - - - 32 - 32 - - - - A - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Role - - - - :/icones/icones/role.png:/icones/icones/role.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Extension - - - - :/icones/icones/extension.png:/icones/icones/extension.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Event Trigger - - - - :/icones/icones/eventtrigger.png:/icones/icones/eventtrigger.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Language - - - - :/icones/icones/language.png:/icones/icones/language.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Generic SQL - - - - :/icones/icones/genericsql.png:/icones/icones/genericsql.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Tag - - - - :/icones/icones/tag.png:/icones/icones/tag.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Textbox - - - - :/icones/icones/textbox.png:/icones/icones/textbox.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - - - - 0 - 0 - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 6 - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::StrongFocus - - - Type - - - - :/icones/icones/usertype.png:/icones/icones/usertype.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Conversion - - - - :/icones/icones/conversion.png:/icones/icones/conversion.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Aggregate - - - - :/icones/icones/aggregate.png:/icones/icones/aggregate.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Operator - - - - :/icones/icones/operator.png:/icones/icones/operator.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Domain - - - - :/icones/icones/domain.png:/icones/icones/domain.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Collation - - - - :/icones/icones/collation.png:/icones/icones/collation.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Sequence - - - - :/icones/icones/sequence.png:/icones/icones/sequence.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Op. Family - - - - :/icones/icones/opfamily.png:/icones/icones/opfamily.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Table - - - - :/icones/icones/table.png:/icones/icones/table.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Function - - - - :/icones/icones/function.png:/icones/icones/function.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - View - - - - :/icones/icones/view.png:/icones/icones/view.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Op. Class - - - - :/icones/icones/opclass.png:/icones/icones/opclass.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - + + 0 0 - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Permissions - - - - :/icones/icones/permission.png:/icones/icones/permission.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - + + + 0 + + + 0 + + + 0 + + + 0 + + + 6 + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Generic SQL + + + + :/icones/icones/genericsql.png:/icones/icones/genericsql.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Extension + + + + :/icones/icones/extension.png:/icones/icones/extension.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Data Wrapper + + + + :/icones/icones/foreigndatawrapper.png:/icones/icones/foreigndatawrapper.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Permissions + + + + :/icones/icones/permission.png:/icones/icones/permission.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Role + + + + :/icones/icones/role.png:/icones/icones/role.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Server + + + + :/icones/icones/foreignserver.png:/icones/icones/foreignserver.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Schema + + + + :/icones/icones/schema.png:/icones/icones/schema.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Event Trigger + + + + :/icones/icones/eventtrigger.png:/icones/icones/eventtrigger.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Language + + + + :/icones/icones/language.png:/icones/icones/language.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Cast + + + + :/icones/icones/cast.png:/icones/icones/cast.png + + + + 32 + 32 + + + + A + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Tablespace + + + + :/icones/icones/tablespace.png:/icones/icones/tablespace.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Tag + + + + :/icones/icones/tag.png:/icones/icones/tag.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Textbox + + + + :/icones/icones/textbox.png:/icones/icones/textbox.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + User mapping + + + + :/icones/icones/usermapping.png:/icones/icones/usermapping.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + - - - - 0 - 0 - + + + Schema objects - + - 0 + 4 - 0 + 4 - 0 + 4 - 0 + 4 - - 6 - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Constraint - - - - :/icones/icones/constraint.png:/icones/icones/constraint.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Column - - - - :/icones/icones/column.png:/icones/icones/column.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Permissions - - - - :/icones/icones/permission.png:/icones/icones/permission.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Index - - - - :/icones/icones/index.png:/icones/icones/index.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Rule - - - - :/icones/icones/rule.png:/icones/icones/rule.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Trigger - - - - :/icones/icones/trigger.png:/icones/icones/trigger.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - + + 0 0 - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Policy - - - - :/icones/icones/policy.png:/icones/icones/policy.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - + + + 0 + + + 0 + + + 0 + + + 0 + + + 6 + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::StrongFocus + + + Type + + + + :/icones/icones/usertype.png:/icones/icones/usertype.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Conversion + + + + :/icones/icones/conversion.png:/icones/icones/conversion.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Aggregate + + + + :/icones/icones/aggregate.png:/icones/icones/aggregate.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Operator + + + + :/icones/icones/operator.png:/icones/icones/operator.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Domain + + + + :/icones/icones/domain.png:/icones/icones/domain.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Collation + + + + :/icones/icones/collation.png:/icones/icones/collation.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Sequence + + + + :/icones/icones/sequence.png:/icones/icones/sequence.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Op. Family + + + + :/icones/icones/opfamily.png:/icones/icones/opfamily.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Table + + + + :/icones/icones/table.png:/icones/icones/table.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Function + + + + :/icones/icones/function.png:/icones/icones/function.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + View + + + + :/icones/icones/view.png:/icones/icones/view.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Op. Class + + + + :/icones/icones/opclass.png:/icones/icones/opclass.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + - - - - 0 - 0 - + + + Table objects - + - 0 + 4 - 0 + 4 - 0 + 4 - 0 + 4 - - 6 - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Many-to-many - - - - :/icones/icones/relationshipnn.png:/icones/icones/relationshipnn.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - One-to-many - - - - :/icones/icones/relationship1n.png:/icones/icones/relationship1n.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - - - + 0 0 - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - One-to-one - - - - :/icones/icones/relationship11.png:/icones/icones/relationship11.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - + + + 0 + + + 0 + + + 0 + + + 0 + + + 6 + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Constraint + + + + :/icones/icones/constraint.png:/icones/icones/constraint.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Column + + + + :/icones/icones/column.png:/icones/icones/column.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Permissions + + + + :/icones/icones/permission.png:/icones/icones/permission.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Index + + + + :/icones/icones/index.png:/icones/icones/index.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Rule + + + + :/icones/icones/rule.png:/icones/icones/rule.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Trigger + + + + :/icones/icones/trigger.png:/icones/icones/trigger.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Policy + + + + :/icones/icones/policy.png:/icones/icones/policy.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + - - + + + + + + + Relationships + + + + 4 + + + 4 + + + 4 + + + 4 + + + 0 0 - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Inheritance - - - - :/icones/icones/relationshipgen.png:/icones/icones/relationshipgen.png - - - - 32 - 32 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - + + + 0 + + + 0 + + + 0 + + + 0 + + + 6 + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Many-to-many + + + + :/icones/icones/relationshipnn.png:/icones/icones/relationshipnn.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + One-to-many + + + + :/icones/icones/relationship1n.png:/icones/icones/relationship1n.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + One-to-one + + + + :/icones/icones/relationship11.png:/icones/icones/relationship11.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Inheritance + + + + :/icones/icones/relationshipgen.png:/icones/icones/relationshipgen.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Copy + + + + :/icones/icones/relationshipdep.png:/icones/icones/relationshipdep.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + + + + + 0 + 0 + + + + + 95 + 50 + + + + + 50 + false + + + + Qt::NoFocus + + + Partitioning + + + + :/icones/icones/relationshippart.png:/icones/icones/relationshippart.png + + + + 32 + 32 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextUnderIcon + + + + - - - - - 0 - 0 - - - - - 95 - 50 - - - - - 50 - false - - - - Qt::NoFocus - - - Copy - - - - :/icones/icones/relationshipdep.png:/icones/icones/relationshipdep.png + + + + Qt::Horizontal - + - 32 - 32 + 40 + 20 - - QToolButton::InstantPopup - - - Qt::ToolButtonTextUnderIcon - - + diff --git a/libpgmodeler_ui/ui/objectdepsrefswidget.ui b/libpgmodeler_ui/ui/objectdepsrefswidget.ui index b9845ed5c9..009eb5398c 100644 --- a/libpgmodeler_ui/ui/objectdepsrefswidget.ui +++ b/libpgmodeler_ui/ui/objectdepsrefswidget.ui @@ -109,7 +109,7 @@ false - 25 + 26 false @@ -262,7 +262,7 @@ false - 25 + 26 false diff --git a/libpgmodeler_ui/ui/objectfinderwidget.ui b/libpgmodeler_ui/ui/objectfinderwidget.ui index 48375a48b1..3cb3e2e923 100644 --- a/libpgmodeler_ui/ui/objectfinderwidget.ui +++ b/libpgmodeler_ui/ui/objectfinderwidget.ui @@ -38,19 +38,44 @@ 4 - - + + + + true + - + 0 0 + + + 0 + 0 + + + + Defines the search filter + - ... + Filter - - 10 + + + :/icones/icones/filter.png:/icones/icones/filter.png + + + + 20 + 20 + + + + true + + + Qt::ToolButtonTextBesideIcon @@ -68,10 +93,32 @@ 0 + + true + - - + + + + + 0 + 0 + + + + + 50 + 0 + + + + Pattern: + + + + + false @@ -88,14 +135,14 @@ - Clears the search results + (Un)selects the graphical objects in the results grid - Clear + Select - :/icones/icones/limpartexto.png:/icones/icones/limpartexto.png + :/icones/icones/selmovobjeto.png:/icones/icones/selmovobjeto.png @@ -103,80 +150,73 @@ 20 + + false + + + QToolButton::InstantPopup + Qt::ToolButtonTextBesideIcon - - + + 0 0 - - - 50 - 0 - - - Pattern: + ... + + + 10 - - - - - 20 - 20 - + + + + false - + + + 0 + 0 + + + - 20 - 20 + 0 + 0 - Hide this widget + Clears the search results - ... + Clear - :/icones/icones/fechar1.png:/icones/icones/fechar1.png - - - true - - - - - - - Qt::Horizontal - - - QSizePolicy::Expanding + :/icones/icones/limpartexto.png:/icones/icones/limpartexto.png - + - 40 + 20 20 - + + Qt::ToolButtonTextBesideIcon + + - - - true - + 0 @@ -189,15 +229,12 @@ 0 - - Defines the search filter - - Filter + Find - :/icones/icones/filter.png:/icones/icones/filter.png + :/icones/icones/objselect.png:/icones/icones/objselect.png @@ -205,16 +242,42 @@ 20 - - true - Qt::ToolButtonTextBesideIcon - - + + + + + 20 + 20 + + + + + 20 + 20 + + + + Hide this widget + + + ... + + + + :/icones/icones/fechar1.png:/icones/icones/fechar1.png + + + true + + + + + false @@ -231,14 +294,14 @@ - (Un)selects the graphical objects in the results grid + Fades outs all the graphical objects in the results grid (or those not listed). The current fade in/out state of all objects is modified. - Select + Fade out - :/icones/icones/selmovobjeto.png:/icones/icones/selmovobjeto.png + :/icones/icones/fadeout.png:/icones/icones/fadeout.png @@ -257,7 +320,7 @@ - + Qt::Vertical @@ -303,6 +366,19 @@ 4 + + + + Qt::Horizontal + + + + 40 + 20 + + + + @@ -316,6 +392,19 @@ + + + + + 0 + 0 + + + + Case Sensitive + + + @@ -329,7 +418,7 @@ - + 2 @@ -470,32 +559,6 @@ - - - - - 0 - 0 - - - - Case Sensitive - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - @@ -545,7 +608,7 @@ false - 25 + 26 false @@ -619,82 +682,37 @@ :/icones/icones/usertype.png:/icones/icones/usertype.png + + + Comment + + + AlignLeading|AlignVCenter + + - - - - - 0 - 0 - - - - - 0 - 0 - - - - Find + + + + Qt::Horizontal - - - :/icones/icones/objselect.png:/icones/icones/objselect.png + + QSizePolicy::Expanding - + - 20 + 40 20 - - Qt::ToolButtonTextBesideIcon - - + - - - - false - - - - 0 - 0 - - - - - 0 - 0 - - + + - Fades outs all the graphical objects in the results grid (or those not listed). The current fade in/out state of all objects is modified. - - - Fade out - - - - :/icones/icones/fadeout.png:/icones/icones/fadeout.png - - - - 20 - 20 - - - - false - - - QToolButton::InstantPopup - - - Qt::ToolButtonTextBesideIcon + The attribute of the objects in which the search will occur diff --git a/libpgmodeler_ui/ui/objectrenamewidget.ui b/libpgmodeler_ui/ui/objectrenamewidget.ui index ac46b9b480..3edf8e18ef 100644 --- a/libpgmodeler_ui/ui/objectrenamewidget.ui +++ b/libpgmodeler_ui/ui/objectrenamewidget.ui @@ -229,6 +229,9 @@ 9 + + true + diff --git a/libpgmodeler_ui/ui/objectstablewidget.ui b/libpgmodeler_ui/ui/objectstablewidget.ui index 6a9d6b2686..12dd935879 100644 --- a/libpgmodeler_ui/ui/objectstablewidget.ui +++ b/libpgmodeler_ui/ui/objectstablewidget.ui @@ -43,7 +43,7 @@ true - + 0 0 @@ -62,7 +62,7 @@ - :/icones/icones/adicionar.png:/icones/icones/adicionar.png + :/icones/icones/addrow.png:/icones/icones/addrow.png @@ -81,7 +81,7 @@ false - + 0 0 @@ -100,7 +100,7 @@ - :/icones/icones/remover.png:/icones/icones/remover.png + :/icones/icones/delrow.png:/icones/icones/delrow.png @@ -114,12 +114,12 @@ - + false - + 0 0 @@ -131,14 +131,14 @@ - Update Item + Remove All - :/icones/icones/atualizar.png:/icones/icones/atualizar.png + :/icones/icones/delrows.png:/icones/icones/delrows.png @@ -147,17 +147,17 @@ - Alt+R + Shift+Del - + false - + 0 0 @@ -169,14 +169,14 @@ - Remove All + Duplicate item - :/icones/icones/limpartexto.png:/icones/icones/limpartexto.png + :/icones/icones/duprow.png:/icones/icones/duprow.png @@ -185,17 +185,17 @@ - Shift+Del + Ctrl+D - + false - + 0 0 @@ -207,14 +207,14 @@ - Duplicate item + Edit Item - :/icones/icones/duplicate.png:/icones/icones/duplicate.png + :/icones/icones/editdata.png:/icones/icones/editdata.png @@ -223,17 +223,17 @@ - Ctrl+D + Space - + false - + 0 0 @@ -245,14 +245,14 @@ - Edit Item + Update Item - :/icones/icones/editar.png:/icones/icones/editar.png + :/icones/icones/atualizar.png:/icones/icones/atualizar.png @@ -261,7 +261,7 @@ - Space + Alt+R @@ -271,7 +271,7 @@ false - + 0 0 @@ -309,7 +309,7 @@ false - + 0 0 @@ -347,7 +347,7 @@ false - + 0 0 @@ -385,7 +385,7 @@ false - + 0 0 @@ -417,6 +417,41 @@ + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + Resize columns to fit contents + + + + + + + :/icones/icones/resizecols.png:/icones/icones/resizecols.png + + + + 22 + 22 + + + + @@ -458,7 +493,7 @@ false - 25 + 26 true @@ -471,33 +506,33 @@ - - + + Qt::Horizontal - QSizePolicy::Preferred + QSizePolicy::Expanding - 97 + 92 22 - - + + Qt::Horizontal - QSizePolicy::Preferred + QSizePolicy::Expanding - 92 + 97 22 @@ -508,7 +543,6 @@ add_tb remove_tb - update_tb remove_all_tb edit_tb move_up_tb diff --git a/libpgmodeler_ui/ui/operatorwidget.ui b/libpgmodeler_ui/ui/operatorwidget.ui index 26d7fd8cde..cfa63fb91e 100644 --- a/libpgmodeler_ui/ui/operatorwidget.ui +++ b/libpgmodeler_ui/ui/operatorwidget.ui @@ -7,7 +7,7 @@ 0 0 522 - 192 + 224 diff --git a/libpgmodeler_ui/ui/parameterwidget.ui b/libpgmodeler_ui/ui/parameterwidget.ui index 9e9c1a8442..2ba8605b27 100644 --- a/libpgmodeler_ui/ui/parameterwidget.ui +++ b/libpgmodeler_ui/ui/parameterwidget.ui @@ -50,6 +50,9 @@ 23 + + true + @@ -76,7 +79,7 @@ 83 129 200 - 24 + 30 diff --git a/libpgmodeler_ui/ui/policywidget.ui b/libpgmodeler_ui/ui/policywidget.ui index e06bde08b3..dc8789f42f 100644 --- a/libpgmodeler_ui/ui/policywidget.ui +++ b/libpgmodeler_ui/ui/policywidget.ui @@ -33,7 +33,7 @@ 4 - + Basics @@ -169,6 +169,11 @@ + + command_cmb + permissive_chk + attribs_tbw + diff --git a/libpgmodeler_ui/ui/referencewidget.ui b/libpgmodeler_ui/ui/referencewidget.ui new file mode 100644 index 0000000000..1a08030f29 --- /dev/null +++ b/libpgmodeler_ui/ui/referencewidget.ui @@ -0,0 +1,685 @@ + + + ReferenceWidget + + + + 0 + 0 + 689 + 263 + + + + + 0 + 0 + + + + Reference properties + + + + 4 + + + 4 + + + 4 + + + 4 + + + 6 + + + + + true + + + 0 + + + + Properties + + + + 4 + + + 4 + + + 4 + + + 4 + + + 6 + + + + + + 0 + 0 + + + + + 0 + 0 + + + + Ref. type: + + + + + + + + + + 0 + 0 + + + + + false + + + + + + + <strong>SELECT</strong><br/>The reference will be used as part of the SELECT statement to retrieve columns or expressions that will compose the view's columns.<br/><strong>FROM</strong><br/>The reference is used in the FROM portion of the command in order to reference tables or construct JOIN statements.<br/><strong>WHERE</strong><br/>The reference will be used as part of the WHERE clause in form of conditional expression. <br/><strong>GROUP/HAVING</strong><br/>The reference will be appended to the very end of the view's definition. This is useful when using GROUP BY/HAVING statements.<br/><strong>View definition</strong><br/>The reference's expression is used exclusively as the view's definition.<br/> + + + SELECT + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + false + + + + FROM + + + + + + + + 0 + 0 + + + + + false + + + + WHERE + + + + + + + + 0 + 0 + + + + + false + + + + GROUP/HAVING + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + View Definition + + + + + + + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + + + + + + + + View's references can point to a table, column or expression. + + + Table / Column + + + + Table / Column + + + + + Expression + + + + + + + + + 0 + 0 + + + + Ref. alias: + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + This is a more friendly description for the reference. When displaying the model in compact view this is the text shown for the reference instead of its real description. If this field is empty the real description will be displayed anyway. + + + + + + true + + + + + + + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + + + + + + + 0 + 0 + + + + Used in: + + + + + + + + 0 + 0 + + + + Ref. object: + + + + + + + + 0 + 0 + + + + Table alias: + + + + + + + + 0 + 0 + + + + true + + + + + + + + 0 + 0 + + + + Column alias: + + + + + + + false + + + + 0 + 0 + + + + true + + + + + + + + 0 + 0 + + + + Expression: + + + + + + + + 0 + 0 + + + + Expr. alias: + + + + + + + + 0 + 0 + + + + true + + + + + + + Qt::Horizontal + + + + 318 + 17 + + + + + + + + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + + + + + true + + + Columns + + + + 6 + + + 4 + + + 4 + + + 4 + + + 4 + + + + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Name: + + + + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Alias: + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + This is a more friendly name for the column. When displaying the model in compact view this is the name shown for the column instead of its real name. If this field is empty the real name will be displayed anyway. + + + + + + true + + + + + + + + 0 + 0 + + + + + 6 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + This is the name of the object in the PostgreSQL database. + + + + + + true + + + + + + + + + + Referenced tables + + + + + 30 + 30 + 61 + 22 + + + + Table: + + + + + + + + + properties_tbw + ref_type_cmb + ref_alias_edt + select_from_chk + from_where_chk + after_where_chk + end_expr_chk + view_def_chk + tab_alias_edt + col_alias_edt + expr_alias_edt + name_edt + alias_edt + + + + diff --git a/libpgmodeler_ui/ui/relationshipconfigwidget.ui b/libpgmodeler_ui/ui/relationshipconfigwidget.ui index 76c7f8e4b8..db89e5ad41 100644 --- a/libpgmodeler_ui/ui/relationshipconfigwidget.ui +++ b/libpgmodeler_ui/ui/relationshipconfigwidget.ui @@ -749,33 +749,7 @@ - - - - One to one (1:1) - - - - - One to many (1:n) - - - - - Many to many (n:n) - - - - - Generalization - - - - - Copy - - - + diff --git a/libpgmodeler_ui/ui/relationshipwidget.ui b/libpgmodeler_ui/ui/relationshipwidget.ui index 7078bd1379..fd7fdde52b 100644 --- a/libpgmodeler_ui/ui/relationshipwidget.ui +++ b/libpgmodeler_ui/ui/relationshipwidget.ui @@ -6,8 +6,8 @@ 0 0 - 818 - 1701 + 858 + 1251 @@ -25,7 +25,7 @@ 16777215 - 1701 + 16777215 @@ -52,6 +52,12 @@ 0 + + + 16777215 + 16777215 + + 0 @@ -175,22 +181,6 @@ - - - - Qt::Vertical - - - QSizePolicy::Expanding - - - - 20 - 40 - - - - @@ -293,441 +283,55 @@ - - - - - 0 - 0 - - - - Foreign key Settings - - - false - - - false - - - - 6 - - - 4 - - - 4 - - - 4 - - - 4 - - - - - true - - - Use the values defined on settings dialogs for the fields below - - - Use global settings for these fields - - - true - - - - - - - false - - - - 0 - 20 - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 6 - - - - - - 0 - 0 - - - - - 90 - 0 - - - - - 90 - 16777215 - - - - Deferrable: - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - - - - - - - - false - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - Deferral: - - - - - - - false - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - QComboBox::AdjustToContents - - - - - - - ON DELETE: - - - - - - - - - - ON UPDATE: - - - - - - - - - - - - - - - false - - - - 0 - 0 - - + - 0 - 0 + 22 + 22 - 16777215 - 16777215 + 22 + 22 + + true + + + + + - true + 75 + true - - One to one relationship - - &1-1 + rel_type - - - false + + + Qt::Horizontal - - - 0 - 0 - + + + 40 + 20 + - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - - true - - - - One to many relationship - - - 1-n - - - - - - - false - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - - true - - - - Many to many relationship - - - n-n - - - - - - - false - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - - true - - - - Generalization relationship (inheritance) - - - &gen - - - - - - - false - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - - true - - - - Dependency / Copy relationship - - - dep - - - - - - - false - - - - 0 - 0 - - - - - 50 - 0 - - - - - true - - - - Relationship generated via foreign key - - - fk - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - + + + + 0 @@ -859,18 +463,129 @@ - - + + + + + + + Name of the table generated from many to many relationship + + + true + + + + + - + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + + true + + + + Qt::ScrollBarAlwaysOff + + + Qt::ScrollBarAlwaysOff + + + + + + + 0 0 + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + + true + + + + Qt::ScrollBarAlwaysOff + + + Qt::ScrollBarAlwaysOff + + + + + + + Qt::Vertical + + + QSizePolicy::Expanding + + + + 20 + 40 + + + + + + - Copy Options + Bounding expression - + 4 @@ -883,226 +598,137 @@ 4 - - - - false - - - INDEXES - - - - - - - false - - - COMMENTS - - - - - - - INCLUDING - - - - - - - false - - - DEFAULTS - - - - - - - - 0 - 0 - - - - E&XCLUDING - - - - - - - false - - - CONSTRAINTS - - - - - - - 0 - 0 - - - - Use defaults - - - true - - - - - - - false - - - ALL - - - - - - - false - - - STORAGE - - - - - - - - 0 - 1 - - - - - 16777215 - 1 - - - - QFrame::StyledPanel - - - QFrame::Sunken - - + + + + + Partitioning type: + + + + + + + + 75 + true + + + + NONE + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + Default partitions are only supported on <strong>PostgreSQL 11+</strong>. Using this option and exporting the code to PostgreSQL 10 syntax errors will be raised. + + + Default partition + + + + + + + + 0 + 0 + + + + + 22 + 22 + + + + + 22 + 22 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Generate the partition bounding expression based upon the partitioning type in use. + + + Generate expression + + + + :/icones/icones/codigosql.png:/icones/icones/codigosql.png + + + + 22 + 22 + + + + Qt::ToolButtonTextBesideIcon + + + + - - - - - - - Name of the table generated from many to many relationship - - - - - - - - 0 - 0 - - - - - 22 - 22 - - - - - 22 - 22 - - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - - true - - - - Qt::ScrollBarAlwaysOff - - - Qt::ScrollBarAlwaysOff - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - - true - - - - Qt::ScrollBarAlwaysOff - - - Qt::ScrollBarAlwaysOff - - - - + + + + + Settings + + + + 4 + + + 4 + + + 4 + + + 4 + + @@ -1322,33 +948,224 @@ - + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Qt::ScrollBarAlwaysOff + + + Qt::ScrollBarAlwaysOff + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Qt::ScrollBarAlwaysOff + + + Qt::ScrollBarAlwaysOff + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Qt::ScrollBarAlwaysOff + + + Qt::ScrollBarAlwaysOff + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Qt::ScrollBarAlwaysOff + + + Qt::ScrollBarAlwaysOff + + + + + + + + + + + + + + 0 + 0 + + + + Foreign key Settings + + + false + + + false + + + + 6 + + + 4 + + + 4 + + + 4 + + + 4 + + + + + true + + + Use the values defined on settings dialogs for the fields below + + + Use global settings for these fields + + + true + + + + + + + false + + + + 0 + 20 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 6 + + + + + 0 0 - 0 + 90 0 - 16777215 + 90 16777215 - - Qt::ScrollBarAlwaysOff - - - Qt::ScrollBarAlwaysOff + + Deferrable: - - + + 0 @@ -1367,18 +1184,18 @@ 16777215 - - Qt::ScrollBarAlwaysOff - - - Qt::ScrollBarAlwaysOff + + - - + + + + false + - + 0 0 @@ -1395,16 +1212,16 @@ 16777215 - - Qt::ScrollBarAlwaysOff - - - Qt::ScrollBarAlwaysOff + + Deferral: - - + + + + false + 0 @@ -1423,20 +1240,215 @@ 16777215 - - Qt::ScrollBarAlwaysOff + + QComboBox::AdjustToContents - - Qt::ScrollBarAlwaysOff + + + + + + ON DELETE: + + + + + + + + + + ON UPDATE: + + + + + + + + 0 + 0 + + + + Copy Options + + + + 4 + + + 4 + + + 4 + + + 4 + + + + + false + + + INDEXES + + + + + + + false + + + COMMENTS + + + + + + + INCLUDING + + + + + + + false + + + DEFAULTS + + + + + + + + 0 + 0 + + + + E&XCLUDING + + + + + + + false + + + CONSTRAINTS + + + + + + + + 0 + 0 + + + + Use defaults + + + true + + + + + + + false + + + ALL + + + + + + + false + + + STORAGE + + + + + + + + 0 + 1 + + + + + 16777215 + 1 + + + + QFrame::StyledPanel + + + QFrame::Sunken + + + + + + + false + + + STATISTICS + + + + + + + false + + + IDENTITY + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + @@ -1504,28 +1516,15 @@ rel_attribs_tbw - rel_11_rb - rel_1n_rb - rel_nn_rb - rel_gen_rb - rel_dep_rb - rel_fk_rb table1_mand_chk table2_mand_chk relnn_tab_name_edt ref_table_txt recv_table_txt - defaults_rb - including_rb - excluding_rb - all_chk - defaults_chk - constraints_chk - indexes_chk - storage_chk - comments_chk rel_columns_lst - + + + diff --git a/libpgmodeler_ui/ui/rolewidget.ui b/libpgmodeler_ui/ui/rolewidget.ui index 9d746c7376..ec8505d6c8 100644 --- a/libpgmodeler_ui/ui/rolewidget.ui +++ b/libpgmodeler_ui/ui/rolewidget.ui @@ -213,6 +213,9 @@ 0 + + true + diff --git a/libpgmodeler_ui/ui/sceneinfowidget.ui b/libpgmodeler_ui/ui/sceneinfowidget.ui index ef15a45fca..20fefecc2e 100644 --- a/libpgmodeler_ui/ui/sceneinfowidget.ui +++ b/libpgmodeler_ui/ui/sceneinfowidget.ui @@ -6,8 +6,8 @@ 0 0 - 349 - 20 + 429 + 34 diff --git a/libpgmodeler_ui/ui/sequencewidget.ui b/libpgmodeler_ui/ui/sequencewidget.ui index 91333f0dc3..26819e294c 100644 --- a/libpgmodeler_ui/ui/sequencewidget.ui +++ b/libpgmodeler_ui/ui/sequencewidget.ui @@ -6,8 +6,8 @@ 0 0 - 400 - 214 + 603 + 165 @@ -24,42 +24,52 @@ - 2 + 0 - 2 + 0 - 2 + 0 - 2 + 0 6 + + + Defualt values: + + + + + + + Cyclic: - + - + Start: - + @@ -78,17 +88,20 @@ false + + true + - - + + - Maximum: + Increment: - - + + 0 @@ -106,16 +119,19 @@ false + + true + - + Minimum: - + @@ -134,17 +150,20 @@ false + + true + - - + + - Increment: + Maximum: - - + + 0 @@ -162,16 +181,19 @@ false + + true + - + Cache: - + @@ -190,9 +212,12 @@ false + + true + - + Owner Col.: diff --git a/libpgmodeler_ui/ui/snippetsconfigwidget.ui b/libpgmodeler_ui/ui/snippetsconfigwidget.ui index 2b9c846ebe..259cf6ddc8 100644 --- a/libpgmodeler_ui/ui/snippetsconfigwidget.ui +++ b/libpgmodeler_ui/ui/snippetsconfigwidget.ui @@ -104,6 +104,9 @@ 0 + + true + @@ -146,6 +149,9 @@ 0 + + true + diff --git a/libpgmodeler_ui/ui/sqlexecutionwidget.ui b/libpgmodeler_ui/ui/sqlexecutionwidget.ui index 60d3821d04..bfbba57794 100644 --- a/libpgmodeler_ui/ui/sqlexecutionwidget.ui +++ b/libpgmodeler_ui/ui/sqlexecutionwidget.ui @@ -7,7 +7,7 @@ 0 0 843 - 478 + 349 @@ -127,10 +127,19 @@ + + 4 + - + - true + false + + + + 0 + 0 + @@ -139,14 +148,14 @@ - Handle external SQL script + Run the specified SQL command - &Script + Run - :/icones/icones/codigosql.png:/icones/icones/codigosql.png + :/icones/icones/run.png:/icones/icones/run.png @@ -155,26 +164,64 @@ - Alt+F + F5 - - false + + Qt::ToolButtonTextBesideIcon - - false + + true - - QToolButton::InstantPopup + + + + + + true + + + + 0 + 0 + + + + + 0 + 30 + + + + Cancel the execution of the current SQL command + + + Stop + + + + :/icones/icones/stop.png:/icones/icones/stop.png + + + + 22 + 22 + + + + Esc Qt::ToolButtonTextBesideIcon + + true + - + - false + true @@ -183,14 +230,14 @@ - Search in SQL code + Handle external SQL script - Fi&nd + &Script - :/icones/icones/buscar.png:/icones/icones/buscar.png + :/icones/icones/codigosql.png:/icones/icones/codigosql.png @@ -198,8 +245,11 @@ 22 + + Alt+F + - true + false false @@ -210,19 +260,16 @@ Qt::ToolButtonTextBesideIcon + + true + - + false - - - 0 - 0 - - 0 @@ -230,14 +277,14 @@ - Run the specified SQL command + Search in SQL code - Run SQL + Fi&nd - :/icones/icones/run.png:/icones/icones/run.png + :/icones/icones/buscar.png:/icones/icones/buscar.png @@ -246,11 +293,23 @@ - F6 + Ctrl+F + + + true + + + false + + + QToolButton::InstantPopup Qt::ToolButtonTextBesideIcon + + true + @@ -283,6 +342,9 @@ Qt::ToolButtonTextBesideIcon + + true + @@ -327,6 +389,9 @@ Qt::ToolButtonTextBesideIcon + + true + @@ -368,6 +433,53 @@ Qt::ToolButtonTextBesideIcon + + true + + + + + + + false + + + + 0 + 30 + + + + Filter the retrived results + + + F&ilter + + + + :/icones/icones/filter.png:/icones/icones/filter.png + + + + 22 + 22 + + + + Alt+I + + + true + + + false + + + Qt::ToolButtonTextBesideIcon + + + true + @@ -409,6 +521,9 @@ Qt::ToolButtonTextBesideIcon + + true + @@ -546,11 +661,11 @@ - - - 0 - 0 - + + + 0 + 0 + QTabWidget::South @@ -565,6 +680,9 @@ false + + false + Results @@ -582,14 +700,14 @@ 4 - + - 100 - 200 + 0 + 0 - + 0 @@ -602,17 +720,126 @@ 0 - - 0 - - - - + + + + + + + + 0 + 0 + + + true - + + + + + + + 0 + 0 + + + + Case sensitive + + + + + + + + 0 + 0 + + + + Regular expression + + + + + + + + 0 + 0 + + + + Exact match + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 20 + 20 + + + + + 20 + 20 + + + + Hide this widget + + + ... + + + + :/icones/icones/fechar1.png:/icones/icones/fechar1.png + + true + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 6 + + + QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed @@ -622,34 +849,18 @@ QAbstractItemView::ContiguousSelection - - QAbstractItemView::ScrollPerItem - - - QAbstractItemView::ScrollPerPixel - - + false - + true - 25 + 26 25 - - - ... - - - - - ... - - diff --git a/libpgmodeler_ui/ui/swapobjectsidswidget.ui b/libpgmodeler_ui/ui/swapobjectsidswidget.ui index b36d3604a1..6e57d3ec83 100644 --- a/libpgmodeler_ui/ui/swapobjectsidswidget.ui +++ b/libpgmodeler_ui/ui/swapobjectsidswidget.ui @@ -438,11 +438,6 @@ 81 - - - 9 - - QAbstractItemView::NoEditTriggers diff --git a/libpgmodeler_ui/ui/tabledatawidget.ui b/libpgmodeler_ui/ui/tabledatawidget.ui index 8760d88775..338096de71 100644 --- a/libpgmodeler_ui/ui/tabledatawidget.ui +++ b/libpgmodeler_ui/ui/tabledatawidget.ui @@ -6,7 +6,7 @@ 0 0 - 666 + 658 412 @@ -26,158 +26,7 @@ 0 - - - - - 0 - 0 - - - - - - - - true - - - - 0 - 0 - - - - Add empty rows - - - - :/icones/icones/addrow.png:/icones/icones/addrow.png - - - - 22 - 22 - - - - Ins - - - Qt::ToolButtonIconOnly - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 2 - 20 - - - - - - - - true - - - - 0 - 0 - - - - Add an empty column - - - - :/icones/icones/addcol.png:/icones/icones/addcol.png - - - - 22 - 22 - - - - QToolButton::InstantPopup - - - Qt::ToolButtonIconOnly - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 2 - 20 - - - - - - - - false - - - - 0 - 0 - - - - Remove all rows from the grid preserving columns - - - - :/icones/icones/delrows.png:/icones/icones/delrows.png - - - - 22 - 22 - - - - Shift+Del - - - Qt::ToolButtonIconOnly - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - + true @@ -241,26 +90,10 @@ - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 2 - 20 - - - - - + - true + false @@ -268,12 +101,20 @@ 0 + + + 8 + + - Fills the grid using a CSV file + Copy items on the grid + + + Copy - :/icones/icones/loadcsv.png:/icones/icones/loadcsv.png + :/icones/icones/copiar.png:/icones/icones/copiar.png @@ -281,34 +122,18 @@ 22 - - - - - true + + QToolButton::InstantPopup Qt::ToolButtonIconOnly - - - - Qt::Horizontal - - - - 203 - 20 - - - - - - + + - false + true @@ -317,11 +142,14 @@ - Remove all columns (and rows) from the grid + Add empty rows + + + Add row - :/icones/icones/delcols.png:/icones/icones/delcols.png + :/icones/icones/addrow.png:/icones/icones/addrow.png @@ -330,15 +158,15 @@ - Ctrl+Shift+Del + Ins Qt::ToolButtonIconOnly - - + + false @@ -349,11 +177,14 @@ - Duplicate the selected rows + Delete the selected columns + + + Delete column - :/icones/icones/duprow.png:/icones/icones/duprow.png + :/icones/icones/delcol.png:/icones/icones/delcol.png @@ -362,15 +193,15 @@ - Ctrl+D + Del Qt::ToolButtonIconOnly - - + + false @@ -380,12 +211,20 @@ 0 + + + 8 + + - Delete the selected columns + Paste items on the grid + + + Paste - :/icones/icones/delcol.png:/icones/icones/delcol.png + :/icones/icones/colar.png:/icones/icones/colar.png @@ -394,17 +233,20 @@ - Del + Ctrl+V + + + QToolButton::InstantPopup Qt::ToolButtonIconOnly - - + + - false + true @@ -413,11 +255,11 @@ - Delete the selected rows + Fills the grid using a CSV file - :/icones/icones/delrow.png:/icones/icones/delrow.png + :/icones/icones/loadcsv.png:/icones/icones/loadcsv.png @@ -426,15 +268,18 @@ - Del + + + + true Qt::ToolButtonIconOnly - - + + 0 @@ -453,7 +298,7 @@ QFrame::Raised - + 2 @@ -467,7 +312,7 @@ 2 - + 24 @@ -487,7 +332,7 @@ Qt::AutoText - :/icones/icones/msgbox_info.png + :/icones/icones/msgbox_alerta.png true @@ -495,7 +340,7 @@ - + 0 @@ -512,7 +357,7 @@ - <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in two slashes, e.g., <span style=" font-weight:600;">/value/</span>. To use a slash as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\/</span>.</p></body></html> + <html><head/><body><p>Some invalid or duplicated columns were detected. In order to solve this issue double-click the header of the highlighted ones in order to define the correct name in which the data belongs to or delete the entire column. Note that these columns are completely ignored when generating the <span style=" font-weight:600;">INSERT</span> commands.</p></body></html> true @@ -522,15 +367,247 @@ - - - - - 0 - 0 - - - + + + + true + + + + 0 + 0 + + + + Add an empty column + + + Add column + + + + :/icones/icones/addcol.png:/icones/icones/addcol.png + + + + 22 + 22 + + + + QToolButton::InstantPopup + + + Qt::ToolButtonIconOnly + + + + + + + false + + + + 0 + 0 + + + + Duplicate the selected rows + + + Duplicate rows + + + + :/icones/icones/duprow.png:/icones/icones/duprow.png + + + + 22 + 22 + + + + Ctrl+D + + + Qt::ToolButtonIconOnly + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + false + + + + 0 + 0 + + + + + 8 + + + + Change the values of all selected cells at once + + + Bulk data edit + + + + :/icones/icones/bulkedit.png:/icones/icones/bulkedit.png + + + + 22 + 22 + + + + Ctrl+E + + + Qt::ToolButtonIconOnly + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + + 0 + 0 + + + + + + + + false + + + + 0 + 0 + + + + Remove all columns (and rows) from the grid + + + Delete all columns + + + + :/icones/icones/delcols.png:/icones/icones/delcols.png + + + + 22 + 22 + + + + Ctrl+Shift+Del + + + Qt::ToolButtonIconOnly + + + + + + + false + + + + 0 + 0 + + + + Delete the selected rows + + + Delete rows + + + + :/icones/icones/delrow.png:/icones/icones/delrow.png + + + + 22 + 22 + + + + Del + + + Qt::ToolButtonIconOnly + + + + + + + + 0 + 0 + + + 0 30 @@ -542,7 +619,7 @@ QFrame::Raised - + 2 @@ -556,7 +633,7 @@ 2 - + 24 @@ -576,7 +653,7 @@ Qt::AutoText - :/icones/icones/msgbox_alerta.png + :/icones/icones/msgbox_info.png true @@ -584,7 +661,7 @@ - + 0 @@ -601,7 +678,7 @@ - Some invalid or duplicated columns were detected. In order to solve this issue double-click the header of the highlighted ones in order to define the correct name in which the data belongs to or delete the entire column. Note that these columns are completely igored when generating the <strong>INSERT</strong> commands. + <html><head/><body><p>Empty values are assumed as <span style=" font-weight:600;">DEFAULT</span>. To use special values like <span style=" font-weight:600;">NULL</span>, a function call like <span style=" font-weight:600;">now()</span> or a specific data escaping, enclose values in two slashes, e.g., <span style=" font-weight:600;">/value/</span>. To use a slash as part of the value prepend the backslash character, e.g., <span style=" font-weight:600;">\/</span>.</p></body></html> true @@ -611,6 +688,57 @@ + + + + false + + + + 0 + 0 + + + + Remove all rows from the grid preserving columns + + + Delete all rows + + + + :/icones/icones/delrows.png:/icones/icones/delrows.png + + + + 22 + 22 + + + + Shift+Del + + + Qt::ToolButtonIconOnly + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + clear_rows_tb hint_frm @@ -624,6 +752,9 @@ csv_load_tb csv_load_parent warn_frm + bulkedit_tb + copy_tb + paste_tb diff --git a/libpgmodeler_ui/ui/tablespacewidget.ui b/libpgmodeler_ui/ui/tablespacewidget.ui index 0f8b233ad4..13634b0069 100644 --- a/libpgmodeler_ui/ui/tablespacewidget.ui +++ b/libpgmodeler_ui/ui/tablespacewidget.ui @@ -20,7 +20,16 @@ Form - + + 2 + + + 2 + + + 2 + + 2 @@ -58,6 +67,9 @@ false + + true + diff --git a/libpgmodeler_ui/ui/tablewidget.ui b/libpgmodeler_ui/ui/tablewidget.ui index b04805a16a..07dd20b804 100644 --- a/libpgmodeler_ui/ui/tablewidget.ui +++ b/libpgmodeler_ui/ui/tablewidget.ui @@ -6,7 +6,7 @@ 0 0 - 513 + 658 348 @@ -37,7 +37,7 @@ Options - + 4 @@ -50,30 +50,82 @@ 4 - - - - With OID - - - false + + + + 10 - + + + + With OID + + + false + + + + + + + + 0 + 0 + + + + Unlogged + + + + + + + + 0 + 0 + + + + Enable row level security + + + + + + + true + + + + 0 + 0 + + + + Force RLS for owner + + + + + + + + 0 + 0 + + + + Generate ALTER for columns/constraints + + + + - - - - - 0 - 0 - - - - Unlogged - - + + - + @@ -92,48 +144,6 @@ - - - - - 0 - 0 - - - - Enable row level security - - - - - - - true - - - - 0 - 0 - - - - Force RLS for owner - - - - - - - - 0 - 0 - - - - Generate ALTER for columns/constraints - - - @@ -172,6 +182,65 @@ &Policies + + + Partition &keys + + + + 4 + + + 4 + + + 4 + + + 4 + + + + + + 0 + 0 + + + + Partitioning: + + + + + + + + + + 150 + 0 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + &Tables diff --git a/libpgmodeler_ui/ui/triggerwidget.ui b/libpgmodeler_ui/ui/triggerwidget.ui index 39e8d22090..65b67075d7 100644 --- a/libpgmodeler_ui/ui/triggerwidget.ui +++ b/libpgmodeler_ui/ui/triggerwidget.ui @@ -6,8 +6,8 @@ 0 0 - 511 - 347 + 765 + 419 @@ -29,150 +29,7 @@ 4 - - 6 - - - - - - - - 0 - 0 - - - - Constraint - - - - - - - false - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - Deferrable: - - - - - - - false - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - - - - - - - - - true - - - - 0 - 0 - - - - - 113 - 0 - - - - - 16777215 - 16777215 - - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 5 - 20 - - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - FOR EACH ROW - - - - - - + @@ -193,171 +50,24 @@ - Event: + Events: - - - - QLayout::SetDefaultConstraint - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - INSERT - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - DELETE - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - UPDATE - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - TRUNCATE - - - - - - - - - false - + + 0 0 - - - 0 - 0 - - - - - 16777215 - 16777215 - - - Refer. Table: + Type: - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - Condition: - - - - + 0 @@ -397,6 +107,9 @@ 0 + + true + @@ -467,13 +180,357 @@ + + + Constraint + + + + 4 + + + 4 + + + 4 + + + 4 + + + + + true + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Options: + + + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Deferrable: + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + QFrame::Sunken + + + 1 + + + 0 + + + Qt::ScrollBarAsNeeded + + + Qt::ScrollBarAsNeeded + + + + + + + false + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Refer. Table: + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Condition: + + + + + - - - + + + + + 0 + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + INSERT + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + DELETE + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + UPDATE + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + TRUNCATE + + + + + + + + + + + 0 + 0 + + + + Ordinary trigger + + true + + + + + + + 0 + 0 + + + + Constraint trigger + + + + + 0 @@ -493,12 +550,12 @@ - Function: + FOR EACH ROW - - + + true @@ -520,12 +577,9 @@ 16777215 - - Options: - - + true @@ -553,10 +607,13 @@ - - + + + + true + - + 0 0 @@ -564,45 +621,92 @@ 0 - 50 + 0 16777215 - 90 + 16777215 - - QFrame::Sunken - - - 1 - - - 0 + + Function: - - Qt::ScrollBarAsNeeded + + + + + + + 0 + 0 + - - Qt::ScrollBarAsNeeded + + Transition tables names + + + 4 + + + 4 + + + 4 + + + 4 + + + + + + 180 + 0 + + + + true + + + + + + + OLD: + + + + + + + NEW: + + + + + + + + 180 + 0 + + + + true + + + + - firing_mode_cmb - exec_per_row_chk - insert_chk - delete_chk - update_chk - truncate_chk - constr_trig_chk deferrable_chk deferral_type_cmb - cond_expr_txt arg_cols_tbw argument_edt column_cmb diff --git a/libpgmodeler_ui/ui/typewidget.ui b/libpgmodeler_ui/ui/typewidget.ui index fe646d2b61..b6d7b7cacc 100644 --- a/libpgmodeler_ui/ui/typewidget.ui +++ b/libpgmodeler_ui/ui/typewidget.ui @@ -240,6 +240,9 @@ 1 + + true + @@ -250,7 +253,11 @@ - + + + true + + @@ -414,7 +421,11 @@ - + + + true + + @@ -460,7 +471,11 @@ - + + + true + + diff --git a/libpgmodeler_ui/ui/usermappingwidget.ui b/libpgmodeler_ui/ui/usermappingwidget.ui new file mode 100644 index 0000000000..205741bfab --- /dev/null +++ b/libpgmodeler_ui/ui/usermappingwidget.ui @@ -0,0 +1,78 @@ + + + UserMappingWidget + + + + 0 + 0 + 462 + 210 + + + + + 0 + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + + 0 + 0 + + + + Server: + + + + + + + Options + + + + + + + + 0 + 0 + + + + + 0 + 20 + + + + + + + + + diff --git a/libpgmodeler_ui/ui/viewwidget.ui b/libpgmodeler_ui/ui/viewwidget.ui index 8f2ede6e12..8955fb17ea 100644 --- a/libpgmodeler_ui/ui/viewwidget.ui +++ b/libpgmodeler_ui/ui/viewwidget.ui @@ -28,267 +28,10 @@ 0 - + References - - - 6 - - - 6 - - - 6 - - - 6 - - - 6 - - - - - - 100 - 0 - - - - Reference Type: - - - - - - - - Column - - - - - Expression - - - - - - - - Used in: - - - - - - - Table: - - - - - - - - 0 - 0 - - - - Table Alias: - - - - - - - - 0 - 0 - - - - - - - - Column: - - - - - - - - 0 - 0 - - - - Column Alias: - - - - - - - - 0 - 0 - - - - - - - - Expression: - - - - - - - - 0 - 0 - - - - Expression Alias: - - - - - - - - 0 - 0 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - 0 - 0 - - - - The element will be used as part of the SELECT statement to retrieve columns or expressions that will compose the view's columns - - - SELECT ... - - - - - - - - 0 - 0 - - - - The element will be used as part of the WHERE clause in form of conditional expression - - - WHERE ... - - - - - - - - 0 - 0 - - - - - 137 - 0 - - - - The element is used in the FROM portion of the command in order to reference tables or construct JOIN statements - - - FROM ... - - - - - - - - 0 - 0 - - - - The element's expression is used exclusively as the view's definition - - - View Definition - - - - - - - - 0 - 0 - - - - The element will be appended to the very end of the view's definition. This is useful when using GROUP BY/HAVING statements - - - End expression - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - diff --git a/libpgmodeler_ui/ui/welcomewidget.ui b/libpgmodeler_ui/ui/welcomewidget.ui index 6fbd0c1398..263400061e 100644 --- a/libpgmodeler_ui/ui/welcomewidget.ui +++ b/libpgmodeler_ui/ui/welcomewidget.ui @@ -6,8 +6,8 @@ 0 0 - 658 - 362 + 714 + 353 @@ -35,18 +35,9 @@ 0 - - 0 - - - - 10 - - - 25 - - + + @@ -71,17 +62,23 @@ - - - - 5 + + + + 20 + + + 10 - + + 20 + + - 125 - 85 + 110 + 80 @@ -102,8 +99,8 @@ - 60 - 60 + 55 + 55 @@ -114,12 +111,12 @@ - + - 125 - 85 + 110 + 80 @@ -140,8 +137,8 @@ - 60 - 60 + 55 + 55 @@ -152,15 +149,15 @@ - + true - 125 - 85 + 110 + 80 @@ -181,8 +178,8 @@ - 60 - 60 + 55 + 55 @@ -196,15 +193,15 @@ - + false - 125 - 85 + 110 + 80 @@ -225,8 +222,8 @@ - 60 - 60 + 55 + 55 @@ -240,15 +237,15 @@ - + false - 125 - 85 + 110 + 80 @@ -270,8 +267,50 @@ - 60 - 60 + 55 + 55 + + + + Qt::ToolButtonTextUnderIcon + + + true + + + + + + + true + + + + 110 + 80 + + + + + 50 + false + PreferAntialias + + + + false + + + Support + + + + :/icones/icones/help_big.png:/icones/icones/help_big.png + + + + 55 + 55 diff --git a/libutils/libutils.pro b/libutils/libutils.pro index 7b13ae079d..38e6236b14 100644 --- a/libutils/libutils.pro +++ b/libutils/libutils.pro @@ -15,7 +15,8 @@ windows: DESTDIR = $$PWD HEADERS += src/exception.h \ src/globalattributes.h \ - src/pgsqlversions.h + src/pgsqlversions.h \ + src/doublenan.h SOURCES += src/exception.cpp \ src/globalattributes.cpp \ diff --git a/libutils/src/doublenan.h b/libutils/src/doublenan.h new file mode 100644 index 0000000000..c2ae880199 --- /dev/null +++ b/libutils/src/doublenan.h @@ -0,0 +1,27 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +/** +\ingroup libutils +\brief Definition of a shortcut to double NAN used by some portions of pgModeler mainly when dealing with graphical operations +*/ + +#ifndef DOUBLE_NAN_H +#define DOUBLE_NAN_H + # define DNaN (__builtin_nan ("")) +#endif diff --git a/libutils/src/exception.cpp b/libutils/src/exception.cpp index 7e731343ed..cbc5e578e2 100644 --- a/libutils/src/exception.cpp +++ b/libutils/src/exception.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,279 +18,292 @@ #include "exception.h" #include -QString Exception::messages[ERROR_COUNT][2]={ - {"ERR_CUSTOM", QString(" ")}, - {"ERR_ASG_PSDTYPE_COLUMN", QT_TR_NOOP("Assignment of a pseudo-type to the type of the column!")}, - {"ERR_ASG_INV_PRECISION", QT_TR_NOOP("Assignment of a precision greater than the length of the type!")}, - {"ERR_ASG_INV_PREC_TIMESTAMP", QT_TR_NOOP("Assignment of an invalid precision to type time, timestamp or interval. The precision in this case must be equal to or less than 6!")}, - {"ERR_ASG_NOT_ALOC_COLUMN", QT_TR_NOOP("Assignment of a not allocated column to object `%1' (%2)!")}, - {"ERR_REF_COLUMN_INV_INDEX", QT_TR_NOOP("Reference to a column which index is out of the capacity of the column list!")}, - {"ERR_ASG_NOT_ALOC_OBJECT", QT_TR_NOOP("Assignment of not allocated object!")}, - {"ERR_ASG_NOT_ALOC_SCHEMA", QT_TR_NOOP("Assignment of a not allocated schema to object `%1' (%2)!")}, - {"ERR_ASG_OBJ_INV_DEFINITION", QT_TR_NOOP("The object `%1' (%2) has inconsistent SQL or XML definition!")}, - {"ERR_ASG_DUPLIC_OBJECT", QT_TR_NOOP("The object `%1' (%2) already exists on `%3' (%4)!")}, - {"ERR_ASG_DUPL_OBJ_CONTAINER", QT_TR_NOOP("The object `%1' (%2) cannot be assigned because there is already exists in the container object `%3'!")}, - {"ERR_ASG_OBJECT_INV_TYPE", QT_TR_NOOP("Assigning object of an invalid type!")}, - {"ERR_REM_OBJ_INVALID_TYPE", QT_TR_NOOP("Removing an object of an invalid type!")}, - {"ERR_OBT_OBJ_INVALID_TYPE", QT_TR_NOOP("Obtaining an object of an invalid type!")}, - {"ERR_ASG_EMPTY_NAME_RET_TABLE", QT_TR_NOOP("Assignment of empty name to table return type!")}, - {"ERR_ASG_DUPLIC_PARAM_FUNCTION", QT_TR_NOOP("The insertion of the parameter `%1' will not be possible because there is another parameter with same name in the function `%2'!")}, - {"ERR_INS_DUPLIC_RET_TAB_TYPE", QT_TR_NOOP("The insertion of the table return type `%1' will not be possible because there is another return type with the same name in the `%2'!")}, - {"ERR_REF_PARAM_INV_INDEX", QT_TR_NOOP("Reference to a parameter which index is out of the parameter list bounds!")}, - {"ERR_REF_INV_TRIGGER_EVENT", QT_TR_NOOP("Reference to an event which does not belongs to trigger!")}, - {"ERR_ASG_INV_COLUMN_TRIGGER",QT_TR_NOOP("The column `%1' cannot be assigned to the trigger `%2' because they belongs to different parent tables!")}, - {"ERR_ASG_NOT_ALOC_FUNCTION", QT_TR_NOOP("Assignment of a not allocated function to object `%1' (%2)!")}, - {"ERR_ASG_INV_TRIGGER_FUNCTION", QT_TR_NOOP("Assignment of a function which return type is different from `%1'!")}, - {"ERR_ASG_FUNC_INV_PARAM_COUNT", QT_TR_NOOP("Assignment of a function which parameter count is invalid to the object `%1' (%2)!")}, - {"ERR_ASG_FUNC_INV_LANGUAGE", QT_TR_NOOP("Assignment of a function which language is invalid!")}, - {"ERR_ASG_EVNT_TRIG_FUNC_INV_LANG", QT_TR_NOOP("Event trigger function must be coded in any language other than SQL!")}, - {"ERR_ASG_NOT_ALOC_TABLE", QT_TR_NOOP("Assignment of not allocated table to object `%1' (%2)!")}, - {"ERR_REF_ARG_INV_INDEX", QT_TR_NOOP("Reference to an argument which index is out of argument list bounds!")}, - {"ERR_ASG_EMPTY_NAME_OBJECT", QT_TR_NOOP("Assignment of empty name to an object!")}, - {"ERR_ASG_INV_NAME_OBJECT", QT_TR_NOOP("Assignment of a name which contains invalid characters!")}, - {"ERR_ASG_LONG_NAME_OBJECT", QT_TR_NOOP("Assignment of a name which length exceeds the maximum of 63 characters!")}, - {"ERR_ASG_INV_SCHEMA_OBJECT", QT_TR_NOOP("Assignment of schema object which type is invalid!")}, - {"ERR_ASG_INV_TABLESPACE_OBJECT", QT_TR_NOOP("Assignment of tablespace object with invalid type!")}, - {"ERR_ASG_TABSPC_INV_OBJECT", QT_TR_NOOP("Assignment of tablespace to an invalid object!")}, - {"ERR_ASG_TABSPC_INV_CONSTR_TYPE", QT_TR_NOOP("Assignment of tablespace to a constraint which type is invalid! To belong to a tablespace the constraint must be a primary key or unique!")}, - {"ERR_ASG_INV_ROLE_OBJECT", QT_TR_NOOP("Assignment of owner object which type is invalid!")}, - {"ERR_ASG_ROLE_OBJECT_INV_TYPE", QT_TR_NOOP("Assignment of owner to an invalid object!")}, - {"ERR_ASG_APPSQL_OBJECT_INV_TYPE", QT_TR_NOOP("Assignment of appended or prepended SQL to an invalid object!")}, - {"ERR_REF_FUNCTION_INV_TYPE", QT_TR_NOOP("Reference to a function with invalid type!")}, - {"ERR_REF_OPER_ARG_INV_TYPE", QT_TR_NOOP("Reference to an argument of the operator with invalid type!")}, - {"ERR_REF_OPER_INV_TYPE", QT_TR_NOOP("Reference to an operator with invalid type!")}, - {"ERR_ASG_VAL_INV_ROLE_OPT_TYPE", QT_TR_NOOP("Assignment of value to an invalid option type on role!")}, - {"ERR_REF_INV_ROLE_TYPE", QT_TR_NOOP("Reference to an invalid role type!")}, - {"ERR_INS_DUPLIC_ROLE", QT_TR_NOOP("The insertion of the role `%1' is not possible because this is already being referenced by role `%2'!")}, - {"ERR_ROLE_REF_REDUNDANCY",QT_TR_NOOP("Reference redundancy detected by having the role `%1' referencing the role `%2'!")}, - {"ERR_ROLE_MEMBER_ITSELF", QT_TR_NOOP("The role `%1' can not be listed as a member of itself!")}, - {"ERR_REF_ROLE_INV_INDEX", QT_TR_NOOP("Reference to a role which index is out of role list bounds!")}, - {"ERR_INS_EMPTY_RULE_COMMAND", QT_TR_NOOP("Insertion of empty command to the rule!")}, - {"ERR_REF_RULE_CMD_INV_INDEX", QT_TR_NOOP("Reference to a command which index is out of the command list bounds!")}, - {"ERR_INV_INH_COPY_RELATIONSHIP", QT_TR_NOOP("Is not possible to create a self generalization/copy relationship! The table can not inherit or copy their own attributes!")}, - {"ERR_ASG_OBJ_BELONGS_OTHER_TABLE", QT_TR_NOOP("Assignment of an object that already belongs to another table!")}, - {"ERR_ASG_SEQ_DIF_TABLE_SCHEMA", QT_TR_NOOP("Assignment of a schema to the sequence which differs from the schema of the owner table!")}, - {"ERR_ASG_INV_VALUE_SEQ_ATTRIBS", QT_TR_NOOP("Assignment of an invalid value to one of the sequence attributes!")}, - {"ERR_ASG_INV_SEQ_MIN_VALUE", QT_TR_NOOP("Assignment of a minimum value to the sequence which is greater than the maximum value!")}, - {"ERR_ASG_INV_SEQ_START_VALUE", QT_TR_NOOP("Assignment of a start value to the sequence which is extrapolating the range defined by minimum and maximum values!")}, - {"ERR_ASG_INV_SEQ_INCR_VALUE", QT_TR_NOOP("Assignment of a null increment value to the sequence!")}, - {"ERR_ASG_INV_SEQ_CACHE_VALUE", QT_TR_NOOP("Assignment of null cache value to the sequence!")}, - {"ERR_ASG_TAB_DIF_SEQ_SCHEMA", QT_TR_NOOP("Assignment of owner table which is not in the same schema as the sequence `%1'!")}, - {"ERR_ASG_SEQ_OWNER_DIF_TABLE", QT_TR_NOOP("Assignment of owner table which does not belong to the same owner of the sequence `%1'!")}, - {"ERR_ASG_INEXIST_OWNER_COL_SEQ", QT_TR_NOOP("Assignment of a nonexistent owner column to the sequence `%1'!")}, - {"ERR_ASG_INV_OWNER_COL_SEQ", QT_TR_NOOP("Assignment of an owner column to the sequence `%1' that is not related to any table!")}, - {"ERR_REF_LABEL_INV_INDEX", QT_TR_NOOP("Reference to a label which index is out of labels list bounds!")}, - {"ERR_ALOC_OBJECT_INV_TYPE", QT_TR_NOOP("Allocation of object with invalid type!")}, - {"ERR_ASG_FUNCTION_INV_RET_TYPE", QT_TR_NOOP("Assignment of a function with invalid return type to object `%1' (%2)!")}, - {"ERR_ASG_FUNCTION_INV_PARAMS", QT_TR_NOOP("Assignment of a function with invalid parameter(s) type(s) to object `%1' (%2)!")}, - {"ERR_ASG_NOT_ALOC_LANGUAGE", QT_TR_NOOP("Assignment of not allocated language!")}, - {"ERR_ASG_INV_LANGUAGE_OBJECT", QT_TR_NOOP("Assignment of language object which type is invalid!")}, - {"ERR_REF_TYPE_INV_INDEX", QT_TR_NOOP("Reference to data type with an index outside the capacity of data types list!")}, - {"ERR_ASG_NULL_TYPE_OBJECT", QT_TR_NOOP("Assignment of a null type to object `%1' (%2)!")}, - {"ERR_ASG_INV_TYPE_OBJECT", QT_TR_NOOP("Assignment of invalid type to the object!")}, - {"ERR_ASG_EMPTY_DIR_NAME", QT_TR_NOOP("Assignment of an empty directory to object `%1' (%2)!")}, - {"ERR_OBT_TYPES_INV_QUANTITY", QT_TR_NOOP("Obtaining types with invalid quantity!")}, - {"ERR_INS_DUPLIC_ITEMS", QT_TR_NOOP("Insertion of item which already exists in the attributes list of the type!")}, - {"ERR_INS_INV_TYPE_ATTRIB", QT_TR_NOOP("Insertion of invalid item in the attributes list of the type!")}, - {"ERR_INS_DUPLIC_ENUM_ITEM", QT_TR_NOOP("Insertion of item which already exists in the enumarations list of the type!")}, - {"ERR_INS_INV_TYPE_ENUM_ITEM", QT_TR_NOOP("Insertion of invalid item in the enumerations list of the type!")}, - {"ERR_REF_ATTRIB_INV_INDEX", QT_TR_NOOP("Reference to an attribute which index is out of the attributes list bounds!")}, - {"ERR_REF_ENUM_INV_INDEX", QT_TR_NOOP("Reference to an enumeration which index is out of the enumerations list bounds!")}, - {"ERR_ASG_INV_TYPE_CONFIG", QT_TR_NOOP("Assignment of invalid configuration to the type!")}, - {"ERR_ASG_INV_OPER_ARGS", QT_TR_NOOP("Assignment of an operator which input type count is invalid to aggregate function!")}, - {"ERR_ASG_INV_OPERATOR_TYPES", QT_TR_NOOP("Assignment of an operator which types of arguments is invalid!")}, - {"ERR_ASG_RESERVED_NAME", QT_TR_NOOP("Assignment of system reserved name to the object `%1' (%2)!")}, - {"ERR_USING_INV_FUNC_CONFIG", QT_TR_NOOP("One function with invalid configuration is been used by the object `%1' (%2)!")}, - {"ERR_ASG_INV_SUPSTG_NUMBER", QT_TR_NOOP("Assignment of an invalid strategy/support number to an operator class element!")}, - {"ERR_INS_DUPLIC_ELEMENT", QT_TR_NOOP("Insertion of element which already exists in the element list!")}, - {"ERR_REF_ELEM_INV_INDEX", QT_TR_NOOP("Reference to an element which index is out of element list bounds!")}, - {"ERR_REF_OBJ_INV_INDEX", QT_TR_NOOP("Reference to an object which index is out of object list bounds!")}, - {"ERR_REM_NOT_ALOC_OBJECT", QT_TR_NOOP("Removal of an object not allocated!")}, - {"ERR_REM_DIRECT_REFERENCE", QT_TR_NOOP("The object `%1' (%2) can not be removed because it is being referenced by object `%3' (%4)!")}, - {"ERR_REM_INDIRECT_REFERENCE", QT_TR_NOOP("The object `%1' (%2) can not be removed because it is being referenced by object `%3' (%4) that belongs to `%5' (%6)!")}, - {"ERR_OPR_OBJ_INV_TYPE", QT_TR_NOOP("Operation with object(s) which type(s) is invalid!")}, - {"ERR_REF_OBJ_INV_TYPE", QT_TR_NOOP("Reference to object with invalid type!")}, - {"ERR_OPR_NOT_ALOC_OBJECT", QT_TR_NOOP("Operation with object not allocated!")}, - {"ERR_LINK_TABLES_NO_PK", QT_TR_NOOP("The creation of the relationship `%1' between the table `%2' and `%3' can not be done because one does not have a primary key. If the relationship is of the type n-n both tables must have primary keys!")}, - {"ERR_NOT_IMPL_REL_TYPE", QT_TR_NOOP("The relationship of the type 1-1 where both tables are mandatory participation is not implemented because it requires fusion between the tables that breaks the modeling done by the user!")}, - {"ERR_ASG_INV_EXPR_OBJECT", QT_TR_NOOP("Assignment of an invalid expression to the object!")}, - {"ERR_ASG_EXISTING_PK_TABLE", QT_TR_NOOP("Assignment of a primary key to a table which already has one!")}, - {"ERR_INV_IDENT_RELATIOSHIP", QT_TR_NOOP("Identifier relationship can not be created for a self relationship, relationships of the type n-n, copy or generalization!")}, - {"ERR_DUPLIC_COLS_COPY_REL", QT_TR_NOOP("Unable to create a copy relationship because the column `%1' in table `%2' already exists in table `%3'!")}, - {"ERR_INCOMP_COLS_INHERIT_REL", QT_TR_NOOP("Unable to create the generalization relationship because the column `%1' in table `%2' can not be merged with the column `%3' of table `%4' because they have incompatible types!")}, - {"ERR_INCOMP_CONSTRS_INHERIT_REL", QT_TR_NOOP("Unable to create the generalization relationship because the constraint `%1' in table `%2' can not be merged with the constraint `%3' of table `%4' due to their incompatible composition!")}, - {"ERR_ASG_OBJ_INV_REL_TYPE", QT_TR_NOOP("An attribute can not be added to a copy or generalization relationship!")}, - {"ERR_ASG_FOREIGN_KEY_REL", QT_TR_NOOP("A foreign key can not be added to a relationship because is created automatically when this is connected!")}, - {"ERR_REF_OBJ_INEXISTS_MODEL", QT_TR_NOOP("The object `%1' (%2) is referencing the object `%3' (%4) which was not found in the model!")}, - {"ERR_REF_INEXIST_USER_TYPE", QT_TR_NOOP("Reference to an user-defined data type that not exists in the model!")}, - {"ERR_ASG_INV_MAX_SIZE_OP_LIST", QT_TR_NOOP("Assignment of invalid maximum size to operation list!")}, - {"ERR_FILE_DIR_NOT_WRITTEN", QT_TR_NOOP("Unable to write the file or directory `%1'! Make sure the output directory exists, or if the user has write permissions over it!")}, - {"ERR_FILE_NOT_WRITTER_INV_DEF", QT_TR_NOOP("Unable to write the file `%1' due to one or more errors in the definition generation process!")}, - {"ERR_DUPLIC_RELATIONSHIP", QT_TR_NOOP("There is already a relationship between `%1' (%2) and `%3' (%4) in the model! When using relationships of the type generalization, copy and one-to-one there can't be other relationships linked to the pair of tables.")}, - {"ERR_INS_REL_GENS_REDUNDACY", QT_TR_NOOP("The configuration of the relationship `%1' generates a redundancy between the relationships `%2'. Redundancy on identifier or generalization/copy relationships are not accepted since they result in incorrect column spreading making the model inconsistent!")}, - {"ERR_INVALIDATED_OBJECTS", QT_TR_NOOP("One or more objects were invalidated and automatically removed because they were referencing table columns which were included through relationships and which no longer exists due to disconnection of relationships or exclusion of such generated columns!")}, - {"ERR_INV_PRIM_KEY_ALOCATION", QT_TR_NOOP("The primary key `%1' can only be allocated if declared within a block of code that defines a table or relationship!")}, - {"ERR_REF_INV_PRIVILEGE_TYPE",QT_TR_NOOP("Reference to an invalid privilege type!")}, - {"ERR_INS_DUP_ROLE_PERMISSION", QT_TR_NOOP("Insertion of a role which already exists in the role list of the permission!")}, - {"ERR_ASG_INCOMP_PRIV_OBJECT", QT_TR_NOOP("Assignment of privilege incompatible with the type of object referenced by permission!")}, - {"ERR_ASG_DUPLIC_PERMISSION", QT_TR_NOOP("There is already a permission on object `%1' (%2) which has one or more equal roles from those present on permission to be assigned to the object!")}, - {"ERR_PERM_REF_INEXIST_OBJECT", QT_TR_NOOP("A permission is referencing the object `%1' (%2) which was not found in the model!")}, - {"ERR_ALOC_OBJECT_NO_SCHEMA", QT_TR_NOOP("The object `%1' (%2) can not be created because its not being assigned to any schema!")}, - {"ERR_ASG_DUP_TABLESPACE_DIR", QT_TR_NOOP("The tablespace `%1' can not be inserted into the model because it points to the same directory as the tablespace `%2'!")}, - {"ERR_ASG_INV_DOMAIN_ARRAY", QT_TR_NOOP("It is not possible to create arrays of domains or sequences (dimension >= 1)! PostgreSQL does not yet implement this feature!")}, - {"ERR_ASG_CODE_FUNC_C_LANGUAGE", QT_TR_NOOP("The function `%1' can not get a source code as a definition because its language is set to C. Use the attributes symbol and dynamic library instead!")}, - {"ERR_ASG_FUNC_REFLIB_LANG_NOT_C", QT_TR_NOOP("The function `%1' can have the attributes symbol and dynamic library configured only if the language is set to C. For all other cases you must specify a source code that defines it in the DBMS!")}, - {"ERR_ASG_INV_COM_OPEERATOR", QT_TR_NOOP("The operator `%1' can not be assigned as a comutator of operator `%2' because it has incompatible settings!")}, - {"ERR_ASG_INV_NEG_OPERATOR", QT_TR_NOOP("The operator `%1' can not be assigned as negator of operator `%2' because it has incompatible settings!")}, - {"ERR_USER_TYPE_SELF_REFERENCE", QT_TR_NOOP("The type `%1' can not self refer in the attributes `element' or `copy type' or be used as a data type of an attribute in the configuration of a composite type!")}, - {"ERR_ASG_INV_ELEMENT_TYPE", QT_TR_NOOP("Assignment of invalid element to type `%1'!")}, - {"ERR_ASG_INV_ALIGNMENT_TYPE",QT_TR_NOOP("Assignment of invalid alignment to type `%1'!")}, - {"ERR_ASG_INV_NAME_TABLE_RELNN", QT_TR_NOOP("Assignment of invalid name to the table generated from N-N relationship!")}, - {"ERR_INV_USE_ESPECIAL_PK", QT_TR_NOOP("The relationship `%1' can not make use of the special primary key because it is marked as identifier or it is a self relationship!")}, - {"ERR_OPR_REL_INCL_OBJECT", QT_TR_NOOP("The object `%1' (%2) can not be edited or deleted because it was automatically included through a relationship! If the object is an attribute or constraint the modifications must be done on the relationship editing form.")}, - {"ERR_REM_PROTECTED_OBJECT", QT_TR_NOOP("The object `%1' (%2) can not be deleted because it is protected!")}, - {"ERR_REDECL_HL_GROUP", QT_TR_NOOP("The group `%1' has already been declared earlier!")}, - {"ERR_DEF_INV_GROUP_DECL", QT_TR_NOOP("The group `%1' can not be built in the groups declaration block (%2)!")}, - {"ERR_DEF_NOT_DECL_GROUP", QT_TR_NOOP("The group `%1' was built but not declared in the groups declaration block (%2)!")}, - {"ERR_DEF_EMPTY_GROUP", QT_TR_NOOP("The group `%1' can not be built without possessing child elements!")}, - {"ERR_DEF_DUPLIC_GROUP", QT_TR_NOOP("The group `%1' can not be built once more because this was done in previous blocks!")}, - {"ERR_GROUP_DECL_NOT_DEFINED", QT_TR_NOOP("The group `%1' has been declared but not built!")}, - {"ERR_REF_COL_OBJTAB_INV_INDEX", QT_TR_NOOP("Reference to a column of the objects table with invalid index!")}, - {"ERR_REF_LIN_OBJTAB_INV_INDEX", QT_TR_NOOP("Reference to a row of the objects table with invalid index!")}, - {"ERR_OPR_RESERVED_OBJECT", QT_TR_NOOP("The object `%1' (%2) can not be manipulated because it is reserved to PostgreSQL! This object is present in the database model only as a reference!")}, - {"ERR_FUNC_CONFIG_INV_OBJECT", QT_TR_NOOP("The new configuration of the function invalidates the object `%1' (%2)! In this case it is needed to undo the relationship between the affected object and function in order to the new configuration to take effect!")}, - {"ERR_SQL_SCOPE_INV_VIEW_REF", QT_TR_NOOP("A view reference must be used in at least one these SQL scopes: View Definition, SELECT-FROM, FROM-WHERE or After WHERE!")}, - {"ERR_CONSTR_NO_COLUMNS", QT_TR_NOOP("Constraints like primary key, foreign key or unique must have at least one column related to them! For foreign keys must be selected, in addition, the referenced columns!")}, - {"ERR_CONFIG_NOT_LOADED", QT_TR_NOOP("Unable to load the configuration file `%1'! Please check if file exists in its folder and/or if it is not corrupted!")}, - {"ERR_DEFAULT_CONFIG_NOT_REST", QT_TR_NOOP("Could not find the default settings file `%1'! To restore default settings check the existence of the file and try again!")}, - {"ERR_EXPORT_FAILURE", QT_TR_NOOP("The export process failed due to an error triggered by the PostgreSQL server in an attempt to execute a SQL command. For more details about the error check the exception stack!\n\n** Executed SQL command: **\n\n%1")}, - {"ERR_PLUGIN_NOT_LOADED", QT_TR_NOOP("Could not load the plugin `%1' from the library `%2'! Message returned by plugin manager: `%3'")}, - {"ERR_PLUGINS_NOT_LOADED", QT_TR_NOOP("One or more plugins were not activated due to errors during the loading process! Check the exception stack for more details.")}, - {"ERR_INV_SYNTAX", QT_TR_NOOP("Invalid syntax in file `%1', line %2, column %3!")}, - {"ERR_INV_INSTRUCTION", QT_TR_NOOP("Invalid instruction `%1' on file `%2', line %3, column %4!")}, - {"ERR_UNK_ATTRIBUTE", QT_TR_NOOP("Unknown attribute `%1' in file `%2', line %3, column %4!")}, - {"ERR_INV_METACHARACTER", QT_TR_NOOP("Invalid metacharacter `%1' in file `%2', line %3, column %4!")}, - {"ERR_INV_OPERATOR_IN_EXPR", QT_TR_NOOP("Invalid operator `%1' in comparison expression, file `%2', line %3, column %4!")}, - {"ERR_UNDEF_ATTRIB_VALUE", QT_TR_NOOP("Attribute `%1' with an undefined value in file `%2', line %3, column %4!")}, - {"ERR_INV_ATTRIBUTE", QT_TR_NOOP("Attribute `%1' with an invalid name in file `%2', line %3, column %4!")}, - {"ERR_ASG_EMPTY_XML_BUFFER", QT_TR_NOOP("Assignment of empty XML buffer to parser!")}, - {"ERR_FILE_DIR_NOT_ACCESSED", QT_TR_NOOP("Could not access the file or directory `%1'! Make sure that it exists or if the user has access permissions on it!")}, - {"ERR_ASG_EMPTY_DTD_FILE", QT_TR_NOOP("Assignment of empty DTD file name!")}, - {"ERR_ASG_EMPTY_DTD_NAME", QT_TR_NOOP("Assignment of empty name to the DTD declaration!")}, - {"ERR_LIBXMLERR", QT_TR_NOOP("Error while interpreting XML buffer at line %1 column %2.\nMessage generated by the parser: %3. %4")}, - {"ERR_OPR_NOT_ALOC_ELEM_TREE", QT_TR_NOOP("Operation on unallocated element tree! It is necessary to load the XML parser buffer and interpret it so that the tree is generated!")}, - {"ERR_LOAD_INV_MODEL_FILE", QT_TR_NOOP("Could not load file `%1'. The same appears to be inconsistent or one of its dependencies (DTD files) has errors or is missing!")}, - {"ERR_OPR_NOT_ALOC_ELEMENT", QT_TR_NOOP("Operation with unallocated tree element!")}, - {"ERR_OPR_INEXIST_ELEMENT", QT_TR_NOOP("Operation with element which does not exists in the element tree currently loaded!")}, - {"ERR_ASG_INV_CONN_PARAM", QT_TR_NOOP("Assignment of a value to an invalid connection parameter!")}, - {"ERR_OPR_NOT_ALOC_CONN", QT_TR_NOOP("Operation on connection not established!")}, - {"ERR_CONNECTION_NOT_CONFIGURED", QT_TR_NOOP("Attempt to connect without define configuration parameters!")}, - {"ERR_CONNECTION_ALREADY_STABLISHED", QT_TR_NOOP("Attempt to start a connection already stablished!")}, - {"ERR_CONNECTION_NOT_STABLISHED", QT_TR_NOOP("Could not connect to the database.\nMessage returned: `%1'")}, - {"ERR_ASG_SQL_RESULT_NOT_ALOC", QT_TR_NOOP("Assignment of not allocated SQL command result!")}, - {"ERR_INCOMPREHENSIBLE_DBMS_RESP", QT_TR_NOOP("Unable to allocate the result of the SQL command because the response from the DBMS was not understood by the client!")}, - {"ERR_DBMS_FATAL_ERROR", QT_TR_NOOP("Unable to allocate command result for the SQL because the server has generated a fatal error!\nMessage returned by the DBMS: `%1'")}, - {"ERR_REF_TUPLE_COL_INV_INDEX", QT_TR_NOOP("Reference to a column of tuple with invalid index!")}, - {"ERR_REF_TUPLE_COL_INV_NAME", QT_TR_NOOP("Reference to a column of tuple with invalid name!")}, - {"ERR_REF_TUPLE_INEXISTENT", QT_TR_NOOP("Reference to a tuple with an invalid index or the result is empty (no tuples)!")}, - {"ERR_REF_INV_TUPLE_COLUMN", QT_TR_NOOP("Reference to a column of a tuple which was not yet initialized (tuple navigation not started)!")}, - {"ERR_CMD_SQL_NOT_EXECUTED", QT_TR_NOOP("Could not execute the SQL command.\n Message returned: `%1'")}, - {"ERR_INV_VIEW_DEF_EXPRESSION", QT_TR_NOOP("Invalid use of a view reference as whole SQL definition! The assigned reference must be an expression!")}, - {"ERR_ASG_SEC_VIEW_DEF_EXPRESSION", QT_TR_NOOP("Assignment of a second definition expression to the view!")}, - {"ERR_MIX_VIEW_DEF_EXPR_REFS", QT_TR_NOOP("It is not possible mix ordinary references (SELECT-FROM, FROM-WHERE, After WHERE) with references used as view SQL definition!")}, - {"ERR_ASG_INV_COLLATION_OBJECT", QT_TR_NOOP("Assignment of collation object which type is invalid!")}, - {"ERR_PK_USING_COLS_ADDED_BY_REL", QT_TR_NOOP("At the moment pgModeler does not support the creation of primary keys which some columns were generated by relationship connection. To create primary keys with this feature you can use the field `Identifier' or the tab `Primary key' on relationship editing form!")}, - {"ERR_EMPTY_LOCAL_ATTRIB_COLLATION", QT_TR_NOOP("Collations must be created at least with attributes LC_COLLATE and LC_CTYPE defined!")}, - {"ERR_OBJECT_REFERENCING_ITSELF", QT_TR_NOOP("The object `%1' (%2) cannot reference itself! This operation is not permitted for this kind of object!")}, - {"ERR_ASG_INV_OPFAM_OPCLSELEM", QT_TR_NOOP("Only operator families which uses `btree' as indexing method are accepted by operator class elements!")}, - {"ERR_REF_INV_LIKE_OP_TYPE", QT_TR_NOOP("Reference to an invalid copy table option!")}, - {"ERR_COPY_REL_TAB_DEFINED", QT_TR_NOOP("Copy relationship between tables `%1' and `%2' cannot be done because the first one already copies attributes from `%3'! Tables can have only one copy table!")}, - {"ERR_TABLE_TRIG_INSTEADOF_FIRING",QT_TR_NOOP("The INSTEAD OF mode cannot be used on triggers that belongs to tables! This is available only for view triggers!")}, - {"ERR_TRIGGER_INV_TRUNCATE_USAGE",QT_TR_NOOP("The TRUNCATE event can only be used when the trigger executes for each statement and belongs to a table!")}, - {"ERR_TRIGGER_INV_INSTEADOF_USAGE",QT_TR_NOOP("The INSTEAD OF mode cannot be used on view triggers that executes for each statement!")}, - {"ERR_CONST_TRIG_NOT_AFTER_ROW",QT_TR_NOOP("Constraint triggers can only be executed on AFTER events and for each row!")}, - {"ERR_VIEW_TRIG_INV_AFTBFR_USAGE",QT_TR_NOOP("A view trigger cannot be AFTER/BEFORE when it executes for each row!")}, - {"ERR_TRIGGER_INV_INSTEADOF_UPDATE",QT_TR_NOOP("A trigger cannot make reference to columns when using INSTEAD OF mode and UPDATE event!")}, - {"ERR_ASG_COLUMN_NO_PARENT",QT_TR_NOOP("Assignment of a column which has no parent table to the object `%1' (%2)!")}, - {"ERR_TRIG_USING_CONSTRIG_ATRIBS",QT_TR_NOOP("Only constraint triggers can be deferrable or reference another table!")}, - {"ERR_REF_FUNCTION_INV_TYPE_CONF", QT_TR_NOOP("Reference to a function id which is incompatible with the user define type configuration!")}, - {"ERR_ASG_INV_OPCLASS_OBJ", QT_TR_NOOP("The operator class assigned to the object `%1' (%2) must use `btree' as indexing method!")}, - {"ERR_INV_POSTGRESQL_VERSION", QT_TR_NOOP("Unsupported PostgreSQL version (%1) detected! Valid versions are between %2 and %3.")}, - {"ERR_VALIDATION_FAILURE", QT_TR_NOOP("The validation process failed due to an error triggered by the validation helper. For more details about the error check the exception stack!")}, - {"ERR_REG_EXT_NOT_HANDLING_TYPE", QT_TR_NOOP("The extension `%1' is registered as a data type and cannot have the attribute `handles datatype' modified!")}, - {"ERR_ALOC_INV_FK_RELATIONSHIP", QT_TR_NOOP("The fk relationship `%1' cannot be created because the foreign-key that represents it was not created on table `%2'!")}, - {"ERR_ASG_INV_NAME_PATTERN", QT_TR_NOOP("Assignement of an invalid object name pattern to the relationship `%1'!")}, - {"ERR_REF_INV_NAME_PATTERN_ID", QT_TR_NOOP("Reference to an invalid object name pattern id on the relationship `%1'!")}, - {"ERR_INV_USE_VARIADIC_PARAM_MODE", QT_TR_NOOP("Invalid use of variadic parameter mode! This mode can be used only with an array or \"any\" data type!")}, - {"ERR_MIX_INCOMP_EXPORT_OPTS", QT_TR_NOOP("Mixing incompatibles DBMS export modes: `ignore object duplications', `drop database' or `drop objects' cannot be used with `simulate export'!")}, - {"ERR_MIX_INCOMP_DROP_OPTS", QT_TR_NOOP("Mixing incompatibles DROP options: `drop database' and `drop objects' cannot be used at the same time!")}, - {"ERR_INV_ID_SWAP_SAME_OBJECT", QT_TR_NOOP("Invalid object id swapping operation! The objects involved are the same!")}, - {"ERR_INV_ID_SWAP_INV_OBJ_TYPE", QT_TR_NOOP("Invalid object id swapping operation! The database itself, tablespaces or roles cannot have the ids swapped!")}, - {"ERR_ASG_WGT_ALREADY_HAS_PARENT", QT_TR_NOOP("The widget already has a parent and cannot be assigned to a different object!")}, - {"ERR_OBJECT_NOT_IMPORTED", QT_TR_NOOP("The object `%1' (%2), oid `%3', could not be imported due to one or more errors! Check the exception stack for more details. `HINT:' if the object somehow references objects in `pg_catalog' or `information_schema' consider enable the importing of system objects.")}, - {"ERR_MODEL_FILE_NOT_LOADED", QT_TR_NOOP("Could not load the database model file `%1'. Check the error stack to see details. Try to run `pgmodeler-cli --fix-model' in order to correct the structure of the file if that is the case.")}, - {"ERR_INV_COLUMN_TABLE_TYPE", QT_TR_NOOP("The column `%1' cannot reference it's parent table `%2' as data type!")}, - {"ERR_OPR_INV_ELEMENT_ID", QT_TR_NOOP("Operation with an invalid element id `%1'!")}, - {"ERR_REF_ELEMENT_COLOR_ID", QT_TR_NOOP("Reference to an invalid color id `%1' for element `%2'!")}, - {"ERR_ASG_INV_OBJECT_TYPE", QT_TR_NOOP("Assignment of an invalid object to `%1' (%2)! The assigned object must be of type `%3'.")}, - {"ERR_INCOMP_COL_TYPE_FOR_SEQ", QT_TR_NOOP("The sequence `%1' can't be assigned to the column `%2' because the data type of the latter is incompatible. The type used must be an integer one!")}, - {"ERR_INV_USE_TMPNAMES_EXPORT_OPT", QT_TR_NOOP("The option to generate temporary object names can only be used in simulation mode!")}, - {"ERR_INV_CONV_INTEGER_TO_SERIAL", QT_TR_NOOP("It's not possible convert the type of the column `%1' to serial! It must have an `integer' based type and its default value must be a call to `nextval(seq_name::regclass)' function or a sequence object must be directly assigned to the column!")}, - {"ERR_ASG_INV_EVENT_TRIGGER_VARIABLE", QT_TR_NOOP("Could not assign the variable `%1' to event trigger's filter. Currently, PostgreSQL supports only the `TAG' variable!")}, - {"ERR_ROW_DATA_NOT_MANIPULATED", QT_TR_NOOP("Could not perform the `%1' operation on `%2' using the data on row `%3'! All changes were rolled back. \n\n ** Returned error ** \n\n%4")}, - {"ERR_MALFORMED_UNESCAPED_VALUE", QT_TR_NOOP("Malformed unescaped value on row `%1' column `%2'!")}, - {"ERR_UNDO_REDO_OPR_INV_OBJECT", QT_TR_NOOP("Trying to undo/redo an invalid operation over an object that does not exists anymore or can't be handled! The operation history will be cleaned up.")}, - {"ERR_REQ_FIELDS_NOT_FILLED", QT_TR_NOOP("The object `%1' (%2) can't be handled because some needed fields are not set! Please, make sure to fill at least the requires fields in order to properly create or update the object.")}, - {"ERR_INV_REL_ID_SWAP", QT_TR_NOOP("A relationship can only be swapped by other object of the same kind!")}, - {"ERR_INV_INH_PARENT_TAB_NOT_FOUND", QT_TR_NOOP("A parent table of `%1' which OID is `%2' was not found in the set of imported objects!")}, - {"ERR_ASG_ENUM_INV_CHARS", QT_TR_NOOP("The enumeration `%1' can't be assigned to the type `%2' because contains invalid characters!")}, - {"ERR_ASG_ENUM_LONG_NAME", QT_TR_NOOP("The enumeration `%1' can't be assigned to the type `%2' because is too long!")}, - {"ERR_CONNECTION_TIMEOUT", QT_TR_NOOP("The connection was idle for too long and was automatically closed!")}, - {"ERR_CONNECTION_BROKEN", QT_TR_NOOP("The connection was unexpectedly closed by the database server `%1' at port `%2'!")}, - {"ERR_DROP_CURRDB_DEFAULT", QT_TR_NOOP("Failed to drop the database `%1' because it is defined as the default database for the connection `%2'!")}, - {"ERR_NULL_PK_COLUMN", QT_TR_NOOP("The column `%1' must be `NOT NULL' because it composes the primary key of the table `%2'. You need to remove the column from the mentioned contraint in order to disable the `NOT NULL' on it!")}, - {"ERR_ASG_INV_IDENTITY_COLUMN", QT_TR_NOOP("The identity column `%1' has an invalid data type! The data type must be `smallint', `integer' or `bigint'.")}, - {"ERR_REF_INV_AFFECTED_CMD", QT_TR_NOOP("Reference to an invalid affected command in policy `%1'!")}, - {"ERR_REF_INV_SPECIAL_ROLE", QT_TR_NOOP("Reference to an invalid special role in policy `%1'!")}, +QString Exception::messages[Exception::ErrorCount][2]={ + {"Custom", QString(" ")}, + {"AsgPseudoTypeColumn", QT_TR_NOOP("Assignment of a pseudo-type to the type of the column!")}, + {"AsgInvalidPrecision", QT_TR_NOOP("Assignment of a precision greater than the length of the type!")}, + {"AsgInvalidPrecisionTimestamp", QT_TR_NOOP("Assignment of an invalid precision to type time, timestamp or interval. The precision in this case must be equal to or less than 6!")}, + {"AsgNotAllocatedColumn", QT_TR_NOOP("Assignment of a not allocated column to object `%1' (%2)!")}, + {"RefColumnInvalidIndex", QT_TR_NOOP("Reference to a column which index is out of the capacity of the column list!")}, + {"AsgNotAllocattedObject", QT_TR_NOOP("Assignment of not allocated object!")}, + {"AsgNotAllocatedSchema", QT_TR_NOOP("Assignment of a not allocated schema to object `%1' (%2)!")}, + {"AsgObjectInvalidDefinition", QT_TR_NOOP("The object `%1' (%2) has inconsistent SQL or XML definition!")}, + {"AsgDuplicatedObject", QT_TR_NOOP("The object `%1' (%2) already exists on `%3' (%4)!")}, + {"AsgDuplicatedObjectContainer", QT_TR_NOOP("The object `%1' (%2) cannot be assigned because there is already exists in the container object `%3'!")}, + {"AsgObjectInvalidType", QT_TR_NOOP("Assigning object of an invalid type!")}, + {"RemObjectInvalidType", QT_TR_NOOP("Removing an object of an invalid type!")}, + {"ObtObjectInvalidType", QT_TR_NOOP("Obtaining an object of an invalid type!")}, + {"AsgEmptyNameTableReturnType", QT_TR_NOOP("Assignment of empty name to table return type!")}, + {"AsgDuplicatedParameterFunction", QT_TR_NOOP("The insertion of the parameter `%1' will not be possible because there is another parameter with same name in the function `%2'!")}, + {"InsDuplicatedTableReturnType", QT_TR_NOOP("The insertion of the table return type `%1' will not be possible because there is another return type with the same name in the `%2'!")}, + {"RefParameterInvalidIndex", QT_TR_NOOP("Reference to a parameter which index is out of the parameter list bounds!")}, + {"RefInvalidTriggerEvent", QT_TR_NOOP("Reference to an event which does not belongs to trigger!")}, + {"AsgInvalidColumnTrigger", QT_TR_NOOP("The column `%1' cannot be assigned to the trigger `%2' because they belongs to different parent tables!")}, + {"AsgNotAllocatedFunction", QT_TR_NOOP("Assignment of a not allocated function to object `%1' (%2)!")}, + {"AsgInvalidTriggerFunction", QT_TR_NOOP("Assignment of a function which return type is different from `%1'!")}, + {"AsgFunctionInvalidParamCount", QT_TR_NOOP("Assignment of a function which parameter count is invalid to the object `%1' (%2)!")}, + {"AsgFunctionInvalidLanguage", QT_TR_NOOP("Assignment of a function which language is invalid!")}, + {"AsgEventTriggerFuncInvalidLang", QT_TR_NOOP("Event trigger function must be coded in any language other than SQL!")}, + {"AsgNotAllocatedTable", QT_TR_NOOP("Assignment of not allocated table to object `%1' (%2)!")}, + {"RefArgumentInvalidIndex", QT_TR_NOOP("Reference to an argument which index is out of argument list bounds!")}, + {"AsgEmptyNameObject", QT_TR_NOOP("Assignment of empty name to an object!")}, + {"AsgInvalidNameObject", QT_TR_NOOP("Assignment of a name which contains invalid characters!")}, + {"AsgLongNameObject", QT_TR_NOOP("Assignment of a name which length exceeds the maximum of 63 characters!")}, + {"AsgInvalidSchemaObject", QT_TR_NOOP("Assignment of schema object which type is invalid!")}, + {"AsgInvalidTablespaceObject", QT_TR_NOOP("Assignment of tablespace object with invalid type!")}, + {"AsgTablespaceInvalidObject", QT_TR_NOOP("Assignment of tablespace to an invalid object!")}, + {"AsgTablespaceInvalidConstraintType", QT_TR_NOOP("Assignment of tablespace to a constraint which type is invalid! To belong to a tablespace the constraint must be a primary key or unique!")}, + {"AsgInvalidRoleObject", QT_TR_NOOP("Assignment of owner object which type is invalid!")}, + {"AsgRoleObjectInvalidType", QT_TR_NOOP("Assignment of owner to an invalid object!")}, + {"AsgCustomSQLObjectInvalidType", QT_TR_NOOP("Assignment of appended or prepended SQL to an invalid object!")}, + {"RefFunctionInvalidType", QT_TR_NOOP("Reference to a function with invalid type!")}, + {"RefOperatorArgumentInvalidType", QT_TR_NOOP("Reference to an argument of the operator with invalid type!")}, + {"RefOperatorInvalidType", QT_TR_NOOP("Reference to an operator with invalid type!")}, + {"AsgValueInvalidRoleOptionType", QT_TR_NOOP("Assignment of value to an invalid option type on role!")}, + {"RefInvalidRoleType", QT_TR_NOOP("Reference to an invalid role type!")}, + {"InsDuplicatedRole", QT_TR_NOOP("The insertion of the role `%1' is not possible because this is already being referenced by role `%2'!")}, + {"AsgRoleReferenceRedundancy", QT_TR_NOOP("Reference redundancy detected by having the role `%1' referencing the role `%2'!")}, + {"AsgRoleMemberItself", QT_TR_NOOP("The role `%1' can not be listed as a member of itself!")}, + {"RefRoleInvalidIndex", QT_TR_NOOP("Reference to a role which index is out of role list bounds!")}, + {"InsEmptyRuleCommand", QT_TR_NOOP("Insertion of empty command to the rule!")}, + {"RefRuleCommandInvalidIndex", QT_TR_NOOP("Reference to a command which index is out of the command list bounds!")}, + {"InvInheritCopyPartRelationship", QT_TR_NOOP("It's not possible to create a self generalization/copy/partition relationship! The table can not inherit or copy its own attributes or be a partition of itself!")}, + {"AsgObjectBelongsAnotherTable", QT_TR_NOOP("Assignment of an object that already belongs to another table!")}, + {"AsgSchemaSequenceDiffersTableSchema", QT_TR_NOOP("Assignment of a schema to the sequence which differs from the schema of the owner table!")}, + {"AsgInvalidValueSequenceAttributes", QT_TR_NOOP("Assignment of an invalid value to one of the sequence attributes!")}, + {"AsgInvalidSequenceMinValue", QT_TR_NOOP("Assignment of a minimum value to the sequence which is greater than the maximum value!")}, + {"AsgInvalidSequenceStartValue", QT_TR_NOOP("Assignment of a start value to the sequence which is extrapolating the range defined by minimum and maximum values!")}, + {"AsgInvalidSequenceIncrementValue", QT_TR_NOOP("Assignment of a null increment value to the sequence!")}, + {"AsgInvalidSequenceCacheValue", QT_TR_NOOP("Assignment of null cache value to the sequence!")}, + {"AsgSeqOwnerTableDifferentSchema", QT_TR_NOOP("Assignment of owner table which is not in the same schema as the sequence `%1'!")}, + {"AsgSeqOwnerTableDifferentRole", QT_TR_NOOP("Assignment of owner table which does not belong to the same owner of the sequence `%1'!")}, + {"AsgInexistentSeqOwnerColumn", QT_TR_NOOP("Assignment of a nonexistent owner column to the sequence `%1'!")}, + {"AsgInvalidSeqOwnerColumn", QT_TR_NOOP("Assignment of an owner column to the sequence `%1' that is not related to any table!")}, + {"RefLabelInvalidIndex", QT_TR_NOOP("Reference to a label which index is out of labels list bounds!")}, + {"AllocationObjectInvalidType", QT_TR_NOOP("Allocation of object with invalid type!")}, + {"AsgFunctionInvalidReturnType", QT_TR_NOOP("Assignment of a function with invalid return type to object `%1' (%2)!")}, + {"AsgFunctionInvalidParameters", QT_TR_NOOP("Assignment of a function with invalid parameter(s) type(s) to object `%1' (%2)!")}, + {"AsgNotAllocatedLanguage", QT_TR_NOOP("Assignment of not allocated language!")}, + {"AsgInvalidLanguageObject", QT_TR_NOOP("Assignment of language object which type is invalid!")}, + {"RefTypeInvalidIndex", QT_TR_NOOP("Reference to data type with an index outside the capacity of data types list!")}, + {"AsgNullTypeObject", QT_TR_NOOP("Assignment of a null type to object `%1' (%2)!")}, + {"AsgInvalidTypeObject", QT_TR_NOOP("Assignment of invalid type to the object!")}, + {"AsgEmptyDirectoryName", QT_TR_NOOP("Assignment of an empty directory to object `%1' (%2)!")}, + {"ObtTypesInvalidQuantity", QT_TR_NOOP("Obtaining types with invalid quantity!")}, + {"InsDuplicatedItems", QT_TR_NOOP("Insertion of item which already exists in the attributes list of the type!")}, + {"InsInvalidTypeAttribute", QT_TR_NOOP("Insertion of invalid item in the attributes list of the type!")}, + {"InsDuplicatedEnumerationItem", QT_TR_NOOP("Insertion of item which already exists in the enumarations list of the type!")}, + {"InsInvalidEnumerationItem", QT_TR_NOOP("Insertion of invalid item in the enumerations list of the type!")}, + {"RefAttributeInvalidIndex", QT_TR_NOOP("Reference to an attribute which index is out of the attributes list bounds!")}, + {"RefEnumerationInvalidIndex", QT_TR_NOOP("Reference to an enumeration which index is out of the enumerations list bounds!")}, + {"AsgInvalidTypeConfiguration", QT_TR_NOOP("Assignment of invalid configuration to the type!")}, + {"AsgInvalidOperatorArguments", QT_TR_NOOP("Assignment of an operator which input type count is invalid to aggregate function!")}, + {"AsgInvalidOperatorTypes", QT_TR_NOOP("Assignment of an operator which types of arguments is invalid!")}, + {"AsgReservedName", QT_TR_NOOP("Assignment of system reserved name to the object `%1' (%2)!")}, + {"AsgFunctionInvalidConfiguration", QT_TR_NOOP("One function with invalid configuration is been used by the object `%1' (%2)!")}, + {"AsgInvalidSupportStrategyNumber", QT_TR_NOOP("Assignment of an invalid strategy/support number to an operator class element!")}, + {"InsDuplicatedElement", QT_TR_NOOP("Insertion of element which already exists in the element list!")}, + {"RefElementInvalidIndex", QT_TR_NOOP("Reference to an element which index is out of element list bounds!")}, + {"RefObjectInvalidIndex", QT_TR_NOOP("Reference to an object which index is out of object list bounds!")}, + {"RemNotAllocatedObject", QT_TR_NOOP("Removal of an object not allocated!")}, + {"RemDirectReference", QT_TR_NOOP("The object `%1' (%2) can not be removed because it is being referenced by object `%3' (%4)!")}, + {"RemInderectReference", QT_TR_NOOP("The object `%1' (%2) can not be removed because it is being referenced by object `%3' (%4) that belongs to `%5' (%6)!")}, + {"OprObjectInvalidType", QT_TR_NOOP("Operation with object(s) which type(s) is invalid!")}, + {"RefObjectInvalidType", QT_TR_NOOP("Reference to object with invalid type!")}, + {"OprNotAllocatedObject", QT_TR_NOOP("Operation with object not allocated!")}, + {"InvLinkTablesNoPrimaryKey", QT_TR_NOOP("The creation of the relationship `%1' between the table `%2' and `%3' can not be done because one does not have a primary key. If the relationship is of the type n-n both tables must have primary keys!")}, + {"NotImplementedRelationshipType", QT_TR_NOOP("The relationship of the type 1-1 where both tables are mandatory participation is not implemented because it requires fusion between the tables that breaks the modeling done by the user!")}, + {"AsgInvalidExpressionObject", QT_TR_NOOP("Assignment of an invalid expression to the object!")}, + {"AsgExistingPrimaryKeyTable", QT_TR_NOOP("Assignment of a primary key to a table which already has one!")}, + {"InvIdentifierRelationship", QT_TR_NOOP("Identifier relationship can not be created for a self relationship, relationships of the type n-n, copy or generalization!")}, + {"InvCopyRelationshipDuplicCols", QT_TR_NOOP("Unable to create a copy relationship because the column `%1' in table `%2' already exists in table `%3'!")}, + {"InvInheritRelationshipIncompCols", QT_TR_NOOP("Unable to create the generalization relationship because the column `%1' in table `%2' can not be merged with the column `%3' of table `%4' because they have incompatible types!")}, + {"InvInheritRelationshipIncompConstrs", QT_TR_NOOP("Unable to create the generalization relationship because the constraint `%1' in table `%2' can not be merged with the constraint `%3' of table `%4' due to their incompatible composition!")}, + {"AsgObjectInvalidRelationshipType", QT_TR_NOOP("An attribute can not be added to a copy, generalization or partitioning relationship!")}, + {"AsgForeignKeyRelationship", QT_TR_NOOP("A foreign key can not be added to a relationship because is created automatically when this is connected!")}, + {"RefObjectInexistsModel", QT_TR_NOOP("The object `%1' (%2) is referencing the object `%3' (%4) which was not found in the model!")}, + {"RefUserTypeInexistsModel", QT_TR_NOOP("Reference to an user-defined data type that not exists in the model!")}, + {"AsgInvalidMaxSizeOpList", QT_TR_NOOP("Assignment of invalid maximum size to operation list!")}, + {"FileDirectoryNotWritten", QT_TR_NOOP("Unable to write the file or directory `%1'! Make sure the output directory exists, or if the user has write permissions over it!")}, + {"FileNotWrittenInvalidDefinition", QT_TR_NOOP("Unable to write the file `%1' due to one or more errors in the definition generation process!")}, + {"InsDuplicatedRelationship", QT_TR_NOOP("There is already a relationship between `%1' (%2) and `%3' (%4) in the model! When using relationships of the type generalization, copy and one-to-one there can't be other relationships linked to the pair of tables.")}, + {"InsRelationshipRedundancy", QT_TR_NOOP("The configuration of the relationship `%1' generates a redundancy between the relationships `%2'. Redundancy on identifier or generalization/copy relationships are not accepted since they result in incorrect column spreading making the model inconsistent!")}, + {"RemInvalidatedObjects", QT_TR_NOOP("One or more objects were invalidated and automatically removed because they were referencing table columns which were included through relationships and which no longer exists due to disconnection of relationships or exclusion of such generated columns!")}, + {"InvPrimaryKeyAllocation", QT_TR_NOOP("The primary key `%1' can only be allocated if declared within a block of code that defines a table or relationship!")}, + {"RefInvalidPrivilegeType", QT_TR_NOOP("Reference to an invalid privilege type!")}, + {"InsDuplicatedRolePermission", QT_TR_NOOP("Insertion of a role which already exists in the role list of the permission!")}, + {"AsgInvalidPrivilegeObject", QT_TR_NOOP("Assignment of privilege incompatible with the type of object referenced by permission!")}, + {"AsgDuplicatedPermission", QT_TR_NOOP("There is already a permission on object `%1' (%2) which has one or more equal roles from those present on permission to be assigned to the object!")}, + {"PermissionRefInexistObject", QT_TR_NOOP("A permission is referencing the object `%1' (%2) which was not found in the model!")}, + {"InvObjectAllocationNoSchema", QT_TR_NOOP("The object `%1' (%2) can not be created because its not being assigned to any schema!")}, + {"AsgTablespaceDuplicatedDirectory", QT_TR_NOOP("The tablespace `%1' can not be inserted into the model because it points to the same directory as the tablespace `%2'!")}, + {"AsgInvalidSequenceTypeArray", QT_TR_NOOP("It is not possible to create arrays sequences (dimension >= 1)! PostgreSQL does not yet implement this feature!")}, + {"AsgSourceCodeFuncCLanguage", QT_TR_NOOP("The function `%1' can not get a source code as a definition because its language is set to C. Use the attributes symbol and dynamic library instead!")}, + {"AsgRefLibraryFuncLanguageNotC", QT_TR_NOOP("The function `%1' can have the attributes symbol and dynamic library configured only if the language is set to C. For all other cases you must specify a source code that defines it in the DBMS!")}, + {"AsgInvalidCommutatorOperator", QT_TR_NOOP("The operator `%1' can not be assigned as a commutator of operator `%2' because it has incompatible settings!")}, + {"AsgInvalidNegatorOperator", QT_TR_NOOP("The operator `%1' can not be assigned as negator of operator `%2' because it has incompatible settings!")}, + {"InvUserTypeSelfReference", QT_TR_NOOP("The type `%1' can not self refer in the attributes `element' or `copy type' or be used as a data type of an attribute in the configuration of a composite type!")}, + {"AsgInvalidElementType", QT_TR_NOOP("Assignment of invalid element to type `%1'!")}, + {"AsgInvalidAlignmentType", QT_TR_NOOP("Assignment of invalid alignment to type `%1'!")}, + {"AsgInvalidNameTableRelNN", QT_TR_NOOP("Assignment of invalid name to the table generated from N-N relationship!")}, + {"InvUseSpecialPrimaryKey", QT_TR_NOOP("The relationship `%1' can not make use of the special primary key because it is marked as identifier or it is a self relationship!")}, + {"OprRelationshipAddedObject", QT_TR_NOOP("The object `%1' (%2) can not be edited or deleted because it was automatically included through a relationship! If the object is an attribute or constraint the modifications must be done on the relationship editing form.")}, + {"RemProtectedObject", QT_TR_NOOP("The object `%1' (%2) can not be deleted because it is protected!")}, + {"InvRedeclarationGroup", QT_TR_NOOP("The group `%1' has already been declared earlier!")}, + {"InvGroupDeclaration", QT_TR_NOOP("The group `%1' can not be built in the groups declaration block (%2)!")}, + {"DefNotDeclaredGroup", QT_TR_NOOP("The group `%1' was built but not declared in the groups declaration block (%2)!")}, + {"DefEmptyGroup", QT_TR_NOOP("The group `%1' can not be built without possessing child elements!")}, + {"DefDuplicatedGroup", QT_TR_NOOP("The group `%1' can not be built once more because this was done in previous blocks!")}, + {"InvGroupDeclarationNotDefined", QT_TR_NOOP("The group `%1' has been declared but not built!")}, + {"RefColObjectTabInvalidIndex", QT_TR_NOOP("Reference to a column of the objects table with invalid index!")}, + {"RefRowObjectTabInvalidIndex", QT_TR_NOOP("Reference to a row of the objects table with invalid index!")}, + {"OprReservedObject", QT_TR_NOOP("The object `%1' (%2) can not be manipulated because it is reserved to PostgreSQL! This object is present in the database model only as a reference!")}, + {"InvFuncConfigInvalidatesObject", QT_TR_NOOP("The new configuration of the function invalidates the object `%1' (%2)! In this case it is needed to undo the relationship between the affected object and function in order to the new configuration to take effect!")}, + {"InvSQLScopeViewReference", QT_TR_NOOP("A view reference should be used in at least one of these SQL scopes: View Definition, SELECT, FROM, WHERE or GROUP/HAVING!")}, + {"InvConstratintNoColumns", QT_TR_NOOP("Constraints like primary key, foreign key or unique must have at least one column related to them! For foreign keys must be selected, in addition, the referenced columns!")}, + {"ConfigurationNotLoaded", QT_TR_NOOP("Unable to load the configuration file `%1'! Please check if file exists in its folder and/or if it is not corrupted!")}, + {"DefaultConfigNotRestored", QT_TR_NOOP("Could not find the default settings file `%1'! To restore default settings check the existence of the file and try again!")}, + {"ExportFailure", QT_TR_NOOP("The export process failed due to an error triggered by the PostgreSQL server in an attempt to execute a SQL command. For more details about the error check the exception stack!\n\n** Executed SQL command: **\n\n%1")}, + {"PluginNotLoaded", QT_TR_NOOP("Could not load the plugin `%1' from the library `%2'! Message returned by plugin manager: `%3'")}, + {"PluginsNotLoaded", QT_TR_NOOP("One or more plugins were not activated due to errors during the loading process! Check the exception stack for more details.")}, + {"InvalidSyntax", QT_TR_NOOP("Invalid syntax in file `%1', line %2, column %3!")}, + {"InvalidInstruction", QT_TR_NOOP("Invalid instruction `%1' on file `%2', line %3, column %4!")}, + {"UnkownAttribute", QT_TR_NOOP("Unknown attribute `%1' in file `%2', line %3, column %4!")}, + {"InvalidMetacharacter", QT_TR_NOOP("Invalid metacharacter `%1' in file `%2', line %3, column %4!")}, + {"InvalidOperatorInExpression", QT_TR_NOOP("Invalid operator `%1' in comparison expression, file `%2', line %3, column %4!")}, + {"UndefinedAttributeValue", QT_TR_NOOP("Attribute `%1' with an undefined value in file `%2', line %3, column %4!")}, + {"InvalidAttribute", QT_TR_NOOP("Attribute `%1' with an invalid name in file `%2', line %3, column %4!")}, + {"AsgEmptyXMLBuffer", QT_TR_NOOP("Assignment of empty XML buffer to parser!")}, + {"FileDirectoryNotAccessed", QT_TR_NOOP("Could not access the file or directory `%1'! Make sure that it exists or if the user has access permissions on it!")}, + {"AsgEmptyDTDFile", QT_TR_NOOP("Assignment of empty DTD file name!")}, + {"AsgEmptyDTDName", QT_TR_NOOP("Assignment of empty name to the DTD declaration!")}, + {"LibXMLError", QT_TR_NOOP("Error while interpreting XML buffer at line %1 column %2.\nMessage generated by the parser: %3. %4")}, + {"OprNotAllocatedElementTree", QT_TR_NOOP("Operation on unallocated element tree! It is necessary to load the XML parser buffer and interpret it so that the tree is generated!")}, + {"InvModelFileNotLoaded", QT_TR_NOOP("Could not load file `%1'. The same appears to be inconsistent or one of its dependencies (DTD files) has errors or is missing!")}, + {"OprNotAllocatedElement", QT_TR_NOOP("Operation with unallocated tree element!")}, + {"OprInexistentElement", QT_TR_NOOP("Operation with element which does not exists in the element tree currently loaded!")}, + {"AsgInvalidConnParameter", QT_TR_NOOP("Assignment of a value to an invalid connection parameter!")}, + {"OprNotAllocatedConnection", QT_TR_NOOP("Operation on connection not established!")}, + {"ConnectionNotConfigured", QT_TR_NOOP("Attempt to connect without define configuration parameters!")}, + {"ConnectionAlreadyStablished", QT_TR_NOOP("Attempt to start a connection already stablished!")}, + {"ConnectionNotStablished", QT_TR_NOOP("Could not connect to the database.\nMessage returned: `%1'")}, + {"AsgNotAllocatedSQLResult", QT_TR_NOOP("Assignment of not allocated SQL command result!")}, + {"IncomprehensibleDBMSResponse", QT_TR_NOOP("Unable to allocate the result of the SQL command because the response from the DBMS was not understood by the client!")}, + {"DBMSFatalError", QT_TR_NOOP("Unable to allocate command result for the SQL because the server has generated a fatal error!\nMessage returned by the DBMS: `%1'")}, + {"RefTupleColumnInvalidIndex", QT_TR_NOOP("Reference to a column of tuple with invalid index!")}, + {"RefTupleColumnInvalidName", QT_TR_NOOP("Reference to a column of tuple with invalid name!")}, + {"RefInvalidTuple", QT_TR_NOOP("Reference to a tuple with an invalid index or the result is empty (no tuples)!")}, + {"RefInvalidTupleColumn", QT_TR_NOOP("Reference to a column of a tuple which was not yet initialized (tuple navigation not started)!")}, + {"SQLCommandNotExecuted", QT_TR_NOOP("Could not execute the SQL command.\n Message returned: `%1'")}, + {"AsgInvalidViewDefExpression", QT_TR_NOOP("Invalid use of a view reference as whole SQL definition! The assigned reference must be an expression!")}, + {"AsgSecondViewDefExpression", QT_TR_NOOP("Assignment of a second definition expression to the view!")}, + {"MixingViewDefExprsReferences", QT_TR_NOOP("It is not possible mix ordinary references (SELECT-FROM, FROM-WHERE, After WHERE) with references used as view SQL definition!")}, + {"AsgInvalidCollationObject", QT_TR_NOOP("Assignment of collation object which type is invalid!")}, + {"UnsupportedPKColsAddedByRel", QT_TR_NOOP("At the moment pgModeler does not support the creation of primary keys which some columns were generated by relationship connection. To create primary keys with this feature you can use the field `Identifier' or the tab `Primary key' on relationship editing form!")}, + {"EmptyLCCollationAttributes", QT_TR_NOOP("Collations must be created at least with attributes LC_COLLATE and LC_CTYPE defined!")}, + {"ObjectReferencingItself", QT_TR_NOOP("The object `%1' (%2) cannot reference itself! This operation is not permitted for this kind of object!")}, + {"AsgInvalidOpFamilyOpClassElem", QT_TR_NOOP("Only operator families which uses `btree' as indexing method are accepted by operator class elements!")}, + {"RefInvalidLikeOptionType", QT_TR_NOOP("Reference to an invalid copy table option!")}, + {"InvCopyRelTableDefined", QT_TR_NOOP("The copy relationship between the tables `%1' and `%2' cannot be done because the first one already copies attributes from `%3'! Tables can have only one copy table!")}, + {"InvPartRelPartitionedDefined", QT_TR_NOOP("The paritioning relationship between the tables `%1' and `%2' cannot be done because the first one is already a partition of the table `%3'! Partition tables can be participating of only one partition hierarchy at a time!")}, + {"InvRelTypeForPatitionTables", QT_TR_NOOP("The relationship between the tables `%1' and `%2' can't be created because the first entity is part of a partitioning hierachy! The table `%3' can't be used in `generalization', `copy' and `one-to-one' relationships. In `one-to-many' and `many-to-many' relationships the mentioned table can't be referenced by the generated foreign key(s).")}, + {"InvTableTriggerInsteadOfFiring", QT_TR_NOOP("The INSTEAD OF mode cannot be used on triggers that belongs to tables! This is available only for view triggers!")}, + {"InvUsageTruncateOnTrigger", QT_TR_NOOP("The TRUNCATE event can only be used when the trigger executes for each statement and belongs to a table!")}, + {"InvUsageInsteadOfOnTrigger", QT_TR_NOOP("The INSTEAD OF mode cannot be used on view triggers that executes for each statement!")}, + {"InvConstrTriggerNotAfterRow", QT_TR_NOOP("Constraint triggers can only be executed on AFTER events and for each row!")}, + {"InvUsageAfterBeforeViewTrigger", QT_TR_NOOP("A view trigger cannot be AFTER/BEFORE when it executes for each row!")}, + {"InvUsageInsteadOfUpdateTrigger", QT_TR_NOOP("A trigger cannot make reference to columns when using INSTEAD OF mode and UPDATE event!")}, + {"AsgColumnNoParent", QT_TR_NOOP("Assignment of a column which has no parent table to the object `%1' (%2)!")}, + {"InvUseConstraintTriggerAttribs", QT_TR_NOOP("Only constraint triggers can be deferrable or reference another table!")}, + {"RefInvalidFunctionIdTypeConfig", QT_TR_NOOP("Reference to a function id which is incompatible with the user define type configuration!")}, + {"AsgInvalidOpClassObject", QT_TR_NOOP("The operator class assigned to the object `%1' (%2) must use `btree' as indexing method!")}, + {"InvPostgreSQLVersion", QT_TR_NOOP("Unsupported PostgreSQL version (%1) detected! Valid versions are between %2 and %3.")}, + {"ValidationFailure", QT_TR_NOOP("The validation process failed due to an error triggered by the validation helper. For more details about the error check the exception stack!")}, + {"ExtensionHandlingTypeImmutable", QT_TR_NOOP("The extension `%1' is registered as a data type and cannot have the attribute `handles datatype' modified!")}, + {"InvAllocationFKRelationship", QT_TR_NOOP("The fk relationship `%1' cannot be created because the foreign-key that represents it was not created on table `%2'!")}, + {"AsgInvalidNamePattern", QT_TR_NOOP("Assignement of an invalid object name pattern to the relationship `%1'!")}, + {"RefInvalidNamePatternId", QT_TR_NOOP("Reference to an invalid object name pattern id on the relationship `%1'!")}, + {"InvUsageVariadicParamMode", QT_TR_NOOP("Invalid use of variadic parameter mode! This mode can be used only with an array or \"any\" data type!")}, + {"MixingIncompExportOptions", QT_TR_NOOP("Mixing incompatibles DBMS export modes: `ignore object duplications', `drop database' or `drop objects' cannot be used with `simulate export'!")}, + {"MixingIncompDropOptions", QT_TR_NOOP("Mixing incompatibles DROP options: `drop database' and `drop objects' cannot be used at the same time!")}, + {"InvIdSwapSameObject", QT_TR_NOOP("Invalid object id swapping operation! The objects involved are the same!")}, + {"InvIdSwapInvalidObjectType", QT_TR_NOOP("Invalid object id swapping operation! The database itself, tablespaces or roles cannot have the ids swapped!")}, + {"AsgWidgetAlreadyHasParent", QT_TR_NOOP("The widget already has a parent and cannot be assigned to a different object!")}, + {"ObjectNotImported", QT_TR_NOOP("The object `%1' (%2), oid `%3', could not be imported due to one or more errors! Check the exception stack for more details. `HINT:' if the object somehow references objects in `pg_catalog' or `information_schema' consider enable the importing of system objects.")}, + {"ModelFileNotLoaded", QT_TR_NOOP("Could not load the database model file `%1'. Check the error stack to see details. Try to run `pgmodeler-cli --fix-model' in order to correct the structure of the file if that is the case.")}, + {"InvColumnTableType", QT_TR_NOOP("The column `%1' cannot reference it's parent table `%2' as data type!")}, + {"OprInvalidElementId", QT_TR_NOOP("Operation with an invalid element id `%1'!")}, + {"RefInvalidElementColorId", QT_TR_NOOP("Reference to an invalid color id `%1' for element `%2'!")}, + {"AsgInvalidObjectType", QT_TR_NOOP("Assignment of an invalid object to `%1' (%2)! The assigned object must be of type `%3'.")}, + {"IncompColumnTypeForSequence", QT_TR_NOOP("The sequence `%1' can't be assigned to the column `%2' because the data type of the latter is incompatible. The type used must be an integer one!")}, + {"InvUsageTempNamesExportOption", QT_TR_NOOP("The option to generate temporary object names can only be used in simulation mode!")}, + {"InvConversionIntegerToSerial", QT_TR_NOOP("It's not possible convert the type of the column `%1' to serial! It must have an `integer' based type and its default value must be a call to `nextval(seq_name::regclass)' function or a sequence object must be directly assigned to the column!")}, + {"AsgInvalidEventTriggerVariable", QT_TR_NOOP("Could not assign the variable `%1' to event trigger's filter. Currently, PostgreSQL supports only the `TAG' variable!")}, + {"RowDataNotManipulated", QT_TR_NOOP("Could not perform the `%1' operation on `%2' using the data on row `%3'! All changes were rolled back. \n\n ** Returned error ** \n\n%4")}, + {"MalformedUnescapedValue", QT_TR_NOOP("Malformed unescaped value on row `%1' column `%2'!")}, + {"UndoRedoOperationInvalidObject", QT_TR_NOOP("Trying to undo/redo an invalid operation over an object that does not exists anymore or can't be handled! The operation history will be cleaned up.")}, + {"RequiredFieldsNotFilled", QT_TR_NOOP("The object `%1' (%2) can't be handled because some needed fields are not set! Please, make sure to fill at least the requires fields in order to properly create or update the object.")}, + {"InvRelationshipIdSwap", QT_TR_NOOP("A relationship can only be swapped by other object of the same kind!")}, + {"InvInheritParentTableNotFound", QT_TR_NOOP("A parent table of `%1' which OID is `%2' was not found in the set of imported objects!")}, + {"AsgEnumInvalidChars", QT_TR_NOOP("The enumeration `%1' can't be assigned to the type `%2' because contains invalid characters!")}, + {"AsgEnumLongName", QT_TR_NOOP("The enumeration `%1' can't be assigned to the type `%2' because is too long!")}, + {"ConnectionTimeout", QT_TR_NOOP("The connection was idle for too long and was automatically closed!")}, + {"ConnectionBroken", QT_TR_NOOP("The connection was unexpectedly closed by the database server `%1' at port `%2'!")}, + {"DropCurrentDBDefault", QT_TR_NOOP("Failed to drop the database `%1' because it is defined as the default database for the connection `%2'!")}, + {"NullPrimaryKeyColumn", QT_TR_NOOP("The column `%1' must be `NOT NULL' because it composes the primary key of the table `%2'. You need to remove the column from the mentioned contraint in order to disable the `NOT NULL' on it!")}, + {"InvalidIdentityColumn", QT_TR_NOOP("The identity column `%1' has an invalid data type! The data type must be `smallint', `integer' or `bigint'.")}, + {"RefInvalidAffectedCommand", QT_TR_NOOP("Reference to an invalid affected command in policy `%1'!")}, + {"RefInvalidSpecialRole", QT_TR_NOOP("Reference to an invalid special role in policy `%1'!")}, + {"InvColumnCountPartRel", QT_TR_NOOP("Unable to create a partition relationship because the partion table `%1' is not empty or has columns that are not present on the partitioned table `%2'!")}, + {"InvPartitioningTypePartRel", QT_TR_NOOP("Unable to create a partition relationship between the tables `%1' (partition) and `%2' (partitioned) because no partitioning type is defined on the latter!")}, + {"InvPartitionKeyCount", QT_TR_NOOP("Invalid amount of partition keys being assinged to the table `%1'! Multiples partition keys are allowed only on `HASH' and `RANGE' partitioning strategies.")}, + {"PartKeyObjectInexistsModel", QT_TR_NOOP("A partition key of the table `%1' is referencing the object `%3' (%4) which was not found in the model!")}, + {"AsgInvalidColumnPartitionKey", QT_TR_NOOP("The column `%1' can't be assigned to a partition key because it was created by a relatinship and this kind of operation is not yet supported! HINT: create the column manually on the table and then create the partition key using it.")}, + {"RemColumnRefByPartitionKey", QT_TR_NOOP("The column `%1' on the table `%2' can't be removed because it is being referenced by one or more patition keys!")}, + {"AsgOptionInvalidName", QT_TR_NOOP("Assignment of an option to the object with an invalid name!")}, + {"AsgInvalidNameObjReference", QT_TR_NOOP("Assignment of an invalid name to the object reference!")}, + {"AsgNotAllocatedObjectReference", QT_TR_NOOP("Assignment of a not allocated object to the object reference!")}, + {"InsDuplicatedObjectReference", QT_TR_NOOP("The object reference name `%1' is already defined!")}, + {"ModelFileInvalidSize", QT_TR_NOOP("A zero-byte file was detected while saving to `%1'. In order to avoid data loss the original contents of the file prior to the last saving was restored and a security copy kept on `%2'. You can copy that backup file to a safe place as a last resort to avoid the complete data loss! Note that the backup file will be erased when the application is closed.")} }; Exception::Exception(void) { - configureException(QString(),ERR_CUSTOM,QString(),QString(),-1,QString()); + configureException(QString(),ErrorCode::Custom,QString(),QString(),-1,QString()); } Exception::Exception(const QString &msg, const QString &method, const QString &file, int line, Exception *exception, const QString &extra_info) { - configureException(msg,ERR_CUSTOM, method, file, line, extra_info); + configureException(msg,ErrorCode::Custom, method, file, line, extra_info); if(exception) addException(*exception); } -Exception::Exception(ErrorType error_type, const QString &method, const QString &file, int line, Exception *exception, const QString &extra_info) +Exception::Exception(ErrorCode error_code, const QString &method, const QString &file, int line, Exception *exception, const QString &extra_info) { /* Because the Exception class is not derived from QObject the function tr() is inefficient to translate messages so the translation method is called directly from the application specifying the context (Exception) in the ts file and the text to be translated */ - configureException(QApplication::translate("Exception",messages[error_type][ERROR_MESSAGE].toStdString().c_str(),"", -1), - error_type, method, file, line, extra_info); + configureException(QApplication::translate("Exception",messages[enum_cast(error_code)][ErrorMessage].toStdString().c_str(),"", -1), + error_code, method, file, line, extra_info); if(exception) addException(*exception); } -Exception::Exception(const QString &msg, ErrorType error_type, const QString &method, const QString &file, int line, Exception *exception, const QString &extra_info) +Exception::Exception(const QString &msg, ErrorCode error_code, const QString &method, const QString &file, int line, Exception *exception, const QString &extra_info) { - configureException(msg,error_type, method, file, line, extra_info); + configureException(msg,error_code, method, file, line, extra_info); if(exception) addException(*exception); } -Exception::Exception(ErrorType error_type, const QString &method, const QString &file, int line, vector &exceptions, const QString &extra_info) +Exception::Exception(ErrorCode error_code, const QString &method, const QString &file, int line, vector &exceptions, const QString &extra_info) { vector::iterator itr, itr_end; /* Because the Exception class is not derived from QObject the function tr() is inefficient to translate messages so the translation method is called directly from the application specifying the context (Exception) in the ts file and the text to be translated */ - configureException(QApplication::translate("Exception",messages[error_type][ERROR_MESSAGE].toStdString().c_str(),"",-1), - error_type, method, file, line, extra_info); + configureException(QApplication::translate("Exception",messages[enum_cast(error_code)][ErrorMessage].toStdString().c_str(),"",-1), + error_code, method, file, line, extra_info); itr=exceptions.begin(); itr_end=exceptions.end(); @@ -305,7 +318,7 @@ Exception::Exception(const QString &msg, const QString &method, const QString &f { vector::iterator itr, itr_end; - configureException(msg,ERR_CUSTOM, method, file, line, extra_info); + configureException(msg,ErrorCode::Custom, method, file, line, extra_info); itr=exceptions.begin(); itr_end=exceptions.end(); @@ -316,11 +329,11 @@ Exception::Exception(const QString &msg, const QString &method, const QString &f } } -Exception::Exception(const QString &msg, ErrorType error_type, const QString &method, const QString &file, int line, vector &exceptions, const QString &extra_info) +Exception::Exception(const QString &msg, ErrorCode error_code, const QString &method, const QString &file, int line, vector &exceptions, const QString &extra_info) { vector::iterator itr=exceptions.begin(); - configureException(msg,error_type, method, file, line, extra_info); + configureException(msg,error_code, method, file, line, extra_info); while(itr!=exceptions.end()) { @@ -329,9 +342,9 @@ Exception::Exception(const QString &msg, ErrorType error_type, const QString &me } } -void Exception::configureException(const QString &msg, ErrorType error_type, const QString &method, const QString &file, int line, const QString &extra_info) +void Exception::configureException(const QString &msg, ErrorCode error_code, const QString &method, const QString &file, int line, const QString &extra_info) { - this->error_type=error_type; + this->error_code=error_code; this->error_msg=msg; this->method=method; this->file=file; @@ -344,21 +357,21 @@ QString Exception::getErrorMessage(void) return(error_msg); } -QString Exception::getErrorMessage(ErrorType error_type) +QString Exception::getErrorMessage(ErrorCode error_code) { - if(error_type < ERROR_COUNT) + if(enum_cast(error_code) < ErrorCount) /* Because the Exception class is not derived from QObject the function tr() is inefficient to translate messages so the translation method is called directly from the application specifying the context (Exception) in the ts file and the text to be translated */ - return(QApplication::translate("Exception",messages[error_type][ERROR_MESSAGE].toStdString().c_str(),"", -1)); + return(QApplication::translate("Exception", messages[enum_cast(error_code)][ErrorMessage].toStdString().c_str(), "", -1)); else return(QString()); } -QString Exception::getErrorCode(ErrorType error_type) +QString Exception::getErrorCode(ErrorCode error_code) { - if(error_type < ERROR_COUNT) - return(messages[error_type][ERROR_CODE]); + if(enum_cast(error_code) < ErrorCount) + return(messages[enum_cast(error_code)][ErrorCodeId]); else return(QString()); } @@ -378,9 +391,9 @@ QString Exception::getLine(void) return(QString("%1").arg(line)); } -ErrorType Exception::getErrorType(void) +ErrorCode Exception::getErrorCode(void) { - return(error_type); + return(error_code); } QString Exception::getExtraInfo(void) @@ -397,19 +410,19 @@ void Exception::addException(Exception &exception) while(itr!=itr_end) { - this->exceptions.push_back(Exception(itr->error_msg,itr->error_type, + this->exceptions.push_back(Exception(itr->error_msg,itr->error_code, itr->method,itr->file,itr->line,nullptr,itr->extra_info)); itr++; } exception.exceptions.clear(); - this->exceptions.push_back(Exception(exception.error_msg,exception.error_type, + this->exceptions.push_back(Exception(exception.error_msg,exception.error_code, exception.method,exception.file,exception.line,nullptr,exception.extra_info)); } void Exception::getExceptionsList(vector &list) { list.assign(this->exceptions.begin(), this->exceptions.end()); - list.push_back(Exception(this->error_msg,this->error_type, + list.push_back(Exception(this->error_msg,this->error_code, this->method,this->file,this->line,nullptr,this->extra_info)); } @@ -431,7 +444,7 @@ QString Exception::getExceptionsText(void) { exceptions_txt+=QString("[%1] %2 (%3)\n").arg(idx).arg(itr->getFile()).arg(itr->getLine()); exceptions_txt+=QString(" %1\n").arg(itr->getMethod()); - exceptions_txt+=QString(" [%1] %2\n").arg(Exception::getErrorCode(itr->getErrorType())).arg(itr->getErrorMessage()); + exceptions_txt+=QString(" [%1] %2\n").arg(Exception::getErrorCode(itr->getErrorCode())).arg(itr->getErrorMessage()); if(!itr->getExtraInfo().isEmpty()) exceptions_txt+=QString(" ** %1\n\n").arg(itr->getExtraInfo()); diff --git a/libutils/src/exception.h b/libutils/src/exception.h index 24682bbc44..7dee6d4fa1 100644 --- a/libutils/src/exception.h +++ b/libutils/src/exception.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -27,278 +27,288 @@ #define EXCEPTION_H #include +#include "doublenan.h" #include #include #include #include +#include using namespace std; -/* - ErrorType enum format: ERR_[[OPERATION_CODE][ERROR_CODE]] where: - - OPERATION_CODE is composed as: - INS=Insertion - ASG=Assignment - REF=Reference - REM=Removing - RES=Restoration - OBT=Obtaining -*/ +//! \brief This function causes the provided enum to be converted to its underlying datatype +template +constexpr std::underlying_type_t enum_cast (Enum obj_type) noexcept +{ + return(static_cast>(obj_type)); +} -enum ErrorType { - ERR_CUSTOM, - ERR_ASG_PSDTYPE_COLUMN, - ERR_ASG_INV_PRECISION, - ERR_ASG_INV_PREC_TIMESTAMP, - ERR_ASG_NOT_ALOC_COLUMN, - ERR_REF_COLUMN_INV_INDEX, - ERR_ASG_NOT_ALOC_OBJECT, - ERR_ASG_NOT_ALOC_SCHEMA, - ERR_ASG_OBJ_INV_DEFINITION, - ERR_ASG_DUPLIC_OBJECT, - ERR_ASG_DUPL_OBJ_CONTAINER, - ERR_ASG_OBJECT_INV_TYPE, - ERR_REM_OBJ_INVALID_TYPE, - ERR_OBT_OBJ_INVALID_TYPE, - ERR_ASG_EMPTY_NAME_RET_TABLE, - ERR_ASG_DUPLIC_PARAM_FUNCTION, - ERR_INS_DUPLIC_RET_TAB_TYPE, - ERR_REF_PARAM_INV_INDEX, - ERR_REF_INV_TRIGGER_EVENT, - ERR_ASG_INV_COLUMN_TRIGGER, - ERR_ASG_NOT_ALOC_FUNCTION, - ERR_ASG_INV_TRIGGER_FUNCTION, - ERR_ASG_FUNC_INV_PARAM_COUNT, - ERR_ASG_FUNC_INV_LANGUAGE, - ERR_ASG_EVNT_TRIG_FUNC_INV_LANG, - ERR_ASG_NOT_ALOC_TABLE, - ERR_REF_ARG_INV_INDEX, - ERR_ASG_EMPTY_NAME_OBJECT, - ERR_ASG_INV_NAME_OBJECT, - ERR_ASG_LONG_NAME_OBJECT, - ERR_ASG_INV_SCHEMA_OBJECT, - ERR_ASG_INV_TABLESPACE_OBJECT, - ERR_ASG_TABSPC_INV_OBJECT, - ERR_ASG_TABSPC_INV_CONSTR_TYPE, - ERR_ASG_INV_ROLE_OBJECT, - ERR_ASG_ROLE_OBJECT_INV_TYPE, - ERR_ASG_APPSQL_OBJECT_INV_TYPE, - ERR_REF_FUNCTION_INV_TYPE, - ERR_REF_OPER_ARG_INV_TYPE, - ERR_REF_OPER_INV_TYPE, - ERR_ASG_VAL_INV_ROLE_OPT_TYPE, - ERR_REF_INV_ROLE_TYPE, - ERR_INS_DUPLIC_ROLE, - ERR_ROLE_REF_REDUNDANCY, - ERR_ROLE_MEMBER_ITSELF, - ERR_REF_ROLE_INV_INDEX, - ERR_INS_EMPTY_RULE_COMMAND, - ERR_REF_RULE_CMD_INV_INDEX, - ERR_INV_INH_COPY_RELATIONSHIP, - ERR_ASG_OBJ_BELONGS_OTHER_TABLE, - ERR_ASG_SEQ_DIF_TABLE_SCHEMA, - ERR_ASG_INV_VALUE_SEQ_ATTRIBS, - ERR_ASG_INV_SEQ_MIN_VALUE, - ERR_ASG_INV_SEQ_START_VALUE, - ERR_ASG_INV_SEQ_INCR_VALUE, - ERR_ASG_INV_SEQ_CACHE_VALUE, - ERR_ASG_TAB_DIF_SEQ_SCHEMA, - ERR_ASG_SEQ_OWNER_DIF_TABLE, - ERR_ASG_INEXIST_OWNER_COL_SEQ, - ERR_ASG_INV_OWNER_COL_SEQ, - ERR_REF_LABEL_INV_INDEX, - ERR_ALOC_OBJECT_INV_TYPE, - ERR_ASG_FUNCTION_INV_RET_TYPE, - ERR_ASG_FUNCTION_INV_PARAMS, - ERR_ASG_NOT_ALOC_LANGUAGE, - ERR_ASG_INV_LANGUAGE_OBJECT, - ERR_REF_TYPE_INV_INDEX, - ERR_ASG_NULL_TYPE_OBJECT, - ERR_ASG_INV_TYPE_OBJECT, - ERR_ASG_EMPTY_DIR_NAME, - ERR_OBT_TYPES_INV_QUANTITY, - ERR_INS_DUPLIC_ITEMS, - ERR_INS_INV_TYPE_ATTRIB, - ERR_INS_DUPLIC_ENUM_ITEM, - ERR_INS_INV_TYPE_ENUM_ITEM, - ERR_REF_ATTRIB_INV_INDEX, - ERR_REF_ENUM_INV_INDEX, - ERR_ASG_INV_TYPE_CONFIG, - ERR_ASG_INV_OPER_ARGS, - ERR_ASG_INV_OPERATOR_TYPES, - ERR_ASG_RESERVED_NAME, - ERR_USING_INV_FUNC_CONFIG, - ERR_ASG_INV_SUPSTG_NUMBER, - ERR_INS_DUPLIC_ELEMENT, - ERR_REF_ELEM_INV_INDEX, - ERR_REF_OBJ_INV_INDEX, - ERR_REM_NOT_ALOC_OBJECT, - ERR_REM_DIRECT_REFERENCE, - ERR_REM_INDIRECT_REFERENCE, - ERR_OPR_OBJ_INV_TYPE, - ERR_REF_OBJ_INV_TYPE, - ERR_OPR_NOT_ALOC_OBJECT, - ERR_LINK_TABLES_NO_PK, - ERR_NOT_IMPL_REL_TYPE, - ERR_ASG_INV_EXPR_OBJECT, - ERR_ASG_EXISTING_PK_TABLE, - ERR_INV_IDENT_RELATIOSHIP, - ERR_DUPLIC_COLS_COPY_REL, - ERR_INCOMP_COLS_INHERIT_REL, - ERR_INCOMP_CONSTRS_INHERIT_REL, - ERR_ASG_OBJ_INV_REL_TYPE, - ERR_ASG_FOREIGN_KEY_REL, - ERR_REF_OBJ_INEXISTS_MODEL, - ERR_REF_INEXIST_USER_TYPE, - ERR_ASG_INV_MAX_SIZE_OP_LIST, - ERR_FILE_DIR_NOT_WRITTEN, - ERR_FILE_NOT_WRITTER_INV_DEF, - ERR_DUPLIC_RELATIONSHIP, - ERR_INS_REL_GENS_REDUNDACY, - ERR_INVALIDATED_OBJECTS, - ERR_INV_PRIM_KEY_ALOCATION, - ERR_REF_INV_PRIVILEGE_TYPE, - ERR_INS_DUP_ROLE_PERMISSION, - ERR_ASG_INCOMP_PRIV_OBJECT, - ERR_ASG_DUPLIC_PERMISSION, - ERR_PERM_REF_INEXIST_OBJECT, - ERR_ALOC_OBJECT_NO_SCHEMA, - ERR_ASG_DUP_TABLESPACE_DIR, - ERR_ASG_INV_DOMAIN_ARRAY, - ERR_ASG_CODE_FUNC_C_LANGUAGE, - ERR_ASG_FUNC_REFLIB_LANG_NOT_C, - ERR_ASG_INV_COM_OPEERATOR, - ERR_ASG_INV_NEG_OPERATOR, - ERR_USER_TYPE_SELF_REFERENCE, - ERR_ASG_INV_ELEMENT_TYPE, - ERR_ASG_INV_ALIGNMENT_TYPE, - ERR_ASG_INV_NAME_TABLE_RELNN, - ERR_INV_USE_ESPECIAL_PK, - ERR_OPR_REL_INCL_OBJECT, - ERR_REM_PROTECTED_OBJECT, - ERR_REDECL_HL_GROUP, - ERR_DEF_INV_GROUP_DECL, - ERR_DEF_NOT_DECL_GROUP, - ERR_DEF_EMPTY_GROUP, - ERR_DEF_DUPLIC_GROUP, - ERR_GROUP_DECL_NOT_DEFINED, - ERR_REF_COL_OBJTAB_INV_INDEX, - ERR_REF_LIN_OBJTAB_INV_INDEX, - ERR_OPR_RESERVED_OBJECT, - ERR_FUNC_CONFIG_INV_OBJECT, - ERR_SQL_SCOPE_INV_VIEW_REF, - ERR_CONSTR_NO_COLUMNS, - ERR_CONFIG_NOT_LOADED, - ERR_DEFAULT_CONFIG_NOT_REST, - ERR_EXPORT_FAILURE, - ERR_PLUGIN_NOT_LOADED, - ERR_PLUGINS_NOT_LOADED, - ERR_INV_SYNTAX, - ERR_INV_INSTRUCTION, - ERR_UNK_ATTRIBUTE, - ERR_INV_METACHARACTER, - ERR_INV_OPERATOR_IN_EXPR, - ERR_UNDEF_ATTRIB_VALUE, - ERR_INV_ATTRIBUTE, - ERR_ASG_EMPTY_XML_BUFFER, - ERR_FILE_DIR_NOT_ACCESSED, - ERR_ASG_EMPTY_DTD_FILE, - ERR_ASG_EMPTY_DTD_NAME, - ERR_LIBXMLERR, - ERR_OPR_NOT_ALOC_ELEM_TREE, - ERR_LOAD_INV_MODEL_FILE, - ERR_OPR_NOT_ALOC_ELEMENT, - ERR_OPR_INEXIST_ELEMENT, - ERR_ASG_INV_CONN_PARAM, - ERR_OPR_NOT_ALOC_CONN, - ERR_CONNECTION_NOT_CONFIGURED, - ERR_CONNECTION_ALREADY_STABLISHED, - ERR_CONNECTION_NOT_STABLISHED, - ERR_ASG_SQL_RESULT_NOT_ALOC, - ERR_INCOMPREHENSIBLE_DBMS_RESP, - ERR_DBMS_FATAL_ERROR, - ERR_REF_TUPLE_COL_INV_INDEX, - ERR_REF_TUPLE_COL_INV_NAME, - ERR_REF_TUPLE_INEXISTENT, - ERR_REF_INV_TUPLE_COLUMN, - ERR_CMD_SQL_NOT_EXECUTED, - ERR_INV_VIEW_DEF_EXPRESSION, - ERR_ASG_SEC_VIEW_DEF_EXPRESSION, - ERR_MIX_VIEW_DEF_EXPR_REFS, - ERR_ASG_INV_COLLATION_OBJECT, - ERR_PK_USING_COLS_ADDED_BY_REL, - ERR_EMPTY_LOCAL_ATTRIB_COLLATION, - ERR_OBJECT_REFERENCING_ITSELF, - ERR_ASG_INV_OPFAM_OPCLSELEM, - ERR_REF_INV_LIKE_OP_TYPE, - ERR_COPY_REL_TAB_DEFINED, - ERR_TABLE_TRIG_INSTEADOF_FIRING, - ERR_TRIGGER_INV_TRUNCATE_USAGE, - ERR_TRIGGER_INV_INSTEADOF_USAGE, - ERR_CONST_TRIG_NOT_AFTER_ROW, - ERR_VIEW_TRIG_INV_AFTBFR_USAGE, - ERR_TRIGGER_INV_INSTEADOF_UPDATE, - ERR_ASG_COLUMN_NO_PARENT, - ERR_TRIG_USING_CONSTRIG_ATRIBS, - ERR_REF_FUNCTION_INV_TYPE_CONF, - ERR_ASG_INV_OPCLASS_OBJ, - ERR_INV_POSTGRESQL_VERSION, - ERR_VALIDATION_FAILURE, - ERR_REG_EXT_NOT_HANDLING_TYPE, - ERR_ALOC_INV_FK_RELATIONSHIP, - ERR_ASG_INV_NAME_PATTERN, - ERR_REF_INV_NAME_PATTERN_ID, - ERR_INV_USE_VARIADIC_PARAM_MODE, - ERR_MIX_INCOMP_EXPORT_OPTS, - ERR_MIX_INCOMP_DROP_OPTS, - ERR_INV_ID_SWAP_SAME_OBJECT, - ERR_INV_ID_SWAP_INV_OBJ_TYPE, - ERR_ASG_WGT_ALREADY_HAS_PARENT, - ERR_OBJECT_NOT_IMPORTED, - ERR_MODEL_FILE_NOT_LOADED, - ERR_INV_COLUMN_TABLE_TYPE, - ERR_OPR_INV_ELEMENT_ID, - ERR_REF_ELEMENT_COLOR_ID, - ERR_ASG_INV_OBJECT_TYPE, - ERR_INCOMP_COL_TYPE_FOR_SEQ, - ERR_INV_USE_TMPNAMES_EXPORT_OPT, - ERR_INV_CONV_INTEGER_TO_SERIAL, - ERR_ASG_INV_EVENT_TRIGGER_VARIABLE, - ERR_ROW_DATA_NOT_MANIPULATED, - ERR_MALFORMED_UNESCAPED_VALUE, - ERR_UNDO_REDO_OPR_INV_OBJECT, - ERR_REQ_FIELDS_NOT_FILLED, - ERR_INV_REL_ID_SWAP, - ERR_INV_INH_PARENT_TAB_NOT_FOUND, - ERR_ASG_ENUM_INV_CHARS, - ERR_ASG_ENUM_LONG_NAME, - ERR_CONNECTION_TIMEOUT, - ERR_CONNECTION_BROKEN, - ERR_DROP_CURRDB_DEFAULT, - ERR_NULL_PK_COLUMN, - ERR_INV_IDENTITY_COLUMN, - ERR_REF_INV_AFFECTED_CMD, - ERR_REF_INV_SPECIAL_ROLE +//! \brief This enum defines the global error codes used throughout the application +enum class ErrorCode: unsigned { + Custom, + AsgPseudoTypeColumn, + AsgInvalidPrecision, + AsgInvalidPrecisionTimestamp, + AsgNotAllocatedColumn, + RefColumnInvalidIndex, + AsgNotAllocattedObject, + AsgNotAllocatedSchema, + AsgObjectInvalidDefinition, + AsgDuplicatedObject, + AsgDuplicatedObjectContainer, + AsgObjectInvalidType, + RemObjectInvalidType, + ObtObjectInvalidType, + AsgEmptyNameTableReturnType, + AsgDuplicatedParameterFunction, + InsDuplicatedTableReturnType, + RefParameterInvalidIndex, + RefInvalidTriggerEvent, + AsgInvalidColumnTrigger, + AsgNotAllocatedFunction, + AsgInvalidTriggerFunction, + AsgFunctionInvalidParamCount, + AsgFunctionInvalidLanguage, + AsgEventTriggerFuncInvalidLang, + AsgNotAllocatedTable, + RefArgumentInvalidIndex, + AsgEmptyNameObject, + AsgInvalidNameObject, + AsgLongNameObject, + AsgInvalidSchemaObject, + AsgInvalidTablespaceObject, + AsgTablespaceInvalidObject, + AsgTablespaceInvalidConstraintType, + AsgInvalidRoleObject, + AsgRoleObjectInvalidType, + AsgCustomSQLObjectInvalidType, + RefFunctionInvalidType, + RefOperatorArgumentInvalidType, + RefOperatorInvalidType, + AsgValueInvalidRoleOptionType, + RefInvalidRoleType, + InsDuplicatedRole, + AsgRoleReferenceRedundancy, + AsgRoleMemberItself, + RefRoleInvalidIndex, + InsEmptyRuleCommand, + RefRuleCommandInvalidIndex, + InvInheritCopyPartRelationship, + AsgObjectBelongsAnotherTable, + AsgSchemaSequenceDiffersTableSchema, + AsgInvalidValueSequenceAttributes, + AsgInvalidSequenceMinValue, + AsgInvalidSequenceStartValue, + AsgInvalidSequenceIncrementValue, + AsgInvalidSequenceCacheValue, + AsgSeqOwnerTableDifferentSchema, + AsgSeqOwnerTableDifferentRole, + AsgInexistentSeqOwnerColumn, + AsgInvalidSeqOwnerColumn, + RefLabelInvalidIndex, + AllocationObjectInvalidType, + AsgFunctionInvalidReturnType, + AsgFunctionInvalidParameters, + AsgNotAllocatedLanguage, + AsgInvalidLanguageObject, + RefTypeInvalidIndex, + AsgNullTypeObject, + AsgInvalidTypeObject, + AsgEmptyDirectoryName, + ObtTypesInvalidQuantity, + InsDuplicatedItems, + InsInvalidTypeAttribute, + InsDuplicatedEnumerationItem, + InsInvalidEnumerationItem, + RefAttributeInvalidIndex, + RefEnumerationInvalidIndex, + AsgInvalidTypeConfiguration, + AsgInvalidOperatorArguments, + AsgInvalidOperatorTypes, + AsgReservedName, + AsgFunctionInvalidConfiguration, + AsgInvalidSupportStrategyNumber, + InsDuplicatedElement, + RefElementInvalidIndex, + RefObjectInvalidIndex, + RemNotAllocatedObject, + RemDirectReference, + RemInderectReference, + OprObjectInvalidType, + RefObjectInvalidType, + OprNotAllocatedObject, + InvLinkTablesNoPrimaryKey, + NotImplementedRelationshipType, + AsgInvalidExpressionObject, + AsgExistingPrimaryKeyTable, + InvIdentifierRelationship, + InvCopyRelationshipDuplicCols, + InvInheritRelationshipIncompCols, + InvInheritRelationshipIncompConstrs, + AsgObjectInvalidRelationshipType, + AsgForeignKeyRelationship, + RefObjectInexistsModel, + RefUserTypeInexistsModel, + AsgInvalidMaxSizeOpList, + FileDirectoryNotWritten, + FileNotWrittenInvalidDefinition, + InsDuplicatedRelationship, + InsRelationshipRedundancy, + RemInvalidatedObjects, + InvPrimaryKeyAllocation, + RefInvalidPrivilegeType, + InsDuplicatedRolePermission, + AsgInvalidPrivilegeObject, + AsgDuplicatedPermission, + PermissionRefInexistObject, + InvObjectAllocationNoSchema, + AsgTablespaceDuplicatedDirectory, + AsgInvalidSequenceTypeArray, + AsgSourceCodeFuncCLanguage, + AsgRefLibraryFuncLanguageNotC, + AsgInvalidCommutatorOperator, + AsgInvalidNegatorOperator, + InvUserTypeSelfReference, + AsgInvalidElementType, + AsgInvalidAlignmentType, + AsgInvalidNameTableRelNN, + InvUseSpecialPrimaryKey, + OprRelationshipAddedObject, + RemProtectedObject, + InvRedeclarationGroup, + InvGroupDeclaration, + DefNotDeclaredGroup, + DefEmptyGroup, + DefDuplicatedGroup, + InvGroupDeclarationNotDefined, + RefColObjectTabInvalidIndex, + RefRowObjectTabInvalidIndex, + OprReservedObject, + InvFuncConfigInvalidatesObject, + InvSQLScopeViewReference, + InvConstratintNoColumns, + ConfigurationNotLoaded, + DefaultConfigNotRestored, + ExportFailure, + PluginNotLoaded, + PluginsNotLoaded, + InvalidSyntax, + InvalidInstruction, + UnkownAttribute, + InvalidMetacharacter, + InvalidOperatorInExpression, + UndefinedAttributeValue, + InvalidAttribute, + AsgEmptyXMLBuffer, + FileDirectoryNotAccessed, + AsgEmptyDTDFile, + AsgEmptyDTDName, + LibXMLError, + OprNotAllocatedElementTree, + InvModelFileNotLoaded, + OprNotAllocatedElement, + OprInexistentElement, + AsgInvalidConnParameter, + OprNotAllocatedConnection, + ConnectionNotConfigured, + ConnectionAlreadyStablished, + ConnectionNotStablished, + AsgNotAllocatedSQLResult, + IncomprehensibleDBMSResponse, + DBMSFatalError, + RefTupleColumnInvalidIndex, + RefTupleColumnInvalidName, + RefInvalidTuple, + RefInvalidTupleColumn, + SQLCommandNotExecuted, + AsgInvalidViewDefExpression, + AsgSecondViewDefExpression, + MixingViewDefExprsReferences, + AsgInvalidCollationObject, + UnsupportedPKColsAddedByRel, + EmptyLCCollationAttributes, + ObjectReferencingItself, + AsgInvalidOpFamilyOpClassElem, + RefInvalidLikeOptionType, + InvCopyRelTableDefined, + InvPartRelPartitionedDefined, + InvRelTypeForPatitionTables, + InvTableTriggerInsteadOfFiring, + InvUsageTruncateOnTrigger, + InvUsageInsteadOfOnTrigger, + InvConstrTriggerNotAfterRow, + InvUsageAfterBeforeViewTrigger, + InvUsageInsteadOfUpdateTrigger, + AsgColumnNoParent, + InvUseConstraintTriggerAttribs, + RefInvalidFunctionIdTypeConfig, + AsgInvalidOpClassObject, + InvPostgreSQLVersion, + ValidationFailure, + ExtensionHandlingTypeImmutable, + InvAllocationFKRelationship, + AsgInvalidNamePattern, + RefInvalidNamePatternId, + InvUsageVariadicParamMode, + MixingIncompExportOptions, + MixingIncompDropOptions, + InvIdSwapSameObject, + InvIdSwapInvalidObjectType, + AsgWidgetAlreadyHasParent, + ObjectNotImported, + ModelFileNotLoaded, + InvColumnTableType, + OprInvalidElementId, + RefInvalidElementColorId, + AsgInvalidObjectType, + IncompColumnTypeForSequence, + InvUsageTempNamesExportOption, + InvConversionIntegerToSerial, + AsgInvalidEventTriggerVariable, + RowDataNotManipulated, + MalformedUnescapedValue, + UndoRedoOperationInvalidObject, + RequiredFieldsNotFilled, + InvRelationshipIdSwap, + InvInheritParentTableNotFound, + AsgEnumInvalidChars, + AsgEnumLongName, + ConnectionTimeout, + ConnectionBroken, + DropCurrentDBDefault, + NullPrimaryKeyColumn, + InvalidIdentityColumn, + RefInvalidAffectedCommand, + RefInvalidSpecialRole, + InvColumnCountPartRel, + InvPartitioningTypePartRel, + InvPartitionKeyCount, + PartKeyObjectInexistsModel, + AsgInvalidColumnPartitionKey, + RemColumnRefByPartitionKey, + AsgOptionInvalidName, + AsgInvalidNameObjReference, + AsgNotAllocatedObjectReference, + InsDuplicatedObjectReference, + ModelFileInvalidSize }; class Exception { private: - static const int ERROR_COUNT=233; + static constexpr unsigned ErrorCount=246; /*! \brief Stores other exceptions before raise the 'this' exception. This structure can be used to simulate a stack trace to improve the debug */ vector exceptions; //! \brief Stores the error messages and codes (names of errors) in string format - static QString messages[ERROR_COUNT][2]; + static QString messages[ErrorCount][2]; //! \brief Constants used to access the error details - static const unsigned ERROR_CODE=0, - ERROR_MESSAGE=1; + static constexpr unsigned ErrorCodeId=0, ErrorMessage=1; //! \brief Error type related to the exception - ErrorType error_type; + ErrorCode error_code; //! \brief Formated error message QString error_msg, @@ -319,7 +329,7 @@ class Exception { int line; //! \brief Configures the basic attributes of exception - void configureException(const QString &msg, ErrorType error_type, const QString &method, const QString &file, int line, const QString &extra_info); + void configureException(const QString &msg, ErrorCode error_code, const QString &method, const QString &file, int line, const QString &extra_info); //! \brief Adds a exception to the list of exceptions void addException(Exception &exception); @@ -328,19 +338,19 @@ class Exception { Exception(void); Exception(const QString &msg, const QString &method, const QString &file, int line, Exception *exception=nullptr, const QString &extra_info=QString()); Exception(const QString &msg, const QString &method, const QString &file, int line, vector &exceptions, const QString &extra_info=QString()); - Exception(const QString &msg, ErrorType error_type, const QString &method, const QString &file, int line, Exception *exception=nullptr, const QString &extra_info=QString()); - Exception(const QString &msg, ErrorType error_type, const QString &method, const QString &file, int line, vector &exceptions, const QString &extra_info=QString()); - Exception(ErrorType error_type, const QString &method, const QString &file, int line, Exception *exception=nullptr, const QString &extra_info=QString()); - Exception(ErrorType error_type, const QString &method, const QString &file, int line, vector &exceptions, const QString &extra_info=QString()); + Exception(const QString &msg, ErrorCode error_code, const QString &method, const QString &file, int line, Exception *exception=nullptr, const QString &extra_info=QString()); + Exception(const QString &msg, ErrorCode error_code, const QString &method, const QString &file, int line, vector &exceptions, const QString &extra_info=QString()); + Exception(ErrorCode error_code, const QString &method, const QString &file, int line, Exception *exception=nullptr, const QString &extra_info=QString()); + Exception(ErrorCode error_code, const QString &method, const QString &file, int line, vector &exceptions, const QString &extra_info=QString()); ~Exception(void){} QString getErrorMessage(void); - static QString getErrorMessage(ErrorType error_type); - static QString getErrorCode(ErrorType error_type); + static QString getErrorMessage(ErrorCode error_code); + static QString getErrorCode(ErrorCode error_code); QString getMethod(void); QString getFile(void); QString getLine(void); - ErrorType getErrorType(void); + ErrorCode getErrorCode(void); QString getExtraInfo(void); //! \brief Gets the full exception stack diff --git a/libutils/src/globalattributes.cpp b/libutils/src/globalattributes.cpp index 7410b5116f..2f7b2cf897 100644 --- a/libutils/src/globalattributes.cpp +++ b/libutils/src/globalattributes.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -22,118 +22,127 @@ namespace GlobalAttributes { const QString - PGMODELER_APP_NAME=QString("pgmodeler"), - PGMODELER_URI=QString("pgmodeler.io"), - PGMODELER_REVERSE_URI=QString("io.pgmodeler"), - PGMODELER_VERSION=QString("0.9.1"), - PGMODELER_BUILD_NUMBER=QString(BUILDNUM), - PGMODELER_SITE=QString("https://pgmodeler.io"), - PGMODELER_SUPPORT=QString("https://github.com/pgmodeler/pgmodeler/issues"), - PGMODELER_SRC_URL=QString("https://github.com/pgmodeler/pgmodeler/releases"), - PGMODELER_DOWNLOAD_URL=QString("%1/download").arg(PGMODELER_SITE), - PGMODELER_DONATE_URL=QString("%1/#donationForm").arg(PGMODELER_SITE), - PGMODELER_UPD_CHECK_URL=QString("%1/checkupdate?version=").arg(PGMODELER_SITE), - - BUG_REPORT_EMAIL=QString("bug@pgmodeler.io"), - BUG_REPORT_FILE=QString("pgmodeler%1.bug"), - STACKTRACE_FILE=QString(".stacktrace"), - - DIR_SEPARATOR=QString("/"), - DEFAULT_CONFS_DIR=QString("defaults"), - CONFS_BACKUPS_DIR=QString("backups"), - SCHEMAS_DIR=QString("schemas"), - SQL_SCHEMA_DIR=QString("sql"), - XML_SCHEMA_DIR=QString("xml"), - ALTER_SCHEMA_DIR=QString("alter"), - SCHEMA_EXT=QString(".sch"), - OBJECT_DTD_DIR=QString("dtd"), - OBJECT_DTD_EXT=QString(".dtd"), - ROOT_DTD=QString("dbmodel"), - METADATA_DTD=QString("metadata"), - CONFIGURATION_EXT=QString(".conf"), - HIGHLIGHT_FILE_SUF=QString("-highlight"), - - CODE_HIGHLIGHT_CONF=QString("source-code-highlight"), - OBJECTS_STYLE_CONF=QString("objects-style"), - GENERAL_CONF=QString("pgmodeler"), - CONNECTIONS_CONF=QString("connections"), - RELATIONSHIPS_CONF=QString("relationships"), - SNIPPETS_CONF=QString("snippets"), - SQL_HISTORY_CONF=QString("sql-history"), - - SQL_HIGHLIGHT_CONF=QString("sql-highlight"), - XML_HIGHLIGHT_CONF=QString("xml-highlight"), - PATTERN_HIGHLIGHT_CONF=QString("pattern-highlight"), - - EXAMPLE_MODEL=QString("example.dbm"), - UI_STYLE_CONF=QString("ui-style"), - - DEFAULT_QT_STYLE=QString("Fusion"), - UI_STYLE_OPT=QString("-style"), - - SCHEMAS_ROOT_DIR=getPathFromEnv(QString("PGMODELER_SCHEMAS_DIR"), QString(SCHEMASDIR), QString("./schemas")), - LANGUAGES_DIR=getPathFromEnv(QString("PGMODELER_LANG_DIR"), QString(LANGDIR), QString("./lang")), - SAMPLES_DIR=getPathFromEnv(QString("PGMODELER_SAMPLES_DIR"), QString(SAMPLESDIR), QString("./samples")), - TMPL_CONFIGURATIONS_DIR=getPathFromEnv(QString("PGMODELER_TMPL_CONF_DIR"), QString(CONFDIR), QString("./conf")), + PgModelerVersion=QString("0.9.2-beta1") + + /* Appending the snapshot build number to the version number + * when the external variable SNAPSHOT_BUILD is defined */ + #if defined(SNAPSHOT_BUILD) + + QString("_snapshot") + BUILDNUM + #endif + , + /****/ + + PgModelerAppName=QString("pgmodeler"), + PgModelerURI=QString("pgmodeler.io"), + PgModelerReverseURI=QString("io.pgmodeler"), + PgModelerBuildNumber=QString(BUILDNUM), + PgModelerSite=QString("https://pgmodeler.io"), + PgModelerSupport=QString("https://pgmodeler.io/support/docs"), + PgModelerSourceURL=QString("https://github.com/pgmodeler/pgmodeler/releases"), + PgModelerDownloadURL=QString("%1/download").arg(PgModelerSite), + PgModelerDonateURL=QString("%1/#donationForm").arg(PgModelerSite), + PgModelerUpdateCheckURL=QString("%1/checkupdate?version=").arg(PgModelerSite), + + BugReportEmail=QString("bug@pgmodeler.io"), + BugReportFile=QString("pgmodeler%1.bug"), + StacktraceFile=QString(".stacktrace"), + + DirSeparator=QString("/"), + DefaultConfsDir=QString("defaults"), + ConfsBackupsDir=QString("backups"), + SchemasDir=QString("schemas"), + SQLSchemaDir=QString("sql"), + XMLSchemaDir=QString("xml"), + AlterSchemaDir=QString("alter"), + SchemaExt=QString(".sch"), + ObjectDTDDir=QString("dtd"), + ObjectDTDExt=QString(".dtd"), + RootDTD=QString("dbmodel"), + MetadataDTD=QString("metadata"), + ConfigurationExt=QString(".conf"), + HighlightFileSuffix=QString("-highlight"), + + CodeHighlightConf=QString("source-code-highlight"), + ObjectsStyleConf=QString("objects-style"), + GeneralConf=QString("pgmodeler"), + ConnectionsConf=QString("connections"), + RelationshipsConf=QString("relationships"), + SnippetsConf=QString("snippets"), + SQLHistoryConf=QString("sql-history"), + + SQLHighlightConf=QString("sql-highlight"), + XMLHighlightConf=QString("xml-highlight"), + PatternHighlightConf=QString("pattern-highlight"), + + ExampleModel=QString("example.dbm"), + UiStyleConf=QString("ui-style"), + + DefaultQtStyle=QString("Fusion"), + UiStyleOption=QString("-style"), + + SchemasRootDir=getPathFromEnv(QString("PGMODELER_SCHEMAS_DIR"), QString(SCHEMASDIR), QString("./schemas")), + LanguagesDir=getPathFromEnv(QString("PGMODELER_LANG_DIR"), QString(LANGDIR), QString("./lang")), + SamplesDir=getPathFromEnv(QString("PGMODELER_SAMPLES_DIR"), QString(SAMPLESDIR), QString("./samples")), + TmplConfigurationDir=getPathFromEnv(QString("PGMODELER_TMPL_CONF_DIR"), QString(CONFDIR), QString("./conf")), //Currently, plugins folder is auto-created when missing so it can't be resolved by getPathFromEnv() - PLUGINS_DIR=getenv("PGMODELER_PLUGINS_DIR") ? QString(getenv("PGMODELER_PLUGINS_DIR")).replace('\\','/') : QString(PLUGINSDIR), + PluginsDir=getenv("PGMODELER_PLUGINS_DIR") ? QString(getenv("PGMODELER_PLUGINS_DIR")).replace('\\','/') : QString(PLUGINSDIR), #if defined(Q_OS_MAC) - CONFIGURATIONS_DIR=getPathFromEnv(QString("PGMODELER_CONF_DIR"), - QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QString("/%1").arg(PGMODELER_REVERSE_URI)), + ConfigurationsDir=getPathFromEnv(QString("PGMODELER_CONF_DIR"), + QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QString("/%1").arg(PgModelerReverseURI)), - TEMPORARY_DIR=getPathFromEnv(QString("PGMODELER_TMP_DIR"), - QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QString("/%1/tmp").arg(PGMODELER_REVERSE_URI)), + TemporaryDir=getPathFromEnv(QString("PGMODELER_TMP_DIR"), + QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QString("/%1/tmp").arg(PgModelerReverseURI)), #elif defined(Q_OS_LINUX) - CONFIGURATIONS_DIR=getPathFromEnv(QString("PGMODELER_CONF_DIR"), - QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QString("/%1").arg(PGMODELER_APP_NAME)), + ConfigurationsDir=getPathFromEnv(QString("PGMODELER_CONF_DIR"), + QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QString("/%1").arg(PgModelerAppName)), - TEMPORARY_DIR=getPathFromEnv(QString("PGMODELER_TMP_DIR"), - QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QString("/%1/tmp").arg(PGMODELER_APP_NAME)), + TemporaryDir=getPathFromEnv(QString("PGMODELER_TMP_DIR"), + QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QString("/%1/tmp").arg(PgModelerAppName)), #else - CONFIGURATIONS_DIR=getPathFromEnv(QString("PGMODELER_CONF_DIR"), - QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QString("/%1").arg(PGMODELER_APP_NAME)), + ConfigurationsDir=getPathFromEnv(QString("PGMODELER_CONF_DIR"), + QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QString("/%1").arg(PgModelerAppName)), - TEMPORARY_DIR=getPathFromEnv(QString("PGMODELER_TMP_DIR"), - QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QString("/%1/tmp").arg(PGMODELER_APP_NAME)), + TemporaryDir=getPathFromEnv(QString("PGMODELER_TMP_DIR"), + QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QString("/%1/tmp").arg(PgModelerAppName)), #endif - SQL_HIGHLIGHT_CONF_PATH=CONFIGURATIONS_DIR + DIR_SEPARATOR + SQL_HIGHLIGHT_CONF + CONFIGURATION_EXT, - XML_HIGHLIGHT_CONF_PATH=CONFIGURATIONS_DIR + DIR_SEPARATOR + XML_HIGHLIGHT_CONF + CONFIGURATION_EXT, + SQLHighlightConfPath=ConfigurationsDir + DirSeparator + SQLHighlightConf + ConfigurationExt, + XMLHighlightConfPath=ConfigurationsDir + DirSeparator + XMLHighlightConf + ConfigurationExt, #if defined(Q_OS_UNIX) #if defined(Q_OS_MAC) //For MacOSX the crash handler path is fixed (inside bundle) - PGMODELER_CHANDLER_PATH=getPathFromEnv(QString("PGMODELER_CHANDLER_PATH"), + PgModelerCHandlerPath=getPathFromEnv(QString("PGMODELER_CHANDLER_PATH"), QString(BINDIR) + QString("/pgmodeler-ch"), QString("./pgmodeler-ch")), #else - PGMODELER_CHANDLER_PATH=getPathFromEnv(QString("PGMODELER_CHANDLER_PATH"), + PgModelerCHandlerPath=getPathFromEnv(QString("PGMODELER_CHANDLER_PATH"), QString(PRIVATEBINDIR) + QString("/pgmodeler-ch"), QString("./pgmodeler-ch")), #endif - PGMODELER_CLI_PATH=getPathFromEnv(QString("PGMODELER_CLI_PATH"), + PgModelerCLIPath=getPathFromEnv(QString("PGMODELER_CLI_PATH"), QString(BINDIR) + QString("/pgmodeler-cli"), QString("./pgmodeler-cli")), - PGMODELER_APP_PATH=getPathFromEnv(QString("PGMODELER_APP_PATH"), + PgModelerAppPath=getPathFromEnv(QString("PGMODELER_APP_PATH"), QString(BINDIR) + QString("/pgmodeler"), QString("./pgmodeler")); #else - PGMODELER_CHANDLER_PATH=getPathFromEnv(QString("PGMODELER_CHANDLER_PATH"), + PgModelerCHandlerPath=getPathFromEnv(QString("PGMODELER_CHANDLER_PATH"), QString(PRIVATEBINDIR) + QString("\\pgmodeler-ch.exe"), QString(".\\pgmodeler-ch.exe")), - PGMODELER_CLI_PATH=getPathFromEnv(QString("PGMODELER_CLI_PATH"), + PgModelerCLIPath=getPathFromEnv(QString("PGMODELER_CLI_PATH"), QString(PRIVATEBINDIR) + QString("\\pgmodeler-cli.exe"), QString(".\\pgmodeler-cli.exe")), - PGMODELER_APP_PATH=getPathFromEnv(QString("PGMODELER_APP_PATH"), + PgModelerAppPath=getPathFromEnv(QString("PGMODELER_APP_PATH"), QString(BINDIR) + QString("\\pgmodeler.exe"), QString(".\\pgmodeler.exe")); @@ -141,7 +150,7 @@ namespace GlobalAttributes { #ifdef DEMO_VERSION //Maximum object creation counter for demo version - const unsigned MAX_OBJECT_COUNT=9; + const unsigned MaxObjectCount=15; #endif diff --git a/libutils/src/globalattributes.h b/libutils/src/globalattributes.h index 3127fc6c63..97caa92556 100644 --- a/libutils/src/globalattributes.h +++ b/libutils/src/globalattributes.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -38,58 +38,59 @@ namespace GlobalAttributes { extern const QString - PGMODELER_APP_NAME, - PGMODELER_URI, - PGMODELER_VERSION, - PGMODELER_BUILD_NUMBER, - PGMODELER_SITE, - PGMODELER_SUPPORT, - PGMODELER_SRC_URL, - PGMODELER_DOWNLOAD_URL, - PGMODELER_DONATE_URL, - PGMODELER_UPD_CHECK_URL, - - BUG_REPORT_EMAIL, - BUG_REPORT_FILE, - STACKTRACE_FILE, - - DIR_SEPARATOR, - DEFAULT_CONFS_DIR, //! \brief Directory name which holds the default pgModeler configuration - CONFS_BACKUPS_DIR, //! \brief Directory name which holds the pgModeler configuration backups - SCHEMAS_DIR, //! \brief Default name for the schemas directory - SQL_SCHEMA_DIR, //! \brief Default name for the sql schemas directory - XML_SCHEMA_DIR, //! \brief Default name for the xml schemas directory - ALTER_SCHEMA_DIR, //! \brief Default name for the alter schemas directory - SCHEMA_EXT, //! \brief Default extension for schema files - OBJECT_DTD_DIR, //! \brief Default directory for dtd files - OBJECT_DTD_EXT, //! \brief Default extension for dtd files - ROOT_DTD, //! \brief Root DTD of model xml files - METADATA_DTD, //! \brief Root DTD of objects metadata xml files - CONFIGURATION_EXT, //! \brief Default extension for configuration files - HIGHLIGHT_FILE_SUF, //! \brief Suffix of language highlight configuration files - - CODE_HIGHLIGHT_CONF, //! \brief Default name for the language highlight dtd - OBJECTS_STYLE_CONF, //! \brief Default name for the object style configuration file - GENERAL_CONF, //! \brief Default name for the general pgModeler configuration - CONNECTIONS_CONF, //! \brief Default name for the DBMS connection configuration file - RELATIONSHIPS_CONF, //! \brief Default name for the relationships configuration file - SNIPPETS_CONF, //! \brief Default name for the code snippets configuration file - - SQL_HIGHLIGHT_CONF, //! \brief Configuration file for SQL language highlight - XML_HIGHLIGHT_CONF, //! \brief Configuration file for XML language highlight - PATTERN_HIGHLIGHT_CONF, //! \brief Configuration file for name patterns highlight (relationship editing form) - SQL_HISTORY_CONF, //! \brief Default name for the SQL commands history configuration file - - EXAMPLE_MODEL, //! \brief Default name for the sample model loaded on appearence configuration form - UI_STYLE_CONF, //! \brief Configuration file ui style + PgModelerAppName, + PgModelerURI, + PgModelerReverseURI, + PgModelerVersion, + PgModelerBuildNumber, + PgModelerSite, + PgModelerSupport, + PgModelerSourceURL, + PgModelerDownloadURL, + PgModelerDonateURL, + PgModelerUpdateCheckURL, + + BugReportEmail, + BugReportFile, + StacktraceFile, + + DirSeparator, + DefaultConfsDir, //! \brief Directory name which holds the default pgModeler configuration + ConfsBackupsDir, //! \brief Directory name which holds the pgModeler configuration backups + SchemasDir, //! \brief Default name for the schemas directory + SQLSchemaDir, //! \brief Default name for the sql schemas directory + XMLSchemaDir, //! \brief Default name for the xml schemas directory + AlterSchemaDir, //! \brief Default name for the alter schemas directory + SchemaExt, //! \brief Default extension for schema files + ObjectDTDDir, //! \brief Default directory for dtd files + ObjectDTDExt, //! \brief Default extension for dtd files + RootDTD, //! \brief Root DTD of model xml files + MetadataDTD, //! \brief Root DTD of objects metadata xml files + ConfigurationExt, //! \brief Default extension for configuration files + HighlightFileSuffix, //! \brief Suffix of language highlight configuration files + + CodeHighlightConf, //! \brief Default name for the language highlight dtd + ObjectsStyleConf, //! \brief Default name for the object style configuration file + GeneralConf, //! \brief Default name for the general pgModeler configuration + ConnectionsConf, //! \brief Default name for the DBMS connection configuration file + RelationshipsConf, //! \brief Default name for the relationships configuration file + SnippetsConf, //! \brief Default name for the code snippets configuration file + + SQLHighlightConf, //! \brief Configuration file for SQL language highlight + XMLHighlightConf, //! \brief Configuration file for XML language highlight + PatternHighlightConf, //! \brief Configuration file for name patterns highlight (relationship editing form) + SQLHistoryConf, //! \brief Default name for the SQL commands history configuration file + + ExampleModel, //! \brief Default name for the sample model loaded on appearence configuration form + UiStyleConf, //! \brief Configuration file ui style /*! \brief Fusion is the default widget style for pgModeler. User can change this by calling the executable using -style option. This same style is applied to crash handler. */ - DEFAULT_QT_STYLE, - UI_STYLE_OPT; + DefaultQtStyle, + UiStyleOption; - /*! \brief Variables used to reference the pgModeler directories. + /*! \brief Environment variables used to reference the pgModeler directories. PGMODELER_SCHEMAS_DIR --> "schemas" folder (SQL/XML generation schema files) PGMODELER_CONF_DIR --> "conf" folder (user's own settings for pgModeler) @@ -107,22 +108,22 @@ namespace GlobalAttributes { PGMDOELER_APP_PATH --> Full path to pgmodeler executable */ extern const QString - SCHEMAS_ROOT_DIR, - LANGUAGES_DIR, - PLUGINS_DIR, - TEMPORARY_DIR, - SAMPLES_DIR, - TMPL_CONFIGURATIONS_DIR, - CONFIGURATIONS_DIR, - SQL_HIGHLIGHT_CONF_PATH, - XML_HIGHLIGHT_CONF_PATH, - PGMODELER_CHANDLER_PATH, - PGMODELER_CLI_PATH, - PGMODELER_APP_PATH; + SchemasRootDir, + LanguagesDir, + PluginsDir, + TemporaryDir, + SamplesDir, + TmplConfigurationDir, + ConfigurationsDir, + SQLHighlightConfPath, + XMLHighlightConfPath, + PgModelerCHandlerPath, + PgModelerCLIPath, + PgModelerAppPath; #ifdef DEMO_VERSION //Maximum object creation counter for demo version - extern const unsigned MAX_OBJECT_COUNT; + extern const unsigned MaxObjectCount; #endif /*! \brief Returns the current value for an environment variable. If the current value is a path and the same does not diff --git a/libutils/src/pgsqlversions.cpp b/libutils/src/pgsqlversions.cpp index 39c00ad80d..c4d3072af9 100644 --- a/libutils/src/pgsqlversions.cpp +++ b/libutils/src/pgsqlversions.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,22 +18,24 @@ #include "pgsqlversions.h" -namespace PgSQLVersions { +namespace PgSqlVersions { const QString - PGSQL_VERSION_90=QString("9.0"), - PGSQL_VERSION_91=QString("9.1"), - PGSQL_VERSION_92=QString("9.2"), - PGSQL_VERSION_93=QString("9.3"), - PGSQL_VERSION_94=QString("9.4"), - PGSQL_VERSION_95=QString("9.5"), - PGSQL_VERSION_96=QString("9.6"), - PGSQL_VERSION_100=QString("10.0"), - DEFAULT_VERSION=PGSQL_VERSION_100; + PgSqlVersion90=QString("9.0"), + PgSqlVersion91=QString("9.1"), + PgSqlVersion92=QString("9.2"), + PgSqlVersion93=QString("9.3"), + PgSqlVersion94=QString("9.4"), + PgSqlVersion95=QString("9.5"), + PgSqlVersion96=QString("9.6"), + PgSqlVersion100=QString("10.0"), + PgSqlVersion110=QString("11.0"), + DefaulVersion=PgSqlVersion110; const QStringList - ALL_VERSIONS={ - PGSQL_VERSION_100, PGSQL_VERSION_96, - PGSQL_VERSION_95, PGSQL_VERSION_94, - PGSQL_VERSION_93, PGSQL_VERSION_92, - PGSQL_VERSION_91, PGSQL_VERSION_90 }; + AllVersions={ + PgSqlVersion110, PgSqlVersion100, + PgSqlVersion96, PgSqlVersion95, + PgSqlVersion94, PgSqlVersion93, + PgSqlVersion92, PgSqlVersion91, + PgSqlVersion90 }; } diff --git a/libutils/src/pgsqlversions.h b/libutils/src/pgsqlversions.h index 9470d7ca66..31802e0f11 100644 --- a/libutils/src/pgsqlversions.h +++ b/libutils/src/pgsqlversions.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -28,19 +28,20 @@ #include -namespace PgSQLVersions { +namespace PgSqlVersions { extern const QString - PGSQL_VERSION_90, - PGSQL_VERSION_91, - PGSQL_VERSION_92, - PGSQL_VERSION_93, - PGSQL_VERSION_94, - PGSQL_VERSION_95, - PGSQL_VERSION_96, - PGSQL_VERSION_100, - DEFAULT_VERSION; + PgSqlVersion90, + PgSqlVersion91, + PgSqlVersion92, + PgSqlVersion93, + PgSqlVersion94, + PgSqlVersion95, + PgSqlVersion96, + PgSqlVersion100, + PgSqlVersion110, + DefaulVersion; - extern const QStringList ALL_VERSIONS; + extern const QStringList AllVersions; } #endif diff --git a/linuxdeploy.sh b/linuxdeploy.sh index 045c9c975c..68ed500ee6 100755 --- a/linuxdeploy.sh +++ b/linuxdeploy.sh @@ -4,24 +4,30 @@ case `uname -m` in "x86_64") ARCH="linux64" - FALLBACK_QT_ROOT=/opt/qt-5.9.3/5.9.3/gcc_64 + FALLBACK_QT_ROOT=/opt/qt-5.12.3/5.12.3/gcc_64 FALLBACK_QMAKE_ROOT="$FALLBACK_QT_ROOT/bin" ;; - - *) + + *) ARCH="linux32" FALLBACK_QT_ROOT=/opt/qt-5.6.2/5.6/gcc FALLBACK_QMAKE_ROOT="$FALLBACK_QT_ROOT/bin" ;; esac -# Uncomment this line if your system doesn't have LLVM (clang) compiler tools -#QMAKE_ARGS="-r -spec linux-g++" -QMAKE_ARGS="-r -spec linux-clang" +# Uncomment this line if you want to compile using LLVM (clang) compiler tools +# QMAKE_ARGS="-r -spec linux-clang" + +# Comment this one if you've decided to use LLVM +QMAKE_ARGS="-r -spec linux-g++" + QMAKE_ROOT=/usr/bin QMAKE_CMD=qmake LOG="$PWD/linuxdeploy.log" -QT_IFW_ROOT=/opt/qt-ifw-1.5.0 +QT_IFW_ROOT=/opt/qt-ifw-3.0.4 + +# Detecting current pgModeler version +DEPLOY_VER=`cat libutils/src/globalattributes.cpp | grep PgModelerVersion | sed 's/PgModelerVersion=QString("//g' | sed 's/")//g' | sed 's/^ *//g' | cut -s -f2` STARTUP_SCRIPT="start-pgmodeler.sh" MIME_UPDATE_SCRIPT="dbm-mime-type.sh" @@ -29,19 +35,27 @@ ENV_VARS_SCRIPT="pgmodeler.vars" BUILD_DIR="$PWD/build" DIST_DIR="$PWD/dist" INSTALL_ROOT="/opt/pgmodeler" -INSTALLER_CONF_DIR="$PWD/installer/linux/config" -INSTALLER_PKG_DIR="$PWD/installer/linux/packages" -INSTALLER_DATA_DIR="$INSTALLER_PKG_DIR/br.com.pgmodeler/data" +FMT_PREFIX="\/opt\/pgmodeler" +INSTALLER_APP_VER=`echo $DEPLOY_VER | cut -d '-' -f1` +INSTALLER_CONF_DIR="$PWD/installer/template/config" +INSTALLER_PKG_DIR="$PWD/installer/template/packages" +INSTALLER_DATA_DIR="$INSTALLER_PKG_DIR/io.pgmodeler/data" +INSTALLER_META_DIR="$INSTALLER_PKG_DIR/io.pgmodeler/meta" +INSTALLER_TMPL_CONFIG="config.xml.tmpl" +INSTALLER_CONFIG="config.xml" +INSTALLER_TMPL_PKG_CONFIG="package.xml.tmpl" +INSTALLER_PKG_CONFIG="package.xml" QT_CONF="$BUILD_DIR/$INSTALL_ROOT/qt.conf" DEP_PLUGINS_DIR="$BUILD_DIR/$INSTALL_ROOT/lib/qtplugins" - -# Detecting current pgModeler version -DEPLOY_VER=`cat libutils/src/globalattributes.cpp | grep PGMODELER_VERSION | sed 's/PGMODELER_VERSION=QString("//g' | sed 's/"),//g' | sed 's/^ *//g' | cut -s -f2` +BUILD_DATE=`date '+%Y%m%d'` + +SNAPSHOT_OPT='-snapshot' GEN_INSTALLER_OPT='-gen-installer' DEMO_VERSION_OPT='-demo-version' NO_QT_LIBS_OPT='-no-qt-libs' BUILD_ALL_OPT='-build-all' COMPRESS_INSTALLER_OPT='-comp-installer' +SNAPSHOT=0 GEN_INST_PKG=0 COMP_INST_PKG=0 DEMO_VERSION=0 @@ -89,6 +103,12 @@ for param in $@; do COMP_INST_PKG=1 fi + if [[ "$param" == "$SNAPSHOT_OPT" ]]; then + SNAPSHOT=1 + QMAKE_ARGS="$QMAKE_ARGS SNAPSHOT_BUILD+=true" + DEPLOY_VER="${DEPLOY_VER}_snapshot${BUILD_DATE}" + fi + if [[ "$param" == "$DEMO_VERSION_OPT" ]]; then DEMO_VERSION=1 GEN_INST_PKG=1 @@ -147,17 +167,17 @@ clear echo echo "pgModeler Linux deployment script" echo "PostgreSQL Database Modeler Project - pgmodeler.io" -echo "Copyright 2006-2018 Raphael A. Silva " +echo "Copyright 2006-2019 Raphael A. Silva " # Identifying System Qt version if [ -e "$QMAKE_ROOT/$QMAKE_CMD" ]; then - QT_VER_1=`$QMAKE_ROOT/$QMAKE_CMD --version | grep --color=never -m 1 -o '[0-9].[0-9].[0-9]'` + QT_VER_1=`$QMAKE_ROOT/$QMAKE_CMD --version | grep --color=never -m 1 -o -E '[0-9].[0-9]+\.[0-9]+'` QT_VER_1=${QT_VER_1:0:5} fi # Identifying Fallback Qt version if [ -e "$FALLBACK_QMAKE_ROOT/$QMAKE_CMD" ]; then - QT_VER_2=`$FALLBACK_QMAKE_ROOT/$QMAKE_CMD --version | grep --color=never -m 1 -o '[0-9].[0-9].[0-9]'` + QT_VER_2=`$FALLBACK_QMAKE_ROOT/$QMAKE_CMD --version | grep --color=never -m 1 -o -E '[0-9].[0-9]+\.[0-9]+'` QT_VER_2=${QT_VER_2:0:5} export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:"$FALLBACK_QT_ROOT/lib" fi @@ -208,6 +228,10 @@ if [ $GEN_INST_PKG = 1 ]; then fi +if [ $SNAPSHOT = 1 ]; then + echo "Building snapshot version. (Found $SNAPSHOT_OPT)" +fi + if [ $DEMO_VERSION = 1 ]; then echo "Building demonstration version. (Found $DEMO_VERSION_OPT)" fi @@ -370,6 +394,17 @@ if [ $GEN_INST_PKG = 1 ]; then exit 1 fi + # Configuing installer scripts before packaging + cat $INSTALLER_CONF_DIR/$INSTALLER_TMPL_CONFIG | sed -e "s/{version}/$INSTALLER_APP_VER/g" | sed -e "s/{prefix}/$FMT_PREFIX/g" > $INSTALLER_CONF_DIR/$INSTALLER_CONFIG + + if [ $? -ne 0 ]; then + echo + echo "** Failed to create the installer config file!" + echo + exit 1 + fi + + # Packaging installation $QT_IFW_ROOT/bin/binarycreator -v -c $INSTALLER_CONF_DIR/config.xml -p $INSTALLER_PKG_DIR "$DIST_DIR/$PKGNAME.run" >> $LOG 2>&1 if [ $? -ne 0 ]; then @@ -404,9 +439,16 @@ echo "pgModeler successfully deployed!" echo if [ $BUILD_ALL = 1 ]; then - if [ $COMP_INST_PKG = 1 ]; then - ./linuxdeploy.sh $DEMO_VERSION_OPT $COMPRESS_INSTALLER_OPT - else - ./linuxdeploy.sh $DEMO_VERSION_OPT - fi + + EXTRA_OPT="" + + if [ $SNAPSHOT = 1 ]; then + EXTRA_OPT="$SNAPSHOT_OPT" + fi + + if [ $COMP_INST_PKG = 1 ]; then + ./linuxdeploy.sh $DEMO_VERSION_OPT $COMPRESS_INSTALLER_OPT $EXTRA_OPT + else + ./linuxdeploy.sh $DEMO_VERSION_OPT $EXTRA_OPT + fi fi diff --git a/macdeploy.sh b/macdeploy.sh index 94b50fe822..29db01f2df 100755 --- a/macdeploy.sh +++ b/macdeploy.sh @@ -1,28 +1,31 @@ #!/bin/bash USR=`whoami` -PGSQL_ROOT=/Library/PostgreSQL/10.1 -QT_ROOT=/Users/$USR/Qt5.9.3/5.9.3/clang_64 +PGSQL_ROOT=/Library/PostgreSQL/11 +QT_ROOT=/Users/$USR/Qt5.12.3/5.12.3/clang_64 QMAKE_ARGS="-r CONFIG+=x86_64 CONFIG+=release -spec macx-clang" LOG=macdeploy.log # Detecting current pgModeler version -DEPLOY_VER=`cat libutils/src/globalattributes.cpp | grep PGMODELER_VERSION | sed 's/PGMODELER_VERSION=QString("//g' | sed 's/"),//g' | sed 's/^ *//g' | cut -s -f2` +DEPLOY_VER=`cat libutils/src/globalattributes.cpp | grep PgModelerVersion | sed 's/PgModelerVersion=QString("//g' | sed 's/")//g' | sed 's/^ *//g' | cut -s -f2` BUILD_NUM=$(date '+%Y%m%d') -WITH_BUILD_NUM='-with-build-num' DEMO_VERSION_OPT='-demo-version' DEMO_VERSION=0 +SNAPSHOT_OPT='-snapshot' +SNAPSHOT=0 for param in $@; do - if [[ "$param" == "$WITH_BUILD_NUM" ]]; then - PKGNAME="${PKGNAME}_${BUILD_NUM}" - fi - if [[ "$param" == "$DEMO_VERSION_OPT" ]]; then DEMO_VERSION=1 QMAKE_ARGS="$QMAKE_ARGS DEMO_VERSION+=true" fi + + if [[ "$param" == "$SNAPSHOT_OPT" ]]; then + SNAPSHOT=1 + QMAKE_ARGS="$QMAKE_ARGS SNAPSHOT_BUILD+=true" + DEPLOY_VER="${DEPLOY_VER}_snapshot${BUILD_NUM}" + fi done if [ $DEMO_VERSION = 1 ]; then @@ -41,11 +44,11 @@ clear echo echo "pgModeler Mac OSX deployment script" echo "PostgreSQL Database Modeler Project - pgmodeler.io" -echo "Copyright 2006-2018 Raphael A. Silva " +echo "Copyright 2006-2019 Raphael A. Silva " # Identifying System Qt version if [ -e "$QT_ROOT/bin/qmake" ]; then - QT_VER=`$QT_ROOT/bin/qmake --version | grep -m 1 -o '[0-9].[0-9].[0-9]'` + QT_VER=`$QT_ROOT/bin/qmake --version | grep -m 1 -o -E '[0-9]\.[0-9]+\.[0-9]+'` QT_VER=${QT_VER:0:5} fi @@ -69,6 +72,10 @@ fi echo echo "Deploying version: $DEPLOY_VER" +if [ $SNAPSHOT = 1 ]; then + echo "Building snapshot version. (Found $SNAPSHOT_OPT)" +fi + if [ $DEMO_VERSION = 1 ]; then echo "Building demonstration version. (Found $DEMO_VERSION_OPT)" fi diff --git a/main-cli/src/main.cpp b/main-cli/src/main.cpp index 979f0f809e..8953ce1675 100644 --- a/main-cli/src/main.cpp +++ b/main-cli/src/main.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -25,18 +25,18 @@ int main(int argc, char **argv) #ifdef DEMO_VERSION out << endl; - out << QString("pgModeler ") << GlobalAttributes::PGMODELER_VERSION << QT_TR_NOOP(" command line interface.") << endl; - out << QT_TR_NOOP("PostgreSQL Database Modeler Project - pgmodeler.com.br") << endl; - out << QT_TR_NOOP("Copyright 2006-2015 Raphael A. Silva ") << endl; + out << QString("pgModeler ") << GlobalAttributes::PgModelerVersion << QT_TR_NOOP(" command line interface.") << endl; + out << QT_TR_NOOP("PostgreSQL Database Modeler Project - pgmodeler.io") << endl; + out << QT_TR_NOOP("Copyright 2006-2018 Raphael A. Silva ") << endl; out << QT_TR_NOOP("\n** CLI disabled in demonstration version! **") << endl << endl; #else try { QTranslator translator; - PgModelerCLI pgmodeler_cli(argc, argv); + PgModelerCli pgmodeler_cli(argc, argv); //Tries to load the ui translation according to the system's locale - translator.load(QLocale::system().name(), GlobalAttributes::LANGUAGES_DIR); + translator.load(QLocale::system().name(), GlobalAttributes::LanguagesDir); //Installs the translator on the application pgmodeler_cli.installTranslator(&translator); @@ -49,7 +49,7 @@ int main(int argc, char **argv) out << endl; out << e.getExceptionsText(); out << QString("** pgmodeler-cli aborted due to critical error(s). **") << endl << endl; - return(e.getErrorType()==ERR_CUSTOM ? -1 : e.getErrorType()); + return(e.getErrorCode()==ErrorCode::Custom ? -1 : enum_cast(e.getErrorCode())); } #endif } diff --git a/main-cli/src/pgmodelercli.cpp b/main-cli/src/pgmodelercli.cpp index c21c60a513..1506c459fc 100644 --- a/main-cli/src/pgmodelercli.cpp +++ b/main-cli/src/pgmodelercli.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,69 +18,69 @@ #include "pgmodelercli.h" -QTextStream PgModelerCLI::out(stdout); - -const QRegExp PgModelerCLI::PASSWORD_REGEXP=QRegExp("(password)(=)(.)*( )"); -const QString PgModelerCLI::PASSWORD_PLACEHOLDER=QString("password=******"); - -const QString PgModelerCLI::INPUT=QString("--input"); -const QString PgModelerCLI::OUTPUT=QString("--output"); -const QString PgModelerCLI::INPUT_DB=QString("--input-db"); -const QString PgModelerCLI::EXPORT_TO_FILE=QString("--export-to-file"); -const QString PgModelerCLI::EXPORT_TO_PNG=QString("--export-to-png"); -const QString PgModelerCLI::EXPORT_TO_SVG=QString("--export-to-svg"); -const QString PgModelerCLI::EXPORT_TO_DBMS=QString("--export-to-dbms"); -const QString PgModelerCLI::IMPORT_DB=QString("--import-db"); -const QString PgModelerCLI::DIFF=QString("--diff"); -const QString PgModelerCLI::DROP_DATABASE=QString("--drop-database"); -const QString PgModelerCLI::DROP_OBJECTS=QString("--drop-objects"); -const QString PgModelerCLI::PGSQL_VER=QString("--pgsql-ver"); -const QString PgModelerCLI::HELP=QString("--help"); -const QString PgModelerCLI::SHOW_GRID=QString("--show-grid"); -const QString PgModelerCLI::SHOW_DELIMITERS=QString("--show-delimiters"); -const QString PgModelerCLI::PAGE_BY_PAGE=QString("--page-by-page"); -const QString PgModelerCLI::IGNORE_DUPLICATES=QString("--ignore-duplicates"); -const QString PgModelerCLI::IGNORE_ERROR_CODES=QString("--ignore-error-codes"); -const QString PgModelerCLI::CONN_ALIAS=QString("--conn-alias"); -const QString PgModelerCLI::HOST=QString("--host"); -const QString PgModelerCLI::PORT=QString("--port"); -const QString PgModelerCLI::USER=QString("--user"); -const QString PgModelerCLI::PASSWD=QString("--passwd"); -const QString PgModelerCLI::INITIAL_DB=QString("--initial-db"); -const QString PgModelerCLI::SILENT=QString("--silent"); -const QString PgModelerCLI::LIST_CONNS=QString("--list-conns"); -const QString PgModelerCLI::SIMULATE=QString("--simulate"); -const QString PgModelerCLI::FIX_MODEL=QString("--fix-model"); -const QString PgModelerCLI::FIX_TRIES=QString("--fix-tries"); -const QString PgModelerCLI::ZOOM_FACTOR=QString("--zoom"); -const QString PgModelerCLI::USE_TMP_NAMES=QString("--use-tmp-names"); -const QString PgModelerCLI::DBM_MIME_TYPE=QString("--dbm-mime-type"); -const QString PgModelerCLI::INSTALL=QString("install"); -const QString PgModelerCLI::UNINSTALL=QString("uninstall"); -const QString PgModelerCLI::IGNORE_IMPORT_ERRORS=QString("--ignore-errors"); -const QString PgModelerCLI::IMPORT_SYSTEM_OBJS=QString("--import-sys-objs"); -const QString PgModelerCLI::IMPORT_EXTENSION_OBJS=QString("--import-ext-objs"); -const QString PgModelerCLI::DEBUG_MODE=QString("--debug-mode"); -const QString PgModelerCLI::COMPARE_TO=QString("--compare-to"); -const QString PgModelerCLI::SAVE_DIFF=QString("--save-diff"); -const QString PgModelerCLI::APPLY_DIFF=QString("--apply-diff"); -const QString PgModelerCLI::NO_DIFF_PREVIEW=QString("--no-diff-preview"); -const QString PgModelerCLI::DROP_CLUSTER_OBJS=QString("--drop-cluster-objs"); -const QString PgModelerCLI::REVOKE_PERMISSIONS=QString("--revoke-perms"); -const QString PgModelerCLI::DROP_MISSING_OBJS=QString("--drop-missing"); -const QString PgModelerCLI::FORCE_DROP_COLS_CONSTRS=QString("--force-drop-cols"); -const QString PgModelerCLI::RENAME_DB=QString("--rename-db"); -const QString PgModelerCLI::TRUNC_ON_COLS_TYPE_CHANGE=QString("--trunc-type-change"); -const QString PgModelerCLI::NO_SEQUENCE_REUSE=QString("--no-sequence-reuse"); -const QString PgModelerCLI::NO_CASCADE_DROP_TRUNC=QString("--no-cascade"); -const QString PgModelerCLI::NO_FORCE_OBJ_RECREATION=QString("--no-force-recreation"); -const QString PgModelerCLI::NO_UNMOD_OBJ_RECREATION=QString("--no-unmod-recreation"); - -const QString PgModelerCLI::TAG_EXPR=QString("<%1"); -const QString PgModelerCLI::END_TAG_EXPR=QString("getXMLParser(); - silent_mode=(parsed_opts.count(SILENT)); + silent_mode=(parsed_opts.count(Silent)); //If the export is to png or svg loads additional configurations - if(parsed_opts.count(EXPORT_TO_PNG) || parsed_opts.count(EXPORT_TO_SVG) || parsed_opts.count(IMPORT_DB)) + if(parsed_opts.count(ExportToPng) || parsed_opts.count(ExportToSvg) || parsed_opts.count(ImportDb)) { connect(model, SIGNAL(s_objectAdded(BaseObject*)), this, SLOT(handleObjectAddition(BaseObject *))); connect(model, SIGNAL(s_objectRemoved(BaseObject*)), this, SLOT(handleObjectRemoval(BaseObject *))); @@ -163,23 +163,23 @@ PgModelerCLI::PgModelerCLI(int argc, char **argv) : QApplication(argc, argv) BaseObjectView::loadObjectsStyle(); } - if(parsed_opts.count(EXPORT_TO_DBMS) || parsed_opts.count(IMPORT_DB) || parsed_opts.count(DIFF)) + if(parsed_opts.count(ExportToDbms) || parsed_opts.count(ImportDb) || parsed_opts.count(Diff)) { configureConnection(false); //Replacing the initial db parameter for the input database when reverse engineering - if((parsed_opts.count(IMPORT_DB) || parsed_opts.count(DIFF)) && !parsed_opts[INPUT_DB].isEmpty()) - connection.setConnectionParam(Connection::PARAM_DB_NAME, parsed_opts[INPUT_DB]); + if((parsed_opts.count(ImportDb) || parsed_opts.count(Diff)) && !parsed_opts[InputDb].isEmpty()) + connection.setConnectionParam(Connection::ParamDbName, parsed_opts[InputDb]); } - if(parsed_opts.count(DIFF)) + if(parsed_opts.count(Diff)) { configureConnection(true); if(!extra_connection.isConfigured()) extra_connection = connection; - extra_connection.setConnectionParam(Connection::PARAM_DB_NAME, parsed_opts[COMPARE_TO]); + extra_connection.setConnectionParam(Connection::ParamDbName, parsed_opts[CompareTo]); } if(!silent_mode) @@ -197,147 +197,147 @@ PgModelerCLI::PgModelerCLI(int argc, char **argv) : QApplication(argc, argv) } } -PgModelerCLI::~PgModelerCLI(void) +PgModelerCli::~PgModelerCli(void) { if(scene) delete(scene); delete(model); } -void PgModelerCLI::printMessage(const QString &msg) +void PgModelerCli::printMessage(const QString &msg) { if(!silent_mode) out << msg << endl; } -void PgModelerCLI::configureConnection(bool extra_conn) +void PgModelerCli::configureConnection(bool extra_conn) { QString chr = (extra_conn ? "1" : ""); Connection *conn = (extra_conn ? &extra_connection : &connection); //Getting the connection using its alias - if(parsed_opts.count(CONN_ALIAS + chr)) + if(parsed_opts.count(ConnAlias + chr)) { - if(!connections.count(parsed_opts[CONN_ALIAS + chr])) - throw Exception(trUtf8("Connection aliased as '%1' was not found in the configuration file.").arg(parsed_opts[CONN_ALIAS + chr]), - ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(!connections.count(parsed_opts[ConnAlias + chr])) + throw Exception(trUtf8("Connection aliased as '%1' was not found in the configuration file.").arg(parsed_opts[ConnAlias + chr]), + ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Make a copy of the named connection - *conn = (*connections[parsed_opts[CONN_ALIAS + chr]]); + *conn = (*connections[parsed_opts[ConnAlias + chr]]); } else { - conn->setConnectionParam(Connection::PARAM_SERVER_FQDN, parsed_opts[HOST + chr]); - conn->setConnectionParam(Connection::PARAM_USER, parsed_opts[USER + chr]); - conn->setConnectionParam(Connection::PARAM_PORT, parsed_opts[PORT + chr]); - conn->setConnectionParam(Connection::PARAM_PASSWORD, parsed_opts[PASSWD + chr]); - conn->setConnectionParam(Connection::PARAM_DB_NAME, parsed_opts[INITIAL_DB + chr]); + conn->setConnectionParam(Connection::ParamServerFqdn, parsed_opts[Host + chr]); + conn->setConnectionParam(Connection::ParamUser, parsed_opts[User + chr]); + conn->setConnectionParam(Connection::ParamPort, parsed_opts[Port + chr]); + conn->setConnectionParam(Connection::ParamPassword, parsed_opts[Passwd + chr]); + conn->setConnectionParam(Connection::ParamDbName, parsed_opts[InitialDb + chr]); } } -void PgModelerCLI::initializeOptions(void) +void PgModelerCli::initializeOptions(void) { - long_opts[INPUT]=true; - long_opts[OUTPUT]=true; - long_opts[INPUT_DB]=true; - long_opts[EXPORT_TO_FILE]=false; - long_opts[EXPORT_TO_PNG]=false; - long_opts[EXPORT_TO_SVG]=false; - long_opts[EXPORT_TO_DBMS]=false; - long_opts[IMPORT_DB]=false; - long_opts[DIFF]=false; - long_opts[DROP_DATABASE]=false; - long_opts[DROP_OBJECTS]=false; - long_opts[PGSQL_VER]=true; - long_opts[HELP]=false; - long_opts[SHOW_GRID]=false; - long_opts[SHOW_DELIMITERS]=false; - long_opts[PAGE_BY_PAGE]=false; - long_opts[IGNORE_DUPLICATES]=false; - long_opts[IGNORE_ERROR_CODES]=true; - long_opts[CONN_ALIAS]=true; - long_opts[HOST]=true; - long_opts[PORT]=true; - long_opts[USER]=true; - long_opts[PASSWD]=true; - long_opts[INITIAL_DB]=true; - long_opts[LIST_CONNS]=false; - long_opts[SIMULATE]=false; - long_opts[FIX_MODEL]=false; - long_opts[FIX_TRIES]=true; - long_opts[ZOOM_FACTOR]=true; - long_opts[USE_TMP_NAMES]=false; - long_opts[DBM_MIME_TYPE]=true; - long_opts[IGNORE_IMPORT_ERRORS]=false; - long_opts[IMPORT_SYSTEM_OBJS]=false; - long_opts[IMPORT_EXTENSION_OBJS]=false; - long_opts[DEBUG_MODE]=false; - long_opts[COMPARE_TO]=true; - long_opts[SAVE_DIFF]=false; - long_opts[APPLY_DIFF]=false; - long_opts[NO_DIFF_PREVIEW]=false; - long_opts[DROP_CLUSTER_OBJS]=false; - long_opts[REVOKE_PERMISSIONS]=false; - long_opts[DROP_MISSING_OBJS]=false; - long_opts[FORCE_DROP_COLS_CONSTRS]=false; - long_opts[RENAME_DB]=false; - long_opts[TRUNC_ON_COLS_TYPE_CHANGE]=false; - long_opts[NO_SEQUENCE_REUSE]=false; - long_opts[NO_CASCADE_DROP_TRUNC]=false; - long_opts[NO_FORCE_OBJ_RECREATION]=false; - long_opts[NO_UNMOD_OBJ_RECREATION]=false; - - short_opts[INPUT]=QString("-if"); - short_opts[OUTPUT]=QString("-of"); - short_opts[INPUT_DB]=QString("-id"); - short_opts[EXPORT_TO_FILE]=QString("-ef"); - short_opts[EXPORT_TO_PNG]=QString("-ep"); - short_opts[EXPORT_TO_SVG]=QString("-es"); - short_opts[EXPORT_TO_DBMS]=QString("-ed"); - short_opts[IMPORT_DB]=QString("-im"); - short_opts[DIFF]=QString("-df"); - short_opts[DROP_DATABASE]=QString("-dd"); - short_opts[DROP_OBJECTS]=QString("-do"); - short_opts[PGSQL_VER]=QString("-v"); - short_opts[HELP]=QString("-h"); - short_opts[SHOW_GRID]=QString("-sg"); - short_opts[SHOW_DELIMITERS]=QString("-sl"); - short_opts[PAGE_BY_PAGE]=QString("-pp"); - short_opts[IGNORE_DUPLICATES]=QString("-ir"); - short_opts[IGNORE_ERROR_CODES]=QString("-ic"); - short_opts[CONN_ALIAS]=QString("-ca"); - short_opts[HOST]=QString("-H"); - short_opts[PORT]=QString("-p"); - short_opts[USER]=QString("-u"); - short_opts[PASSWD]=QString("-w"); - short_opts[INITIAL_DB]=QString("-D"); - short_opts[SILENT]=QString("-s"); - short_opts[LIST_CONNS]=QString("-lc"); - short_opts[SIMULATE]=QString("-sm"); - short_opts[FIX_MODEL]=QString("-fm"); - short_opts[FIX_TRIES]=QString("-ft"); - short_opts[ZOOM_FACTOR]=QString("-zf"); - short_opts[USE_TMP_NAMES]=QString("-tn"); - short_opts[DBM_MIME_TYPE]=QString("-mt"); - short_opts[IGNORE_IMPORT_ERRORS]=QString("-ie"); - short_opts[IMPORT_SYSTEM_OBJS]=QString("-is"); - short_opts[IMPORT_EXTENSION_OBJS]=QString("-ix"); - short_opts[DEBUG_MODE]=QString("-d"); - short_opts[COMPARE_TO]=QString("-ct"); - short_opts[SAVE_DIFF]=QString("-sd"); - short_opts[APPLY_DIFF]=QString("-ad"); - short_opts[NO_DIFF_PREVIEW]=QString("-np"); - short_opts[DROP_CLUSTER_OBJS]=QString("-dc"); - short_opts[REVOKE_PERMISSIONS]=QString("-rv"); - short_opts[DROP_MISSING_OBJS]=QString("-dm"); - short_opts[FORCE_DROP_COLS_CONSTRS]=QString("-fd"); - short_opts[RENAME_DB]=QString("-rn"); - short_opts[TRUNC_ON_COLS_TYPE_CHANGE]=QString("-tt"); - short_opts[NO_SEQUENCE_REUSE]=QString("-ns"); - short_opts[NO_CASCADE_DROP_TRUNC]=QString("-nd"); - short_opts[NO_FORCE_OBJ_RECREATION]=QString("-nf"); - short_opts[NO_UNMOD_OBJ_RECREATION]=QString("-nu"); + long_opts[Input]=true; + long_opts[Output]=true; + long_opts[InputDb]=true; + long_opts[ExportToFile]=false; + long_opts[ExportToPng]=false; + long_opts[ExportToSvg]=false; + long_opts[ExportToDbms]=false; + long_opts[ImportDb]=false; + long_opts[Diff]=false; + long_opts[DropDatabase]=false; + long_opts[DropObjects]=false; + long_opts[PgSqlVer]=true; + long_opts[Help]=false; + long_opts[ShowGrid]=false; + long_opts[ShowDelimiters]=false; + long_opts[PageByPage]=false; + long_opts[IgnoreDuplicates]=false; + long_opts[IgnoreErrorCodes]=true; + long_opts[ConnAlias]=true; + long_opts[Host]=true; + long_opts[Port]=true; + long_opts[User]=true; + long_opts[Passwd]=true; + long_opts[InitialDb]=true; + long_opts[ListConns]=false; + long_opts[Simulate]=false; + long_opts[FixModel]=false; + long_opts[FixTries]=true; + long_opts[ZoomFactor]=true; + long_opts[UseTmpNames]=false; + long_opts[DbmMimeType]=true; + long_opts[IgnoreImportErrors]=false; + long_opts[ImportSystemObjs]=false; + long_opts[ImportExtensionObjs]=false; + long_opts[DebugMode]=false; + long_opts[CompareTo]=true; + long_opts[SaveDiff]=false; + long_opts[ApplyDiff]=false; + long_opts[NoDiffPreview]=false; + long_opts[DropClusterObjs]=false; + long_opts[RevokePermissions]=false; + long_opts[DropMissingObjs]=false; + long_opts[ForceDropColsConstrs]=false; + long_opts[RenameDb]=false; + long_opts[TruncOnColsTypeChange]=false; + long_opts[NoSequenceReuse]=false; + long_opts[NoCascadeDropTrunc]=false; + long_opts[NoForceObjRecreation]=false; + long_opts[NoUnmodObjRecreation]=false; + + short_opts[Input]=QString("-if"); + short_opts[Output]=QString("-of"); + short_opts[InputDb]=QString("-id"); + short_opts[ExportToFile]=QString("-ef"); + short_opts[ExportToPng]=QString("-ep"); + short_opts[ExportToSvg]=QString("-es"); + short_opts[ExportToDbms]=QString("-ed"); + short_opts[ImportDb]=QString("-im"); + short_opts[Diff]=QString("-df"); + short_opts[DropDatabase]=QString("-dd"); + short_opts[DropObjects]=QString("-do"); + short_opts[PgSqlVer]=QString("-v"); + short_opts[Help]=QString("-h"); + short_opts[ShowGrid]=QString("-sg"); + short_opts[ShowDelimiters]=QString("-sl"); + short_opts[PageByPage]=QString("-pp"); + short_opts[IgnoreDuplicates]=QString("-ir"); + short_opts[IgnoreErrorCodes]=QString("-ic"); + short_opts[ConnAlias]=QString("-ca"); + short_opts[Host]=QString("-H"); + short_opts[Port]=QString("-p"); + short_opts[User]=QString("-u"); + short_opts[Passwd]=QString("-w"); + short_opts[InitialDb]=QString("-D"); + short_opts[Silent]=QString("-s"); + short_opts[ListConns]=QString("-lc"); + short_opts[Simulate]=QString("-sm"); + short_opts[FixModel]=QString("-fm"); + short_opts[FixTries]=QString("-ft"); + short_opts[ZoomFactor]=QString("-zf"); + short_opts[UseTmpNames]=QString("-tn"); + short_opts[DbmMimeType]=QString("-mt"); + short_opts[IgnoreImportErrors]=QString("-ie"); + short_opts[ImportSystemObjs]=QString("-is"); + short_opts[ImportExtensionObjs]=QString("-ix"); + short_opts[DebugMode]=QString("-d"); + short_opts[CompareTo]=QString("-ct"); + short_opts[SaveDiff]=QString("-sd"); + short_opts[ApplyDiff]=QString("-ad"); + short_opts[NoDiffPreview]=QString("-np"); + short_opts[DropClusterObjs]=QString("-dc"); + short_opts[RevokePermissions]=QString("-rv"); + short_opts[DropMissingObjs]=QString("-dm"); + short_opts[ForceDropColsConstrs]=QString("-fd"); + short_opts[RenameDb]=QString("-rn"); + short_opts[TruncOnColsTypeChange]=QString("-tt"); + short_opts[NoSequenceReuse]=QString("-ns"); + short_opts[NoCascadeDropTrunc]=QString("-nd"); + short_opts[NoForceObjRecreation]=QString("-nf"); + short_opts[NoUnmodObjRecreation]=QString("-nu"); } -bool PgModelerCLI::isOptionRecognized(QString &op, bool &accepts_val) +bool PgModelerCli::isOptionRecognized(QString &op, bool &accepts_val) { bool found=false, append_chr = false; @@ -363,112 +363,112 @@ bool PgModelerCLI::isOptionRecognized(QString &op, bool &accepts_val) return(found); } -void PgModelerCLI::showMenu(void) +void PgModelerCli::showMenu(void) { out << endl; - out << trUtf8("Usage: pgmodeler-cli [OPTIONS]") << endl; - out << QString("pgModeler ") << GlobalAttributes::PGMODELER_VERSION << trUtf8(" command line interface.") << endl; + out << QString("pgModeler ") << GlobalAttributes::PgModelerVersion << trUtf8(" command line interface.") << endl; out << trUtf8("PostgreSQL Database Modeler Project - pgmodeler.io") << endl; out << trUtf8("Copyright 2006-2018 Raphael A. Silva ") << endl; out << endl; - out << trUtf8("This CLI tool provides several operations over models and databases without the need to perform them\non pgModeler's graphical interface. All available options are described below.") << endl; + out << trUtf8("Usage: pgmodeler-cli [OPTIONS]") << endl << endl; + out << trUtf8("This CLI tool provides several operations over models and databases without the need to perform them\nin pgModeler's graphical interface. All available options are described below.") << endl; out << endl; out << trUtf8("General options: ") << endl; - out << trUtf8(" %1, %2 [FILE]\t\t Input model file (.dbm). This is mandatory in fix, export operations.").arg(short_opts[INPUT]).arg(INPUT) << endl; - out << trUtf8(" %1, %2 [DBNAME]\t Input database name. This is mandatory import operation.").arg(short_opts[INPUT_DB]).arg(INPUT_DB) << endl; - out << trUtf8(" %1, %2 [FILE]\t\t Output file. Mandatory use in fixing model or exporting to file, png or svg.").arg(short_opts[OUTPUT]).arg(OUTPUT) << endl; - out << trUtf8(" %1, %2\t\t Try to fix the structure of the input model file in order to make it loadable again.").arg(short_opts[FIX_MODEL]).arg(FIX_MODEL) << endl; - out << trUtf8(" %1, %2 [NUMBER]\t Model fix tries. When reaching the maximum count the invalid objects will be discard.").arg(short_opts[FIX_TRIES]).arg(FIX_TRIES) << endl; - out << trUtf8(" %1, %2\t\t Export the input model to a sql script file.").arg(short_opts[EXPORT_TO_FILE]).arg(EXPORT_TO_FILE)<< endl; - out << trUtf8(" %1, %2\t\t Export the input model to a png image.").arg(short_opts[EXPORT_TO_PNG]).arg(EXPORT_TO_PNG) << endl; - out << trUtf8(" %1, %2\t\t Export the input model to a svg file.").arg(short_opts[EXPORT_TO_SVG]).arg(EXPORT_TO_SVG) << endl; - out << trUtf8(" %1, %2\t\t Export the input model directly to a PostgreSQL server.").arg(short_opts[EXPORT_TO_DBMS]).arg(EXPORT_TO_DBMS) << endl; - out << trUtf8(" %1, %2\t\t Import a database to an output file.").arg(short_opts[IMPORT_DB]).arg(IMPORT_DB) << endl; - out << trUtf8(" %1, %2\t\t\t Compares a model and database or two databases generating a SQL script to synch the latter in relation to the first.").arg(short_opts[DIFF]).arg(DIFF) << endl; - out << trUtf8(" %1, %2\t\t Force the PostgreSQL version of generated SQL code.").arg(short_opts[PGSQL_VER]).arg(PGSQL_VER) << endl; - out << trUtf8(" %1, %2\t\t\t Silent execution. Only critical errors are shown during process.").arg(short_opts[SILENT]).arg(SILENT) << endl; - out << trUtf8(" %1, %2\t\t\t Show this help menu.").arg(short_opts[HELP]).arg(HELP) << endl; + out << trUtf8(" %1, %2 [FILE]\t\t Input model file (.dbm). This is mandatory for fix, export operations.").arg(short_opts[Input]).arg(Input) << endl; + out << trUtf8(" %1, %2 [DBNAME]\t Input database name. This is mandatory for import operation.").arg(short_opts[InputDb]).arg(InputDb) << endl; + out << trUtf8(" %1, %2 [FILE]\t\t Output file. This is mandatory for fixing model or exporting to file, png or svg.").arg(short_opts[Output]).arg(Output) << endl; + out << trUtf8(" %1, %2\t\t Try to fix the structure of the input model file in order to make it loadable again.").arg(short_opts[FixModel]).arg(FixModel) << endl; + out << trUtf8(" %1, %2 [NUMBER]\t Model fix tries. When reaching the maximum count the invalid objects will be discarded.").arg(short_opts[FixTries]).arg(FixTries) << endl; + out << trUtf8(" %1, %2\t\t Export the input model to a sql script file.").arg(short_opts[ExportToFile]).arg(ExportToFile)<< endl; + out << trUtf8(" %1, %2\t\t Export the input model to a png image.").arg(short_opts[ExportToPng]).arg(ExportToPng) << endl; + out << trUtf8(" %1, %2\t\t Export the input model to a svg file.").arg(short_opts[ExportToSvg]).arg(ExportToSvg) << endl; + out << trUtf8(" %1, %2\t\t Export the input model directly to a PostgreSQL server.").arg(short_opts[ExportToDbms]).arg(ExportToDbms) << endl; + out << trUtf8(" %1, %2\t\t Import a database to an output file.").arg(short_opts[ImportDb]).arg(ImportDb) << endl; + out << trUtf8(" %1, %2\t\t\t Compares a model and a database or two databases generating the SQL script to synch the latter in relation to the first.").arg(short_opts[Diff]).arg(Diff) << endl; + out << trUtf8(" %1, %2\t\t Force the PostgreSQL version of generated SQL code.").arg(short_opts[PgSqlVer]).arg(PgSqlVer) << endl; + out << trUtf8(" %1, %2\t\t\t Silent execution. Only critical messages and errors are shown during process.").arg(short_opts[Silent]).arg(Silent) << endl; + out << trUtf8(" %1, %2\t\t\t Show this help menu.").arg(short_opts[Help]).arg(Help) << endl; out << endl; out << trUtf8("Connection options: ") << endl; - out << trUtf8(" %1, %2\t\t List available connections in file %3.").arg(short_opts[LIST_CONNS]).arg(LIST_CONNS).arg(GlobalAttributes::CONNECTIONS_CONF + GlobalAttributes::CONFIGURATION_EXT) << endl; - out << trUtf8(" %1, %2 [ALIAS]\t Connection configuration alias to be used.").arg(short_opts[CONN_ALIAS]).arg(CONN_ALIAS) << endl; - out << trUtf8(" %1, %2 [HOST]\t\t PostgreSQL host which a task will operate.").arg(short_opts[HOST]).arg(HOST) << endl; - out << trUtf8(" %1, %2 [PORT]\t\t PostgreSQL host listening port.").arg(short_opts[PORT]).arg(PORT) << endl; - out << trUtf8(" %1, %2 [USER]\t\t PostgreSQL username.").arg(short_opts[USER]).arg(USER) << endl; - out << trUtf8(" %1, %2 [PASSWORD]\t PostgreSQL user password.").arg(short_opts[PASSWD]).arg(PASSWD) << endl; - out << trUtf8(" %1, %2 [DBNAME]\t Connection's initial database.").arg(short_opts[INITIAL_DB]).arg(INITIAL_DB) << endl; + out << trUtf8(" %1, %2\t\t List available connections in file %3.").arg(short_opts[ListConns]).arg(ListConns).arg(GlobalAttributes::ConnectionsConf + GlobalAttributes::ConfigurationExt) << endl; + out << trUtf8(" %1, %2 [ALIAS]\t Connection configuration alias to be used.").arg(short_opts[ConnAlias]).arg(ConnAlias) << endl; + out << trUtf8(" %1, %2 [HOST]\t\t PostgreSQL host in which a task will operate.").arg(short_opts[Host]).arg(Host) << endl; + out << trUtf8(" %1, %2 [PORT]\t\t PostgreSQL host listening port.").arg(short_opts[Port]).arg(Port) << endl; + out << trUtf8(" %1, %2 [USER]\t\t PostgreSQL username.").arg(short_opts[User]).arg(User) << endl; + out << trUtf8(" %1, %2 [PASSWORD]\t PostgreSQL user password.").arg(short_opts[Passwd]).arg(Passwd) << endl; + out << trUtf8(" %1, %2 [DBNAME]\t Connection's initial database.").arg(short_opts[InitialDb]).arg(InitialDb) << endl; out << endl; out << trUtf8("PNG and SVG export options: ") << endl; - out << trUtf8(" %1, %2\t\t Draws the grid on the exported png image.").arg(short_opts[SHOW_GRID]).arg(SHOW_GRID) << endl; - out << trUtf8(" %1, %2\t Draws the page delimiters on the exported png image.").arg(short_opts[SHOW_DELIMITERS]).arg(SHOW_DELIMITERS) << endl; - out << trUtf8(" %1, %2\t\t Each page will be exported on a separated png image. (Only for PNG)").arg(short_opts[PAGE_BY_PAGE]).arg(PAGE_BY_PAGE) << endl; - out << trUtf8(" %1, %2 [FACTOR]\t\t Applies a zoom (in percent) before export to png image. Accepted zoom interval: %3-%4 (Only for PNG)").arg(short_opts[ZOOM_FACTOR]).arg(ZOOM_FACTOR).arg(ModelWidget::MINIMUM_ZOOM*100).arg(ModelWidget::MAXIMUM_ZOOM*100) << endl; + out << trUtf8(" %1, %2\t\t Draws the grid in the exported image.").arg(short_opts[ShowGrid]).arg(ShowGrid) << endl; + out << trUtf8(" %1, %2\t Draws the page delimiters in the exported image.").arg(short_opts[ShowDelimiters]).arg(ShowDelimiters) << endl; + out << trUtf8(" %1, %2\t\t Each page will be exported in a separated png image. (Only for PNG images)").arg(short_opts[PageByPage]).arg(PageByPage) << endl; + out << trUtf8(" %1, %2 [FACTOR]\t\t Applies a zoom (in percent) before export to png image. Accepted zoom interval: %3-%4 (Only for PNG images)").arg(short_opts[ZoomFactor]).arg(ZoomFactor).arg(ModelWidget::MinimumZoom*100).arg(ModelWidget::MaximumZoom*100) << endl; out << endl; out << trUtf8("DBMS export options: ") << endl; - out << trUtf8(" %1, %2\t Ignores errors related to duplicated objects that eventually exists on server side.").arg(short_opts[IGNORE_DUPLICATES]).arg(IGNORE_DUPLICATES) << endl; - out << trUtf8(" %1, %2 [CODES] Ignores additional errors by their codes. A comma-separated list of alphanumeric codes should be provided.").arg(short_opts[IGNORE_ERROR_CODES]).arg(IGNORE_ERROR_CODES) << endl; - out << trUtf8(" %1, %2\t\t Drop the database before execute a export process.").arg(short_opts[DROP_DATABASE]).arg(DROP_DATABASE) << endl; - out << trUtf8(" %1, %2\t\t Runs the DROP commands attached to SQL-enabled objects.").arg(short_opts[DROP_OBJECTS]).arg(DROP_OBJECTS) << endl; - out << trUtf8(" %1, %2\t\t Simulates a export process. Actually executes all steps but undoing any modification.").arg(short_opts[SIMULATE]).arg(SIMULATE) << endl; - out << trUtf8(" %1, %2\t\t Generates temporary names for database, roles and tablespaces when in simulation mode.").arg(short_opts[USE_TMP_NAMES]).arg(USE_TMP_NAMES) << endl; + out << trUtf8(" %1, %2\t Ignores errors related to duplicated objects that eventually exist in the server.").arg(short_opts[IgnoreDuplicates]).arg(IgnoreDuplicates) << endl; + out << trUtf8(" %1, %2 [CODES] Ignores additional errors by their codes. A comma-separated list of alphanumeric codes should be provided.").arg(short_opts[IgnoreErrorCodes]).arg(IgnoreErrorCodes) << endl; + out << trUtf8(" %1, %2\t\t Drop the database before execute a export process.").arg(short_opts[DropDatabase]).arg(DropDatabase) << endl; + out << trUtf8(" %1, %2\t\t Runs the DROP commands attached to SQL-enabled objects.").arg(short_opts[DropObjects]).arg(DropObjects) << endl; + out << trUtf8(" %1, %2\t\t Simulates an export process by executing all steps but undoing any modification in the end.").arg(short_opts[Simulate]).arg(Simulate) << endl; + out << trUtf8(" %1, %2\t\t Generates temporary names for database, roles and tablespaces when in simulation mode.").arg(short_opts[UseTmpNames]).arg(UseTmpNames) << endl; out << endl; out << trUtf8("Database import options: ") << endl; - out << trUtf8(" %1, %2\t\t Ignore all errors and try to create as many as possible objects.").arg(short_opts[IGNORE_IMPORT_ERRORS]).arg(IGNORE_IMPORT_ERRORS) << endl; - out << trUtf8(" %1, %2\t Import system built-in objects. This option causes the model bloating due to the importing of unneeded objects.").arg(short_opts[IMPORT_SYSTEM_OBJS]).arg(IMPORT_SYSTEM_OBJS) << endl; - out << trUtf8(" %1, %2\t Import extension objects. This option causes the model bloating due to the importing of unneeded objects.").arg(short_opts[IMPORT_EXTENSION_OBJS]).arg(IMPORT_EXTENSION_OBJS) << endl; - out << trUtf8(" %1, %2\t\t Run import in debug mode printing all queries executed in the server.").arg(short_opts[DEBUG_MODE]).arg(DEBUG_MODE) << endl; + out << trUtf8(" %1, %2\t\t Ignore all errors and try to create as many as possible objects.").arg(short_opts[IgnoreImportErrors]).arg(IgnoreImportErrors) << endl; + out << trUtf8(" %1, %2\t Import system built-in objects. This option causes the model bloating due to the importing of unneeded objects.").arg(short_opts[ImportSystemObjs]).arg(ImportSystemObjs) << endl; + out << trUtf8(" %1, %2\t Import extension objects. This option causes the model bloating due to the importing of unneeded objects.").arg(short_opts[ImportExtensionObjs]).arg(ImportExtensionObjs) << endl; + out << trUtf8(" %1, %2\t\t Run import in debug mode printing all queries executed in the server.").arg(short_opts[DebugMode]).arg(DebugMode) << endl; out << endl; out << trUtf8("Diff options: ") << endl; - out << trUtf8(" %1, %2 [DBNAME]\t The database used in the comparison. All the SQL code generated is applied to it.").arg(short_opts[COMPARE_TO]).arg(COMPARE_TO) << endl; - out << trUtf8(" %1, %2\t\t Save the generated diff code to output file.").arg(short_opts[SAVE_DIFF]).arg(SAVE_DIFF) << endl; - out << trUtf8(" %1, %2\t\t Apply the generated diff code to the database.").arg(short_opts[APPLY_DIFF]).arg(APPLY_DIFF) << endl; - out << trUtf8(" %1, %2\t Don't preview the generated diff code.").arg(short_opts[NO_DIFF_PREVIEW]).arg(NO_DIFF_PREVIEW) << endl; - out << trUtf8(" %1, %2\t Drop cluster level objects like roles and tablespaces.").arg(short_opts[DROP_CLUSTER_OBJS]).arg(DROP_CLUSTER_OBJS) << endl; - out << trUtf8(" %1, %2\t\t Revoke permissions already set on the database. New permissions configured in the input model are still applied.").arg(short_opts[REVOKE_PERMISSIONS]).arg(REVOKE_PERMISSIONS) << endl; - out << trUtf8(" %1, %2\t\t Drop missing objects. Generates DROP commands for objects that are present in the input model but not in the compared database.").arg(short_opts[DROP_MISSING_OBJS]).arg(DROP_MISSING_OBJS) << endl; - out << trUtf8(" %1, %2\t Force the drop of missing columns and constraints. Causes only columns and constraints to be dropped, other missing objects aren't removed.").arg(short_opts[FORCE_DROP_COLS_CONSTRS]).arg(FORCE_DROP_COLS_CONSTRS) << endl; - out << trUtf8(" %1, %2\t\t Rename the destination database. When the databases have different names the destination one has its name changed.").arg(short_opts[RENAME_DB]).arg(RENAME_DB) << endl; - out << trUtf8(" %1, %2\t\t Don't drop or truncate objects in cascade mode.").arg(short_opts[NO_CASCADE_DROP_TRUNC]).arg(NO_CASCADE_DROP_TRUNC) << endl; - out << trUtf8(" %1, %2\t Truncate tables prior to alter columns. Avoids errors related to type casting when the new type of a column isn't compatible to the old one.").arg(short_opts[TRUNC_ON_COLS_TYPE_CHANGE]).arg(TRUNC_ON_COLS_TYPE_CHANGE) << endl; - out << trUtf8(" %1, %2\t Don't reuse sequences on serial columns. Drop the old sequence assigned to a serial column and creates a new one.").arg(short_opts[NO_SEQUENCE_REUSE]).arg(NO_SEQUENCE_REUSE) << endl; - out << trUtf8(" %1, %2\t Don't force the recreation of objects. Avoids the usage of a DROP and CREATE commands to create a new version of the objects.").arg(short_opts[NO_FORCE_OBJ_RECREATION]).arg(NO_FORCE_OBJ_RECREATION) << endl; - out << trUtf8(" %1, %2\t Don't recreate the unmodifiable objects. These objects are the ones which can't be changed via ALTER command.").arg(short_opts[NO_UNMOD_OBJ_RECREATION]).arg(NO_UNMOD_OBJ_RECREATION) << endl; + out << trUtf8(" %1, %2 [DBNAME]\t The database used in the comparison. All the SQL code generated is applied to it.").arg(short_opts[CompareTo]).arg(CompareTo) << endl; + out << trUtf8(" %1, %2\t\t Save the generated diff code to output file.").arg(short_opts[SaveDiff]).arg(SaveDiff) << endl; + out << trUtf8(" %1, %2\t\t Apply the generated diff code on the database server.").arg(short_opts[ApplyDiff]).arg(ApplyDiff) << endl; + out << trUtf8(" %1, %2\t Don't preview the generated diff code when applying it to the server.").arg(short_opts[NoDiffPreview]).arg(NoDiffPreview) << endl; + out << trUtf8(" %1, %2\t Drop cluster level objects like roles and tablespaces.").arg(short_opts[DropClusterObjs]).arg(DropClusterObjs) << endl; + out << trUtf8(" %1, %2\t\t Revoke permissions already set on the database. New permissions configured in the input model are still applied.").arg(short_opts[RevokePermissions]).arg(RevokePermissions) << endl; + out << trUtf8(" %1, %2\t\t Drop missing objects. Generates DROP commands for objects that are present in the input model but not in the compared database.").arg(short_opts[DropMissingObjs]).arg(DropMissingObjs) << endl; + out << trUtf8(" %1, %2\t Force the drop of missing columns and constraints. Causes only columns and constraints to be dropped, other missing objects aren't removed.").arg(short_opts[ForceDropColsConstrs]).arg(ForceDropColsConstrs) << endl; + out << trUtf8(" %1, %2\t\t Rename the destination database when the names of the involved databases are different.").arg(short_opts[RenameDb]).arg(RenameDb) << endl; + out << trUtf8(" %1, %2\t\t Don't drop or truncate objects in cascade mode.").arg(short_opts[NoCascadeDropTrunc]).arg(NoCascadeDropTrunc) << endl; + out << trUtf8(" %1, %2\t Truncate tables prior to alter columns. Avoids errors related to type casting when the new type of a column isn't compatible to the old one.").arg(short_opts[TruncOnColsTypeChange]).arg(TruncOnColsTypeChange) << endl; + out << trUtf8(" %1, %2\t Don't reuse sequences on serial columns. Drop the old sequence assigned to a serial column and creates a new one.").arg(short_opts[NoSequenceReuse]).arg(NoSequenceReuse) << endl; + out << trUtf8(" %1, %2\t Don't force the recreation of objects. Avoids the usage of a DROP and CREATE commands to create a new version of the objects.").arg(short_opts[NoForceObjRecreation]).arg(NoForceObjRecreation) << endl; + out << trUtf8(" %1, %2\t Don't recreate the unmodifiable objects. These objects are the ones which can't be changed via ALTER command.").arg(short_opts[NoUnmodObjRecreation]).arg(NoUnmodObjRecreation) << endl; out << endl; #ifndef Q_OS_MAC out << trUtf8("Miscellaneous options: ") << endl; - out << trUtf8(" %1, %2 [ACTION]\t Handles the file association to .dbm files. The ACTION can be [%3 | %4].").arg(short_opts[DBM_MIME_TYPE]).arg(DBM_MIME_TYPE).arg(INSTALL).arg(UNINSTALL) << endl; + out << trUtf8(" %1, %2 [ACTION]\t Handles the file association to .dbm files. The ACTION can be [%3 | %4].").arg(short_opts[DbmMimeType]).arg(DbmMimeType).arg(Install).arg(Uninstall) << endl; out << endl; #endif out << trUtf8("** The diff process allows the usage of the following options related to import and export operations: ") << endl; - out << " " << QStringList({ trUtf8("* Export: "), IGNORE_DUPLICATES, IGNORE_ERROR_CODES, "\n ", trUtf8("* Import: "), IMPORT_SYSTEM_OBJS, IMPORT_EXTENSION_OBJS, IGNORE_IMPORT_ERRORS, DEBUG_MODE }).join(" ") << endl; + out << " " << QStringList({ trUtf8("* Export: "), IgnoreDuplicates, IgnoreErrorCodes, "\n ", trUtf8("* Import: "), ImportSystemObjs, ImportExtensionObjs, IgnoreImportErrors, DebugMode }).join(" ") << endl; out << endl; - out << trUtf8("** When running the diff using two databases (%1 and %2) there's the need to specify two connections/aliases. ").arg(INPUT_DB).arg(COMPARE_TO) << endl; + out << trUtf8("** When running the diff using two databases (%1 and %2) there's the need to specify two connections/aliases. ").arg(InputDb).arg(CompareTo) << endl; out << trUtf8(" If only one connection is set it will be used to import the input database as well to retrieve database used in the comparison.") << endl; out << trUtf8(" A second connection can be specified by appending a 1 on any connection configuration parameter listed above.") << endl; out << endl; } -void PgModelerCLI::parseOptions(attribs_map &opts) +void PgModelerCli::parseOptions(attribs_map &opts) { //Loading connections - if(opts.count(LIST_CONNS) || opts.count(EXPORT_TO_DBMS) || opts.count(IMPORT_DB) || opts.count(DIFF)) + if(opts.count(ListConns) || opts.count(ExportToDbms) || opts.count(ImportDb) || opts.count(Diff)) { conn_conf.loadConfiguration(); conn_conf.getConnections(connections, false); } //Loading general and relationship settings when exporting to image formats - else if(opts.count(EXPORT_TO_PNG) || opts.count(EXPORT_TO_SVG)) + else if(opts.count(ExportToPng) || opts.count(ExportToSvg)) { general_conf.loadConfiguration(); rel_conf.loadConfiguration(); } - if(opts.empty() || opts.count(HELP)) + if(opts.empty() || opts.count(Help)) showMenu(); //Listing connections - else if(opts.count(LIST_CONNS)) + else if(opts.count(ListConns)) { map::iterator itr=connections.begin(); @@ -482,7 +482,7 @@ void PgModelerCLI::parseOptions(attribs_map &opts) while(itr != connections.end()) { out << QString("[") << id++ << QString("] ") << itr->first << QString(" : ") << - itr->second->getConnectionString().replace(PASSWORD_REGEXP, PASSWORD_PLACEHOLDER) << endl; + itr->second->getConnectionString().replace(PasswordRegExp, PasswordPlaceholder) << endl; itr++; } @@ -492,100 +492,100 @@ void PgModelerCLI::parseOptions(attribs_map &opts) else { int mode_cnt=0, other_modes_cnt=0; - bool fix_model=(opts.count(FIX_MODEL) > 0), upd_mime=(opts.count(DBM_MIME_TYPE) > 0), - import_db=(opts.count(IMPORT_DB) > 0), diff=(opts.count(DIFF) > 0); + bool fix_model=(opts.count(FixModel) > 0), upd_mime=(opts.count(DbmMimeType) > 0), + import_db=(opts.count(ImportDb) > 0), diff=(opts.count(Diff) > 0); //Checking if multiples export modes were specified - mode_cnt+=opts.count(EXPORT_TO_FILE); - mode_cnt+=opts.count(EXPORT_TO_PNG); - mode_cnt+=opts.count(EXPORT_TO_SVG); - mode_cnt+=opts.count(EXPORT_TO_DBMS); + mode_cnt+=opts.count(ExportToFile); + mode_cnt+=opts.count(ExportToPng); + mode_cnt+=opts.count(ExportToSvg); + mode_cnt+=opts.count(ExportToDbms); - other_modes_cnt+=opts.count(FIX_MODEL); - other_modes_cnt+=opts.count(IMPORT_DB); - other_modes_cnt+=opts.count(DIFF); - other_modes_cnt+=opts.count(DBM_MIME_TYPE); + other_modes_cnt+=opts.count(FixModel); + other_modes_cnt+=opts.count(ImportDb); + other_modes_cnt+=opts.count(Diff); + other_modes_cnt+=opts.count(DbmMimeType); - if(opts.count(ZOOM_FACTOR)) - zoom=opts[ZOOM_FACTOR].toDouble()/static_cast(100); + if(opts.count(ZoomFactor)) + zoom=opts[ZoomFactor].toDouble()/static_cast(100); if(other_modes_cnt==0 && mode_cnt==0) - throw Exception(trUtf8("No operation mode was specified!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(trUtf8("No operation mode was specified!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); if((mode_cnt > 0 && (fix_model || upd_mime || import_db || diff)) || (mode_cnt==0 && other_modes_cnt > 1)) - throw Exception(trUtf8("Export, fix model, import database, diff and update mime operations can't be used at the same time!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(trUtf8("Export, fix model, import database, diff and update mime operations can't be used at the same time!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); if(!fix_model && !upd_mime && mode_cnt > 1) - throw Exception(trUtf8("Multiple export mode was specified!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(trUtf8("Multiple export mode was specified!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(!upd_mime && !import_db && !diff && opts[INPUT].isEmpty()) - throw Exception(trUtf8("No input file was specified!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(!upd_mime && !import_db && !diff && opts[Input].isEmpty()) + throw Exception(trUtf8("No input file was specified!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(import_db && opts[INPUT_DB].isEmpty()) - throw Exception(trUtf8("No input database was specified!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(import_db && opts[InputDb].isEmpty()) + throw Exception(trUtf8("No input database was specified!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(!opts.count(EXPORT_TO_DBMS) && !upd_mime && !diff && opts[OUTPUT].isEmpty()) - throw Exception(trUtf8("No output file was specified!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(!opts.count(ExportToDbms) && !upd_mime && !diff && opts[Output].isEmpty()) + throw Exception(trUtf8("No output file was specified!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(!opts.count(EXPORT_TO_DBMS) && !upd_mime && !import_db && - !opts[INPUT].isEmpty() && !opts[OUTPUT].isEmpty() && - QFileInfo(opts[INPUT]).absoluteFilePath() == QFileInfo(opts[OUTPUT]).absoluteFilePath()) - throw Exception(trUtf8("Input file must be different from output!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(!opts.count(ExportToDbms) && !upd_mime && !import_db && + !opts[Input].isEmpty() && !opts[Output].isEmpty() && + QFileInfo(opts[Input]).absoluteFilePath() == QFileInfo(opts[Output]).absoluteFilePath()) + throw Exception(trUtf8("Input file must be different from output!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(opts.count(EXPORT_TO_DBMS) && !opts.count(CONN_ALIAS) && - (!opts.count(HOST) || !opts.count(USER) || !opts.count(PASSWD) || !opts.count(INITIAL_DB)) ) - throw Exception(trUtf8("Incomplete connection information!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(opts.count(ExportToDbms) && !opts.count(ConnAlias) && + (!opts.count(Host) || !opts.count(User) || !opts.count(Passwd) || !opts.count(InitialDb)) ) + throw Exception(trUtf8("Incomplete connection information!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(opts.count(EXPORT_TO_PNG) && (zoom < ModelWidget::MINIMUM_ZOOM || zoom > ModelWidget::MAXIMUM_ZOOM)) - throw Exception(trUtf8("Invalid zoom specified!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(opts.count(ExportToPng) && (zoom < ModelWidget::MinimumZoom || zoom > ModelWidget::MaximumZoom)) + throw Exception(trUtf8("Invalid zoom specified!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(upd_mime && opts[DBM_MIME_TYPE]!=INSTALL && opts[DBM_MIME_TYPE]!=UNINSTALL) - throw Exception(trUtf8("Invalid action specified to update mime option!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(upd_mime && opts[DbmMimeType]!=Install && opts[DbmMimeType]!=Uninstall) + throw Exception(trUtf8("Invalid action specified to update mime option!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(opts.count(DIFF)) + if(opts.count(Diff)) { - if(opts[INPUT].isEmpty() && opts[INPUT_DB].isEmpty()) - throw Exception(trUtf8("No input file or database was specified!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(opts[Input].isEmpty() && opts[InputDb].isEmpty()) + throw Exception(trUtf8("No input file or database was specified!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(!opts[INPUT].isEmpty() && !opts[INPUT_DB].isEmpty()) - throw Exception(trUtf8("The input file and database can't be used at the same time!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(!opts[Input].isEmpty() && !opts[InputDb].isEmpty()) + throw Exception(trUtf8("The input file and database can't be used at the same time!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(!opts.count(COMPARE_TO)) - throw Exception(trUtf8("No database to be compared was specified!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(!opts.count(CompareTo)) + throw Exception(trUtf8("No database to be compared was specified!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(!opts.count(SAVE_DIFF) && !opts.count(APPLY_DIFF)) - throw Exception(trUtf8("No diff action (save or apply) was specified!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(!opts.count(SaveDiff) && !opts.count(ApplyDiff)) + throw Exception(trUtf8("No diff action (save or apply) was specified!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); - if(opts.count(SAVE_DIFF) && opts[OUTPUT].isEmpty()) - throw Exception(trUtf8("No output file for the diff code was specified!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + if(opts.count(SaveDiff) && opts[Output].isEmpty()) + throw Exception(trUtf8("No output file for the diff code was specified!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); } //Converting input and output files to absolute paths to avoid that they are read/written on the app's working dir - if(!opts[INPUT].isEmpty()) - opts[INPUT]=QFileInfo(opts[INPUT]).absoluteFilePath(); + if(!opts[Input].isEmpty()) + opts[Input]=QFileInfo(opts[Input]).absoluteFilePath(); - if(!opts[OUTPUT].isEmpty()) - opts[OUTPUT]=QFileInfo(opts[OUTPUT]).absoluteFilePath(); + if(!opts[Output].isEmpty()) + opts[Output]=QFileInfo(opts[Output]).absoluteFilePath(); parsed_opts=opts; } } -int PgModelerCLI::exec(void) +int PgModelerCli::exec(void) { try { if(!parsed_opts.empty()) { - printMessage(QString("\npgModeler %1 %2").arg(GlobalAttributes::PGMODELER_VERSION).arg(trUtf8(" command line interface."))); + printMessage(QString("\npgModeler %1 %2").arg(GlobalAttributes::PgModelerVersion).arg(trUtf8(" command line interface."))); - if(parsed_opts.count(FIX_MODEL)) + if(parsed_opts.count(FixModel)) fixModel(); - else if(parsed_opts.count(DBM_MIME_TYPE)) + else if(parsed_opts.count(DbmMimeType)) updateMimeType(); - else if(parsed_opts.count(IMPORT_DB)) + else if(parsed_opts.count(ImportDb)) importDatabase(); - else if(parsed_opts.count(DIFF)) + else if(parsed_opts.count(Diff)) diffModelDatabase(); else exportModel(); @@ -599,7 +599,7 @@ int PgModelerCLI::exec(void) } } -void PgModelerCLI::updateProgress(int progress, QString msg, ObjectType) +void PgModelerCli::updateProgress(int progress, QString msg, ObjectType) { if(progress > 0) out << QString("[%1%] ").arg(progress > 100 ? 100 : progress) << msg << endl; @@ -607,7 +607,7 @@ void PgModelerCLI::updateProgress(int progress, QString msg, ObjectType) out << msg << endl; } -void PgModelerCLI::printIgnoredError(QString err_cod, QString err_msg, QString cmd) +void PgModelerCli::printIgnoredError(QString err_cod, QString err_msg, QString cmd) { out << endl; out << trUtf8("** Error code `%1' found and ignored. Proceeding with export.").arg(err_cod) << endl; @@ -616,7 +616,7 @@ void PgModelerCLI::printIgnoredError(QString err_cod, QString err_msg, QString c out << endl; } -void PgModelerCLI::handleObjectAddition(BaseObject *object) +void PgModelerCli::handleObjectAddition(BaseObject *object) { BaseGraphicObject *graph_obj=dynamic_cast(object); @@ -627,59 +627,58 @@ void PgModelerCLI::handleObjectAddition(BaseObject *object) switch(obj_type) { - case OBJ_TABLE: + case ObjectType::Table: item=new TableView(dynamic_cast
(graph_obj)); break; - case OBJ_VIEW: + case ObjectType::View: item=new GraphicalView(dynamic_cast(graph_obj)); break; - case OBJ_RELATIONSHIP: - case BASE_RELATIONSHIP: - item=new RelationshipView(dynamic_cast(graph_obj)); break; + case ObjectType::Relationship: + case ObjectType::BaseRelationship: + item=new RelationshipView(dynamic_cast(graph_obj)); break; - case OBJ_SCHEMA: - item=new SchemaView(dynamic_cast(graph_obj)); break; + case ObjectType::Schema: + item=new SchemaView(dynamic_cast(graph_obj)); break; default: - item=new StyledTextboxView(dynamic_cast(graph_obj)); break; + item=new StyledTextboxView(dynamic_cast(graph_obj)); break; } scene->addItem(item); - if(obj_type==OBJ_TABLE || obj_type==OBJ_VIEW) + if(obj_type==ObjectType::Table || obj_type==ObjectType::View) dynamic_cast(graph_obj->getSchema())->setModified(true); } } -void PgModelerCLI::handleObjectRemoval(BaseObject *object) +void PgModelerCli::handleObjectRemoval(BaseObject *object) { BaseGraphicObject *graph_obj=dynamic_cast(object); if(graph_obj) { - scene->removeItem(dynamic_cast(graph_obj->getReceiverObject())); + scene->removeItem(dynamic_cast(graph_obj->getOverlyingObject())); //Updates the parent schema if the removed object were a table or view if(graph_obj->getSchema() && - (graph_obj->getObjectType()==OBJ_TABLE || graph_obj->getObjectType()==OBJ_VIEW)) + (graph_obj->getObjectType()==ObjectType::Table || graph_obj->getObjectType()==ObjectType::View)) dynamic_cast(graph_obj->getSchema())->setModified(true); } } -void PgModelerCLI::extractObjectXML(void) +void PgModelerCli::extractObjectXML(void) { QFile input; QString buf, lin, def_xml, end_tag; QTextStream ts; - QRegExp regexp(QString("^(\\<\\?xml)(.)*(\\<%1)( )*").arg(ParsersAttributes::DB_MODEL)), - default_obj=QRegExp(QString("(default)(\\-)(schema|owner|collation|tablespace)")), + QRegExp regexp(QString("^(\\<\\?xml)(.)*(\\<%1)( )*").arg(Attributes::DbModel)), //[schema].[func_name](...OUT [type]...) func_signature=QRegExp(QString("(\")(.)+(\\.)(.)+(\\()(.)*(OUT )(.)+(\\))(\")")), @@ -691,12 +690,12 @@ void PgModelerCLI::extractObjectXML(void) printMessage(trUtf8("Extracting objects' XML...")); - input.setFileName(parsed_opts[INPUT]); + input.setFileName(parsed_opts[Input]); input.open(QFile::ReadOnly); if(!input.isOpen()) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED).arg(parsed_opts[INPUT]), - ERR_FILE_DIR_NOT_ACCESSED,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed).arg(parsed_opts[Input]), + ErrorCode::FileDirectoryNotAccessed,__PRETTY_FUNCTION__,__FILE__,__LINE__); buf.append(input.readAll()); input.close(); @@ -705,13 +704,52 @@ void PgModelerCLI::extractObjectXML(void) start=regexp.indexIn(buf); if(start < 0) - throw Exception(trUtf8("Invalid input file! It seems that is not a pgModeler generated model or the file is corrupted!"), ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(trUtf8("Invalid input file! It seems that is not a pgModeler generated model or the file is corrupted!"), ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { + //Extracting layers informations from the tag + QRegExp dbm_regexp = QRegExp(TagExpr.arg(Attributes::DbModel)), + db_end_regexp = QRegExp(EndTagExpr.arg(Attributes::Database)); + int attr_start =-1, attr_end = -1, dbm_start = dbm_regexp.indexIn(buf); + QString aux_buf = buf.mid(dbm_start, buf.indexOf(db_end_regexp) - dbm_start), + layers, active_layers, attr_expr = QString("(%1)( )*(=)(\")"); + QList act_layers_ids; + + //Layers names + attr_start = aux_buf.indexOf(Attributes::Layers); + attr_end = aux_buf.indexOf(Attributes::ActiveLayers); + layers = aux_buf.mid(attr_start, attr_end - attr_start); + layers.remove(QRegExp(attr_expr.arg(Attributes::Layers))); + layers.remove('"'); + model->setLayers(layers.trimmed().split(';', QString::SkipEmptyParts)); + + //Active layers + attr_start = attr_end; + attr_end = aux_buf.indexOf('>', attr_start); + active_layers = aux_buf.mid(attr_start, attr_end - attr_start); + active_layers.remove(QRegExp(attr_expr.arg(Attributes::ActiveLayers))); + active_layers.remove('"'); + + for(auto id : active_layers.trimmed().split(';', QString::SkipEmptyParts)) + act_layers_ids.push_back(id.toUInt()); + + model->setActiveLayers(act_layers_ids); + //Remove the header entry from buffer buf.remove(start, regexp.matchedLength()+1); - buf.remove(0, buf.indexOf(QString("\n"))); - buf.remove(QString("<\\%1>").arg(ParsersAttributes::DB_MODEL)); + + //Checking if the header ends on a role declaration + QRegExp role_regexp = QRegExp(QString("(<%1)(.)*(<\\/%2>)").arg(Attributes::Role).arg(Attributes::Role)); + end = buf.indexOf(role_regexp); + + // If we found role declarations we clear the header until there + if(end >= 0) + buf.remove(0, end); + else + // Instead, we clear the header until the starting of database declaration + buf.remove(0, buf.indexOf(QString("<%1").arg(Attributes::Database))); + + buf.remove(QString("<\\%1>").arg(Attributes::DbModel)); ts.setString(&buf); //Extracts the objects xml line by line @@ -722,12 +760,12 @@ void PgModelerCLI::extractObjectXML(void) /* Special case for empty tags like , they will be converted to in order to be correctly extracted further. Currently only language has this behaviour, so additional object may be added in the future. */ - if(lin.contains(QString("<%1").arg(BaseObject::getSchemaName(OBJ_LANGUAGE)))) + if(lin.contains(QString("<%1").arg(BaseObject::getSchemaName(ObjectType::Language)))) { lin=lin.simplified(); if(lin.contains(QString("/>"))) - lin.replace(QString("/>"), QString(">").arg(BaseObject::getSchemaName(OBJ_LANGUAGE))); + lin.replace(QString("/>"), QString(">").arg(BaseObject::getSchemaName(ObjectType::Language))); } /* Special case for function signatures. In previous releases, the function's signature was wrongly including OUT parameters and according to docs they are not part of the signature, so it is needed @@ -737,16 +775,11 @@ void PgModelerCLI::extractObjectXML(void) if(is_rel && (((short_tag && lin.contains(QString("/>"))) || - (lin.contains(QString("[a-z]+")) && !containsRelAttributes(lin))))) + (lin.contains(QString("[a-z]+")) && !containsRelAttributes(lin))))) open_tag=close_tag=true; - else if(lin.contains(default_obj)) - { - lin.clear(); - } else { //If the line contains an objects open tag - //if((lin.startsWith('<') || lin.startsWith(QString("\n<"))) && !open_tag) if(lin.contains(QRegExp("^(((\n)|(\t))*(<))")) && !open_tag) { //Check the flag indicating an open tag @@ -766,7 +799,7 @@ void PgModelerCLI::extractObjectXML(void) /* Checking if the line start a relationship. Relationships are treated a little different because they can be empty or contain open and close tags */ - is_rel=lin.contains(ParsersAttributes::RELATIONSHIP); + is_rel=lin.contains(Attributes::Relationship); if(is_rel) { @@ -815,16 +848,16 @@ void PgModelerCLI::extractObjectXML(void) } } -void PgModelerCLI::recreateObjects(void) +void PgModelerCli::recreateObjects(void) { QStringList fail_objs, constr, list; QString xml_def, aux_def, start_tag="<%1", end_tag="", aux_tag; BaseObject *object=nullptr; - ObjectType obj_type=BASE_OBJECT; - vector types={ OBJ_INDEX, OBJ_TRIGGER, OBJ_RULE }; + ObjectType obj_type=ObjectType::BaseObject; + vector types={ ObjectType::Index, ObjectType::Trigger, ObjectType::Rule }; attribs_map attribs; bool use_fail_obj=false; - unsigned tries=0, max_tries=parsed_opts[FIX_TRIES].toUInt(); + unsigned tries=0, max_tries=parsed_opts[FixTries].toUInt(); int start_pos=-1, end_pos=-1, len=0; printMessage(trUtf8("Recreating objects...")); @@ -858,11 +891,11 @@ void PgModelerCLI::recreateObjects(void) xmlparser->getElementAttributes(attribs); - if(obj_type==OBJ_DATABASE) + if(obj_type==ObjectType::Database) model->configureDatabase(attribs); else { - if(obj_type==OBJ_TABLE) + if(obj_type==ObjectType::Table) { //Before create a table extract it's foreign keys list=extractForeignKeys(xml_def); @@ -878,14 +911,14 @@ void PgModelerCLI::recreateObjects(void) } //Discarding fk relationships - if(obj_type!=OBJ_RELATIONSHIP || - (obj_type==OBJ_RELATIONSHIP && !xml_def.contains(QString("\"%1\"").arg(ParsersAttributes::RELATIONSHIP_FK)))) + if(obj_type!=ObjectType::Relationship || + (obj_type==ObjectType::Relationship && !xml_def.contains(QString("\"%1\"").arg(Attributes::RelationshipFk)))) { object=model->createObject(obj_type); if(object) { - if(!dynamic_cast(object) && obj_type!=OBJ_RELATIONSHIP && obj_type!=BASE_RELATIONSHIP) + if(!dynamic_cast(object) && obj_type!=ObjectType::Relationship && obj_type!=ObjectType::BaseRelationship) model->addObject(object); } @@ -895,7 +928,7 @@ void PgModelerCLI::recreateObjects(void) /* Additional step to extract indexes/triggers/rules from within tables/views and putting their xml on the list of object to be created */ - if((obj_type==OBJ_TABLE || obj_type==OBJ_VIEW) && + if((obj_type==ObjectType::Table || obj_type==ObjectType::View) && xml_def.contains(QRegExp("(<)(index|trigger|rule)"))) { for(ObjectType type : types) @@ -933,10 +966,10 @@ void PgModelerCLI::recreateObjects(void) } catch(Exception &e) { - if(obj_type!=OBJ_DATABASE) + if(obj_type!=ObjectType::Database) fail_objs.push_back(xml_def); else - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } if(objs_xml.isEmpty() && (!fail_objs.isEmpty() || !constr.isEmpty())) @@ -969,17 +1002,17 @@ void PgModelerCLI::recreateObjects(void) } } -void PgModelerCLI::fixObjectAttributes(QString &obj_xml) +void PgModelerCli::fixObjectAttributes(QString &obj_xml) { //Placing objects , , outside of
- if(!obj_xml.startsWith(TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_TABLESPACE))) && - obj_xml.startsWith(TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_TABLE)))) + if(!obj_xml.startsWith(TagExpr.arg(BaseObject::getSchemaName(ObjectType::Tablespace))) && + obj_xml.startsWith(TagExpr.arg(BaseObject::getSchemaName(ObjectType::Table)))) { int start_idx=-1, end_idx=-1, len=0; - ObjectType obj_types[3]={ OBJ_RULE, OBJ_TRIGGER, OBJ_INDEX }; + ObjectType obj_types[3]={ ObjectType::Rule, ObjectType::Trigger, ObjectType::Index }; QString curr_tag, curr_end_tag, def, tab_name, sch_name, name_attr=QString("name=\""), - sch_name_attr=TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_SCHEMA)) + QString(" ") + name_attr; + sch_name_attr=TagExpr.arg(BaseObject::getSchemaName(ObjectType::Schema)) + QString(" ") + name_attr; //Extracting the table's name start_idx=obj_xml.indexOf(name_attr); @@ -996,8 +1029,8 @@ void PgModelerCLI::fixObjectAttributes(QString &obj_xml) for(unsigned idx=0; idx < 3; idx++) { - curr_tag=TAG_EXPR.arg(BaseObject::getSchemaName(obj_types[idx])); - curr_end_tag=END_TAG_EXPR.arg(BaseObject::getSchemaName(obj_types[idx])) + QString(">"); + curr_tag=TagExpr.arg(BaseObject::getSchemaName(obj_types[idx])); + curr_end_tag=EndTagExpr.arg(BaseObject::getSchemaName(obj_types[idx])) + QString(">"); start_idx=obj_xml.indexOf(curr_tag); while(start_idx >=0) @@ -1008,7 +1041,7 @@ void PgModelerCLI::fixObjectAttributes(QString &obj_xml) obj_xml.remove(start_idx, len); //If the object is a rule include the table attribute - if(def.startsWith(TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_RULE)))) + if(def.startsWith(TagExpr.arg(BaseObject::getSchemaName(ObjectType::Rule)))) { start_idx=def.indexOf('>'); def.replace(start_idx, 1, QString(" ") + tab_name + QString(">")); @@ -1024,11 +1057,11 @@ void PgModelerCLI::fixObjectAttributes(QString &obj_xml) } //Remove recheck attribute from tags. - if(obj_xml.contains(TAG_EXPR.arg(ParsersAttributes::ELEMENT))) - obj_xml.remove(QRegExp(ATTRIBUTE_EXPR.arg(QString("recheck")))); + if(obj_xml.contains(TagExpr.arg(Attributes::Element))) + obj_xml.remove(QRegExp(AttributeExpr.arg(QString("recheck")))); //Remove values greater-op, less-op, sort-op or sort2-op from ref-type attribute from tags. - if(obj_xml.contains(TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_OPERATOR)))) + if(obj_xml.contains(TagExpr.arg(BaseObject::getSchemaName(ObjectType::Operator)))) { obj_xml.remove(QString("greater-op")); obj_xml.remove(QString("less-op")); @@ -1037,102 +1070,109 @@ void PgModelerCLI::fixObjectAttributes(QString &obj_xml) } //Replacing attribute owner by onwer-col for sequences - if(obj_xml.contains(TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_SEQUENCE)))) - obj_xml.replace(ParsersAttributes::OWNER, ParsersAttributes::OWNER_COLUMN); + if(obj_xml.contains(TagExpr.arg(BaseObject::getSchemaName(ObjectType::Sequence)))) + obj_xml.replace(QRegExp(QString("(%1)( )*(=)(\")").arg(Attributes::Owner)), QString("%1 = \"").arg(Attributes::OwnerColumn)); //Remove sysid attribute from tags. - if(obj_xml.contains(TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_ROLE)))) - obj_xml.remove(QRegExp(ATTRIBUTE_EXPR.arg(QString("sysid")))); + if(obj_xml.contains(TagExpr.arg(BaseObject::getSchemaName(ObjectType::Role)))) + obj_xml.remove(QRegExp(AttributeExpr.arg(QString("sysid")))); //Replace tag by on tags. - if(obj_xml.contains(TAG_EXPR.arg(QString("usertype")))) + if(obj_xml.contains(TagExpr.arg(QString("usertype")))) { - obj_xml.replace(TAG_EXPR.arg(ParsersAttributes::PARAMETER), TAG_EXPR.arg(ParsersAttributes::TYPE_ATTRIBUTE)); - obj_xml.replace(END_TAG_EXPR.arg(ParsersAttributes::PARAMETER), END_TAG_EXPR.arg(ParsersAttributes::TYPE_ATTRIBUTE)); + obj_xml.replace(TagExpr.arg(Attributes::Parameter), TagExpr.arg(Attributes::TypeAttribute)); + obj_xml.replace(EndTagExpr.arg(Attributes::Parameter), EndTagExpr.arg(Attributes::TypeAttribute)); } - if(obj_xml.contains(TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_RELATIONSHIP)))) + if(obj_xml.contains(TagExpr.arg(BaseObject::getSchemaName(ObjectType::Relationship)))) { //Remove auto-sufix, src-sufix, dst-sufix, col-indexes, constr-indexes, attrib-indexes from tags. - obj_xml.remove(QRegExp(ATTRIBUTE_EXPR.arg(QString("auto-sufix")))); - obj_xml.remove(QRegExp(ATTRIBUTE_EXPR.arg(QString("src-sufix")))); - obj_xml.remove(QRegExp(ATTRIBUTE_EXPR.arg(QString("dst-sufix")))); - obj_xml.remove(QRegExp(ATTRIBUTE_EXPR.arg(QString("col-indexes")))); - obj_xml.remove(QRegExp(ATTRIBUTE_EXPR.arg(QString("constr-indexes")))); - obj_xml.remove(QRegExp(ATTRIBUTE_EXPR.arg(QString("attrib-indexes")))); - - obj_xml.replace(QString("line-color"), ParsersAttributes::CUSTOM_COLOR); + obj_xml.remove(QRegExp(AttributeExpr.arg(QString("auto-sufix")))); + obj_xml.remove(QRegExp(AttributeExpr.arg(QString("src-sufix")))); + obj_xml.remove(QRegExp(AttributeExpr.arg(QString("dst-sufix")))); + obj_xml.remove(QRegExp(AttributeExpr.arg(QString("col-indexes")))); + obj_xml.remove(QRegExp(AttributeExpr.arg(QString("constr-indexes")))); + obj_xml.remove(QRegExp(AttributeExpr.arg(QString("attrib-indexes")))); + + obj_xml.replace(QString("line-color"), Attributes::CustomColor); } //Renaming the tag to on indexes - if(obj_xml.contains(TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_INDEX)))) + if(obj_xml.contains(TagExpr.arg(BaseObject::getSchemaName(ObjectType::Index)))) { - obj_xml.replace(TAG_EXPR.arg(ParsersAttributes::CONDITION), TAG_EXPR.arg(ParsersAttributes::PREDICATE)); - obj_xml.replace(END_TAG_EXPR.arg(ParsersAttributes::CONDITION), END_TAG_EXPR.arg(ParsersAttributes::PREDICATE)); + obj_xml.replace(TagExpr.arg(Attributes::Condition), TagExpr.arg(Attributes::Predicate)); + obj_xml.replace(EndTagExpr.arg(Attributes::Condition), EndTagExpr.arg(Attributes::Predicate)); } //Renaming the attribute default to default-value on domain - if(obj_xml.contains(TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_DOMAIN)))) - obj_xml.replace(ParsersAttributes::DEFAULT, ParsersAttributes::DEFAULT_VALUE); + if(obj_xml.contains(TagExpr.arg(BaseObject::getSchemaName(ObjectType::Domain)))) + obj_xml.replace(Attributes::Default, Attributes::DefaultValue); //Renaming the tag to - if(obj_xml.contains(TAG_EXPR.arg(QString("grant")))) + if(obj_xml.contains(TagExpr.arg(QString("grant")))) { - obj_xml.replace(TAG_EXPR.arg(QString("grant")), TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_PERMISSION))); - obj_xml.replace(END_TAG_EXPR.arg(QString("grant")), END_TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_PERMISSION))); + obj_xml.replace(TagExpr.arg(QString("grant")), TagExpr.arg(BaseObject::getSchemaName(ObjectType::Permission))); + obj_xml.replace(EndTagExpr.arg(QString("grant")), EndTagExpr.arg(BaseObject::getSchemaName(ObjectType::Permission))); } //Replace the constraint attribute and tag expression by constraint tag in . - if(obj_xml.contains(TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_DOMAIN))) && - obj_xml.contains(TAG_EXPR.arg(ParsersAttributes::EXPRESSION))) + if(obj_xml.contains(TagExpr.arg(BaseObject::getSchemaName(ObjectType::Domain))) && + obj_xml.contains(TagExpr.arg(Attributes::Expression))) { int start_idx=-1, end_idx=-1; - QRegExp regexp = QRegExp(ATTRIBUTE_EXPR.arg(ParsersAttributes::CONSTRAINT)); + QRegExp regexp = QRegExp(AttributeExpr.arg(Attributes::Constraint)); QString constr_name; regexp.indexIn(obj_xml); constr_name = regexp.capturedTexts().at(0); - constr_name.remove(QString("%1=\"").arg(ParsersAttributes::CONSTRAINT)); + constr_name.remove(QString("%1=\"").arg(Attributes::Constraint)); constr_name.remove(constr_name.length() - 1, 1); - obj_xml.remove(QRegExp(ATTRIBUTE_EXPR.arg(ParsersAttributes::CONSTRAINT))); + obj_xml.remove(QRegExp(AttributeExpr.arg(Attributes::Constraint))); - start_idx = obj_xml.indexOf(TAG_EXPR.arg(ParsersAttributes::EXPRESSION)); + start_idx = obj_xml.indexOf(TagExpr.arg(Attributes::Expression)); obj_xml.insert(start_idx, QString("\n\t\n\t\t").arg(constr_name)); - end_idx = obj_xml.indexOf(END_TAG_EXPR.arg(ParsersAttributes::EXPRESSION)); - obj_xml.insert(end_idx + END_TAG_EXPR.arg(ParsersAttributes::EXPRESSION).length() + 1, QString("\n\t\n")); + end_idx = obj_xml.indexOf(EndTagExpr.arg(Attributes::Expression)); + obj_xml.insert(end_idx + EndTagExpr.arg(Attributes::Expression).length() + 1, QString("\n\t\n")); + } + + //Remove the deprecated attribute hide-ext-attribs from
and + if(obj_xml.contains(TagExpr.arg(BaseObject::getSchemaName(ObjectType::Table))) || + obj_xml.contains(TagExpr.arg(BaseObject::getSchemaName(ObjectType::View)))) + { + obj_xml.replace(QRegExp(AttributeExpr.arg(Attributes::HideExtAttribs)), QString()); } //Fix the references to op. classes and families if needed fixOpClassesFamiliesReferences(obj_xml); } -void PgModelerCLI::fixOpClassesFamiliesReferences(QString &obj_xml) +void PgModelerCli::fixOpClassesFamiliesReferences(QString &obj_xml) { ObjectType ref_obj_type; - if(obj_xml.contains(TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_INDEX))) || + if(obj_xml.contains(TagExpr.arg(BaseObject::getSchemaName(ObjectType::Index))) || obj_xml.contains(QRegExp(QString("(%1)(.)+(type=)(\")(%2)(\")") - .arg(TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_CONSTRAINT))) - .arg(ParsersAttributes::EX_CONSTR)))) - ref_obj_type=OBJ_OPCLASS; - else if(obj_xml.contains(TAG_EXPR.arg(BaseObject::getSchemaName(OBJ_OPCLASS)))) - ref_obj_type=OBJ_OPFAMILY; + .arg(TagExpr.arg(BaseObject::getSchemaName(ObjectType::Constraint))) + .arg(Attributes::ExConstr)))) + ref_obj_type=ObjectType::OpClass; + else if(obj_xml.contains(TagExpr.arg(BaseObject::getSchemaName(ObjectType::OpClass)))) + ref_obj_type=ObjectType::OpFamily; else return; QString ref_obj_name=BaseObject::getSchemaName(ref_obj_type); - if(!obj_xml.contains(TAG_EXPR.arg(ref_obj_name))) + if(!obj_xml.contains(TagExpr.arg(ref_obj_name))) return; QString obj_name, aux_obj_name, signature=QString("%1 USING %2"); - QRegExp sign_regexp=QRegExp(ATTRIBUTE_EXPR.arg(QString("signature"))); + QRegExp sign_regexp=QRegExp(AttributeExpr.arg(QString("signature"))); QStringList index_types; int pos=0; - obj_xml.replace(TAG_EXPR.arg(ref_obj_name) + QString(" name="), - TAG_EXPR.arg(ref_obj_name) + QString(" signature=")); + obj_xml.replace(TagExpr.arg(ref_obj_name) + QString(" name="), + TagExpr.arg(ref_obj_name) + QString(" signature=")); IndexingType::getTypes(index_types); @@ -1150,7 +1190,7 @@ void PgModelerCLI::fixOpClassesFamiliesReferences(QString &obj_xml) obj_name.remove('"'); //Transforming xml entity for quote into the char - obj_name.replace(XMLParser::CHAR_QUOT, QString("\"")); + obj_name.replace(XmlParser::CharQuot, QString("\"")); for(QString idx_type : index_types) { @@ -1160,7 +1200,7 @@ void PgModelerCLI::fixOpClassesFamiliesReferences(QString &obj_xml) if(model->getObjectIndex(aux_obj_name, ref_obj_type) >= 0) { //Replacing the old signature with the corrected form - aux_obj_name.replace(QString("\""), XMLParser::CHAR_QUOT); + aux_obj_name.replace(QString("\""), XmlParser::CharQuot); obj_xml.replace(pos, sign_regexp.matchedLength(), QString("signature=\"%1\"").arg(aux_obj_name)); break; } @@ -1172,77 +1212,77 @@ void PgModelerCLI::fixOpClassesFamiliesReferences(QString &obj_xml) while(pos >= 0); } -void PgModelerCLI::fixModel(void) +void PgModelerCli::fixModel(void) { printMessage(trUtf8("Starting model fixing...")); - printMessage(trUtf8("Loading input file: %1").arg(parsed_opts[INPUT])); - printMessage(trUtf8("Fixed model file: %1").arg(parsed_opts[OUTPUT])); + printMessage(trUtf8("Loading input file: %1").arg(parsed_opts[Input])); + printMessage(trUtf8("Fixed model file: %1").arg(parsed_opts[Output])); extractObjectXML(); recreateObjects(); model->updateTablesFKRelationships(); - model->saveModel(parsed_opts[OUTPUT], SchemaParser::XML_DEFINITION); + model->saveModel(parsed_opts[Output], SchemaParser::XmlDefinition); printMessage(trUtf8("Model successfully fixed!")); } -void PgModelerCLI::exportModel(void) +void PgModelerCli::exportModel(void) { printMessage(trUtf8("Starting model export...")); - printMessage(trUtf8("Loading input file: %1").arg(parsed_opts[INPUT])); + printMessage(trUtf8("Loading input file: %1").arg(parsed_opts[Input])); //Create the systems objects on model before loading it model->createSystemObjects(false); //Load the model file - model->loadModel(parsed_opts[INPUT]); + model->loadModel(parsed_opts[Input]); //Export to PNG - if(parsed_opts.count(EXPORT_TO_PNG)) + if(parsed_opts.count(ExportToPng)) { - printMessage(trUtf8("Export to PNG image: %1").arg(parsed_opts[OUTPUT])); + printMessage(trUtf8("Export to PNG image: %1").arg(parsed_opts[Output])); - export_hlp.exportToPNG(scene, parsed_opts[OUTPUT], zoom, - parsed_opts.count(SHOW_GRID) > 0, - parsed_opts.count(SHOW_DELIMITERS) > 0, - parsed_opts.count(PAGE_BY_PAGE) > 0); + export_hlp.exportToPNG(scene, parsed_opts[Output], zoom, + parsed_opts.count(ShowGrid) > 0, + parsed_opts.count(ShowDelimiters) > 0, + parsed_opts.count(PageByPage) > 0); } //Export to SVG - else if(parsed_opts.count(EXPORT_TO_SVG)) + else if(parsed_opts.count(ExportToSvg)) { - printMessage(trUtf8("Export to SVG file: %1").arg(parsed_opts[OUTPUT])); + printMessage(trUtf8("Export to SVG file: %1").arg(parsed_opts[Output])); - export_hlp.exportToSVG(scene, parsed_opts[OUTPUT], - parsed_opts.count(SHOW_GRID) > 0, - parsed_opts.count(SHOW_DELIMITERS) > 0); + export_hlp.exportToSVG(scene, parsed_opts[Output], + parsed_opts.count(ShowGrid) > 0, + parsed_opts.count(ShowDelimiters) > 0); } //Export to SQL file - else if(parsed_opts.count(EXPORT_TO_FILE)) + else if(parsed_opts.count(ExportToFile)) { - printMessage(trUtf8("Export to SQL script file: %1").arg(parsed_opts[OUTPUT])); + printMessage(trUtf8("Export to SQL script file: %1").arg(parsed_opts[Output])); - export_hlp.exportToSQL(model, parsed_opts[OUTPUT], parsed_opts[PGSQL_VER]); + export_hlp.exportToSQL(model, parsed_opts[Output], parsed_opts[PgSqlVer]); } //Export to DBMS else { - printMessage(trUtf8("Export to DBMS: %1").arg(connection.getConnectionString().replace(PASSWORD_REGEXP, PASSWORD_PLACEHOLDER))); + printMessage(trUtf8("Export to DBMS: %1").arg(connection.getConnectionString().replace(PasswordRegExp, PasswordPlaceholder))); - if(parsed_opts.count(IGNORE_ERROR_CODES)) - export_hlp.setIgnoredErrors(parsed_opts[IGNORE_ERROR_CODES].split(',')); + if(parsed_opts.count(IgnoreErrorCodes)) + export_hlp.setIgnoredErrors(parsed_opts[IgnoreErrorCodes].split(',')); - export_hlp.exportToDBMS(model, connection, parsed_opts[PGSQL_VER], - parsed_opts.count(IGNORE_DUPLICATES) > 0, - parsed_opts.count(DROP_DATABASE) > 0, - parsed_opts.count(DROP_OBJECTS) > 0, - parsed_opts.count(SIMULATE) > 0, - parsed_opts.count(USE_TMP_NAMES) > 0); + export_hlp.exportToDBMS(model, connection, parsed_opts[PgSqlVer], + parsed_opts.count(IgnoreDuplicates) > 0, + parsed_opts.count(DropDatabase) > 0, + parsed_opts.count(DropObjects) > 0, + parsed_opts.count(Simulate) > 0, + parsed_opts.count(UseTmpNames) > 0); } printMessage(trUtf8("Export successfully ended!\n")); } -void PgModelerCLI::importDatabase(void) +void PgModelerCli::importDatabase(void) { printMessage(trUtf8("Starting database import...")); printMessage(trUtf8("Input database: %1").arg(connection.getConnectionId(true, true))); @@ -1254,14 +1294,14 @@ void PgModelerCLI::importDatabase(void) printMessage(trUtf8("Saving the imported database to file...")); - model_wgt->getDatabaseModel()->saveModel(parsed_opts[OUTPUT], SchemaParser::XML_DEFINITION); + model_wgt->getDatabaseModel()->saveModel(parsed_opts[Output], SchemaParser::XmlDefinition); printMessage(trUtf8("Import successfully ended!\n")); delete(model_wgt); } -void PgModelerCLI::importDatabase(DatabaseModel *model, Connection conn) +void PgModelerCli::importDatabase(DatabaseModel *model, Connection conn) { try { @@ -1273,23 +1313,23 @@ void PgModelerCLI::importDatabase(DatabaseModel *model, Connection conn) catalog.setConnection(conn); //For diff we don't need the oids of all system objects - catalog.setFilter(Catalog::LIST_ALL_OBJS | Catalog::EXCL_BUILTIN_ARRAY_TYPES | - Catalog::EXCL_EXTENSION_OBJS | Catalog::EXCL_SYSTEM_OBJS); + catalog.setFilter(Catalog::ListAllObjects | Catalog::ExclBuiltinArrayTypes | + Catalog::ExclExtensionObjs | Catalog::ExclSystemObjs); - catalog.getObjectsOIDs(obj_oids, col_oids, {{ParsersAttributes::FILTER_TABLE_TYPES, ParsersAttributes::_TRUE_}}); + catalog.getObjectsOIDs(obj_oids, col_oids, {{Attributes::FilterTableTypes, Attributes::True}}); - db_oid = catalog.getObjectOID(conn.getConnectionParam(Connection::PARAM_DB_NAME), OBJ_DATABASE); - obj_oids[OBJ_DATABASE].push_back(db_oid.toUInt()); + db_oid = catalog.getObjectOID(conn.getConnectionParam(Connection::ParamDbName), ObjectType::Database); + obj_oids[ObjectType::Database].push_back(db_oid.toUInt()); catalog.closeConnection(); import_hlp.setConnection(conn); - import_hlp.setImportOptions(parsed_opts.count(IMPORT_SYSTEM_OBJS) > 0, - parsed_opts.count(IMPORT_EXTENSION_OBJS) > 0, + import_hlp.setImportOptions(parsed_opts.count(ImportSystemObjs) > 0, + parsed_opts.count(ImportExtensionObjs) > 0, true, - parsed_opts.count(IGNORE_IMPORT_ERRORS) > 0, - parsed_opts.count(DEBUG_MODE) > 0, - !parsed_opts.count(DIFF), !parsed_opts.count(DIFF)); + parsed_opts.count(IgnoreImportErrors) > 0, + parsed_opts.count(DebugMode) > 0, + !parsed_opts.count(Diff), !parsed_opts.count(Diff)); model->createSystemObjects(true); import_hlp.setSelectedOIDs(model, obj_oids, col_oids); @@ -1298,30 +1338,30 @@ void PgModelerCLI::importDatabase(DatabaseModel *model, Connection conn) } catch(Exception &e) { - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } -void PgModelerCLI::diffModelDatabase(void) +void PgModelerCli::diffModelDatabase(void) { DatabaseModel *model_aux = new DatabaseModel(); QString dbname; printMessage(trUtf8("Starting diff process...")); - if(!parsed_opts[INPUT].isEmpty()) - printMessage(trUtf8("Input model: %1").arg(parsed_opts[INPUT])); + if(!parsed_opts[Input].isEmpty()) + printMessage(trUtf8("Input model: %1").arg(parsed_opts[Input])); else printMessage(trUtf8("Input database: %1").arg(connection.getConnectionId(true, true))); dbname = extra_connection.getConnectionId(true, true); printMessage(trUtf8("Compare to: %1").arg(dbname)); - if(!parsed_opts[INPUT].isEmpty()) + if(!parsed_opts[Input].isEmpty()) { printMessage(trUtf8("Loading input model...")); model->createSystemObjects(false); - model->loadModel(parsed_opts[INPUT]); + model->loadModel(parsed_opts[Input]); } else { @@ -1333,16 +1373,25 @@ void PgModelerCLI::diffModelDatabase(void) importDatabase(model_aux, extra_connection); diff_hlp.setModels(model, model_aux); - diff_hlp.setDiffOption(ModelsDiffHelper::OPT_KEEP_CLUSTER_OBJS, !parsed_opts.count(DROP_CLUSTER_OBJS)); - diff_hlp.setDiffOption(ModelsDiffHelper::OPT_CASCADE_MODE, !parsed_opts.count(NO_CASCADE_DROP_TRUNC)); - diff_hlp.setDiffOption(ModelsDiffHelper::OPT_TRUCANTE_TABLES, parsed_opts.count(TRUNC_ON_COLS_TYPE_CHANGE)); - diff_hlp.setDiffOption(ModelsDiffHelper::OPT_FORCE_RECREATION, !parsed_opts.count(NO_FORCE_OBJ_RECREATION)); - diff_hlp.setDiffOption(ModelsDiffHelper::OPT_RECREATE_UNCHANGEBLE, !parsed_opts.count(NO_UNMOD_OBJ_RECREATION)); - diff_hlp.setDiffOption(ModelsDiffHelper::OPT_KEEP_OBJ_PERMS, !parsed_opts.count(REVOKE_PERMISSIONS)); - diff_hlp.setDiffOption(ModelsDiffHelper::OPT_REUSE_SEQUENCES, !parsed_opts.count(NO_SEQUENCE_REUSE)); - diff_hlp.setDiffOption(ModelsDiffHelper::OPT_PRESERVE_DB_NAME, !parsed_opts.count(RENAME_DB)); - diff_hlp.setDiffOption(ModelsDiffHelper::OPT_DONT_DROP_MISSING_OBJS, !parsed_opts.count(DROP_MISSING_OBJS)); - diff_hlp.setDiffOption(ModelsDiffHelper::OPT_DROP_MISSING_COLS_CONSTR, !parsed_opts.count(FORCE_DROP_COLS_CONSTRS)); + diff_hlp.setDiffOption(ModelsDiffHelper::OptKeepClusterObjs, !parsed_opts.count(DropClusterObjs)); + diff_hlp.setDiffOption(ModelsDiffHelper::OptCascadeMode, !parsed_opts.count(NoCascadeDropTrunc)); + diff_hlp.setDiffOption(ModelsDiffHelper::OptTruncateTables, parsed_opts.count(TruncOnColsTypeChange)); + diff_hlp.setDiffOption(ModelsDiffHelper::OptForceRecreation, !parsed_opts.count(NoForceObjRecreation)); + diff_hlp.setDiffOption(ModelsDiffHelper::OptRecreateUnchangeble, !parsed_opts.count(NoUnmodObjRecreation)); + diff_hlp.setDiffOption(ModelsDiffHelper::OptKeepObjectPerms, !parsed_opts.count(RevokePermissions)); + diff_hlp.setDiffOption(ModelsDiffHelper::OptReuseSequences, !parsed_opts.count(NoSequenceReuse)); + diff_hlp.setDiffOption(ModelsDiffHelper::OptPreserveDbName, !parsed_opts.count(RenameDb)); + diff_hlp.setDiffOption(ModelsDiffHelper::OptDontDropMissingObjs, !parsed_opts.count(DropMissingObjs)); + diff_hlp.setDiffOption(ModelsDiffHelper::OptDropMissingColsConstr, !parsed_opts.count(ForceDropColsConstrs)); + + if(!parsed_opts[PgSqlVer].isEmpty()) + diff_hlp.setPgSQLVersion(parsed_opts[PgSqlVer]); + else + { + extra_connection.connect(); + diff_hlp.setPgSQLVersion(extra_connection.getPgSQLVersion(true)); + extra_connection.close(); + } printMessage(trUtf8("Comparing the generated models...")); diff_hlp.diffModels(); @@ -1351,17 +1400,16 @@ void PgModelerCLI::diffModelDatabase(void) printMessage(trUtf8("No differences were detected.")); else { - if(parsed_opts.count(SAVE_DIFF)) + if(parsed_opts.count(SaveDiff)) { QFile output; - printMessage(trUtf8("Saving diff to file `%1'").arg(parsed_opts[OUTPUT])); - output.setFileName(parsed_opts[OUTPUT]); + printMessage(trUtf8("Saving diff to file `%1'").arg(parsed_opts[Output])); + output.setFileName(parsed_opts[Output]); if(!output.open(QFile::WriteOnly)) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(parsed_opts[OUTPUT]), - ERR_FILE_DIR_NOT_WRITTEN, __PRETTY_FUNCTION__,__FILE__,__LINE__); - + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotWritten).arg(parsed_opts[Output]), + ErrorCode::FileDirectoryNotWritten, __PRETTY_FUNCTION__,__FILE__,__LINE__); output.write(diff_hlp.getDiffDefinition().toUtf8()); output.close(); } @@ -1369,14 +1417,15 @@ void PgModelerCLI::diffModelDatabase(void) { bool apply_diff = true; - if(!parsed_opts.count(NO_DIFF_PREVIEW)) + if(!parsed_opts.count(NoDiffPreview)) { QString res, buff, line; QTextStream in(stdin), preview; + buff += "\n** Press ENTER to scroll the preview **\n"; buff += "\n### DIFF PREVIEW ###\n\n"; buff += diff_hlp.getDiffDefinition(); - buff += "\n### END PREVIEW ###\n\n"; + buff += "\n### END OF PREVIEW ###\n\n"; preview.setString(&buff, QIODevice::ReadOnly); @@ -1397,7 +1446,7 @@ void PgModelerCLI::diffModelDatabase(void) } out << endl; - out << trUtf8("** WARNING: you are about to apply the generated SQL code to the server! Data can be lost in the process.") << endl; + out << trUtf8("** WARNING: You are about to apply the generated diff code to the server. Data can be lost in the process!") << endl; do { @@ -1420,11 +1469,11 @@ void PgModelerCLI::diffModelDatabase(void) { printMessage(trUtf8("Applying diff to the database `%1'...").arg(dbname)); export_hlp.setExportToDBMSParams(diff_hlp.getDiffDefinition(), - &extra_connection, - parsed_opts[COMPARE_TO], parsed_opts.count(IGNORE_DUPLICATES)); + &extra_connection, + parsed_opts[CompareTo], parsed_opts.count(IgnoreDuplicates)); - if(parsed_opts.count(IGNORE_ERROR_CODES)) - export_hlp.setIgnoredErrors(parsed_opts[IGNORE_ERROR_CODES].split(',')); + if(parsed_opts.count(IgnoreErrorCodes)) + export_hlp.setIgnoredErrors(parsed_opts[IgnoreErrorCodes].split(',')); export_hlp.exportToDBMS(); } @@ -1434,23 +1483,30 @@ void PgModelerCLI::diffModelDatabase(void) printMessage(trUtf8("Diff successfully ended!\n")); } -void PgModelerCLI::updateMimeType(void) +void PgModelerCli::updateMimeType(void) { #ifndef Q_OS_MAC + try + { printMessage(trUtf8("Starting mime update...")); - handleMimeDatabase(parsed_opts[DBM_MIME_TYPE]==UNINSTALL); + handleMimeDatabase(parsed_opts[DbmMimeType]==Uninstall); printMessage(trUtf8("Mime database successfully updated!\n")); + } + catch (Exception &e) + { + out << e.getExceptionsText() << endl; + } #endif } -QStringList PgModelerCLI::extractForeignKeys(QString &obj_xml) +QStringList PgModelerCli::extractForeignKeys(QString &obj_xml) { QStringList constr_lst; int start=0, end=0, pos=0, count=0; - QString start_tag=QString("<%1").arg(ParsersAttributes::CONSTRAINT), - end_tag=QString(" attribs={ ParsersAttributes::RELATIONSHIP, - ParsersAttributes::TYPE, ParsersAttributes::SRC_REQUIRED, ParsersAttributes::DST_REQUIRED, - ParsersAttributes::SRC_TABLE, ParsersAttributes::DST_TABLE, ParsersAttributes::POINTS, - ParsersAttributes::COLUMNS, ParsersAttributes::COLUMN, ParsersAttributes::CONSTRAINT, - ParsersAttributes::LABEL, ParsersAttributes::LINE, ParsersAttributes::POSITION, - ParsersAttributes::IDENTIFIER, ParsersAttributes::DEFERRABLE, ParsersAttributes::DEFER_TYPE, - ParsersAttributes::TABLE_NAME, ParsersAttributes::SPECIAL_PK_COLS, ParsersAttributes::TABLE, - ParsersAttributes::ANCESTOR_TABLE, ParsersAttributes::COPY_OPTIONS, ParsersAttributes::COPY_MODE, - ParsersAttributes::SRC_COL_PATTERN, ParsersAttributes::DST_COL_PATTERN, ParsersAttributes::PK_PATTERN, - ParsersAttributes::UQ_PATTERN, ParsersAttributes::SRC_FK_PATTERN, ParsersAttributes::DST_FK_PATTERN }; + static vector attribs={ Attributes::Relationship, + Attributes::Type, Attributes::SrcRequired, Attributes::DstRequired, + Attributes::SrcTable, Attributes::DstTable, Attributes::Points, + Attributes::Columns, Attributes::Column, Attributes::Constraint, + Attributes::Label, Attributes::Line, Attributes::Position, + Attributes::Identifier, Attributes::Deferrable, Attributes::DeferType, + Attributes::TableName, Attributes::SpecialPkCols, Attributes::Table, + Attributes::AncestorTable, Attributes::CopyOptions, Attributes::CopyMode, + Attributes::SrcColPattern, Attributes::DstColPattern, Attributes::PkPattern, + Attributes::UqPattern, Attributes::SrcFkPattern, Attributes::DstFkPattern }; for(unsigned i=0; i < attribs.size() && !found; i++) found=str.contains(attribs[i]); @@ -1500,7 +1556,7 @@ bool PgModelerCLI::containsRelAttributes(const QString &str) return(found); } -void PgModelerCLI::handleMimeDatabase(bool uninstall) +void PgModelerCli::handleMimeDatabase(bool uninstall) { SchemaParser schparser; QString msg_file_associated=trUtf8("Database model files (.dbm) are already associated to pgModeler!"), @@ -1513,12 +1569,12 @@ void PgModelerCLI::handleMimeDatabase(bool uninstall) QString str_aux, //Configures the path to the application logo - exec_icon=QDir(GlobalAttributes::TMPL_CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + QString("pgmodeler_logo.png")).absolutePath(), + exec_icon=QDir(GlobalAttributes::TmplConfigurationDir + + GlobalAttributes::DirSeparator + QString("pgmodeler_logo.png")).absolutePath(), //Configures the path to the document logo - dbm_icon=QDir(GlobalAttributes::TMPL_CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + QString("pgmodeler_dbm.png")).absolutePath(), + dbm_icon=QDir(GlobalAttributes::TmplConfigurationDir + + GlobalAttributes::DirSeparator + QString("pgmodeler_dbm.png")).absolutePath(), //Path to directory that register mime types mime_db_dir=QDir::homePath() + QString("/.local/share/mime"), @@ -1526,36 +1582,36 @@ void PgModelerCLI::handleMimeDatabase(bool uninstall) //Path to the file that associates apps to mimetypes mimeapps=QDir::homePath() + QString("/.local/share/applications/mimeapps.list"), - base_conf_dir=GlobalAttributes::TMPL_CONFIGURATIONS_DIR + GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::SCHEMAS_DIR + GlobalAttributes::DIR_SEPARATOR, + base_conf_dir=GlobalAttributes::TmplConfigurationDir + GlobalAttributes::DirSeparator + + GlobalAttributes::SchemasDir + GlobalAttributes::DirSeparator, //Files generated after update file association (application-dbm.xml and pgModeler.desktop) files[] = { QDir::homePath() + QString("/.local/share/applications/pgModeler.desktop"), mime_db_dir + QString("/packages/application-dbm.xml") }, - schemas[] = { base_conf_dir + QString("desktop") + GlobalAttributes::SCHEMA_EXT, - base_conf_dir + QString("application-dbm") + GlobalAttributes::SCHEMA_EXT }; + schemas[] = { base_conf_dir + QString("desktop") + GlobalAttributes::SchemaExt, + base_conf_dir + QString("application-dbm") + GlobalAttributes::SchemaExt }; QByteArray buf, buf_aux; QFile out; //When installing, check if the necessary file exists. If exists, raises an error and abort. if(!uninstall && (QFileInfo(files[0]).exists() || QFileInfo(files[1]).exists())) { - throw Exception(msg_file_associated, ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(msg_file_associated, ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); } else if(uninstall && (!QFileInfo(files[0]).exists() && !QFileInfo(files[1]).exists())) { - throw Exception(msg_no_association, ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(msg_no_association, ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); } else if(!uninstall) { QString startup_script=QString("%1/start-pgmodeler.sh") - .arg(QFileInfo(GlobalAttributes::PGMODELER_APP_PATH).absolutePath()); + .arg(QFileInfo(GlobalAttributes::PgModelerAppPath).absolutePath()); - attribs[ParsersAttributes::WORKING_DIR]=QStandardPaths::writableLocation(QStandardPaths::HomeLocation); - attribs[ParsersAttributes::APPLICATION]=(QFileInfo(startup_script).exists() ? - startup_script : GlobalAttributes::PGMODELER_APP_PATH); - attribs[ParsersAttributes::ICON]=exec_icon; + attribs[Attributes::WorkingDir]=QStandardPaths::writableLocation(QStandardPaths::HomeLocation); + attribs[Attributes::Application]=(QFileInfo(startup_script).exists() ? + startup_script : GlobalAttributes::PgModelerAppPath); + attribs[Attributes::Icon]=exec_icon; } try @@ -1566,7 +1622,7 @@ void PgModelerCLI::handleMimeDatabase(bool uninstall) { if(!QFile(files[i]).remove()) throw Exception(trUtf8("Can't erase the file %1! Check if the current user has permissions to delete it and if the file exists.").arg(files[i]), - ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); } else { @@ -1578,13 +1634,13 @@ void PgModelerCLI::handleMimeDatabase(bool uninstall) out.open(QFile::WriteOnly); if(!out.isOpen()) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(files[i]), - ERR_FILE_DIR_NOT_WRITTEN,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotWritten).arg(files[i]), + ErrorCode::FileDirectoryNotWritten,__PRETTY_FUNCTION__,__FILE__,__LINE__); out.write(buf.data(), buf.size()); out.close(); buf.clear(); - attribs[ParsersAttributes::ICON]=dbm_icon; + attribs[Attributes::Icon]=dbm_icon; } } @@ -1603,8 +1659,8 @@ void PgModelerCLI::handleMimeDatabase(bool uninstall) out.open(QFile::ReadOnly); if(!out.isOpen()) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(mimeapps), - ERR_FILE_DIR_NOT_WRITTEN,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotWritten).arg(mimeapps), + ErrorCode::FileDirectoryNotWritten,__PRETTY_FUNCTION__,__FILE__,__LINE__); //Opens the mimeapps.list to add a entry linking pgModeler to .dbm files buf=out.readAll(); @@ -1646,20 +1702,20 @@ void PgModelerCLI::handleMimeDatabase(bool uninstall) } catch(Exception &e) { - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } #else #ifdef Q_OS_WIN //Checking if the .dbm registry key exists QSettings dbm_ext(QString("HKEY_CURRENT_USER\\Software\\Classes\\.dbm"), QSettings::NativeFormat); - QString exe_path=QDir::toNativeSeparators(GlobalAttributes::PGMODELER_APP_PATH); + QString exe_path=QDir::toNativeSeparators(GlobalAttributes::PgModelerAppPath); //If there is no value assigned to .dbm/Default key and the user wants to uninstall file association, raises an error if(uninstall && dbm_ext.value(QString("Default")).toString().isEmpty()) - throw Exception(msg_no_association, ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(msg_no_association, ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); else if(!uninstall && !dbm_ext.value(QString("Default")).toString().isEmpty()) - throw Exception(msg_file_associated, ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(msg_file_associated, ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); else { if(!uninstall) diff --git a/main-cli/src/pgmodelercli.h b/main-cli/src/pgmodelercli.h index ab240d1c4a..19f8999127 100644 --- a/main-cli/src/pgmodelercli.h +++ b/main-cli/src/pgmodelercli.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ /** \ingroup pgmodeler-cli -\class PgModelerCLI +\class PgModelerCli \brief Implements the operations export models whitout use the graphical interface */ @@ -39,11 +39,11 @@ #include "databaseimporthelper.h" #include "modelsdiffhelper.h" -class PgModelerCLI: public QApplication { +class PgModelerCli: public QApplication { private: Q_OBJECT - XMLParser *xmlparser; + XmlParser *xmlparser; //! \brief Export helper object ModelExportHelper export_hlp; @@ -98,69 +98,69 @@ class PgModelerCLI: public QApplication { //! \brief Zoom to be applied onto the png export double zoom; - static const QRegExp PASSWORD_REGEXP; + static const QRegExp PasswordRegExp; - static const QString PASSWORD_PLACEHOLDER; + static const QString PasswordPlaceholder; //! \brief Option names constants - static const QString INPUT, - OUTPUT, - INPUT_DB, - EXPORT_TO_FILE, - EXPORT_TO_PNG, - EXPORT_TO_SVG, - EXPORT_TO_DBMS, - IMPORT_DB, - DIFF, - DROP_DATABASE, - DROP_OBJECTS, - PGSQL_VER, - HELP, - SHOW_GRID, - SHOW_DELIMITERS, - PAGE_BY_PAGE, - IGNORE_DUPLICATES, - IGNORE_ERROR_CODES, - CONN_ALIAS, - HOST, - PORT, - USER, - PASSWD, - INITIAL_DB, - SILENT, - LIST_CONNS, - SIMULATE, - FIX_MODEL, - FIX_TRIES, - ZOOM_FACTOR, - USE_TMP_NAMES, - DBM_MIME_TYPE, - INSTALL, - UNINSTALL, - - IGNORE_IMPORT_ERRORS, - IMPORT_SYSTEM_OBJS, - IMPORT_EXTENSION_OBJS, - DEBUG_MODE, - - COMPARE_TO, - SAVE_DIFF, - APPLY_DIFF, - NO_DIFF_PREVIEW, - DROP_CLUSTER_OBJS, - REVOKE_PERMISSIONS, - DROP_MISSING_OBJS, - FORCE_DROP_COLS_CONSTRS, - RENAME_DB, - TRUNC_ON_COLS_TYPE_CHANGE, - NO_SEQUENCE_REUSE, - NO_CASCADE_DROP_TRUNC, - NO_FORCE_OBJ_RECREATION, - NO_UNMOD_OBJ_RECREATION, - - TAG_EXPR, - END_TAG_EXPR, - ATTRIBUTE_EXPR; + static const QString Input, + Output, + InputDb, + ExportToFile, + ExportToPng, + ExportToSvg, + ExportToDbms, + ImportDb, + Diff, + DropDatabase, + DropObjects, + PgSqlVer, + Help, + ShowGrid, + ShowDelimiters, + PageByPage, + IgnoreDuplicates, + IgnoreErrorCodes, + ConnAlias, + Host, + Port, + User, + Passwd, + InitialDb, + Silent, + ListConns, + Simulate, + FixModel, + FixTries, + ZoomFactor, + UseTmpNames, + DbmMimeType, + Install, + Uninstall, + + IgnoreImportErrors, + ImportSystemObjs, + ImportExtensionObjs, + DebugMode, + + CompareTo, + SaveDiff, + ApplyDiff, + NoDiffPreview, + DropClusterObjs, + RevokePermissions, + DropMissingObjs, + ForceDropColsConstrs, + RenameDb, + TruncOnColsTypeChange, + NoSequenceReuse, + NoCascadeDropTrunc, + NoForceObjRecreation, + NoUnmodObjRecreation, + + TagExpr, + EndTagExpr, + AttributeExpr; //! \brief Parsers the options and executes the action specified by them void parseOptions(attribs_map &parsed_opts); @@ -212,13 +212,13 @@ class PgModelerCLI: public QApplication { void printMessage(const QString &msg); public: - PgModelerCLI(int argc, char **argv); - ~PgModelerCLI(void); + PgModelerCli(int argc, char **argv); + ~PgModelerCli(void); int exec(void); private slots: void handleObjectAddition(BaseObject *); - void updateProgress(int progress, QString msg, ObjectType = BASE_OBJECT); + void updateProgress(int progress, QString msg, ObjectType = ObjectType::BaseObject); void printIgnoredError(QString err_cod, QString err_msg, QString cmd); void handleObjectRemoval(BaseObject *object); }; diff --git a/main/res/Info.plist b/main/res/Info.plist index 330902878e..0df7f3ecf9 100644 --- a/main/res/Info.plist +++ b/main/res/Info.plist @@ -33,7 +33,7 @@ CFBundleSignature ???? CFBundleVersion - 0.8.0 + 0.9.2 CSResourcesFileMapped NSPrincipalClass diff --git a/main/src/application.cpp b/main/src/application.cpp index 014e3eb64e..c1de046df2 100644 --- a/main/src/application.cpp +++ b/main/src/application.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,15 +18,15 @@ #include "application.h" #include "globalattributes.h" #include "messagebox.h" -#include "parsersattributes.h" +#include "attributes.h" Application::Application(int &argc, char **argv) : QApplication(argc,argv) { QTranslator *main_translator=nullptr, *plugin_translator=nullptr; - QFile ui_style(GlobalAttributes::TMPL_CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::UI_STYLE_CONF + - GlobalAttributes::CONFIGURATION_EXT); + QFile ui_style(GlobalAttributes::TmplConfigurationDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::UiStyleConf + + GlobalAttributes::ConfigurationExt); QString plugin_name, plug_lang_dir, plug_lang_file; QStringList dir_list; QDir dir; @@ -41,25 +41,25 @@ Application::Application(int &argc, char **argv) : QApplication(argc,argv) this->addLibraryPath(this->applicationDirPath()); //If pgModeler bundles plugins, add the root plugins path to lib search paths - if(dir.exists(GlobalAttributes::PLUGINS_DIR)) - this->addLibraryPath(GlobalAttributes::PLUGINS_DIR); + if(dir.exists(GlobalAttributes::PluginsDir)) + this->addLibraryPath(GlobalAttributes::PluginsDir); //Check if the temporary dir exists, if not, creates it. - if(!dir.exists(GlobalAttributes::TEMPORARY_DIR)) + if(!dir.exists(GlobalAttributes::TemporaryDir)) { - if(!dir.mkdir(GlobalAttributes::TEMPORARY_DIR)) + if(!dir.mkdir(GlobalAttributes::TemporaryDir)) { Messagebox msg; - msg.show(Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(GlobalAttributes::TEMPORARY_DIR), - ERR_FILE_DIR_NOT_WRITTEN, __PRETTY_FUNCTION__,__FILE__,__LINE__)); + msg.show(Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotWritten).arg(GlobalAttributes::TemporaryDir), + ErrorCode::FileDirectoryNotWritten, __PRETTY_FUNCTION__,__FILE__,__LINE__)); } } //Trying to identify if the user defined a custom UI language in the pgmodeler.conf file - QString conf_file = GlobalAttributes::CONFIGURATIONS_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::GENERAL_CONF + - GlobalAttributes::CONFIGURATION_EXT; + QString conf_file = GlobalAttributes::ConfigurationsDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::GeneralConf + + GlobalAttributes::ConfigurationExt; QFile input; QString lang_id = QLocale::system().name(); @@ -68,23 +68,23 @@ Application::Application(int &argc, char **argv) : QApplication(argc,argv) if(input.open(QFile::ReadOnly)) { QString buf = QString(input.readAll()); - QRegExp regexp = QRegExp(QString("(%1)(.*)(=)(\\\")(.)+(\\\")(\\\n)").arg(ParsersAttributes::UI_LANGUAGE)); + QRegExp regexp = QRegExp(QString("(%1)(.*)(=)(\\\")(.)+(\\\")(\\\n)").arg(Attributes::UiLanguage)); int idx = regexp.indexIn(QString(buf)); //Extract the value of the ui-language attribute in the conf file lang_id = buf.mid(idx, regexp.matchedLength()); - lang_id.remove(ParsersAttributes::UI_LANGUAGE); + lang_id.remove(Attributes::UiLanguage); lang_id.remove(QChar('"')).remove(QChar('=')).remove(QChar('\n')); } //Tries to load the main ui translation according to the system's locale main_translator=new QTranslator(this); - main_translator->load(lang_id, GlobalAttributes::LANGUAGES_DIR); + main_translator->load(lang_id, GlobalAttributes::LanguagesDir); this->installTranslator(main_translator); //Trying to load plugins translations - dir_list=QDir(GlobalAttributes::PLUGINS_DIR + - GlobalAttributes::DIR_SEPARATOR, + dir_list=QDir(GlobalAttributes::PluginsDir + + GlobalAttributes::DirSeparator, QString("*"), QDir::Name, QDir::AllDirs | QDir::NoDotAndDotDot).entryList(); while(!dir_list.isEmpty()) @@ -93,10 +93,10 @@ Application::Application(int &argc, char **argv) : QApplication(argc,argv) dir_list.pop_front(); //Configure the path to "lang" subdir at current plugin directory - plug_lang_dir=GlobalAttributes::PLUGINS_DIR + - GlobalAttributes::DIR_SEPARATOR + plugin_name + - GlobalAttributes::DIR_SEPARATOR + QString("lang") + - GlobalAttributes::DIR_SEPARATOR; + plug_lang_dir=GlobalAttributes::PluginsDir + + GlobalAttributes::DirSeparator + plugin_name + + GlobalAttributes::DirSeparator + QString("lang") + + GlobalAttributes::DirSeparator; plug_lang_file=plugin_name + QString(".") + lang_id; @@ -116,8 +116,8 @@ Application::Application(int &argc, char **argv) : QApplication(argc,argv) if(!ui_style.isOpen()) { Messagebox msg; - msg.show(Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED).arg(ui_style.fileName()), - ERR_FILE_DIR_NOT_ACCESSED,__PRETTY_FUNCTION__,__FILE__,__LINE__)); + msg.show(Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed).arg(ui_style.fileName()), + ErrorCode::FileDirectoryNotAccessed,__PRETTY_FUNCTION__,__FILE__,__LINE__)); } else this->setStyleSheet(ui_style.readAll()); @@ -138,28 +138,28 @@ bool Application::notify(QObject *receiver, QEvent *event) catch(...) { Messagebox msg_box; - msg_box.show(trUtf8("Unknown exception caught!"), Messagebox::ERROR_ICON); + msg_box.show(trUtf8("Unknown exception caught!"), Messagebox::ErrorIcon); return(false); } } void Application::createUserConfiguration(void) { - QDir config_dir(GlobalAttributes::CONFIGURATIONS_DIR); + QDir config_dir(GlobalAttributes::ConfigurationsDir); try { //If the directory not exists or is empty if(!config_dir.exists() || - config_dir.entryList({QString("*%1").arg(GlobalAttributes::CONFIGURATION_EXT)}, + config_dir.entryList({QString("*%1").arg(GlobalAttributes::ConfigurationExt)}, QDir::Files | QDir::NoDotAndDotDot).isEmpty()) - copyFilesRecursively(GlobalAttributes::TMPL_CONFIGURATIONS_DIR, GlobalAttributes::CONFIGURATIONS_DIR); + copyFilesRecursively(GlobalAttributes::TmplConfigurationDir, GlobalAttributes::ConfigurationsDir); } catch(Exception &e) { Messagebox msg_box; - msg_box.show(e, trUtf8("Failed to create initial configuration in `%1'! Check if the current user has write permission over that path and at least read permission over `%2'.").arg(GlobalAttributes::CONFIGURATIONS_DIR, CONFDIR)); - throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); + msg_box.show(e, trUtf8("Failed to create initial configuration in `%1'! Check if the current user has write permission over that path and at least read permission over `%2'.").arg(GlobalAttributes::ConfigurationsDir, CONFDIR)); + throw Exception(e.getErrorMessage(),e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e); } } @@ -168,7 +168,7 @@ void Application::copyFilesRecursively(const QString &src_path, const QString &d QFileInfo src_file(src_path); if(!src_file.exists()) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED).arg(src_path), + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed).arg(src_path), __PRETTY_FUNCTION__,__FILE__,__LINE__); if(src_file.isDir()) @@ -179,16 +179,16 @@ void Application::copyFilesRecursively(const QString &src_path, const QString &d src_dir(src_path); if(!dst_dir.exists() && !dst_dir.mkpath(dst_path)) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(dst_path), + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotWritten).arg(dst_path), __PRETTY_FUNCTION__,__FILE__,__LINE__); - filenames = src_dir.entryList({QString("*%1").arg(GlobalAttributes::CONFIGURATION_EXT)}, + filenames = src_dir.entryList({QString("*%1").arg(GlobalAttributes::ConfigurationExt)}, QDir::Files | QDir::NoDotAndDotDot); for(QString filename : filenames) { //Avoiding the copy of ui-style.conf file - if(!filename.contains(GlobalAttributes::UI_STYLE_CONF)) + if(!filename.contains(GlobalAttributes::UiStyleConf)) { new_src_path = src_path + src_dir.separator() + filename; new_dst_path = dst_path + dst_dir.separator() + filename; @@ -198,7 +198,7 @@ void Application::copyFilesRecursively(const QString &src_path, const QString &d } else if(!QFile::exists(dst_path) && !QFile::copy(src_path, dst_path)) { - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(dst_path), + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotWritten).arg(dst_path), __PRETTY_FUNCTION__,__FILE__,__LINE__); } } diff --git a/main/src/application.h b/main/src/application.h index ae9c530c9e..ee29177470 100644 --- a/main/src/application.h +++ b/main/src/application.h @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/main/src/main.cpp b/main/src/main.cpp index 8c29ccaaa6..1b8d49dc91 100644 --- a/main/src/main.cpp +++ b/main/src/main.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -38,12 +38,12 @@ void startCrashHandler(int signal) symbols = backtrace_symbols(stack, stack_size); #endif - cmd=QString("\"%1\"").arg(GlobalAttributes::PGMODELER_CHANDLER_PATH) + QString(" -style ") + GlobalAttributes::DEFAULT_QT_STYLE; + cmd=QString("\"%1\"").arg(GlobalAttributes::PgModelerCHandlerPath) + QString(" -style ") + GlobalAttributes::DefaultQtStyle; //Creates the stacktrace file - output.setFileName(GlobalAttributes::TEMPORARY_DIR + - GlobalAttributes::DIR_SEPARATOR + - GlobalAttributes::STACKTRACE_FILE); + output.setFileName(GlobalAttributes::TemporaryDir + + GlobalAttributes::DirSeparator + + GlobalAttributes::StacktraceFile); output.open(QFile::WriteOnly); if(output.isOpen()) @@ -51,8 +51,8 @@ void startCrashHandler(int signal) lin=QString("** pgModeler crashed after receive signal: %1 **\n\nDate/Time: %2 \nVersion: %3 \nBuild: %4 \n") .arg(signal) .arg(QDateTime::currentDateTime().toString(QString("yyyy-MM-dd hh:mm:ss"))) - .arg(GlobalAttributes::PGMODELER_VERSION) - .arg(GlobalAttributes::PGMODELER_BUILD_NUMBER); + .arg(GlobalAttributes::PgModelerVersion) + .arg(GlobalAttributes::PgModelerBuildNumber); lin+=QString("Compilation Qt version: %1\nRunning Qt version: %2\n\n") .arg(QT_VERSION_STR) @@ -88,7 +88,7 @@ int main(int argc, char **argv) try { /* Registering the below classes as metatypes in order to make - them liable to be sent through signal parameters. */ + * them liable to be sent through signal parameters. */ qRegisterMetaType("ObjectType"); qRegisterMetaType("Exception"); qRegisterMetaType("ValidationInfo"); @@ -116,7 +116,7 @@ int main(int argc, char **argv) //If no custom style is specified we force the usage of Fusion (the default for Qt and pgModeler) if(!using_style) - app.setStyle(GlobalAttributes::DEFAULT_QT_STYLE); + app.setStyle(GlobalAttributes::DefaultQtStyle); //Loading the application splash screen QSplashScreen splash; @@ -139,7 +139,7 @@ int main(int argc, char **argv) fmain.loadModels(params); #endif - fmain.showMaximized(); + fmain.show(); splash.finish(&fmain); res=app.exec(); app.closeAllWindows(); @@ -150,6 +150,6 @@ int main(int argc, char **argv) { QTextStream ts(stdout); ts << e.getExceptionsText(); - return(e.getErrorType()); + return(enum_cast(e.getErrorCode())); } } diff --git a/pgmodeler.pri b/pgmodeler.pri index d74b69a94d..5bb9c5905d 100644 --- a/pgmodeler.pri +++ b/pgmodeler.pri @@ -11,12 +11,15 @@ # General Qt settings QT += core widgets printsupport network svg -CONFIG += ordered qt stl rtti exceptions warn_on c++11 +CONFIG += ordered qt stl rtti exceptions warn_on c++14 TEMPLATE = subdirs MOC_DIR = moc OBJECTS_DIR = obj UI_DIR = src +# Setting up the flag passed to compiler to indicate a snapshot build +defined(SNAPSHOT_BUILD, var): DEFINES+=SNAPSHOT_BUILD + # Setting up the flag passed to compiler to build the demo version defined(DEMO_VERSION, var): DEFINES+=DEMO_VERSION @@ -146,18 +149,18 @@ unix:!macx { } macx { - PGSQL_LIB = /Library/PostgreSQL/10/lib/libpq.dylib - PGSQL_INC = /Library/PostgreSQL/10/include + PGSQL_LIB = /Library/PostgreSQL/11/lib/libpq.dylib + PGSQL_INC = /Library/PostgreSQL/11/include XML_INC = /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/libxml2 XML_LIB = /usr/lib/libxml2.dylib INCLUDEPATH += $$PGSQL_INC $$XML_INC } windows { - !defined(PGSQL_LIB, var): PGSQL_LIB = C:/PostgreSQL/10.1/lib/libpq.dll - !defined(PGSQL_INC, var): PGSQL_INC = C:/PostgreSQL/10.1/include - !defined(XML_INC, var): XML_INC = C:/PostgreSQL/10.1/include - !defined(XML_LIB, var): XML_LIB = C:/PostgreSQL/10.1/bin/libxml2.dll + !defined(PGSQL_LIB, var): PGSQL_LIB = C:/msys_64/mingw64/bin/libpq.dll + !defined(PGSQL_INC, var): PGSQL_INC = C:/msys_64/mingw64/include + !defined(XML_INC, var): XML_INC = C:/msys_64/mingw64/include/libxml2 + !defined(XML_LIB, var): XML_LIB = C:/msys_64/mingw64/bin/libxml2-2.dll # Workaround to solve bug of timespec struct on MingW + PostgreSQL < 9.4 QMAKE_CXXFLAGS+="-DHAVE_STRUCT_TIMESPEC" diff --git a/pgmodeler.vars b/pgmodeler.vars index 96c558bdfa..7a7fbdddce 100644 --- a/pgmodeler.vars +++ b/pgmodeler.vars @@ -9,19 +9,36 @@ # In both cases above you will need to set the PGMODELER_ROOT variable with # the full path to pgModeler root directory. -# Specify here the full path to Qt framework installation in QT_ROOT -# The path used here must be until the "gcc" directory. For instance, if you have -# Qt 5.1.1 installed on your home directory then the path must be: /home/user/Qt5.1.1/5.1.1/gcc + +# ---[ Custom Qt configuration ]--- +# +# This section specifies some environment vars responsible to find Qt framework installation in your system. +# Make sure to have the command "qtpaths" correctly mapped into your PATH environment variable or use the +# QT_PATHS_BIN variable below to specify the mentioned command. # -# NOTE: Use this configuration only if you have a custom Qt installation other than as defined by +# If you have a custom Qt installation at /opt/qt-5.9.6 for example, the path to the command above should be +# /opt/qt-5.9.6/5.9.6/gcc_64 +# +# NOTE: Use the configuration below only if you have a custom Qt installation other than as defined by # your system or if Qt isn't included/installed by default on your distro. -# export QT_ROOT="/path/to/qt/gcc" -# export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:"$QT_ROOT/lib" -# export PATH=$PATH:"$QT_ROOT/bin" + +# Replace the value of this variable by the full path to "qtpaths" if you have a custom Qt installation +# export QT_PATHS_BIN=qtpaths + +# Qt's main environment variables +# export QT_ROOT="$($QT_PATHS_BIN --install-prefix)" +# export QT_BIN="$($QT_PATHS_BIN --binaries-dir)" +# export QT_PLUGIN_PATH="$($QT_PATHS_BIN --plugin-dir)" + +# Change the "lib64" by "lib" if you're running a 32 bit system +# export QT_LIBS="$QT_ROOT/lib64" + +# export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:"$QT_LIBS" +# export PATH=$PATH:"$QT_BIN" +# --- [ End custom configuration ] --- # Specify here the full path to the pgmodeler's root directory -# export PGMODELER_ROOT="/path/to/pgmodeler" export PGMODELER_ROOT="$(dirname "$(readlink -f "$0")")" export PGMODELER_TMPL_CONF_DIR="$PGMODELER_ROOT/conf" diff --git a/plugins/dummy/src/dummy.cpp b/plugins/dummy/src/dummy.cpp index e74b5980fd..13cf98e63e 100644 --- a/plugins/dummy/src/dummy.cpp +++ b/plugins/dummy/src/dummy.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -19,6 +19,7 @@ #include "dummy.h" #include "exception.h" #include "messagebox.h" +#include "mainwindow.h" Dummy::Dummy(void) { @@ -27,10 +28,10 @@ Dummy::Dummy(void) getPluginAuthor(), getPluginDescription(), - GlobalAttributes::PLUGINS_DIR + - GlobalAttributes::DIR_SEPARATOR + + GlobalAttributes::PluginsDir + + GlobalAttributes::DirSeparator + QString("dummy") + - GlobalAttributes::DIR_SEPARATOR + QString("dummy.png")); + GlobalAttributes::DirSeparator + QString("dummy.png")); } QString Dummy::getPluginTitle(void) @@ -64,7 +65,28 @@ void Dummy::executePlugin(ModelWidget *) Messagebox msgbox; msgbox.show(trUtf8("Plugin successfully loaded!"), trUtf8("Plugin successfully loaded! Check the plugins wiki page to know how to create your own plugins."), - Messagebox::INFO_ICON); + Messagebox::InfoIcon); +} + +void Dummy::setMainWindow(QMainWindow *main_window) +{ + this->main_window = main_window; + + /* The sample code below shows how to interact with the exposed main window by adding + * a tool button to the bottom widgets bar. + * + * You can use this basic approach to add more UI elements to it. + * To do so, open the design file mainwindow.ui to see the name of the widgets you + * need to handle */ + + //MainWindow *mw = dynamic_cast(main_window); + //QToolButton *tb = new QToolButton(mw->tool_btns_bar_wgt); + //mw->tool_btns_bar_wgt->layout()->addWidget(tb); + //tb->setText("This is a test button"); + //connect(tb, &QToolButton::clicked, [&](){ + // Messagebox msgbox; + // msgbox.show(trUtf8("Alert"), trUtf8("This is a message box triggered by the click signal emitted by the test button!"), Messagebox::AlertIcon); + //}); } QKeySequence Dummy::getPluginShortcut(void) diff --git a/plugins/dummy/src/dummy.h b/plugins/dummy/src/dummy.h index a9f7ed13ec..83ce79850c 100644 --- a/plugins/dummy/src/dummy.h +++ b/plugins/dummy/src/dummy.h @@ -1,7 +1,7 @@ /* # Projeto: Modelador de Banco de Dados PostgreSQL (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -46,6 +46,8 @@ class Dummy: public QObject, public PgModelerPlugin { QKeySequence getPluginShortcut(void); void executePlugin(ModelWidget *); + virtual void setMainWindow(QMainWindow *main_window); + public slots: void showPluginInfo(void); }; diff --git a/plugins/xml2object/src/xml2object.cpp b/plugins/xml2object/src/xml2object.cpp index 1b8d722c71..22d034010d 100644 --- a/plugins/xml2object/src/xml2object.cpp +++ b/plugins/xml2object/src/xml2object.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -27,10 +27,10 @@ Xml2Object::Xml2Object(void) getPluginAuthor(), getPluginDescription(), - GlobalAttributes::PLUGINS_DIR + - GlobalAttributes::DIR_SEPARATOR + + GlobalAttributes::PluginsDir + + GlobalAttributes::DirSeparator + QString("xml2object") + - GlobalAttributes::DIR_SEPARATOR + QString("xml2object.png")); + GlobalAttributes::DirSeparator + QString("xml2object.png")); } QString Xml2Object::getPluginTitle(void) @@ -61,7 +61,7 @@ void Xml2Object::showPluginInfo(void) void Xml2Object::executePlugin(ModelWidget *model) { if(!model) - throw Exception(trUtf8("This plugin must be executed with at least one model opened!"),ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(trUtf8("This plugin must be executed with at least one model opened!"),ErrorCode::Custom,__PRETTY_FUNCTION__,__FILE__,__LINE__); xml2obj_wgt.show(model->getDatabaseModel(), model->getOperationList()); } diff --git a/plugins/xml2object/src/xml2object.h b/plugins/xml2object/src/xml2object.h index 005d7d660a..18bc64963d 100644 --- a/plugins/xml2object/src/xml2object.h +++ b/plugins/xml2object/src/xml2object.h @@ -1,7 +1,7 @@ /* # Projeto: Modelador de Banco de Dados PostgreSQL (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/plugins/xml2object/src/xml2objectwidget.cpp b/plugins/xml2object/src/xml2objectwidget.cpp index 8af39d604a..4b60e2310d 100644 --- a/plugins/xml2object/src/xml2objectwidget.cpp +++ b/plugins/xml2object/src/xml2objectwidget.cpp @@ -5,7 +5,7 @@ Xml2ObjectWidget::Xml2ObjectWidget(QWidget *parent, Qt::WindowFlags f) : QDialog setupUi(this); code_hl=new SyntaxHighlighter(code_txt); - code_hl->loadConfiguration(GlobalAttributes::XML_HIGHLIGHT_CONF_PATH); + code_hl->loadConfiguration(GlobalAttributes::XMLHighlightConfPath); connect(close_btn, SIGNAL(clicked(void)), this, SLOT(close(void))); connect(clear_btn, SIGNAL(clicked(void)), this, SLOT(clearSource(void))); @@ -34,8 +34,8 @@ void Xml2ObjectWidget::loadXML(void) f.open(QFile::ReadOnly); if(!f.isOpen()) - throw Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED).arg(file_dlg.selectedFiles().at(0)), - ERR_FILE_DIR_NOT_ACCESSED,__PRETTY_FUNCTION__,__FILE__,__LINE__); + throw Exception(Exception::getErrorMessage(ErrorCode::FileDirectoryNotAccessed).arg(file_dlg.selectedFiles().at(0)), + ErrorCode::FileDirectoryNotAccessed,__PRETTY_FUNCTION__,__FILE__,__LINE__); code_txt->setPlainText(QString::fromUtf8(f.readAll())); @@ -59,7 +59,7 @@ void Xml2ObjectWidget::generateObject(void) BaseObject *object=nullptr; ObjectType obj_type; QString elem_name; - XMLParser *xmlparser=model->getXMLParser(); + XmlParser *xmlparser=model->getXMLParser(); if(!op_list->isOperationChainStarted()) op_list->startOperationChain(); @@ -67,7 +67,7 @@ void Xml2ObjectWidget::generateObject(void) xmlparser->restartParser(); xmlparser->loadXMLBuffer(code_txt->toPlainText().toUtf8()); - if(xmlparser->accessElement(XMLParser::CHILD_ELEMENT)) + if(xmlparser->accessElement(XmlParser::ChildElement)) { do { @@ -81,16 +81,16 @@ void Xml2ObjectWidget::generateObject(void) object=model->createObject(obj_type); if(object && !dynamic_cast(object) && - obj_type!=OBJ_RELATIONSHIP && obj_type!=BASE_RELATIONSHIP) + obj_type!=ObjectType::Relationship && obj_type!=ObjectType::BaseRelationship) { model->addObject(object); - op_list->registerObject(object, Operation::OBJECT_CREATED, -1, model); + op_list->registerObject(object, Operation::ObjectCreated, -1, model); } xmlparser->restorePosition(); } } - while(xmlparser->accessElement(xmlparser->NEXT_ELEMENT)); + while(xmlparser->accessElement(xmlparser->NextElement)); } op_list->finishOperationChain(); @@ -102,7 +102,7 @@ void Xml2ObjectWidget::generateObject(void) op_list->undoOperation(); op_list->removeLastOperation(); - throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); + throw Exception(e.getErrorMessage(), e.getErrorCode(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } } diff --git a/plugins/xml2object/src/xml2objectwidget.h b/plugins/xml2object/src/xml2objectwidget.h index 638f33a4b5..2c5ab3fbf1 100644 --- a/plugins/xml2object/src/xml2objectwidget.h +++ b/plugins/xml2object/src/xml2objectwidget.h @@ -14,7 +14,7 @@ class Xml2ObjectWidget: public QDialog, public Ui::Xml2ObjectWidget { OperationList *op_list; public: - Xml2ObjectWidget(QWidget *parent = 0, Qt::WindowFlags f = 0); + Xml2ObjectWidget(QWidget *parent = nullptr, Qt::WindowFlags f = Qt::Widget); public slots: void show(DatabaseModel *model, OperationList *op_list); diff --git a/samples/oldsample.dbm b/samples/oldsample.dbm index 9c1986dbd2..d60dd02458 100644 --- a/samples/oldsample.dbm +++ b/samples/oldsample.dbm @@ -1042,9 +1042,6 @@ CAUTION: Do not modify this file unless you know what you are doing. - - - - - - -
+
diff --git a/schemas/alter/collation.sch b/schemas/alter/collation.sch index 8f62142d6e..4c0a835499 100644 --- a/schemas/alter/collation.sch +++ b/schemas/alter/collation.sch @@ -1,5 +1,4 @@ # SQL definition for collation's attributes change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/alter/column.sch b/schemas/alter/column.sch index 445b085986..4a81625faa 100644 --- a/schemas/alter/column.sch +++ b/schemas/alter/column.sch @@ -1,5 +1,4 @@ # SQL definition for columns's attributes change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. @@ -44,6 +43,48 @@ {ddl-end} %end + %if {cur-identity-type} %and {min-value} %then + {alter-table} + [ SET GENERATED ] {cur-identity-type} [ SET MINVALUE ] {min-value} + {ddl-end} + %end + + %if {cur-identity-type} %and {max-value} %then + {alter-table} + [ SET GENERATED ] {cur-identity-type} [ SET MAXVALUE ] {max-value} + {ddl-end} + %end + + %if {cur-identity-type} %and {start} %then + {alter-table} + [ SET GENERATED ] {cur-identity-type} [ SET START WITH ] {start} + {ddl-end} + %end + + %if {cur-identity-type} %and {cache} %then + {alter-table} + [ SET GENERATED ] {cur-identity-type} [ SET CACHE ] {cache} + {ddl-end} + %end + + %if {cur-identity-type} %and {increment} %then + {alter-table} + [ SET GENERATED ] {cur-identity-type} [ SET INCREMENT ] {increment} + {ddl-end} + %end + + %if {cur-identity-type} %and {cycle} %then + + {alter-table} + [ SET GENERATED ] {cur-identity-type} [ SET] + + %if ({cycle}=="false") %then [ NO] %end + + [ CYCLE] + + {ddl-end} + %end + %if {identity-type} %or {new-identity-type} %then {alter-table} diff --git a/schemas/alter/database.sch b/schemas/alter/database.sch index c476f185d1..ef61cd55d0 100644 --- a/schemas/alter/database.sch +++ b/schemas/alter/database.sch @@ -1,5 +1,4 @@ # SQL definition for database's attributes change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/alter/diff.sch b/schemas/alter/diff.sch index d0d91af49a..297542ce4e 100644 --- a/schemas/alter/diff.sch +++ b/schemas/alter/diff.sch @@ -1,5 +1,4 @@ # Basic structure for the diff script file generated by diff process -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/alter/domain.sch b/schemas/alter/domain.sch index c65758dc3d..4cabe3448f 100644 --- a/schemas/alter/domain.sch +++ b/schemas/alter/domain.sch @@ -1,5 +1,4 @@ # SQL definition for domain's attributes change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/alter/domconstraint.sch b/schemas/alter/domconstraint.sch index 74145e32ff..abaaed0f64 100644 --- a/schemas/alter/domconstraint.sch +++ b/schemas/alter/domconstraint.sch @@ -1,5 +1,4 @@ # SQL definition for domain's constraints change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/alter/eventtrigger.sch b/schemas/alter/eventtrigger.sch index 8e27434190..f7096fe611 100644 --- a/schemas/alter/eventtrigger.sch +++ b/schemas/alter/eventtrigger.sch @@ -1,5 +1,4 @@ # SQL definition for event trigger's attributes change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/alter/extension.sch b/schemas/alter/extension.sch index 921f52f8ea..5aebe0e6c4 100644 --- a/schemas/alter/extension.sch +++ b/schemas/alter/extension.sch @@ -1,5 +1,4 @@ # SQL definition for extension's attributes change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/alter/foreigndatawrapper.sch b/schemas/alter/foreigndatawrapper.sch new file mode 100644 index 0000000000..7c836ff53e --- /dev/null +++ b/schemas/alter/foreigndatawrapper.sch @@ -0,0 +1,40 @@ +# SQL definition for function's attributes change +# CAUTION: Do not modify this file unless you know what you are doing. +# Code generation can be broken if incorrect changes are made. + +{alter-cmds} + +%if {has-changes} %then + [ALTER ] {sql-object} $sp {signature} + + %if ({pgsql-ver} >=f "9.1") %and {handler} %then + $br $tb + + %if ({handler} == "unset") %then + [ NO HANDLER] + %else + [ HANDLER ] {handler} + %end + %end + + %if {validator} %then + $br $tb + + %if ({validator} == "unset") %then + [ NO VALIDATOR] + %else + [ VALIDATOR ] {validator} + %end + %end + + %if {options} %then + $br $tb + [ OPTIONS (] {options} [)] + %end + +; $br + +[-- ddl-end --] $br + +%end + diff --git a/schemas/alter/foreignserver.sch b/schemas/alter/foreignserver.sch new file mode 100644 index 0000000000..528ce6b27d --- /dev/null +++ b/schemas/alter/foreignserver.sch @@ -0,0 +1,25 @@ +# SQL definition for foreign sever's attributes change +# CAUTION: Do not modify this file unless you know what you are doing. +# Code generation can be broken if incorrect changes are made. + +{alter-cmds} + +%if {has-changes} %then + [ALTER ] {sql-object} $sp {signature} + + %if {version} %then + [ VERSION ] '{version}' + + %end + + %if {options} %then + $br $tb + [ OPTIONS (] {options} [)] + %end + +; $br + +[-- ddl-end --] $br + +%end + diff --git a/schemas/alter/function.sch b/schemas/alter/function.sch index d51abaa23b..1518de3c4c 100644 --- a/schemas/alter/function.sch +++ b/schemas/alter/function.sch @@ -1,5 +1,4 @@ # SQL definition for function's attributes change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/alter/index.sch b/schemas/alter/index.sch index dd64d15e89..8ba154afe5 100644 --- a/schemas/alter/index.sch +++ b/schemas/alter/index.sch @@ -1,5 +1,4 @@ # SQL definition for index's attributes change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/alter/owner.sch b/schemas/alter/owner.sch index 00f8aa4d98..19e7c4c406 100644 --- a/schemas/alter/owner.sch +++ b/schemas/alter/owner.sch @@ -1,8 +1,6 @@ # SQL definition for object's owner attribute change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. [ALTER ] {sql-object} $sp {signature} [ OWNER TO ] {owner}; - $br [-- ddl-end --] $br diff --git a/schemas/alter/permission.sch b/schemas/alter/permission.sch index dcc4650176..dc73c85559 100644 --- a/schemas/alter/permission.sch +++ b/schemas/alter/permission.sch @@ -1,5 +1,4 @@ # SQL definition for permissions change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/alter/policy.sch b/schemas/alter/policy.sch index 66d9f1107c..0828298d00 100644 --- a/schemas/alter/policy.sch +++ b/schemas/alter/policy.sch @@ -1,5 +1,4 @@ # SQL definition for policy's attributes change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. @@ -25,5 +24,6 @@ %if {check-exp} %then $br $tb [WITH CHECK (] {check-exp} [)] %end - {ddl-end} + + ; $br [-- ddl-end --] $br %end diff --git a/schemas/alter/relationship.sch b/schemas/alter/relationship.sch index 47619fb5e8..799de44393 100644 --- a/schemas/alter/relationship.sch +++ b/schemas/alter/relationship.sch @@ -1,13 +1,42 @@ # SQL definition for table inheritance configuration -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. -[ALTER TABLE ] {table} +%set {alter-table} [ALTER TABLE ] + +%if {partitioned-table} %then + + %if ({pgsql-ver} >=f "10.0") %then + + {alter-table} {partitioned-table} + + %if ({partitioning}=="unset") %then [ DETACH] %else [ ATTACH] %end + + [ PARTITION ] {table} + + %if ({partitioning}!="unset") %then + + %if {partition-bound-expr} %then + [ FOR VALUES ] {partition-bound-expr} + %else + [ DEFAULT] + %end + + %end + + %end + +%else + + {alter-table} {table} -%if ({inherit}=="unset") %then [ NO] %end + %if ({inherit}=="unset") %then [ NO] %end -[ INHERIT ] {ancestor-table} ; $br + [ INHERIT ] {ancestor-table} +%end + +; $br + [-- ddl-end --] $br diff --git a/schemas/alter/rename.sch b/schemas/alter/rename.sch index 4e6f1a5055..e20b155542 100644 --- a/schemas/alter/rename.sch +++ b/schemas/alter/rename.sch @@ -1,5 +1,4 @@ # SQL definition for object renaming -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/alter/role.sch b/schemas/alter/role.sch index 33ed88e867..fd47303672 100644 --- a/schemas/alter/role.sch +++ b/schemas/alter/role.sch @@ -1,5 +1,4 @@ # SQL definition for role's attributes change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/alter/schema.sch b/schemas/alter/schema.sch index f470eb0c18..2391647c8f 100644 --- a/schemas/alter/schema.sch +++ b/schemas/alter/schema.sch @@ -1,5 +1,4 @@ # SQL definition for object's schema attribute change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/alter/sequence.sch b/schemas/alter/sequence.sch index a6729a63a0..35083b7d7b 100644 --- a/schemas/alter/sequence.sch +++ b/schemas/alter/sequence.sch @@ -1,5 +1,4 @@ # SQL definition for sequence's attributes change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. @@ -52,4 +51,4 @@ %end [-- ddl-end --] $br -%end \ No newline at end of file +%end diff --git a/schemas/alter/table.sch b/schemas/alter/table.sch index 5d28bd1e07..0ceff39d4b 100644 --- a/schemas/alter/table.sch +++ b/schemas/alter/table.sch @@ -1,5 +1,4 @@ # SQL definition for table's attributes change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/alter/tablespace.sch b/schemas/alter/tablespace.sch index 3cc84b0f62..e04fce7433 100644 --- a/schemas/alter/tablespace.sch +++ b/schemas/alter/tablespace.sch @@ -1,5 +1,4 @@ # SQL definition for object's tablespace attribute change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/alter/truncate.sch b/schemas/alter/truncate.sch index f7b26cbb44..96b18d5f88 100644 --- a/schemas/alter/truncate.sch +++ b/schemas/alter/truncate.sch @@ -1,13 +1,17 @@ # SQL definition for trucate tables -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. [TRUNCATE ] {sql-object} $sp {signature} +%if {restart-seq} %then + [ RESTART IDENTITY ] +%end + %if {cascade} %then - [ CASCADE] - %end - ; + [ CASCADE] +%end + +; $br [-- ddl-end --] $br diff --git a/schemas/alter/usermapping.sch b/schemas/alter/usermapping.sch new file mode 100644 index 0000000000..fcc312ebe8 --- /dev/null +++ b/schemas/alter/usermapping.sch @@ -0,0 +1,21 @@ +# SQL definition for user mapping's attributes change +# CAUTION: Do not modify this file unless you know what you are doing. +# Code generation can be broken if incorrect changes are made. + +{alter-cmds} + +%if {has-changes} %then + [ALTER ] {sql-object} $sp {signature} + + + %if {options} %then + $br $tb + [ OPTIONS (] {options} [)] + %end + +; $br + +[-- ddl-end --] $br + +%end + diff --git a/schemas/alter/usertype.sch b/schemas/alter/usertype.sch index 8a33d348f9..46fd268ae1 100644 --- a/schemas/alter/usertype.sch +++ b/schemas/alter/usertype.sch @@ -1,5 +1,4 @@ # SQL definition for user defined types' attributes change -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/catalog/aggregate.sch b/schemas/catalog/aggregate.sch index 36f5092bfc..7ee693d1ae 100644 --- a/schemas/catalog/aggregate.sch +++ b/schemas/catalog/aggregate.sch @@ -2,6 +2,12 @@ # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. +%if ({pgsql-ver} <=f "10.0") %then + %set {is-agg} [pr.proisagg IS TRUE] +%else + %set {is-agg} [pr.prokind = 'a'] +%end + %if {list} %then [SELECT pr.oid, proname || '(' || @@ -14,9 +20,9 @@ %if {schema} %then [ LEFT JOIN pg_namespace AS ns ON pr.pronamespace = ns.oid - WHERE pr.proisagg IS TRUE AND ns.nspname = ] '{schema}' + WHERE ] {is-agg} [ AND ns.nspname = ] '{schema}' %else - [ WHERE pr.proisagg IS TRUE ] + [ WHERE ] {is-agg} %end %if {last-sys-oid} %then @@ -24,7 +30,7 @@ %end %if {not-ext-object} %then - [ AND ] ( {not-ext-object} ) # [ IS FALSE ] + [ AND ] ( {not-ext-object} ) %end %else @@ -43,23 +49,24 @@ [ LEFT JOIN pg_namespace AS ns ON pr.pronamespace = ns.oid ] %end - [ WHERE pr.proisagg IS TRUE ] + [ WHERE ] {is-agg} + %if {last-sys-oid} %then - [ AND pr.oid ] {oid-filter-op} $sp {last-sys-oid} + [ AND pr.oid ] {oid-filter-op} $sp {last-sys-oid} %end %if {not-ext-object} %then - [ AND ] ( {not-ext-object} ) + [ AND ] ( {not-ext-object} ) %end %if {filter-oids} %or {schema} %then - %if {filter-oids} %then - [ AND pr.oid IN (] {filter-oids} ) - %end + %if {filter-oids} %then + [ AND pr.oid IN (] {filter-oids} ) + %end - %if {schema} %then - [ AND ns.nspname = ] '{schema}' - %end + %if {schema} %then + [ AND ns.nspname = ] '{schema}' + %end %end %end %end diff --git a/schemas/catalog/constraint.sch b/schemas/catalog/constraint.sch index 22d125f48b..2e357ba4f2 100644 --- a/schemas/catalog/constraint.sch +++ b/schemas/catalog/constraint.sch @@ -11,7 +11,7 @@ WHERE nspname= ] '{schema}' %if {table} %then - [ AND relkind='r' AND relname=] '{table}' + [ AND relkind IN ('r','p') AND relname=] '{table}' %end %end @@ -30,8 +30,9 @@ [ WHERE ] %end - #Avoiding the listing of constraint generated by constraint triggers - [ cs.oid NOT IN (SELECT DISTINCT tgconstraint FROM pg_trigger WHERE tgconstrindid=0)] + #Avoiding the listing of constraint generated by constraint triggers and those inherited + [ cs.oid NOT IN (SELECT DISTINCT tgconstraint FROM pg_trigger WHERE tgconstrindid=0) + AND cs.conislocal IS TRUE ] %if {not-ext-object} %then [ AND ]( {not-ext-object} ) @@ -115,37 +116,38 @@ WHERE ns.nspname= ] '{schema}' %if {table} %then - [ AND tb.relkind='r' AND tb.relname= ] '{table}' + [ AND tb.relkind IN ('r','p') AND tb.relname= ] '{table}' %end %end %if {last-sys-oid} %then - %if {schema} %then - [ AND ] - %else - [ WHERE ] - %end - [ cs.oid ] {oid-filter-op} $sp {last-sys-oid} + %if {schema} %then + [ AND ] + %else + [ WHERE ] + %end + [ cs.oid ] {oid-filter-op} $sp {last-sys-oid} %end %if {filter-oids} %then - %if {schema} %or {last-sys-oid} %then - [ AND ] - %else - [ WHERE ] - %end + %if {schema} %or {last-sys-oid} %then + [ AND ] + %else + [ WHERE ] + %end [ cs.oid IN (] {filter-oids} ) %end %if {filter-oids} %or {last-sys-oid} %or {schema} %then - [ AND ] + [ AND ] %else - [ WHERE ] + [ WHERE ] %end - #Avoiding the listing of constraint generated by constraint triggers - [ cs.oid NOT IN (SELECT DISTINCT tgconstraint FROM pg_trigger WHERE tgconstrindid=0)] + #Avoiding the listing of constraint generated by constraint triggers and those inherited + [ cs.oid NOT IN (SELECT DISTINCT tgconstraint FROM pg_trigger WHERE tgconstrindid=0) + AND cs.conislocal IS TRUE ] %if {not-ext-object} %then [ AND ]( {not-ext-object} ) diff --git a/schemas/catalog/domain.sch b/schemas/catalog/domain.sch index 04c8d0e539..469c18c811 100644 --- a/schemas/catalog/domain.sch +++ b/schemas/catalog/domain.sch @@ -45,7 +45,7 @@ dm.typnotnull AS not_null_bool, _dm1.interval_type, _dm1.domain_default AS default_value, - (select array_agg(conname || ':' || consrc) from pg_constraint where contypid = dm.oid) as constraints, + (select array_agg(conname || '•' || consrc) from pg_constraint where contypid = dm.oid) as constraints, ] ({comment}) [ AS comment ] diff --git a/schemas/catalog/foreigndatawrapper.sch b/schemas/catalog/foreigndatawrapper.sch new file mode 100644 index 0000000000..f290036f2b --- /dev/null +++ b/schemas/catalog/foreigndatawrapper.sch @@ -0,0 +1,65 @@ +# Catalog queries for foreign data wrappers +# CAUTION: Do not modify this file unless you know what you are doing. +# Code generation can be broken if incorrect changes are made. + +%if {list} %then + [ SELECT fw.oid, fdwname AS name FROM pg_foreign_data_wrapper AS fw ] + + %if {last-sys-oid} %or {not-ext-object} %then + [ WHERE ] + + %if {last-sys-oid} %then + [ fw.oid ] {oid-filter-op} $sp {last-sys-oid} + %end + + %if {not-ext-object} %then + + %if {last-sys-oid} %then + [ AND ] + %end + + ( {not-ext-object} ) + %end + %end +%else + %if {attribs} %then + [SELECT oid, fdwname AS name, ] + + %if ({pgsql-ver} >=f "9.1") %then + [ fdwhandler AS handler, ] + %else + [ NULL AS handler, ] + %end + + [ fdwvalidator AS validator, + fdwacl AS permission, fdwowner AS owner, fdwoptions AS options, ] + + ({comment}) [ AS comment ] + + [ FROM pg_foreign_data_wrapper AS fw ] + + %if {last-sys-oid} %then + [ WHERE oid ] {oid-filter-op} $sp {last-sys-oid} + %end + + %if {not-ext-object} %then + %if {last-sys-oid} %then + [ AND ] + %else + [ WHERE ] + %end + + ( {not-ext-object} ) + %end + + %if {filter-oids} %then + %if {last-sys-oid} %or {not-ext-object} %then + [ AND ] + %else + [ WHERE ] + %end + + [ oid IN (] {filter-oids} ) + %end + %end +%end diff --git a/schemas/catalog/foreignserver.sch b/schemas/catalog/foreignserver.sch new file mode 100644 index 0000000000..58d00b63be --- /dev/null +++ b/schemas/catalog/foreignserver.sch @@ -0,0 +1,58 @@ +# Catalog queries for foreign server +# CAUTION: Do not modify this file unless you know what you are doing. +# Code generation can be broken if incorrect changes are made. + +%if {list} %then + [ SELECT sv.oid, srvname AS name FROM pg_foreign_server AS sv ] + + %if {last-sys-oid} %or {not-ext-object} %then + [ WHERE ] + + %if {last-sys-oid} %then + [ sv.oid ] {oid-filter-op} $sp {last-sys-oid} + %end + + %if {not-ext-object} %then + + %if {last-sys-oid} %then + [ AND ] + %end + + ( {not-ext-object} ) + %end + %end +%else + %if {attribs} %then + [SELECT oid, srvname AS name, srvversion AS version, srvtype AS type, + srvfdw AS fdw, srvacl AS permission, srvowner AS owner, + srvoptions AS options, ] + + ({comment}) [ AS comment ] + + [ FROM pg_foreign_server AS sv ] + + %if {last-sys-oid} %then + [ WHERE oid ] {oid-filter-op} $sp {last-sys-oid} + %end + + %if {not-ext-object} %then + %if {last-sys-oid} %then + [ AND ] + %else + [ WHERE ] + %end + + ( {not-ext-object} ) + %end + + %if {filter-oids} %then + %if {last-sys-oid} %or {not-ext-object} %then + [ AND ] + %else + [ WHERE ] + %end + + [ oid IN (] {filter-oids} ) + %end + %end +%end diff --git a/schemas/catalog/function.sch b/schemas/catalog/function.sch index fea8fbe3ad..2e76ba35ab 100644 --- a/schemas/catalog/function.sch +++ b/schemas/catalog/function.sch @@ -2,15 +2,23 @@ # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. +%if ({pgsql-ver} <=f "10.0") %then + %set {is-not-agg} [pr.proisagg IS FALSE] + %set {window-func} [pr.proiswindow AS window_func_bool] +%else + %set {is-not-agg} [pr.prokind <> 'a'] + %set {window-func} [CASE pr.prokind WHEN 'w' THEN TRUE ELSE FALSE END AS window_func_bool] +%end + %if {list} %then [SELECT pr.oid, proname || '(' || array_to_string(proargtypes::regtype] $ob $cb [,',') || ')' AS name FROM pg_proc AS pr ] %if {schema} %then [ LEFT JOIN pg_namespace AS ns ON pr.pronamespace = ns.oid - WHERE pr.proisagg IS FALSE AND ns.nspname = ] '{schema}' + WHERE ] {is-not-agg} [ AND ns.nspname = ] '{schema}' %else - [ WHERE pr.proisagg IS FALSE ] + [ WHERE ] {is-not-agg} %end %if {last-sys-oid} %then @@ -30,9 +38,11 @@ pr.proname AS name, pr.prolang AS language, pr.procost AS execution_cost, - pr.prorows AS row_amount, - pr.proiswindow AS window_func_bool, - pr.proretset AS returns_setof_bool, + pr.prorows AS row_amount, ] + + {window-func}, + + [ pr.proretset AS returns_setof_bool, pr.pronargs AS arg_count, pr.pronargdefaults AS arg_def_count, pr.prorettype AS return_type, ] @@ -64,7 +74,7 @@ ELSE 'CALLED ON NULL INPUT' END AS behavior_type, ] - %if ({pgsql-ver} <=f "9.1") %then + %if ({pgsql-ver} <=f "9.1") %then [ NULL AS leakproof_bool, ] %else [ pr.proleakproof AS leakproof_bool, ] @@ -78,7 +88,7 @@ [ LEFT JOIN pg_namespace AS ns ON pr.pronamespace = ns.oid ] %end - [ WHERE pr.proisagg IS FALSE ] + [ WHERE ] {is-not-agg} %if {last-sys-oid} %then [ AND pr.oid ] {oid-filter-op} $sp {last-sys-oid} diff --git a/schemas/catalog/policy.sch b/schemas/catalog/policy.sch index 5ef4071ac4..43f7934c9a 100644 --- a/schemas/catalog/policy.sch +++ b/schemas/catalog/policy.sch @@ -15,12 +15,15 @@ %if {table} %then [ AND tb.relkind='r' AND tb.relname=] '{table}' %end + + %if {last-sys-oid} %or {not-ext-object} %then + [ AND ] + %end - [ AND ] %else [ WHERE ] %end - + %if {last-sys-oid} %then [ pl.oid ] {oid-filter-op} $sp {last-sys-oid} %end diff --git a/schemas/catalog/table.sch b/schemas/catalog/table.sch index aefff00e4a..a710487fcf 100644 --- a/schemas/catalog/table.sch +++ b/schemas/catalog/table.sch @@ -7,9 +7,9 @@ %if {schema} %then [ LEFT JOIN pg_namespace AS ns ON ns.oid=tb.relnamespace - WHERE tb.relkind='r' AND ns.nspname= ] '{schema}' + WHERE tb.relkind IN ('r','p') AND ns.nspname= ] '{schema}' %else - [ WHERE tb.relkind='r'] + [ WHERE tb.relkind IN ('r','p')] %end %if {last-sys-oid} %then @@ -22,8 +22,8 @@ %else %if {attribs} %then - [SELECT tb.oid, tb.relname AS name, tb.relnamespace AS schema, tb.relowner AS owner, tb.reltuples::int8 AS row_amount, - tb.reltablespace AS tablespace, tb.relacl AS permission, relhasoids AS oids_bool, ] + [SELECT tb.oid, tb.relname AS name, tb.relnamespace AS schema, tb.relowner AS owner, + tb.reltablespace AS tablespace, tb.relacl AS permission, relhasoids AS oids_bool, ] %if ({pgsql-ver} == "9.0") %then [ FALSE AS unlogged_bool, ] @@ -36,43 +36,97 @@ %end %if ({pgsql-ver} =f "10.0") %then + [ AND inhparent NOT IN (SELECT partrelid FROM pg_partitioned_table)] + %end + + [)], + + %if ({pgsql-ver} >=f "10.0") %then + [ CASE relkind + WHEN 'p' THEN TRUE + ELSE FALSE + END AS is_partitioned_bool, + + CASE relispartition + WHEN TRUE THEN + (SELECT inhparent FROM pg_inherits WHERE inhrelid = tb.oid) + ELSE + NULL + END AS partitioned_table, + + pg_get_expr(relpartbound, tb.oid) AS partition_bound_expr, + + ] + %else + [ FALSE AS is_partitioned_bool, NULL AS partitioned_table, NULL AS partition_bound_expr,] + %end + ({comment}) [ AS comment ] - + + [ , st.n_tup_ins AS tuples_ins, st.n_tup_upd AS tuples_upd, st.n_tup_del AS tuples_del, st.n_live_tup AS row_amount, + st.n_dead_tup AS dead_rows_amount, st.last_vacuum, st.last_autovacuum, st.last_analyze, ] + + %if ({pgsql-ver} >=f "10.0") %then + [ CASE partstrat + WHEN 'l' then 'LIST' + WHEN 'r' then 'RANGE' + ELSE 'HASH' + END AS partitioning, + pg_get_expr(partexprs, partrelid) AS part_key_exprs, + partattrs::oid] $ob $cb [ AS part_key_cols, + partclass::oid] $ob $cb [ AS part_key_opcls, + partcollation::oid] $ob $cb [ AS part_key_colls ] + %else + [ NULL AS partitioning, NULL AS part_key_exprs, NULL AS part_key_cols, + NULL AS part_key_opcls, NULL AS part_key_colls ] + %end + [ FROM pg_class AS tb - LEFT JOIN pg_tables AS _tb1 ON _tb1.tablename=tb.relname - WHERE tb.relkind='r' ] + LEFT JOIN pg_tables AS _tb1 ON _tb1.tablename=tb.relname + LEFT JOIN pg_stat_all_tables AS st ON st.relid=tb.oid ] + + %if ({pgsql-ver} >=f "10.0") %then + [ LEFT JOIN pg_partitioned_table AS pt ON pt.partrelid = tb.oid ] + %end + + + [ WHERE tb.relkind IN ('r','p') ] %if {last-sys-oid} %then - [ AND tb.oid ] {oid-filter-op} $sp {last-sys-oid} + [ AND tb.oid ] {oid-filter-op} $sp {last-sys-oid} %end %if {not-ext-object} %then - [ AND ] ( {not-ext-object} ) + [ AND ] ( {not-ext-object} ) %end %if {filter-oids} %or {schema} %then - [ AND ] - %if {filter-oids} %then - [ tb.oid IN (] {filter-oids} ) + [ AND ] + %if {filter-oids} %then + [ tb.oid IN (] {filter-oids} ) - %if {schema} %then - [ AND ] - %end - %end + %if {schema} %then + [ AND ] + %end + %end - %if {schema} %then - [ _tb1.schemaname= ] '{schema}' - %end + %if {schema} %then + [ _tb1.schemaname= ] '{schema}' + %end %end %end + %end diff --git a/schemas/catalog/trigger.sch b/schemas/catalog/trigger.sch index 6a990369e2..46c861048a 100644 --- a/schemas/catalog/trigger.sch +++ b/schemas/catalog/trigger.sch @@ -75,6 +75,13 @@ regexp_replace(regexp_replace(pg_get_triggerdef(tg.oid), '(.)+((INSERT|DELETE|UPDATE)|( OF))', ''), '( ON)(.)*','') ELSE NULL END AS columns, ] + + + %if ({pgsql-ver} >=f "10.0") %then + [ tgoldtable AS old_table_name, tgnewtable AS new_table_name, ] + %else + [ NULL AS old_table_name, NULL AS new_table_name, ] + %end ({comment}) [ AS comment ] diff --git a/schemas/catalog/usermapping.sch b/schemas/catalog/usermapping.sch new file mode 100644 index 0000000000..4b07d85127 --- /dev/null +++ b/schemas/catalog/usermapping.sch @@ -0,0 +1,54 @@ +# Catalog queries for user mapping +# CAUTION: Do not modify this file unless you know what you are doing. +# Code generation can be broken if incorrect changes are made. + +%if {list} %then + [ SELECT um.umid AS oid, um.usename || '@' || um.srvname AS name FROM pg_user_mappings AS um ] + + %if {last-sys-oid} %or {not-ext-object} %then + [ WHERE ] + + %if {last-sys-oid} %then + [ um.umid ] {oid-filter-op} $sp {last-sys-oid} + %end + + %if {not-ext-object} %then + + %if {last-sys-oid} %then + [ AND ] + %end + + ( {not-ext-object} ) + %end + %end +%else + %if {attribs} %then + [SELECT umid AS oid, usename || '@' || srvname AS name, um.srvid AS server, + umuser AS owner, umoptions AS options + FROM pg_user_mappings AS um ] + + %if {last-sys-oid} %then + [ WHERE umid ] {oid-filter-op} $sp {last-sys-oid} + %end + + %if {not-ext-object} %then + %if {last-sys-oid} %then + [ AND ] + %else + [ WHERE ] + %end + + ( {not-ext-object} ) + %end + + %if {filter-oids} %then + %if {last-sys-oid} %or {not-ext-object} %then + [ AND ] + %else + [ WHERE ] + %end + + [ umid IN (] {filter-oids} ) + %end + %end +%end diff --git a/schemas/catalog/usertype.sch b/schemas/catalog/usertype.sch index 155838171a..7006193e01 100644 --- a/schemas/catalog/usertype.sch +++ b/schemas/catalog/usertype.sch @@ -3,7 +3,7 @@ # Code generation can be broken if incorrect changes are made. %if {list} %then - [SELECT tp.oid, replace(tp.oid::regtype::text, ns.nspname || '.', '') AS name FROM pg_type AS tp ] + [SELECT tp.oid, replace(replace(tp.oid::regtype::text,'"', ''), ns.nspname || '.', '') AS name FROM pg_type AS tp ] [ LEFT JOIN pg_namespace AS ns ON tp.typnamespace = ns.oid ] %if {schema} %then @@ -14,9 +14,9 @@ [ typtype IN ('p','b','c','e','r') AND typname NOT LIKE 'pg_%' ] - #Excluding types related to tables/views/sequeces/materialized views + #Excluding types related to tables/views/sequeces/materialized views/foreign tables %if {filter-tab-types} %then - [ AND (SELECT count(oid) FROM pg_class WHERE relname=typname AND relkind IN ('r','S','v','m'))=0 ] + [ AND (SELECT count(oid) FROM pg_class WHERE relname=typname AND relkind IN ('r','S','v','m','p','f'))=0 ] %end %if {exc-builtin-arrays} %then @@ -34,7 +34,7 @@ %else %if {attribs} %then - [SELECT tp.oid, replace(tp.oid::regtype::text, ns.nspname || '.', '') AS name, tp.typnamespace AS schema, tp.typowner AS owner, ] + [SELECT tp.oid, replace(replace(tp.oid::regtype::text,'"', ''), ns.nspname || '.', '') AS name, tp.typnamespace AS schema, tp.typowner AS owner, ] #Retrieve the OID for table/view/sequence that generates the composite type [ (SELECT @@ -44,6 +44,8 @@ WHEN relkind = 'v' THEN 'view' WHEN relkind = 'm' THEN 'view' WHEN typtype = 'd' THEN 'domain' + WHEN typtype = 'p' THEN 'table' + WHEN typtype = 'f' THEN 'foreigntable' END AS type_class FROM pg_class WHERE oid=tp.typrelid), tp.typrelid AS object_id, ] #TODO: Discover which field is the acl for user defined types on PgSQL 9.0 @@ -134,7 +136,7 @@ #Excluding types related to tables/views/sequeces/materialized views %if {filter-tab-types} %then - [ AND (SELECT count(oid) FROM pg_class WHERE relname=typname AND relkind IN ('r','S','v','m'))=0 ] + [ AND (SELECT count(oid) FROM pg_class WHERE relname=typname AND relkind IN ('r','S','v','m','p','f'))=0 ] %end %if {exc-builtin-arrays} %then diff --git a/schemas/catalog/view.sch b/schemas/catalog/view.sch index c59a4a9015..af31181cb1 100644 --- a/schemas/catalog/view.sch +++ b/schemas/catalog/view.sch @@ -3,74 +3,90 @@ # Code generation can be broken if incorrect changes are made. %if {list} %then - [SELECT vw.oid, vw.relname AS name FROM pg_class AS vw ] + [SELECT vw.oid, vw.relname AS name FROM pg_class AS vw ] - %if {schema} %then - [ LEFT JOIN pg_namespace AS ns ON ns.oid=vw.relnamespace ] - %end + %if {schema} %then + [ LEFT JOIN pg_namespace AS ns ON ns.oid=vw.relnamespace ] + %end - %if ({pgsql-ver} <=f "9.2") %then - [ WHERE vw.relkind='v'] - %else - [ WHERE vw.relkind IN ('v','m') ] - %end + %if ({pgsql-ver} <=f "9.2") %then + [ WHERE vw.relkind='v'] + %else + [ WHERE vw.relkind IN ('v','m') ] + %end - %if {schema} %then - [ AND ns.nspname= ] '{schema}' - %end - - %if {last-sys-oid} %then - [ AND vw.oid ] {oid-filter-op} $sp {last-sys-oid} - %end + %if {schema} %then + [ AND ns.nspname= ] '{schema}' + %end - %if {not-ext-object} %then - [ AND ] ( {not-ext-object} ) - %end + %if {last-sys-oid} %then + [ AND vw.oid ] {oid-filter-op} $sp {last-sys-oid} + %end + %if {not-ext-object} %then + [ AND ] ( {not-ext-object} ) + %end %else - %if {attribs} %then - [SELECT vw.oid, vw.relname AS name, vw.relnamespace AS schema, vw.relowner AS owner, - vw.reltablespace AS tablespace, - vw.relacl AS permission, pg_get_viewdef(vw.oid) AS definition, ] - - [ CASE - WHEN vw.relkind='m' THEN TRUE - ELSE FALSE - END AS materialized_bool, ] - + %if {attribs} %then + [SELECT vw.oid, vw.relname AS name, vw.relnamespace AS schema, vw.relowner AS owner, + vw.reltablespace AS tablespace, + vw.relacl AS permission, pg_get_viewdef(vw.oid) AS definition, ] + + # Subquery that retrieves the tables that the view refereces + # Extracted from the definition of the relation information_schema.view_table_usage + [(SELECT array_agg(DISTINCT dt.refobjid) + FROM pg_namespace AS nv, + pg_class AS v, + pg_depend AS dv, + pg_depend AS dt, + pg_class AS t, + pg_namespace AS nt + WHERE nv.oid = v.relnamespace AND v.relkind IN ('v','m') + AND v.oid = dv.refobjid AND dv.refclassid = 'pg_class'::regclass::oid + AND dv.classid = 'pg_rewrite'::regclass::oid AND dv.deptype = 'i' + AND dv.objid = dt.objid AND dv.refobjid <> dt.refobjid AND dt.classid = 'pg_rewrite'::regclass::oid + AND dt.refclassid = 'pg_class'::regclass::oid AND dt.refobjid = t.oid + AND t.relnamespace = nt.oid AND t.relkind IN ('r', 'p') + AND v.oid = ] vw.oid [) AS ref_tables, ] + + [ CASE + WHEN vw.relkind='m' THEN TRUE + ELSE FALSE + END AS materialized_bool, ] + + ({comment}) [ AS comment ] - ({comment}) [ AS comment ] - - [ FROM pg_class AS vw - LEFT JOIN pg_namespace AS ns ON ns.oid = vw.relnamespace ] + [ FROM pg_class AS vw + LEFT JOIN pg_namespace AS ns ON ns.oid = vw.relnamespace ] - %if ({pgsql-ver} <=f "9.2") %then - [ WHERE vw.relkind='v'] - %else - [ WHERE vw.relkind IN ('v','m') ] - %end + %if ({pgsql-ver} <=f "9.2") %then + [ WHERE vw.relkind='v'] + %else + [ WHERE vw.relkind IN ('v','m') ] + %end - %if {last-sys-oid} %then - [ AND vw.oid ] {oid-filter-op} $sp {last-sys-oid} - %end + %if {last-sys-oid} %then + [ AND vw.oid ] {oid-filter-op} $sp {last-sys-oid} + %end - %if {not-ext-object} %then - [ AND ] ( {not-ext-object} ) - %end + %if {not-ext-object} %then + [ AND ] ( {not-ext-object} ) + %end - %if {filter-oids} %or {schema} %then - [ AND ] - %if {filter-oids} %then - [ vw.oid IN (] {filter-oids} ) + %if {filter-oids} %or {schema} %then + [ AND ] + + %if {filter-oids} %then + [ vw.oid IN (] {filter-oids} ) - %if {schema} %then - [ AND ] - %end - %end + %if {schema} %then + [ AND ] + %end + %end - %if {schema} %then - [ ns.nspname= ] '{schema}' - %end - %end + %if {schema} %then + [ ns.nspname= ] '{schema}' + %end + %end %end %end diff --git a/schemas/sql/aggregate.sch b/schemas/sql/aggregate.sch index e09d50c723..1cdfabc9d6 100644 --- a/schemas/sql/aggregate.sch +++ b/schemas/sql/aggregate.sch @@ -1,5 +1,4 @@ # SQL definition for aggregate functions -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/cast.sch b/schemas/sql/cast.sch index dc58b061b1..93473b6774 100644 --- a/schemas/sql/cast.sch +++ b/schemas/sql/cast.sch @@ -1,5 +1,4 @@ # SQL definition for type casts -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/collation.sch b/schemas/sql/collation.sch index be15a801b9..7f84ea9110 100644 --- a/schemas/sql/collation.sch +++ b/schemas/sql/collation.sch @@ -1,5 +1,4 @@ # SQL definition for collations -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/column.sch b/schemas/sql/column.sch index 165be70e55..a9e2f8dd6e 100644 --- a/schemas/sql/column.sch +++ b/schemas/sql/column.sch @@ -1,16 +1,15 @@ # SQL definition for columns -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. %if {decl-in-table} %then $tb %else -[-- object: ] {name} [ | type: ] {sql-object} [ --] $br -[-- ] {drop} - %if {table} %then - [ALTER TABLE ] {table} [ ADD COLUMN ] - %end + [-- object: ] {name} [ | type: ] {sql-object} [ --] $br + [-- ] {drop} + %if {table} %then + [ALTER TABLE ] {table} [ ADD COLUMN ] + %end %end {name} $sp {type} @@ -21,6 +20,39 @@ %if ({pgsql-ver} >=f "10.0") %and {identity-type} %then [ GENERATED ] {identity-type} [ AS IDENTITY ] + + %if {increment} %or {min-value} %or {max-value} %or {start} %or {cache} %or {cycle} %then + [(] + %end + + %if {increment} %then + [ INCREMENT BY ] {increment} + %end + + %if {min-value} %then + [ MINVALUE ] {min-value} + %end + + %if {max-value} %then + [ MAXVALUE ] {max-value} + %end + + %if {start} %then + [ START WITH ] {start} + %end + + %if {cache} %then + [ CACHE ] {cache} + %end + + %if {cycle} %then + [ CYCLE] + %end + + %if {increment} %or {min-value} %or {max-value} %or {start} %or {cache} %or {cycle} %then + [ )] + %end + %else %if {default-value} %then [ DEFAULT ] {default-value} @@ -37,4 +69,8 @@ $br [-- ddl-end --] $br $br %end +%if %not {decl-in-table} %and {comment} %then + {comment} $br +%end + $br diff --git a/schemas/sql/comment.sch b/schemas/sql/comment.sch index 7aea1c7bea..e6f653ef4f 100644 --- a/schemas/sql/comment.sch +++ b/schemas/sql/comment.sch @@ -1,5 +1,4 @@ # SQL definition for comments -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/constraint.sch b/schemas/sql/constraint.sch index a6564653a2..af3fc24101 100644 --- a/schemas/sql/constraint.sch +++ b/schemas/sql/constraint.sch @@ -1,5 +1,4 @@ # SQL definition for constraints -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. %if {decl-in-table} %then @@ -76,4 +75,8 @@ [-- ddl-end --] $br %end +%if %not {decl-in-table} %and {comment} %then + {comment} $br +%end + $br diff --git a/schemas/sql/conversion.sch b/schemas/sql/conversion.sch index 0d8d064325..40eb07f226 100644 --- a/schemas/sql/conversion.sch +++ b/schemas/sql/conversion.sch @@ -1,5 +1,4 @@ # SQL definition for encoding conversions -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. [-- object: ] {name} [ | type: ] {sql-object} [ --] $br diff --git a/schemas/sql/database.sch b/schemas/sql/database.sch index deee7dfe15..2ba717302b 100644 --- a/schemas/sql/database.sch +++ b/schemas/sql/database.sch @@ -1,5 +1,4 @@ # SQL definition for databases -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/dbmodel.sch b/schemas/sql/dbmodel.sch index 722d21f128..a7d1b13860 100644 --- a/schemas/sql/dbmodel.sch +++ b/schemas/sql/dbmodel.sch @@ -1,5 +1,4 @@ # SQL definition for database model -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. @@ -25,14 +24,14 @@ $br $br %if {role} %then {role} %end %if {tablespace} %then - [-- Tablespaces creation must be done outside an multicommand file.] $br - [-- These commands were put in this file only for convenience.] $br + [-- Tablespaces creation must be done outside a multicommand file.] $br + [-- These commands were put in this file only as a convenience.] $br {tablespace} $br %end $br - [-- Database creation must be done outside an multicommand file.] $br - [-- These commands were put in this file only for convenience.] $br + [-- Database creation must be done outside a multicommand file.] $br + [-- These commands were put in this file only as a convenience.] $br {database} $br %end diff --git a/schemas/sql/domain.sch b/schemas/sql/domain.sch index d9d4857674..dc08d42a77 100644 --- a/schemas/sql/domain.sch +++ b/schemas/sql/domain.sch @@ -1,5 +1,4 @@ # SQL definition for domains -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/domconstraint.sch b/schemas/sql/domconstraint.sch index 47f67bc7d8..f96c599e87 100644 --- a/schemas/sql/domconstraint.sch +++ b/schemas/sql/domconstraint.sch @@ -1,5 +1,4 @@ # SQL definition for domain's check constraint -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/drop.sch b/schemas/sql/drop.sch index 18ba224b99..becfd741d8 100644 --- a/schemas/sql/drop.sch +++ b/schemas/sql/drop.sch @@ -1,5 +1,4 @@ # SQL command to drop an object -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/element.sch b/schemas/sql/element.sch index 9f708f5156..36a8b7b8c6 100644 --- a/schemas/sql/element.sch +++ b/schemas/sql/element.sch @@ -1,5 +1,4 @@ # SQL definition for operator class elements -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. %if {function} %then diff --git a/schemas/sql/eventtrigger.sch b/schemas/sql/eventtrigger.sch index 75d936f1de..643f4f7eb3 100644 --- a/schemas/sql/eventtrigger.sch +++ b/schemas/sql/eventtrigger.sch @@ -1,5 +1,4 @@ # SQL definition for event triggers -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/excelement.sch b/schemas/sql/excelement.sch index b7f0778d5e..5db94ba2f9 100644 --- a/schemas/sql/excelement.sch +++ b/schemas/sql/excelement.sch @@ -1,5 +1,4 @@ # SQL definition for exclude constraints elements -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. $br $tb $sp $sp diff --git a/schemas/sql/extension.sch b/schemas/sql/extension.sch index 845c7eacd7..78f374385d 100644 --- a/schemas/sql/extension.sch +++ b/schemas/sql/extension.sch @@ -1,5 +1,4 @@ # SQL definition for extensions -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. @@ -17,15 +16,15 @@ [CREATE EXTENSION ] {name} $br %if {schema} %then - [ WITH SCHEMA ] {schema} + [WITH SCHEMA ] {schema} %end %if {cur-version} %then - $br [ VERSION ] '{cur-version}' + $br [VERSION ] '{cur-version}' %end %if {old-version} %then - $br [ FROM ] '{old-version}' + $br [FROM ] '{old-version}' %end ; $br diff --git a/schemas/sql/foreigndatawrapper.sch b/schemas/sql/foreigndatawrapper.sch new file mode 100644 index 0000000000..a65d7e6a38 --- /dev/null +++ b/schemas/sql/foreigndatawrapper.sch @@ -0,0 +1,49 @@ +# SQL definition for foreign data wrappers +# CAUTION: Do not modify this file unless you know what you are doing. +# Code generation can be broken if incorrect changes are made. +[-- object: ] {name} [ | type: ] {sql-object} [ --] $br + +[-- ] {drop} + +%if {prepended-sql} %then + {prepended-sql} + $br [-- ddl-end --] $br $br +%end + +[CREATE ] {sql-object} $sp {name} + +%if ({pgsql-ver} >=f "9.1") %then + $br + + %if %not {handler} %then + [NO HANDLER] + %else + [HANDLER ] {handler} + %end +%end + +$br + +%if %not {validator} %then + [NO VALIDATOR] +%else + [VALIDATOR ] {validator} +%end + +%if {options} %then + $br [OPTIONS (] {options} ) +%end + +; + +$br [-- ddl-end --] $br + +%if {owner} %then {owner} %end +%if {comment} %then {comment} %end + +%if {appended-sql} %then + {appended-sql} + $br [-- ddl-end --] $br +%end + +$br diff --git a/schemas/sql/foreignserver.sch b/schemas/sql/foreignserver.sch new file mode 100644 index 0000000000..7d8462edfe --- /dev/null +++ b/schemas/sql/foreignserver.sch @@ -0,0 +1,42 @@ +# SQL definition for foreign server +# CAUTION: Do not modify this file unless you know what you are doing. +# Code generation can be broken if incorrect changes are made. + +[-- object: ] {name} [ | type: ] {sql-object} [ --] $br + +[-- ] {drop} + +%if {prepended-sql} %then + {prepended-sql} + $br [-- ddl-end --] $br $br +%end + +[CREATE SERVER ] {name} + +%if {type} %then + [ TYPE ] '{type}' +%end + +%if {version} %then + [ VERSION ] '{version}' +%end + +$br [FOREIGN DATA WRAPPER ] {fdw} + +%if {options} %then + $br [OPTIONS (] {options} ) +%end + +; + +$br [-- ddl-end --] $br + +%if {owner} %then {owner} %end +%if {comment} %then {comment} %end + +%if {appended-sql} %then + {appended-sql} + $br [-- ddl-end --] $br +%end + +$br diff --git a/schemas/sql/function.sch b/schemas/sql/function.sch index 2c96924ab3..d558e9e108 100644 --- a/schemas/sql/function.sch +++ b/schemas/sql/function.sch @@ -1,5 +1,4 @@ # SQL definition for functions -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. [-- object: ] {name} [ | type: ] {sql-object} [ --] $br diff --git a/schemas/sql/genericsql.sch b/schemas/sql/genericsql.sch index 748a4b62de..bd1a12c24b 100644 --- a/schemas/sql/genericsql.sch +++ b/schemas/sql/genericsql.sch @@ -1,5 +1,4 @@ # SQL definition for generic sql objects -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/idxelement.sch b/schemas/sql/idxelement.sch index 2616540bc6..b51232cf96 100644 --- a/schemas/sql/idxelement.sch +++ b/schemas/sql/idxelement.sch @@ -1,5 +1,4 @@ # SQL definition for index elements -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. $br $tb $sp $sp diff --git a/schemas/sql/index.sch b/schemas/sql/index.sch index ddc673b658..aab06a9e5d 100644 --- a/schemas/sql/index.sch +++ b/schemas/sql/index.sch @@ -1,5 +1,4 @@ # SQL definition for indexes -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/language.sch b/schemas/sql/language.sch index dab7447c42..ec73098679 100644 --- a/schemas/sql/language.sch +++ b/schemas/sql/language.sch @@ -1,5 +1,4 @@ # SQL definition for procedural languages -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. @@ -25,11 +24,11 @@ %end %if {validator} %then - $br $tb [VALIDATOR ] {validator} + $br [VALIDATOR ] {validator} %end %if {inline} %then - $br $tb [INLINE ] {inline} + $br [INLINE ] {inline} %end ; $br diff --git a/schemas/sql/opclass.sch b/schemas/sql/opclass.sch index aee3a856a4..12c9b7c0f7 100644 --- a/schemas/sql/opclass.sch +++ b/schemas/sql/opclass.sch @@ -1,5 +1,4 @@ # SQL definition for operator classes -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/operator.sch b/schemas/sql/operator.sch index 2f6eb3a84f..6213d6169c 100644 --- a/schemas/sql/operator.sch +++ b/schemas/sql/operator.sch @@ -1,5 +1,4 @@ # SQL definition for operators -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/opfamily.sch b/schemas/sql/opfamily.sch index 2edd8e3065..6046c21b26 100644 --- a/schemas/sql/opfamily.sch +++ b/schemas/sql/opfamily.sch @@ -1,5 +1,4 @@ # SQL definition for operator family -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/parameter.sch b/schemas/sql/parameter.sch index 4681fdcd01..4c5881e413 100644 --- a/schemas/sql/parameter.sch +++ b/schemas/sql/parameter.sch @@ -1,5 +1,4 @@ # SQL definition for function parameters -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/partitionkey.sch b/schemas/sql/partitionkey.sch new file mode 100644 index 0000000000..9016651918 --- /dev/null +++ b/schemas/sql/partitionkey.sch @@ -0,0 +1,19 @@ +# SQL definition for partition key elements +# CAUTION: Do not modify this file unless you know what you are doing. +# Code generation can be broken if incorrect changes are made. + +%if {column} %then + {column} +%else + %if {expression} %then + ({expression}) + %end +%end + +%if {collation} %then + [ COLLATE ] {collation} +%end + +%if {opclass} %then + $sp {opclass} +%end diff --git a/schemas/sql/permission.sch b/schemas/sql/permission.sch index a4c456736b..98649d960c 100644 --- a/schemas/sql/permission.sch +++ b/schemas/sql/permission.sch @@ -1,5 +1,4 @@ # SQL definition for permissions on objects -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/policy.sch b/schemas/sql/policy.sch index 4856c44fdf..aa5e477f1d 100644 --- a/schemas/sql/policy.sch +++ b/schemas/sql/policy.sch @@ -1,5 +1,4 @@ # SQL definition for policy -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/relationship.sch b/schemas/sql/relationship.sch index 2841ae5cee..329322bfd2 100644 --- a/schemas/sql/relationship.sch +++ b/schemas/sql/relationship.sch @@ -1,5 +1,4 @@ # SQL definition for relationships -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/role.sch b/schemas/sql/role.sch index d73d511c5e..99afc85013 100644 --- a/schemas/sql/role.sch +++ b/schemas/sql/role.sch @@ -1,5 +1,4 @@ # SQL definition for type roles -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/rule.sch b/schemas/sql/rule.sch index 0ea1bef2f4..c6f40f28a2 100644 --- a/schemas/sql/rule.sch +++ b/schemas/sql/rule.sch @@ -1,5 +1,4 @@ # SQL definition for rules -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/schema.sch b/schemas/sql/schema.sch index f76cbee720..d21d282463 100644 --- a/schemas/sql/schema.sch +++ b/schemas/sql/schema.sch @@ -1,5 +1,4 @@ # SQL definition for schemas -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/sequence.sch b/schemas/sql/sequence.sch index 32a997fd72..024877de9b 100644 --- a/schemas/sql/sequence.sch +++ b/schemas/sql/sequence.sch @@ -1,5 +1,4 @@ # SQL definition for sequences -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/table.sch b/schemas/sql/table.sch index dcbdfd89c4..2f2c19fabf 100644 --- a/schemas/sql/table.sch +++ b/schemas/sql/table.sch @@ -1,5 +1,4 @@ # SQL definition for tables -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. @@ -18,7 +17,13 @@ [ UNLOGGED] %end -[ TABLE ] {name} ( $br +[ TABLE ] {name} + +%if ({pgsql-ver} >=f "10.0") %and {partitioned-table} %then [ PARTITION OF ] {partitioned-table} $sp %end + +%if %not {partitioned-table} %or ({pgsql-ver} =f "10.0") %and {partitioned-table} %then + %if {partition-bound-expr} %then + $br [FOR VALUES ] {partition-bound-expr} + %else + DEFAULT + %end +%end + +%if ({pgsql-ver} >=f "10.0") %and {partitioning} %then $br [PARTITION BY ] {partitioning} [ (] {partitionkey} [)] %end +%if {ancestor-table} %then [ INHERITS(] {ancestor-table} [)] %end +%if {oids} %then $br [WITH ( OIDS = TRUE )] %end %if {tablespace} %then $br [TABLESPACE ] {tablespace} %end diff --git a/schemas/sql/tablespace.sch b/schemas/sql/tablespace.sch index b5b56f8a4e..2c1e5970b1 100644 --- a/schemas/sql/tablespace.sch +++ b/schemas/sql/tablespace.sch @@ -1,5 +1,4 @@ # SQL definition for tablespaces -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/trigger.sch b/schemas/sql/trigger.sch index 027449e911..14bc5f2ff1 100644 --- a/schemas/sql/trigger.sch +++ b/schemas/sql/trigger.sch @@ -1,5 +1,4 @@ # SQL definition for triggers -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. @@ -31,6 +30,13 @@ $tb [ON ] {table} $br %end %end +%if {old-table-name} %or {new-table-name} %and ({pgsql-ver} >=f "10.0") %then + $tb REFERENCING + %if {old-table-name} %then [ OLD TABLE AS ] {old-table-name} %end + %if {new-table-name} %then [ NEW TABLE AS ] {new-table-name} %end + $br +%end + $tb [FOR EACH ] %if {per-line} %then ROW %else STATEMENT %end $br %if {condition} %then $tb WHEN $sp ({condition}) $br %end diff --git a/schemas/sql/typeattribute.sch b/schemas/sql/typeattribute.sch index d5486eeb3d..6e6a344cd5 100644 --- a/schemas/sql/typeattribute.sch +++ b/schemas/sql/typeattribute.sch @@ -1,5 +1,4 @@ # SQL definition for user defined type attributes -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. [ ] {name} $sp {type} diff --git a/schemas/sql/usermapping.sch b/schemas/sql/usermapping.sch new file mode 100644 index 0000000000..f7f007a98f --- /dev/null +++ b/schemas/sql/usermapping.sch @@ -0,0 +1,35 @@ +# SQL definition for user mapping +# CAUTION: Do not modify this file unless you know what you are doing. +# Code generation can be broken if incorrect changes are made. + +[-- object: ] {name} [ | type: ] {sql-object} [ --] $br + +[-- ] {drop} + +%if {prepended-sql} %then + {prepended-sql} + $br [-- ddl-end --] $br $br +%end + +[CREATE USER MAPPING FOR ] + +%if {owner} %then {owner} %else PUBLIC %end $br + +[SERVER ] {server} + +%if {options} %then + $br [OPTIONS (] {options} ) +%end + +; + +$br [-- ddl-end --] $br + +%if {comment} %then {comment} %end + +%if {appended-sql} %then + {appended-sql} + $br [-- ddl-end --] $br +%end + +$br diff --git a/schemas/sql/usertype.sch b/schemas/sql/usertype.sch index dc24feb500..73d8c11ff3 100644 --- a/schemas/sql/usertype.sch +++ b/schemas/sql/usertype.sch @@ -1,5 +1,4 @@ # SQL definition for user defined types -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/sql/view.sch b/schemas/sql/view.sch index 336c75a14f..8771b07a58 100644 --- a/schemas/sql/view.sch +++ b/schemas/sql/view.sch @@ -1,5 +1,4 @@ # SQL definition for views -# PostgreSQL Version: 9.x # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. diff --git a/schemas/xml/column.sch b/schemas/xml/column.sch index cbf10ba1b9..780737d903 100644 --- a/schemas/xml/column.sch +++ b/schemas/xml/column.sch @@ -3,6 +3,10 @@ # Code generation can be broken if incorrect changes are made. $tb [ $br %if {objects} %then {objects} %end diff --git a/schemas/xml/dtd/column.dtd b/schemas/xml/dtd/column.dtd index 4fc46fb714..27fb67892e 100644 --- a/schemas/xml/dtd/column.dtd +++ b/schemas/xml/dtd/column.dtd @@ -4,9 +4,16 @@ --> + + + + + + + diff --git a/schemas/xml/dtd/constraint.dtd b/schemas/xml/dtd/constraint.dtd index be1946fbdb..55588c535c 100644 --- a/schemas/xml/dtd/constraint.dtd +++ b/schemas/xml/dtd/constraint.dtd @@ -4,6 +4,7 @@ --> + diff --git a/schemas/xml/dtd/dbmodel.dtd b/schemas/xml/dtd/dbmodel.dtd index 32c45743a1..affe172c16 100644 --- a/schemas/xml/dtd/dbmodel.dtd +++ b/schemas/xml/dtd/dbmodel.dtd @@ -6,6 +6,8 @@ %baseelements; %basetype; + +%object; %role; @@ -66,9 +68,14 @@ %genericsql; %policy; + +%foreigndatawrapper; + +%foreignserver; + +%usermapping; - @@ -78,3 +85,6 @@ + + + diff --git a/schemas/xml/dtd/foreigndatawrapper.dtd b/schemas/xml/dtd/foreigndatawrapper.dtd new file mode 100644 index 0000000000..78b4689c6e --- /dev/null +++ b/schemas/xml/dtd/foreigndatawrapper.dtd @@ -0,0 +1,9 @@ + + + + + + diff --git a/schemas/xml/dtd/foreignserver.dtd b/schemas/xml/dtd/foreignserver.dtd new file mode 100644 index 0000000000..b9abb46e87 --- /dev/null +++ b/schemas/xml/dtd/foreignserver.dtd @@ -0,0 +1,11 @@ + + + + + + + + diff --git a/schemas/xml/dtd/genericsql.dtd b/schemas/xml/dtd/genericsql.dtd index 40ec0a02f5..f1a1c8ea5a 100644 --- a/schemas/xml/dtd/genericsql.dtd +++ b/schemas/xml/dtd/genericsql.dtd @@ -2,7 +2,7 @@ CAUTION: Do not modify this file directly on it's code unless you know what you are doing. Unexpected results may occur if the code is changed deliberately. --> - + diff --git a/schemas/xml/dtd/index.dtd b/schemas/xml/dtd/index.dtd index f7d02fe9e3..250bdb8d4e 100644 --- a/schemas/xml/dtd/index.dtd +++ b/schemas/xml/dtd/index.dtd @@ -4,6 +4,7 @@ --> + diff --git a/schemas/xml/dtd/metadata.dtd b/schemas/xml/dtd/metadata.dtd index 00e795ab52..4d9d6d5100 100644 --- a/schemas/xml/dtd/metadata.dtd +++ b/schemas/xml/dtd/metadata.dtd @@ -14,6 +14,9 @@ %tag; + +%object; + %genericsql; @@ -40,5 +43,7 @@ + + diff --git a/schemas/xml/dtd/object.dtd b/schemas/xml/dtd/object.dtd new file mode 100644 index 0000000000..2047dd8dc2 --- /dev/null +++ b/schemas/xml/dtd/object.dtd @@ -0,0 +1,12 @@ + + + + + + + + + diff --git a/schemas/xml/dtd/permission.dtd b/schemas/xml/dtd/permission.dtd index f7db5da3d0..a470a5c0ca 100644 --- a/schemas/xml/dtd/permission.dtd +++ b/schemas/xml/dtd/permission.dtd @@ -21,10 +21,3 @@ - - - - - - - diff --git a/schemas/xml/dtd/policy.dtd b/schemas/xml/dtd/policy.dtd index bc5c4d06b3..eba99706e2 100644 --- a/schemas/xml/dtd/policy.dtd +++ b/schemas/xml/dtd/policy.dtd @@ -4,6 +4,7 @@ --> + diff --git a/schemas/xml/dtd/relationship.dtd b/schemas/xml/dtd/relationship.dtd index 01baad3ad9..fed2d8449c 100644 --- a/schemas/xml/dtd/relationship.dtd +++ b/schemas/xml/dtd/relationship.dtd @@ -5,11 +5,13 @@ %label; - + + + - + diff --git a/schemas/xml/dtd/rule.dtd b/schemas/xml/dtd/rule.dtd index a340b78336..0ce3103323 100644 --- a/schemas/xml/dtd/rule.dtd +++ b/schemas/xml/dtd/rule.dtd @@ -4,6 +4,7 @@ --> + diff --git a/schemas/xml/dtd/schema.dtd b/schemas/xml/dtd/schema.dtd index 8e17e3fc82..2713a87464 100644 --- a/schemas/xml/dtd/schema.dtd +++ b/schemas/xml/dtd/schema.dtd @@ -4,6 +4,8 @@ --> + + diff --git a/schemas/xml/dtd/table.dtd b/schemas/xml/dtd/table.dtd index 5e4c9aa922..ed1a638455 100644 --- a/schemas/xml/dtd/table.dtd +++ b/schemas/xml/dtd/table.dtd @@ -8,17 +8,28 @@ %constraint; + - + + + + + + - + + + + + + diff --git a/schemas/xml/dtd/textbox.dtd b/schemas/xml/dtd/textbox.dtd index 5c3c86984a..7357956775 100644 --- a/schemas/xml/dtd/textbox.dtd +++ b/schemas/xml/dtd/textbox.dtd @@ -4,6 +4,7 @@ --> + diff --git a/schemas/xml/dtd/trigger.dtd b/schemas/xml/dtd/trigger.dtd index 22d745cd16..6c6f8672f9 100644 --- a/schemas/xml/dtd/trigger.dtd +++ b/schemas/xml/dtd/trigger.dtd @@ -4,6 +4,7 @@ --> + @@ -18,3 +19,5 @@ + + diff --git a/schemas/xml/dtd/usermapping.dtd b/schemas/xml/dtd/usermapping.dtd new file mode 100644 index 0000000000..bf99399153 --- /dev/null +++ b/schemas/xml/dtd/usermapping.dtd @@ -0,0 +1,9 @@ + + + + + + diff --git a/schemas/xml/dtd/view.dtd b/schemas/xml/dtd/view.dtd index ef084530bd..8ffbdbbdeb 100644 --- a/schemas/xml/dtd/view.dtd +++ b/schemas/xml/dtd/view.dtd @@ -4,16 +4,27 @@ --> + + - + + + + + - + + + + + + diff --git a/schemas/xml/foreigndatawrapper.sch b/schemas/xml/foreigndatawrapper.sch new file mode 100644 index 0000000000..79e33dd23e --- /dev/null +++ b/schemas/xml/foreigndatawrapper.sch @@ -0,0 +1,37 @@ +# XML definition for indexes +# CAUTION: Do not modify this file unless you know what you are doing. +# Code generation can be broken if incorrect changes are made. + +%if {reduced-form} %then + $tb +%end + +[ $br +%else + %if {options} %then + [ options=] "{options}" + %end + + %if {protected} %then + [ protected=] "true" + %end + + %if {sql-disabled} %then + [ sql-disabled=] "true" + %end + + > $br + + %if {owner} %then {owner} %end + %if {comment} %then {comment} %end + %if {appended-sql} %then {appended-sql} %end + %if {prepended-sql} %then {prepended-sql} %end + + %if {handler} %then {handler} %end + %if {validator} %then {validator} %end + + $br $br +%end diff --git a/schemas/xml/foreignserver.sch b/schemas/xml/foreignserver.sch new file mode 100644 index 0000000000..0774c4016d --- /dev/null +++ b/schemas/xml/foreignserver.sch @@ -0,0 +1,41 @@ +# XML definition for servers +# CAUTION: Do not modify this file unless you know what you are doing. +# Code generation can be broken if incorrect changes are made. + +%if {reduced-form} %then $tb %end + +[ $br +%else + %if {type} %then + [ type=] "{type}" + %end + + %if {version} %then + [ version=] "{version}" + %end + + %if {options} %then + [ options=] "{options}" + %end + + %if {protected} %then + [ protected=] "true" + %end + + %if {sql-disabled} %then + [ sql-disabled=] "true" + %end + + > $br + + %if {owner} %then {owner} %end + %if {comment} %then {comment} %end + %if {appended-sql} %then {appended-sql} %end + %if {prepended-sql} %then {prepended-sql} %end + %if {fdw} %then {fdw} %end + + $br $br +%end diff --git a/schemas/xml/genericsql.sch b/schemas/xml/genericsql.sch index 7e307e41c0..895c48ec9f 100644 --- a/schemas/xml/genericsql.sch +++ b/schemas/xml/genericsql.sch @@ -15,4 +15,6 @@ $tb $br + %if {objects} %then {objects} %end + $br $br diff --git a/schemas/xml/index.sch b/schemas/xml/index.sch index f544636b16..1202f0fb71 100644 --- a/schemas/xml/index.sch +++ b/schemas/xml/index.sch @@ -3,7 +3,11 @@ # Code generation can be broken if incorrect changes are made. [ $br %if {position} %then {position} %end diff --git a/schemas/xml/object.sch b/schemas/xml/object.sch index 0824ef1f02..716a3a4810 100644 --- a/schemas/xml/object.sch +++ b/schemas/xml/object.sch @@ -1,4 +1,15 @@ # XML definition for custom index for a single column or constraint # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. -$tb $tb [ $br \ No newline at end of file + +%if {index} %then $tb %end +$tb [ $br diff --git a/schemas/xml/partitionkey.sch b/schemas/xml/partitionkey.sch new file mode 100644 index 0000000000..375151ada9 --- /dev/null +++ b/schemas/xml/partitionkey.sch @@ -0,0 +1,20 @@ +# XML definition for indexes elements +# CAUTION: Do not modify this file unless you know what you are doing. +# Code generation can be broken if incorrect changes are made. +$tb $tb $br + +%if {column} %then + $tb $tb $tb [ $br +%else + $tb $tb $tb $br +%end + +%if {collation} %then + $tb $tb {collation} +%end + +%if {opclass} %then + $tb $tb $tb {opclass} +%end + +$tb $tb $br diff --git a/schemas/xml/permission.sch b/schemas/xml/permission.sch index 8b03dd5b8c..003275cef6 100644 --- a/schemas/xml/permission.sch +++ b/schemas/xml/permission.sch @@ -16,13 +16,12 @@ > $br - $tb [] $br + [ type=] "{type}" [/>] $br %if {roles} %then $tb [] $br diff --git a/schemas/xml/policy.sch b/schemas/xml/policy.sch index d33cacec7a..10df7afdd0 100644 --- a/schemas/xml/policy.sch +++ b/schemas/xml/policy.sch @@ -2,7 +2,13 @@ # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. -[ $br + $tb $tb $br -$tb $br + + %if {columns} %then {columns} %end + %if {ref-tables} %then {ref-tables} %end + + $tb $br %else /> $br %end diff --git a/schemas/xml/reftable.sch b/schemas/xml/reftable.sch new file mode 100644 index 0000000000..07519b3fba --- /dev/null +++ b/schemas/xml/reftable.sch @@ -0,0 +1,5 @@ +# XML definition for view references +# CAUTION: Do not modify this file unless you know what you are doing. +# Code generation can be broken if incorrect changes are made. + +$tb $tb [] $br diff --git a/schemas/xml/relationship.sch b/schemas/xml/relationship.sch index beec9afdb9..0e5fbf71f6 100644 --- a/schemas/xml/relationship.sch +++ b/schemas/xml/relationship.sch @@ -1,7 +1,13 @@ # XML definition for relationships # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. -[ $br $tb {points} $tb $br %end %if {labels-pos} %then {labels-pos} %end - %if %not {relgen} %and %not {reldep} %then + %if %not {relgen} %and %not {reldep} %and %not {relpart} %then %if {columns} %then {columns} %end %if {constraints} %then {constraints} %end %end + + %if {original-pk} %then + {original-pk} + %end %if {special-pk-cols} %then $tb [ $br %end + + %if {partition-bound-expr} %then + $tb $br + %end $br $br %end diff --git a/schemas/xml/rule.sch b/schemas/xml/rule.sch index ec3434ee24..6962f62d78 100644 --- a/schemas/xml/rule.sch +++ b/schemas/xml/rule.sch @@ -3,6 +3,10 @@ # Code generation can be broken if incorrect changes are made. [ $br diff --git a/schemas/xml/sequence.sch b/schemas/xml/sequence.sch index a4d39a5011..f6759115b8 100644 --- a/schemas/xml/sequence.sch +++ b/schemas/xml/sequence.sch @@ -3,26 +3,39 @@ # Code generation can be broken if incorrect changes are made. [ $br diff --git a/schemas/xml/table.sch b/schemas/xml/table.sch index f7d29dddfd..272ffac2b2 100644 --- a/schemas/xml/table.sch +++ b/schemas/xml/table.sch @@ -2,15 +2,21 @@ # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. [
$br {schema} @@ -28,6 +34,12 @@ %if {col-indexes} %then {col-indexes} %end %if {constr-indexes} %then {constr-indexes} %end + %if {partitioning} %and {partitionkey} %then + $tb [] $br + {partitionkey} + $tb [] $br + %end + %if {initial-data} %then $tb $br diff --git a/schemas/xml/textbox.sch b/schemas/xml/textbox.sch index 77dafe4075..6426335f1d 100644 --- a/schemas/xml/textbox.sch +++ b/schemas/xml/textbox.sch @@ -1,7 +1,7 @@ # XML definition for textboxes # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. -[ $br %if {comment} %then $tb {comment} %end diff --git a/schemas/xml/usermapping.sch b/schemas/xml/usermapping.sch new file mode 100644 index 0000000000..25c1d364e8 --- /dev/null +++ b/schemas/xml/usermapping.sch @@ -0,0 +1,26 @@ +# XML definition for user mappings +# CAUTION: Do not modify this file unless you know what you are doing. +# Code generation can be broken if incorrect changes are made. + +[ $br + +%if {owner} %then {owner} %end +%if {server} %then {server} %end +%if {appended-sql} %then {appended-sql} %end +%if {prepended-sql} %then {prepended-sql} %end + + $br $br diff --git a/schemas/xml/view.sch b/schemas/xml/view.sch index fb4d9d0ef3..eef8811e6b 100644 --- a/schemas/xml/view.sch +++ b/schemas/xml/view.sch @@ -1,16 +1,21 @@ # XML definition for views # CAUTION: Do not modify this file unless you know what you are doing. # Code generation can be broken if incorrect changes are made. -[ $br {schema} diff --git a/tests/src/baseobjecttest/baseobjecttest.cpp b/tests/src/baseobjecttest/baseobjecttest.cpp index 374d7b0414..b6d0a9aef4 100644 --- a/tests/src/baseobjecttest/baseobjecttest.cpp +++ b/tests/src/baseobjecttest/baseobjecttest.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/tests/src/databasemodeltest/databasemodeltest.cpp b/tests/src/databasemodeltest/databasemodeltest.cpp index d6f319ae85..a4dccd55e2 100644 --- a/tests/src/databasemodeltest/databasemodeltest.cpp +++ b/tests/src/databasemodeltest/databasemodeltest.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -32,8 +32,8 @@ void DatabaseModelTest::saveObjectsMetadata(void) { DatabaseModel dbmodel; QTextStream out(stdout); - QString output=QFileInfo(BINDIR).absolutePath() + GlobalAttributes::DIR_SEPARATOR + QString("demo.omf"), - input=SAMPLESDIR + GlobalAttributes::DIR_SEPARATOR + QString("demo.dbm"); + QString output=QFileInfo(BINDIR).absolutePath() + GlobalAttributes::DirSeparator + QString("demo.omf"), + input=SAMPLESDIR + GlobalAttributes::DirSeparator + QString("demo.dbm"); try { @@ -55,16 +55,16 @@ void DatabaseModelTest::loadObjectsMetadata(void) { DatabaseModel dbmodel; QTextStream out(stdout); - QString input_opf=QFileInfo(BINDIR).absolutePath() + GlobalAttributes::DIR_SEPARATOR + QString("demo.omf"), - input_dbm=SAMPLESDIR + GlobalAttributes::DIR_SEPARATOR + QString("demo.dbm"), - output=QFileInfo(BINDIR).absolutePath() + GlobalAttributes::DIR_SEPARATOR + QString("demo_changed.dbm"); + QString input_opf=QFileInfo(BINDIR).absolutePath() + GlobalAttributes::DirSeparator + QString("demo.omf"), + input_dbm=SAMPLESDIR + GlobalAttributes::DirSeparator + QString("demo.dbm"), + output=QFileInfo(BINDIR).absolutePath() + GlobalAttributes::DirSeparator + QString("demo_changed.dbm"); try { dbmodel.createSystemObjects(false); dbmodel.loadModel(input_dbm); dbmodel.loadObjectsMetadata(input_opf); - dbmodel.saveModel(output, SchemaParser::XML_DEFINITION); + dbmodel.saveModel(output, SchemaParser::XmlDefinition); QCOMPARE(true, true); } catch (Exception &e) diff --git a/tests/src/foreigndatawrappertest/foreigndatawrappertest.cpp b/tests/src/foreigndatawrappertest/foreigndatawrappertest.cpp new file mode 100644 index 0000000000..6bf70bb55c --- /dev/null +++ b/tests/src/foreigndatawrappertest/foreigndatawrappertest.cpp @@ -0,0 +1,328 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include +#include "databasemodel.h" + +class ForeignDataWrapperTest: public QObject { + private: + Q_OBJECT + + private slots: + void assignValidFunctionDoesntRaiseException(void); + void assignInvalidFunctionRaisesException(void); + void codeGeneratedIsWellFormed(void); + void modelReturnsDepsAndRefsForFDW(void); + void modelCreatesFDWfromXMLandResultingXMLisEqual(void); +}; + +void ForeignDataWrapperTest::assignValidFunctionDoesntRaiseException(void) +{ + ForeignDataWrapper fdw; + Function func_handler, func_validator; + + fdw.setName("fdw"); + + try + { + func_handler.setName("func_handler"); + func_handler.setReturnType(PgSqlType("fdw_handler")); + fdw.setHandlerFunction(&func_handler); + } + catch(Exception &e) + { + QFAIL(e.getErrorMessage().toStdString().c_str()); + } + + try + { + func_validator.setName("func_validator"); + func_validator.addParameter(Parameter("param1", PgSqlType("text", 1))); + func_validator.addParameter(Parameter("param2", PgSqlType("oid"))); + fdw.setValidatorFunction(&func_validator); + } + catch(Exception &e) + { + QFAIL(e.getErrorMessage().toStdString().c_str()); + } +} + +void ForeignDataWrapperTest::assignInvalidFunctionRaisesException(void) +{ + ForeignDataWrapper fdw; + Function func_handler, func_validator; + + fdw.setName("fdw"); + func_handler.setName("func_handler"); + func_validator.setName("func_validator"); + + try + { + func_handler.setReturnType(PgSqlType("fdw_handler")); + func_handler.addParameter(Parameter("param1", PgSqlType("integer"))); + fdw.setHandlerFunction(&func_handler); + QFAIL("Expected exception(s) not raised!"); + } + catch(Exception &e) + { + QVERIFY(e.getErrorCode() == ErrorCode::AsgFunctionInvalidParamCount); + } + + try + { + func_handler.removeParameters(); + func_handler.setReturnType(PgSqlType("trigger")); + fdw.setHandlerFunction(&func_handler); + QFAIL("Expected exception(s) not raised!"); + } + catch(Exception &e) + { + QVERIFY(e.getErrorCode() == ErrorCode::AsgFunctionInvalidReturnType); + } + + try + { + func_validator.addParameter(Parameter("param1", PgSqlType("integer"))); + func_validator.addParameter(Parameter("param2", PgSqlType("varchar"))); + fdw.setValidatorFunction(&func_validator); + QFAIL("Expected exception(s) not raised!"); + } + catch(Exception &e) + { + QVERIFY(e.getErrorCode() == ErrorCode::AsgFunctionInvalidParameters); + } + + try + { + func_validator.removeParameters(); + func_validator.addParameter(Parameter("param1", PgSqlType("text"))); + func_validator.addParameter(Parameter("param2", PgSqlType("oid"))); + func_validator.addParameter(Parameter("param3", PgSqlType("smallint"))); + fdw.setValidatorFunction(&func_validator); + QFAIL("Expected exception(s) not raised!"); + } + catch(Exception &e) + { + QVERIFY(e.getErrorCode() == ErrorCode::AsgFunctionInvalidParamCount); + } +} + +void ForeignDataWrapperTest::codeGeneratedIsWellFormed(void) +{ + ForeignDataWrapper fdw; + Role owner; + Schema public_sch; + Function func_handler, func_validator; + QString sql_code =QString( +"-- object: fdw | type: FOREIGN DATA WRAPPER -- \ +-- DROP FOREIGN DATA WRAPPER IF EXISTS fdw CASCADE; \ +CREATE FOREIGN DATA WRAPPER fdw \ +HANDLER public.func_handler \ +VALIDATOR public.func_validator \ +OPTIONS (opt1 'value1',opt2 'value2'); \ +-- ddl-end -- \ +ALTER FOREIGN DATA WRAPPER fdw OWNER TO postgres; \ + -- ddl-end -- \ + COMMENT ON FOREIGN DATA WRAPPER fdw IS 'This is a test comment on FDW'; \ +-- ddl-end -- ").simplified(); + + QString xml_code =QString( +" \ + \ + \ + \ + \ +").replace("#", ForeignDataWrapper::OptionValueSeparator) + .replace("*", ForeignDataWrapper::OptionsSeparator).simplified(); + + try + { + public_sch.setName("public"); + owner.setName("postgres"); + + fdw.setName("fdw"); + fdw.setOwner(&owner); + func_handler.setName("func_handler"); + func_handler.setReturnType(PgSqlType("fdw_handler")); + func_handler.setSchema(&public_sch); + fdw.setHandlerFunction(&func_handler); + + func_validator.setName("func_validator"); + func_validator.addParameter(Parameter("param1", PgSqlType("text", 1))); + func_validator.addParameter(Parameter("param2", PgSqlType("oid"))); + func_validator.setSchema(&public_sch); + fdw.setValidatorFunction(&func_validator); + + fdw.setOption("opt1", "value1"); + fdw.setOption("opt2", "value2"); + fdw.setComment("This is a test comment on FDW"); + + QString res_sql_code = fdw.getCodeDefinition(SchemaParser::SqlDefinition).simplified(); + QCOMPARE(sql_code, res_sql_code); + + QString res_xml_code = fdw.getCodeDefinition(SchemaParser::XmlDefinition).simplified(); + QCOMPARE(xml_code, res_xml_code); + } + catch (Exception &e) + { + QFAIL(e.getErrorMessage().toStdString().c_str()); + } +} + +void ForeignDataWrapperTest::modelReturnsDepsAndRefsForFDW(void) +{ + DatabaseModel model; + Role owner; + Schema public_sch; + Language lang; + Function func_handler, func_validator; + ForeignDataWrapper fdw; + + try + { + public_sch.setName("public"); + owner.setName("postgres"); + + model.addSchema(&public_sch); + model.addRole(&owner); + + fdw.setName("fdw"); + fdw.setOwner(&owner); + func_handler.setName("func_handler"); + func_handler.setReturnType(PgSqlType("fdw_handler")); + func_handler.setSchema(&public_sch); + func_handler.setSourceCode("foo"); + func_handler.setOwner(&owner); + func_handler.setLanguage(&lang); + fdw.setHandlerFunction(&func_handler); + + func_validator.setName("func_validator"); + func_validator.addParameter(Parameter("param1", PgSqlType("text", 1))); + func_validator.addParameter(Parameter("param2", PgSqlType("oid"))); + func_validator.setSchema(&public_sch); + func_validator.setSourceCode("foo"); + func_validator.setOwner(&owner); + func_validator.setLanguage(&lang); + fdw.setValidatorFunction(&func_validator); + + fdw.setOption("opt1", "value1"); + fdw.setOption("opt2", "value2"); + fdw.setComment("This is a test comment on FDW"); + + model.addFunction(&func_handler); + model.addFunction(&func_validator); + model.addForeignDataWrapper(&fdw); + + vector deps; + model.getObjectDependecies(&fdw, deps); + + QVERIFY(deps.size() >= 3); + + deps.clear(); + model.getObjectReferences(&func_validator, deps); + QVERIFY(deps.size() == 1); + + deps.clear(); + model.getObjectReferences(&func_handler, deps); + QVERIFY(deps.size() == 1); + + model.removeForeignDataWrapper(&fdw); + model.removeFunction(&func_handler); + model.removeFunction(&func_validator); + model.removeLanguage(&lang); + model.removeSchema(&public_sch); + model.removeRole(&owner); + } + catch (Exception &e) + { + QFAIL(e.getErrorMessage().toStdString().c_str()); + } +} + +void ForeignDataWrapperTest::modelCreatesFDWfromXMLandResultingXMLisEqual(void) +{ + DatabaseModel model; + Role owner; + Schema public_sch; + Language lang; + Function func_handler, func_validator; + ForeignDataWrapper *fdw = nullptr; + QString xml_code, res_xml_code; + + try + { + public_sch.setName("public"); + owner.setName("postgres"); + + model.addSchema(&public_sch); + model.addRole(&owner); + + func_handler.setName("func_handler"); + func_handler.setReturnType(PgSqlType("fdw_handler")); + func_handler.setSchema(&public_sch); + func_handler.setSourceCode("foo"); + func_handler.setOwner(&owner); + func_handler.setLanguage(&lang); + + func_validator.setName("func_validator"); + func_validator.addParameter(Parameter("param1", PgSqlType("text", 1))); + func_validator.addParameter(Parameter("param2", PgSqlType("oid"))); + func_validator.setSchema(&public_sch); + func_validator.setSourceCode("foo"); + func_validator.setOwner(&owner); + func_validator.setLanguage(&lang); + + model.addFunction(&func_handler); + model.addFunction(&func_validator); + + xml_code=QString(" \ + \ + \ + \ + \ +").replace("#", ForeignDataWrapper::OptionValueSeparator) + .replace("*", ForeignDataWrapper::OptionsSeparator); + + model.getXMLParser()->loadXMLBuffer(xml_code); + fdw = dynamic_cast(model.createObject(ObjectType::ForeignDataWrapper)); + + model.removeForeignDataWrapper(fdw); + model.removeFunction(&func_handler); + model.removeFunction(&func_validator); + model.removeLanguage(&lang); + model.removeSchema(&public_sch); + model.removeRole(&owner); + + QVERIFY(fdw != nullptr); + + res_xml_code = fdw->getCodeDefinition(SchemaParser::XmlDefinition).simplified(); + xml_code = xml_code.simplified(); + + if(fdw) + delete(fdw); + + QCOMPARE(xml_code, res_xml_code); + } + catch (Exception &e) + { + QFAIL(e.getErrorMessage().toStdString().c_str()); + } +} + +QTEST_MAIN(ForeignDataWrapperTest) +#include "foreigndatawrappertest.moc" diff --git a/tests/src/foreigndatawrappertest/foreigndatawrappertest.pro b/tests/src/foreigndatawrappertest/foreigndatawrappertest.pro new file mode 100644 index 0000000000..279537eb88 --- /dev/null +++ b/tests/src/foreigndatawrappertest/foreigndatawrappertest.pro @@ -0,0 +1,2 @@ +include(../../tests.pri) +SOURCES += foreigndatawrappertest.cpp diff --git a/tests/src/linenumberstest/linenumberstest.cpp b/tests/src/linenumberstest/linenumberstest.cpp new file mode 100644 index 0000000000..5b0b0d027b --- /dev/null +++ b/tests/src/linenumberstest/linenumberstest.cpp @@ -0,0 +1,90 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include +#include "numberedtexteditor.h" +#include +#include + +class LineNumbersTest: public QObject { + private: + Q_OBJECT + + private slots: + void handleLineSelectionUsingMouse(void); +}; + +void LineNumbersTest::handleLineSelectionUsingMouse(void) +{ + QDialog *dlg=new QDialog; + NumberedTextEditor *edt=new NumberedTextEditor(dlg); + QHBoxLayout *layout=new QHBoxLayout(dlg); + + LineNumbersWidget::setColors(Qt::darkGray, QColor(230,230,230)); + layout->addWidget(edt); + dlg->setMinimumSize(640,220); + + edt->setPlainText("--\n\ +-- PostgreSQL database dump\n\ +--\n\ +-- Dumped from database version 9.4.4\n\ +-- Dumped by pg_dump version 9.4.4\n\ +-- Started on 2015-07-20 19:24:52 WEST\n\ +\n\ +SET statement_timeout = 0;\n\ +SET lock_timeout = 0;\n\ +SET client_encoding = 'UTF8';\n\ +SET standard_conforming_strings = on;\n\ +SET check_function_bodies = false;\n\ +SET client_min_messages = warning;\n\ +--\n\ +-- PostgreSQL database dump\n\ +--\n\ +-- Dumped from database version 9.4.4\n\ +-- Dumped by pg_dump version 9.4.4\n\ +-- Started on 2015-07-20 19:24:52 WEST\n\ +SET statement_timeout = 0;\n\ +SET lock_timeout = 0;\n\ +SET client_encoding = 'UTF8';\n\ +SET standard_conforming_strings = on;\n\ +SET check_function_bodies = false;\n\ +SET client_min_messages = warning;\n\ +-- Dumped from database version 9.4.4\n\ +-- Dumped by pg_dump version 9.4.4\n\ +-- Started on 2015-07-20 19:24:52 WEST\n\ +SET statement_timeout = 0;\n\ +SET lock_timeout = 0;\n\ +SET client_encoding = 'UTF8';\n\ +SET standard_conforming_strings = on;\n\ +SET check_function_bodies = false;\n\ +SET client_min_messages = warning;\n\ +-- Dumped from database version 9.4.4\n\ +-- Dumped by pg_dump version 9.4.4\n\ +-- Started on 2015-07-20 19:24:52 WEST\n\ +SET statement_timeout = 0;\n\ +SET lock_timeout = 0;\n\ +SET client_encoding = 'UTF8';\n\ +SET standard_conforming_strings = on;\n\ +SET check_function_bodies = false;\n\ +SET client_min_messages = warning;"); + + dlg->exec(); +} + +QTEST_MAIN(LineNumbersTest) +#include "linenumberstest.moc" diff --git a/tests/src/linenumberstest/linenumberstest.pro b/tests/src/linenumberstest/linenumberstest.pro new file mode 100644 index 0000000000..728f7a5aa1 --- /dev/null +++ b/tests/src/linenumberstest/linenumberstest.pro @@ -0,0 +1,3 @@ +include(../../tests.pri) +SOURCES += linenumberstest.cpp + diff --git a/tests/src/main/main.cpp b/tests/src/main/main.cpp index 65e12c4912..ca8d4f94b1 100644 --- a/tests/src/main/main.cpp +++ b/tests/src/main/main.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/tests/src/partrelationshiptest/partrelationshiptest.cpp b/tests/src/partrelationshiptest/partrelationshiptest.cpp new file mode 100644 index 0000000000..bb39c7499c --- /dev/null +++ b/tests/src/partrelationshiptest/partrelationshiptest.cpp @@ -0,0 +1,269 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include +#include "relationship.h" + +class PartRelationhipTest: public QObject { + private: + Q_OBJECT + + private slots: + void connRelTableNoColumnsAndTableTwoColumns(void); + void connRelTablesTwoColumnsSameNameShouldNotRaiseError(void); + void connRelTablePartionHasMoreColsThanPartitionedTableShouldRaiseError(void); + void connRelTablePartionHasDifferentColsThanPartitionedTableShouldRaiseError(void); + void connRelShouldInvalidateIfPartitionedColumnChanges(void); +}; + +void PartRelationhipTest::connRelTableNoColumnsAndTableTwoColumns(void) +{ + Schema *schema = new Schema; + Table *partitioned = new Table; + Table *partition = new Table; + Column *col = new Column, *col1 = new Column; + Relationship *part_rel = nullptr; + + try + { + schema->setName("public"); + partitioned->setSchema(schema); + partition->setSchema(schema); + + partitioned->setPartitioningType(PartitioningType::List); + partitioned->setName("table_a"); + partition->setName("partion_a"); + + col->setName("id"); + col->setType(PgSqlType("serial")); + col1->setName("sku"); + col1->setType(PgSqlType("smallint")); + + partitioned->addColumn(col); + partitioned->addColumn(col1); + + part_rel = new Relationship(BaseRelationship::RelationshipPart, partition, partitioned); + part_rel->connectRelationship(); + + QVERIFY(partitioned->getColumnCount() == partition->getColumnCount()); + } + catch(Exception &e) + { + QFAIL(e.getErrorMessage().toStdString().c_str()); + } +} + +void PartRelationhipTest::connRelTablesTwoColumnsSameNameShouldNotRaiseError(void) +{ + Schema *schema = new Schema; + Table *partitioned = new Table; + Table *partition = new Table; + Column *col = new Column, *col1 = new Column; + Relationship *part_rel = nullptr; + + try + { + schema->setName("public"); + partitioned->setSchema(schema); + partition->setSchema(schema); + + partitioned->setPartitioningType(PartitioningType::List); + partitioned->setName("table_a"); + partition->setName("partion_a"); + + col->setName("id"); + col->setType(PgSqlType("serial")); + col1->setName("sku"); + col1->setType(PgSqlType("smallint")); + + partitioned->addColumn(col); + partitioned->addColumn(col1); + + col = new Column; + col1 = new Column; + col->setName("id"); + col->setType(PgSqlType("serial")); + col1->setName("sku"); + col1->setType(PgSqlType("smallint")); + + partition->addColumn(col); + partition->addColumn(col1); + + part_rel = new Relationship(BaseRelationship::RelationshipPart, partition, partitioned); + part_rel->connectRelationship(); + + QVERIFY(partitioned->getColumnCount() == partition->getColumnCount()); + } + catch(Exception &e) + { + QFAIL(e.getErrorMessage().toStdString().c_str()); + } +} + +void PartRelationhipTest::connRelTablePartionHasMoreColsThanPartitionedTableShouldRaiseError(void) +{ + Schema *schema = new Schema; + Table *partitioned = new Table; + Table *partition = new Table; + Column *col = new Column, *col1 = new Column, *col2 = nullptr; + Relationship *part_rel = nullptr; + + try + { + schema->setName("public"); + partitioned->setSchema(schema); + partition->setSchema(schema); + + partitioned->setPartitioningType(PartitioningType::List); + partitioned->setName("table_a"); + partition->setName("partion_a"); + + col->setName("id"); + col->setType(PgSqlType("serial")); + col1->setName("sku"); + col1->setType(PgSqlType("smallint")); + + partitioned->addColumn(col); + partitioned->addColumn(col1); + + col = new Column; + col1 = new Column; + col->setName("id"); + col->setType(PgSqlType("serial")); + col1->setName("sku"); + col1->setType(PgSqlType("smallint")); + col2 = new Column; + col2->setName("date"); + col2->setType(PgSqlType("date")); + + partition->addColumn(col); + partition->addColumn(col1); + partition->addColumn(col2); + + part_rel = new Relationship(BaseRelationship::RelationshipPart, partition, partitioned); + part_rel->connectRelationship(); + + QFAIL("Should return exception because tables have different column count!"); + } + catch(Exception &e) + { + QVERIFY(e.getErrorCode() == ErrorCode::InvColumnCountPartRel); + } +} + +void PartRelationhipTest::connRelTablePartionHasDifferentColsThanPartitionedTableShouldRaiseError(void) +{ + Schema *schema = new Schema; + Table *partitioned = new Table; + Table *partition = new Table; + Column *col = new Column, *col1 = new Column; + Relationship *part_rel = nullptr; + + try + { + schema->setName("public"); + partitioned->setSchema(schema); + partition->setSchema(schema); + + partitioned->setPartitioningType(PartitioningType::List); + partitioned->setName("table_a"); + partition->setName("partion_a"); + + col->setName("id"); + col->setType(PgSqlType("serial")); + col1->setName("sku"); + col1->setType(PgSqlType("smallint")); + + partitioned->addColumn(col); + partitioned->addColumn(col1); + + col = new Column; + col1 = new Column; + col->setName("tag_id"); + col->setType(PgSqlType("serial")); + col1->setName("serial_number"); + col1->setType(PgSqlType("smallint")); + + partition->addColumn(col); + partition->addColumn(col1); + + part_rel = new Relationship(BaseRelationship::RelationshipPart, partition, partitioned); + part_rel->connectRelationship(); + + QFAIL("Should return exception because tables have different columns names!"); + } + catch(Exception &e) + { + QVERIFY(e.getErrorCode() == ErrorCode::InvColumnCountPartRel); + } +} + +void PartRelationhipTest::connRelShouldInvalidateIfPartitionedColumnChanges(void) +{ + Schema *schema = new Schema; + Table *partitioned = new Table; + Table *partition = new Table; + Column *col = new Column, *col1 = new Column; + Relationship *part_rel = nullptr; + + try + { + schema->setName("public"); + partitioned->setSchema(schema); + partition->setSchema(schema); + + partitioned->setPartitioningType(PartitioningType::List); + partitioned->setName("table_a"); + partition->setName("partion_a"); + + col->setName("id"); + col->setType(PgSqlType("serial")); + col1->setName("sku"); + col1->setType(PgSqlType("smallint")); + + partitioned->addColumn(col); + partitioned->addColumn(col1); + + col = new Column; + col1 = new Column; + col->setName("id"); + col->setType(PgSqlType("serial")); + col1->setName("sku"); + col1->setType(PgSqlType("smallint")); + + partition->addColumn(col); + partition->addColumn(col1); + + part_rel = new Relationship(BaseRelationship::RelationshipPart, partition, partitioned); + part_rel->connectRelationship(); + + partitioned->getColumn(0)->setName("new_id"); + QVERIFY(part_rel->isInvalidated() == true); + + partitioned->getColumn(0)->setName("id"); + partitioned->getColumn(0)->setType(PgSqlType("date")); + QVERIFY(part_rel->isInvalidated() == true); + } + catch(Exception &e) + { + QFAIL(e.getErrorMessage().toStdString().c_str()); + } +} + +QTEST_MAIN(PartRelationhipTest) +#include "partrelationshiptest.moc" diff --git a/tests/src/partrelationshiptest/partrelationshiptest.pro b/tests/src/partrelationshiptest/partrelationshiptest.pro new file mode 100644 index 0000000000..9274ff84b3 --- /dev/null +++ b/tests/src/partrelationshiptest/partrelationshiptest.pro @@ -0,0 +1,2 @@ +include(../../tests.pri) +SOURCES += partrelationshiptest.cpp diff --git a/tests/src/roletest/roletest.cpp b/tests/src/roletest/roletest.cpp index d3d5824721..554922c30c 100644 --- a/tests/src/roletest/roletest.cpp +++ b/tests/src/roletest/roletest.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -34,15 +34,15 @@ void RoleTest::alterCommandEndsWithSemiColon(void) QString alter_cmd; role1.setName("role1"); - role1.setOption(Role::OP_SUPERUSER, true); + role1.setOption(Role::OpSuperuser, true); role2.setName("role2"); - role2.setOption(Role::OP_CREATEDB, false); - role2.setOption(Role::OP_CREATEROLE, false); - role2.setOption(Role::OP_LOGIN, false); + role2.setOption(Role::OpCreateDb, false); + role2.setOption(Role::OpCreateRole, false); + role2.setOption(Role::OpLogin, false); alter_cmd=role1.getAlterDefinition(&role2); - alter_cmd.remove(QString("\n%1\n").arg(ParsersAttributes::DDL_END_TOKEN)); + alter_cmd.remove(QString("\n%1\n").arg(Attributes::DdlEndToken)); QCOMPARE(alter_cmd.endsWith(";"), true); } diff --git a/tests/src/schemaparsertest/schemaparsertest.cpp b/tests/src/schemaparsertest/schemaparsertest.cpp index da23dd864e..945ad689b0 100644 --- a/tests/src/schemaparsertest/schemaparsertest.cpp +++ b/tests/src/schemaparsertest/schemaparsertest.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -25,6 +25,7 @@ class SchemaParserTest: public QObject { private slots: void testExpressionEvaluationWithCasts(void); + void testSetOperationInIf(void); }; void SchemaParserTest::testExpressionEvaluationWithCasts(void) @@ -51,5 +52,32 @@ void SchemaParserTest::testExpressionEvaluationWithCasts(void) } } +void SchemaParserTest::testSetOperationInIf(void) +{ + SchemaParser schparser; + QString buffer; + attribs_map attribs; + + buffer = "%set {ver} 10.0\n"; + buffer += "\n%if ({ver} <=f \"9.3\") %then"; + buffer += "\n %set {variable1} [don't ]"; + buffer += "\n %set {variable2} [extract]"; + buffer += "\n%else"; + buffer += "\n %set {variable3} [extract ]"; + buffer += "\n %set {variable4} [in else]"; + buffer += "\n{variable3}{variable4}"; + buffer += "\n%end"; + + try + { + schparser.loadBuffer(buffer); + QCOMPARE(schparser.getCodeDefinition(attribs) == "extract in else", true); + } + catch(Exception &e) + { + QFAIL(e.getExceptionsText().toStdString().c_str()); + } +} + QTEST_MAIN(SchemaParserTest) #include "schemaparsertest.moc" diff --git a/tests/src/servertest/servertest.cpp b/tests/src/servertest/servertest.cpp new file mode 100644 index 0000000000..80393bee4b --- /dev/null +++ b/tests/src/servertest/servertest.cpp @@ -0,0 +1,178 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include +#include "databasemodel.h" + +class ServerTest: public QObject { + private: + Q_OBJECT + + private slots: + void codeGeneratedIsWellFormed(void); + void modelReturnsDepsAndRefsForServer(void); + void modelCreatesServerfromXMLandResultingXMLisEqual(void); +}; + +void ServerTest::codeGeneratedIsWellFormed(void) +{ + ForeignDataWrapper fdw; + ForeignServer server; + Role owner; + QString sql_code =QString( +"-- object: server_test | type: SERVER -- \ +-- DROP SERVER IF EXISTS server_test CASCADE; \ +CREATE SERVER server_test \ +TYPE 'dbtype' \ +VERSION '1.0' \ +FOREIGN DATA WRAPPER fdw \ +OPTIONS (opt1 'value1',opt2 'value2'); \ +-- ddl-end -- \ +ALTER SERVER server_test OWNER TO postgres; \ +-- ddl-end -- \ +COMMENT ON SERVER server_test IS 'This is a test comment on server'; \ +-- ddl-end -- ").simplified(); + + QString xml_code =QString( +" \ + \ + \ + \ +").replace("#", ForeignServer::OptionValueSeparator) + .replace("*", ForeignServer::OptionsSeparator).simplified(); + + try + { + owner.setName("postgres"); + fdw.setName("fdw"); + + server.setName("server_test"); + server.setOwner(&owner); + server.setType("dbtype"); + server.setVersion("1.0"); + server.setOption("opt1", "value1"); + server.setOption("opt2", "value2"); + server.setComment("This is a test comment on server"); + server.setForeignDataWrapper(&fdw); + + QString res_sql_code = server.getCodeDefinition(SchemaParser::SqlDefinition).simplified(); + QCOMPARE(sql_code, res_sql_code); + + QString res_xml_code = server.getCodeDefinition(SchemaParser::XmlDefinition).simplified(); + QCOMPARE(xml_code, res_xml_code); + } + catch (Exception &e) + { + QFAIL(e.getExceptionsText().toStdString().c_str()); + } +} + +void ServerTest::modelReturnsDepsAndRefsForServer(void) +{ + DatabaseModel model; + Role owner; + Schema public_sch; + ForeignDataWrapper fdw; + ForeignServer server; + + try + { + public_sch.setName("public"); + owner.setName("postgres"); + + model.addSchema(&public_sch); + model.addRole(&owner); + + fdw.setName("fdw"); + model.addForeignDataWrapper(&fdw); + + server.setName("server_test"); + server.setForeignDataWrapper(&fdw); + model.addForeignServer(&server); + + vector refs, deps; + model.getObjectDependecies(&server, deps); + + model.getObjectReferences(&fdw, refs); + model.removeForeignServer(&server); + model.removeForeignDataWrapper(&fdw); + model.removeSchema(&public_sch); + model.removeRole(&owner); + + QVERIFY(deps.size() >= 2); + QVERIFY(refs.size() == 1); + } + catch (Exception &e) + { + QFAIL(e.getErrorMessage().toStdString().c_str()); + } +} + +void ServerTest::modelCreatesServerfromXMLandResultingXMLisEqual(void) +{ + DatabaseModel model; + Role owner; + Schema public_sch; + ForeignDataWrapper fdw; + ForeignServer *server = nullptr; + QString xml_code, res_xml_code; + + try + { + public_sch.setName("public"); + owner.setName("postgres"); + + model.addSchema(&public_sch); + model.addRole(&owner); + + fdw.setName("fdw"); + model.addForeignDataWrapper(&fdw); + + xml_code=QString(" \ + \ + \ + \ +").replace("#", ForeignDataWrapper::OptionValueSeparator) + .replace("*", ForeignDataWrapper::OptionsSeparator); + + model.getXMLParser()->loadXMLBuffer(xml_code); + server = dynamic_cast(model.createObject(ObjectType::ForeignServer)); + + QVERIFY(server != nullptr); + + res_xml_code = server->getCodeDefinition(SchemaParser::XmlDefinition).simplified(); + xml_code = xml_code.simplified(); + + model.removeForeignServer(server); + model.removeForeignDataWrapper(&fdw); + model.removeSchema(&public_sch); + model.removeRole(&owner); + + if(server) + delete(server); + + QCOMPARE(xml_code, res_xml_code); + } + catch (Exception &e) + { + QFAIL(e.getErrorMessage().toStdString().c_str()); + } +} + +QTEST_MAIN(ServerTest) +#include "servertest.moc" diff --git a/tests/src/servertest/servertest.pro b/tests/src/servertest/servertest.pro new file mode 100644 index 0000000000..be77102343 --- /dev/null +++ b/tests/src/servertest/servertest.pro @@ -0,0 +1,2 @@ +include(../../tests.pri) +SOURCES += servertest.cpp diff --git a/tests/src/syntaxhighlightertest/syntaxhighlightertest.cpp b/tests/src/syntaxhighlightertest/syntaxhighlightertest.cpp index cd6abe6421..b816022cc1 100644 --- a/tests/src/syntaxhighlightertest/syntaxhighlightertest.cpp +++ b/tests/src/syntaxhighlightertest/syntaxhighlightertest.cpp @@ -1,7 +1,7 @@ /* # PostgreSQL Database Modeler (pgModeler) # -# Copyright 2006-2018 - Raphael Araújo e Silva +# Copyright 2006-2019 - Raphael Araújo e Silva # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -35,7 +35,7 @@ void SyntaxHighlighterTest::handleMultiLineComment(void) SyntaxHighlighter *sql_hl=nullptr; sql_hl=new SyntaxHighlighter(edt, false); - sql_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH); + sql_hl->loadConfiguration(GlobalAttributes::SQLHighlightConfPath); layout->addWidget(edt); dlg->exec(); diff --git a/tests/src/usermappingtest/usermappingtest.cpp b/tests/src/usermappingtest/usermappingtest.cpp new file mode 100644 index 0000000000..a2327939bc --- /dev/null +++ b/tests/src/usermappingtest/usermappingtest.cpp @@ -0,0 +1,203 @@ +/* +# PostgreSQL Database Modeler (pgModeler) +# +# Copyright 2006-2019 - Raphael Araújo e Silva +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# The complete text of GPLv3 is at LICENSE file on source code root directory. +# Also, you can get the complete GNU General Public License at +*/ + +#include +#include "databasemodel.h" + +class UserMappingTest: public QObject { + private: + Q_OBJECT + + private slots: + void generatesNameCorrectly(void); + void codeGeneratedIsWellFormed(void); + void modelReturnsDepsAndRefsForUserMapping(void); + void modelCreatesUserMappingfromXMLandResultingXMLisEqual(void); +}; + +void UserMappingTest::generatesNameCorrectly(void) +{ + ForeignDataWrapper fdw; + ForeignServer server; + Role role; + UserMapping usr_mapping; + + role.setName("postgres"); + fdw.setName("fdw"); + + server.setName("server_test"); + server.setOwner(&role); + server.setForeignDataWrapper(&fdw); + + QCOMPARE(usr_mapping.getName(), "public@"); + + usr_mapping.setForeignServer(&server); + QCOMPARE(usr_mapping.getName(), "public@server_test"); + + usr_mapping.setOwner(&role); + QCOMPARE(usr_mapping.getName(), "postgres@server_test"); + + usr_mapping.setOwner(nullptr); + usr_mapping.setForeignServer(nullptr); + QCOMPARE(usr_mapping.getName(), "public@"); +} + +void UserMappingTest::codeGeneratedIsWellFormed(void) +{ + ForeignDataWrapper fdw; + ForeignServer server; + Role role; + UserMapping usr_mapping; + QString sql_code =QString( +"-- object: postgres@server_test | type: USER MAPPING -- \ +-- DROP USER MAPPING IF EXISTS FOR postgres SERVER server_test; \ +CREATE USER MAPPING FOR postgres \ +SERVER server_test \ +OPTIONS (opt1 'value1',opt2 'value2'); \ +-- ddl-end -- ").simplified(); + +QString xml_code =QString( +" \ + \ + \ +") + .replace("#", ForeignServer::OptionValueSeparator) + .replace("*", ForeignServer::OptionsSeparator).simplified(); + + try + { + role.setName("postgres"); + fdw.setName("fdw"); + + server.setName("server_test"); + server.setOwner(&role); + server.setForeignDataWrapper(&fdw); + usr_mapping.setForeignServer(&server); + usr_mapping.setOwner(&role); + usr_mapping.setOption("opt1", "value1"); + usr_mapping.setOption("opt2", "value2"); + + QString res_sql_code = usr_mapping.getCodeDefinition(SchemaParser::SqlDefinition).simplified(); + QCOMPARE(sql_code, res_sql_code); + + QString res_xml_code = usr_mapping.getCodeDefinition(SchemaParser::XmlDefinition).simplified(); + QCOMPARE(xml_code, res_xml_code); + } + catch (Exception &e) + { + QFAIL(e.getExceptionsText().toStdString().c_str()); + } +} + +void UserMappingTest::modelReturnsDepsAndRefsForUserMapping(void) +{ + DatabaseModel model; + ForeignDataWrapper fdw; + ForeignServer server; + Role role; + UserMapping usr_mapping; + + try + { + role.setName("postgres"); + fdw.setName("fdw"); + + server.setName("server_test"); + server.setOwner(&role); + server.setForeignDataWrapper(&fdw); + usr_mapping.setForeignServer(&server); + usr_mapping.setOwner(&role); + usr_mapping.setOption("opt1", "value1"); + usr_mapping.setOption("opt2", "value2"); + + model.addRole(&role); + model.addForeignServer(&server); + model.addUserMapping(&usr_mapping); + + vector refs, deps; + model.getObjectDependecies(&usr_mapping, deps); + + model.getObjectReferences(&server, refs); + model.removeUserMapping(&usr_mapping); + model.removeForeignServer(&server); + model.removeForeignDataWrapper(&fdw); + model.removeRole(&role); + + QVERIFY(deps.size() >= 2); + QVERIFY(refs.size() == 1); + } + catch (Exception &e) + { + QFAIL(e.getErrorMessage().toStdString().c_str()); + } +} + +void UserMappingTest::modelCreatesUserMappingfromXMLandResultingXMLisEqual(void) +{ + DatabaseModel model; + ForeignDataWrapper fdw; + ForeignServer server; + Role role; + UserMapping *usr_map = nullptr; + QString xml_code, res_xml_code; + + try + { + role.setName("postgres"); + fdw.setName("fdw"); + + server.setName("server_test"); + server.setOwner(&role); + server.setForeignDataWrapper(&fdw); + + model.addRole(&role); + model.addForeignServer(&server); + model.addForeignDataWrapper(&fdw); + + xml_code=QString(" \ + \ + \ +").replace("#", ForeignObject::OptionValueSeparator) + .replace("*", ForeignObject::OptionsSeparator); + + model.getXMLParser()->loadXMLBuffer(xml_code); + usr_map = dynamic_cast(model.createObject(ObjectType::UserMapping)); + + QVERIFY(usr_map != nullptr); + + res_xml_code = usr_map->getCodeDefinition(SchemaParser::XmlDefinition).simplified(); + xml_code = xml_code.simplified(); + + model.removeUserMapping(usr_map); + model.removeForeignServer(&server); + model.removeForeignDataWrapper(&fdw); + model.removeRole(&role); + + if(usr_map) + delete(usr_map); + + QCOMPARE(xml_code, res_xml_code); + } + catch (Exception &e) + { + QFAIL(e.getErrorMessage().toStdString().c_str()); + } +} + +QTEST_MAIN(UserMappingTest) +#include "usermappingtest.moc" diff --git a/tests/src/usermappingtest/usermappingtest.pro b/tests/src/usermappingtest/usermappingtest.pro new file mode 100644 index 0000000000..a72afdc380 --- /dev/null +++ b/tests/src/usermappingtest/usermappingtest.pro @@ -0,0 +1,2 @@ +include(../../tests.pri) +SOURCES += usermappingtest.cpp diff --git a/tests/tests.pro b/tests/tests.pro index 6e60d5c27b..8cebc9177a 100644 --- a/tests/tests.pro +++ b/tests/tests.pro @@ -8,9 +8,15 @@ # refactored code, containing almost all changes done by the refactoring author. TEMPLATE = subdirs SUBDIRS = src/main \ - src/baseobjecttest \ - src/roletest \ - src/syntaxhighlightertest \ - src/databasemodeltest \ - src/schemaparsertest +src/baseobjecttest \ +src/roletest \ +src/syntaxhighlightertest \ +src/databasemodeltest \ +src/schemaparsertest \ +src/linenumberstest \ +src/partrelationshiptest \ +src/foreigndatawrappertest \ +src/servertest \ +src/usermappingtest + diff --git a/windeploy.sh b/windeploy.sh index cffd57d6b9..fae2a823d5 100644 --- a/windeploy.sh +++ b/windeploy.sh @@ -1,13 +1,9 @@ #!/bin/bash -QT_INSTALL_VERSION='5.9.3' -QT_BASE_VERSION='5.9.3' -PGSQL_VERSION='10.1' -INNOSETUP_CMD='/c/Program Files (x86)/Inno Setup 5/ISCC.exe' LOG=windeploy.log # Detecting current pgModeler version -DEPLOY_VER=`cat libutils/src/globalattributes.cpp | grep PGMODELER_VERSION | sed 's/PGMODELER_VERSION=QString("//g' | sed 's/"),//g'` +DEPLOY_VER=`cat libutils/src/globalattributes.cpp | grep PgModelerVersion | sed 's/PgModelerVersion=QString("//g' | sed 's/")//g'` DEPLOY_VER=${DEPLOY_VER/PGMODELER_VERSION=\"/} DEPLOY_VER=`echo ${DEPLOY_VER/\",/} | tr -d ' '` @@ -17,6 +13,23 @@ DEMO_VERSION=0 BUILD_ALL_OPT='-build-all' BUILD_ALL=0 +SNAPSHOT_OPT='-snapshot' +SNAPSHOT=0 + +# Installer settings +FMT_PREFIX="C:\/Program Files\/pgmodeler" +INSTALLER_APP_VER=`echo $DEPLOY_VER | cut -d '-' -f1` +INSTALLER_CONF_DIR="$PWD/installer/template/config" +INSTALLER_PKG_DIR="$PWD/installer/template/packages" +INSTALLER_DATA_DIR="$INSTALLER_PKG_DIR/io.pgmodeler/data" +INSTALLER_META_DIR="$INSTALLER_PKG_DIR/io.pgmodeler/meta" +INSTALLER_TMPL_CONFIG="config.xml.tmpl" +INSTALLER_CONFIG="config.xml" +INSTALLER_TMPL_PKG_CONFIG="package.xml.tmpl" +INSTALLER_PKG_CONFIG="package.xml" +BUILD_DATE=`date '+%Y-%m-%d'` +BUILD_NUM=`date '+%Y%m%d'` + # Setting key paths according to the arch build (x86|x64) # If none of the build type parameter is specified, the default is tu use x86 X64_BUILD_OPT='-x64-build' @@ -33,11 +46,16 @@ for param in $@; do X64_BUILD=1 DEST_ARCH="x64" WIN_BITS="64" + BUILD_ARCH_PARAM=$X64_BUILD_OPT fi if [[ "$param" == "$BUILD_ALL_OPT" ]]; then BUILD_ALL=1 DEMO_VERSION=0 fi + if [[ "$param" == "$SNAPSHOT_OPT" ]]; then + SNAPSHOT=1 + DEPLOY_VER="${DEPLOY_VER}_snapshot${BUILD_NUM}" + fi done # Define the base name of the binary @@ -47,67 +65,81 @@ else PKGNAME="pgmodeler-$DEPLOY_VER-windows$WIN_BITS" fi -if [ $X64_BUILD = 1 ]; then - # Settings for x64 build - QT_ROOT="/c/Qt/Qt${QT_INSTALL_VERSION}-x64/" - QMAKE_ROOT=$QT_ROOT/bin - MINGW_ROOT="/c/msys_64/mingw64/bin" - PGSQL_ROOT="/c/PostgreSQL/${PGSQL_VERSION}-x64/bin" - QMAKE_ARGS="-r -spec win32-g++ CONFIG+=release \ - XML_INC+=$MINGW_ROOT/../include/libxml2 \ - XML_LIB+=$MINGW_ROOT/libxml2-2.dll \ - PGSQL_INC+=$MINGW_ROOT/../include \ - PGSQL_LIB+=$MINGW_ROOT/libpq.dll" - DEP_LIBS="$MINGW_ROOT/libgcc_s_seh-1.dll \ - $MINGW_ROOT/libstdc++-6.dll \ - $MINGW_ROOT/libwinpthread-1.dll \ - $MINGW_ROOT/libiconv-2.dll \ - $MINGW_ROOT/libintl-8.dll \ - $MINGW_ROOT/zlib1.dll \ - $MINGW_ROOT/libxml2-2.dll \ - $MINGW_ROOT/libpq.dll \ - $MINGW_ROOT/libeay32.dll \ - $MINGW_ROOT/ssleay32.dll \ - $MINGW_ROOT/liblzma-5.dll" +# Settings for x64 build +if [ $X64_BUILD = 1 ]; then + QT_ROOT="/c/msys_64/mingw64" + MINGW_ROOT="/c/msys_64/mingw64/bin" + DEP_LIBS="$DEP_LIBS \ + $MINGW_ROOT/libssl-1_1-x64.dll \ + $MINGW_ROOT/libcrypto-1_1-x64.dll \ + $MINGW_ROOT/libgcc_s_seh-1.dll" +# Settings for x86 build else - # Default setting for x86 build - QT_ROOT="/c/Qt/Qt${QT_INSTALL_VERSION}/${QT_BASE_VERSION}/mingw53_32/" - QMAKE_ROOT=$QT_ROOT/bin - QMAKE_ARGS="-r -spec win32-g++ CONFIG+=release" - MINGW_ROOT="/c/Qt/Qt${QT_INSTALL_VERSION}/Tools/mingw530_32/bin" - PGSQL_ROOT="/c/PostgreSQL/${PGSQL_VERSION}/bin" - DEP_LIBS="$QMAKE_ROOT/libgcc_s_dw2-1.dll \ - $QMAKE_ROOT/libstdc++-6.dll \ - $QMAKE_ROOT/libwinpthread-1.dll \ - $PGSQL_ROOT/libiconv-2.dll \ - $PGSQL_ROOT/libintl-8.dll \ - $PGSQL_ROOT/zlib1.dll \ - $PGSQL_ROOT/libxml2.dll \ - $PGSQL_ROOT/libpq.dll \ - $PGSQL_ROOT/libeay32.dll \ - $PGSQL_ROOT/ssleay32.dll" + QT_ROOT="/c/msys_64/mingw32" + MINGW_ROOT="/c/msys_64/mingw32/bin" + DEP_LIBS="$DEP_LIBS \ + $MINGW_ROOT/libssl-1_1.dll \ + $MINGW_ROOT/libcrypto-1_1.dll \ + $MINGW_ROOT/libgcc_s_dw2-1.dll" fi +# Common settings for both architectures +QT_INSTALL_VERSION='5.12.3' +QT_BASE_VERSION='5.12.3' +QT_PLUGINS_ROOT="$QT_ROOT/share/qt5/plugins" +QMAKE_ROOT=$MINGW_ROOT +QT_IFW_ROOT=/c/qt-ifw +PGSQL_ROOT=$MINGW_ROOT +QMAKE_ARGS="-r -spec win32-g++ CONFIG+=release \ + XML_INC+=$MINGW_ROOT/../include/libxml2 \ + XML_LIB+=$MINGW_ROOT/libxml2-2.dll \ + PGSQL_INC+=$MINGW_ROOT/../include \ + PGSQL_LIB+=$MINGW_ROOT/libpq.dll" + if [ $DEMO_VERSION = 1 ]; then QMAKE_ARGS="$QMAKE_ARGS DEMO_VERSION+=true" fi +if [ $SNAPSHOT = 1 ]; then + QMAKE_ARGS="$QMAKE_ARGS SNAPSHOT_BUILD+=true" +fi + + PKGFILE=$PKGNAME.exe GENINSTALLER=pgmodeler.exe INSTALL_ROOT="$PWD/build" DIST_ROOT="$PWD/dist" -ISSFILE=./installer/windows/pgmodeler.iss QT_CONF="$INSTALL_ROOT/qt.conf" DEP_PLUGINS_DIR="$INSTALL_ROOT/qtplugins" PLUGINS="dummy xml2object" # Common dependency libraries -DEP_LIBS+=" $QMAKE_ROOT/Qt5Core.dll \ - $QMAKE_ROOT/Qt5Gui.dll \ - $QMAKE_ROOT/Qt5Widgets.dll \ - $QMAKE_ROOT/Qt5PrintSupport.dll \ - $QMAKE_ROOT/Qt5Network.dll \ - $QMAKE_ROOT/Qt5Svg.dll " +DEP_LIBS="$DEP_LIBS \ + $MINGW_ROOT/libicuin*.dll \ + $MINGW_ROOT/libicuuc*.dll \ + $MINGW_ROOT/libicudt*.dll \ + $MINGW_ROOT/libpcre2-16-0.dll \ + $MINGW_ROOT/libharfbuzz-0.dll \ + $MINGW_ROOT/libpng16-16.dll \ + $MINGW_ROOT/libfreetype-6.dll \ + $MINGW_ROOT/libgraphite2.dll \ + $MINGW_ROOT/libglib-2.0-0.dll \ + $MINGW_ROOT/libpcre-1.dll \ + $MINGW_ROOT/libbz2-1.dll \ + $MINGW_ROOT/libstdc++-6.dll \ + $MINGW_ROOT/libwinpthread-1.dll \ + $MINGW_ROOT/zlib1.dll \ + $MINGW_ROOT/libpq.dll \ + $MINGW_ROOT/libxml2-2.dll \ + $MINGW_ROOT/liblzma-5.dll \ + $MINGW_ROOT/libiconv-2.dll \ + $MINGW_ROOT/libintl-8.dll \ + $QMAKE_ROOT/Qt5Core.dll \ + $QMAKE_ROOT/Qt5Gui.dll \ + $QMAKE_ROOT/Qt5Widgets.dll \ + $QMAKE_ROOT/Qt5PrintSupport.dll \ + $QMAKE_ROOT/Qt5Network.dll \ + $QMAKE_ROOT/Qt5Svg.dll " #Dependency qt plugins copied to build dir DEP_PLUGINS="imageformats/qicns.dll \ @@ -127,11 +159,11 @@ clear echo echo "pgModeler Windows deployment script" echo "PostgreSQL Database Modeler Project - pgmodeler.io" -echo "Copyright 2006-2018 Raphael A. Silva " +echo "Copyright 2006-2019 Raphael A. Silva " # Identifying Qt version if [ -e "$QMAKE_ROOT/qmake" ]; then - QT_VER=`$QMAKE_ROOT/qmake --version | grep '[0-9].[0-9].[0-9]'` + QT_VER=`$QMAKE_ROOT/qmake --version | grep -E '[0-9]\.[0-9]+\.[0-9]+'` QT_VER=${QT_VER:0:5} fi @@ -156,6 +188,10 @@ fi echo echo "Deploying version: $DEPLOY_VER" +if [ $SNAPSHOT = 1 ]; then + echo "Building snapshot version. (Found $SNAPSHOT_OPT)" +fi + if [ $DEMO_VERSION = 1 ]; then echo "Building demonstration version. (Found $DEMO_VERSION_OPT)" fi @@ -181,7 +217,7 @@ if [ $? -ne 0 ]; then fi echo "Compiling code..." -$MINGW_ROOT/mingw32-make.exe -j7 >> $LOG 2>&1 +$MINGW_ROOT/mingw32-make.exe -j10 >> $LOG 2>&1 if [ $? -ne 0 ]; then echo @@ -222,7 +258,7 @@ echo "Libraries=." >> $QT_CONF for plug in $DEP_PLUGINS; do pdir=`dirname $plug` mkdir -p $DEP_PLUGINS_DIR/$pdir >> $LOG 2>&1 - cp $QT_ROOT/plugins/$plug $DEP_PLUGINS_DIR/$pdir >> $LOG 2>&1 + cp $QT_PLUGINS_ROOT/$plug $DEP_PLUGINS_DIR/$pdir >> $LOG 2>&1 if [ $? -ne 0 ]; then echo @@ -232,53 +268,57 @@ for plug in $DEP_PLUGINS; do fi done -$MINGW_ROOT/mingw32-make.exe install >> $LOG 2>&1 +echo "Packaging installation..." + +rm -r $INSTALLER_DATA_DIR >> $LOG 2>&1 +ln -sf "$INSTALL_ROOT" $INSTALLER_DATA_DIR >> $LOG 2>&1 + +if [ $? -ne 0 ]; then + echo + echo "** Failed to configure installer data dir!" + echo + exit 1 +fi +# Configuing installer scripts before packaging +cat $INSTALLER_CONF_DIR/$INSTALLER_TMPL_CONFIG | sed -e "s/{version}/$INSTALLER_APP_VER/g" | sed -e "s/{prefix}/$FMT_PREFIX/g" > $INSTALLER_CONF_DIR/$INSTALLER_CONFIG + if [ $? -ne 0 ]; then echo - echo "** Installation failed!" + echo "** Failed to create the installer config file!" echo exit 1 -fi +fi -echo "Packaging installation..." +cat $INSTALLER_META_DIR/$INSTALLER_TMPL_PKG_CONFIG | sed -e "s/{version}/$INSTALLER_APP_VER/g" | sed -e "s/{date}/$BUILD_DATE/g" > $INSTALLER_META_DIR/$INSTALLER_PKG_CONFIG + +if [ $? -ne 0 ]; then + echo + echo "** Failed to create the package info file!" + echo + exit 1 +fi -"$INNOSETUP_CMD" $ISSFILE >> $LOG 2>&1 +$QT_IFW_ROOT/bin/binarycreator -v -c $INSTALLER_CONF_DIR/config.xml -p $INSTALLER_PKG_DIR "$DIST_ROOT/$PKGNAME.exe" >> $LOG 2>&1 if [ $? -ne 0 ]; then echo - echo "** Failed to create installer package!" - echo "** Proceeding with basic deployment." - - mkdir $PKGNAME >> $LOG 2>&1 - mv $INSTALL_ROOT/* $PKGNAME >> $LOG 2>&1 - mv $PKGNAME $INSTALL_ROOT >> $LOG 2>&1 - - if [ $? -ne 0 ]; then - echo "** Failed to execute basic deployment!" - exit 1 - fi - + echo "** Failed to create installer!" echo - echo "Directory created: $PKGNAME" -else - mv $GENINSTALLER build/$PKGFILE >> $LOG 2>&1 - echo "File created: $PKGFILE" + exit 1 fi -mkdir -p $DIST_ROOT >> $LOG 2>&1 -mv $INSTALL_ROOT/$PKGFILE $DIST_ROOT >> $LOG 2>&1 - -if [ $? -ne 0 ]; then - echo "** Failed to move $PKGFILE to $DIST_ROOT!" - exit 1 -fi +echo "File created: dist/$PKGNAME.exe" echo "pgModeler successfully deployed!" echo if [ $BUILD_ALL -eq 1 ]; then - sh windeploy.sh -demo-version - sh windeploy.sh -x64-build - sh windeploy.sh -x64-build -demo-version + EXTRA_OPT="" + + if [ $SNAPSHOT = 1 ]; then + EXTRA_OPT="$SNAPSHOT_OPT" + fi + + sh windeploy.sh -demo-version $BUILD_ARCH_PARAM $EXTRA_OPT fi