Compare commits

..

105 Commits

Author SHA1 Message Date
f18ddcf188 CE-847 Add omitTriggeringAutomations to updateInput to ... let you say that you want to ... omit trigger automations 2024-02-12 18:57:05 -06:00
a7dfad5b28 CE-847 Add fluent appender 'withSubFilter()' 2024-02-12 18:56:30 -06:00
2f83b7ba7d CE-847 Remove setting modifyDate in memory update action - happens now via field behaviors. 2024-02-12 18:56:06 -06:00
62560ab82c CE-847 Add STYLE_YELLOW... 2024-02-12 18:55:11 -06:00
718701aaff CE-847 Add method getTopAndBottomMessages 2024-02-12 18:54:53 -06:00
b8f9469477 CE-847 New process to "heal" records w/ an unhealthy automation status (failed or leaked-running) back to pending. 2024-02-12 18:51:34 -06:00
4bf29807e3 CE-847 New process to manually run automations (the same code that scheduler runs - so that'll only process records that are pending). 2024-02-12 15:00:19 -06:00
b28000932b CE-847 take in the list of oldRecords - since updateAction will often already have them! 2024-02-12 14:46:56 -06:00
ee1c20b1c6 CE-847 Add permissions check in runProcess... 2024-02-12 14:45:51 -06:00
e3ce1cdbc3 Merged dev into feature/CE-847-bug-triggers-running 2024-02-12 11:14:59 -06:00
a9999ee8ce Merge pull request #63 from Kingsrook/feature/column-stats-date-time-to-hour
Fix how column-stats backend handles date-times, grouping by hour.  u…
2024-02-12 11:05:07 -06:00
f50e6d1a94 Merge pull request #62 from Kingsrook/feature/CE-798-quick-filters
Feature/ce 798 quick filters
2024-02-12 11:04:53 -06:00
72735607c6 CE-847 Remove debug logger usage 2024-02-09 19:46:50 -06:00
bbba43ef80 CE-847 Main implementation of fix for missing insert automations, by updating status to pending-update-automations when a record is still pending insert automations. added memoization of areThereTableTriggersForTableMemoization; small cleanup (remove session & instance params, pass transaction 2024-02-09 19:38:00 -06:00
efa84d03e6 CE-847 New test on automation status runner - for where a child table has a post-insert that updates the parent! 2024-02-09 17:02:13 -06:00
8572c5cb7e Add LinkedList as a class that the copy constructor knows how to handle w/o Serialization 2024-02-09 17:01:02 -06:00
871d133a37 CE-847 Add overload of getResult that takes the lookup function to use if not found - much more clear & useful. 2024-02-09 17:00:00 -06:00
61c9f1fe75 CE-847 Update to put script name in context a little bit lower in the stack, so scripts ran via triggers have them too. 2024-02-09 16:59:35 -06:00
c77e37d6dc Revert "Updated 1Password vault"
This reverts commit aef42a4a5e.
2024-02-08 16:12:59 -06:00
aef42a4a5e Updated 1Password vault 2024-02-08 13:57:17 -06:00
c0b5d11a09 added getAPIResponseLogLevel as base method that can be overridden in subsclasses 2024-02-07 09:18:57 -06:00
8e8d3b5d2b downgraded some loggly infos to debugs to stop filling up 2024-02-06 14:55:38 -06:00
4ca9c9dcaf Merge branch 'feature/create-and-modify-date-as-field-behaviors' into dev 2024-02-05 16:00:08 -06:00
c6a58ac68f added tests to StringUtils.safeAppend() 2024-02-01 16:00:45 -06:00
bb69dddb81 Merge pull request #64 from Kingsrook/feature/CE-779-order-level-ship-date
Feature/ce 779 order level ship date
2024-02-01 12:07:29 -06:00
052cb9fab9 Merge branch 'dev' into feature/CE-779-order-level-ship-date 2024-02-01 11:28:40 -06:00
2681d66b32 CE-779: updated all addHeader calls to setHeader to avoid duplicate entries 2024-02-01 11:13:30 -06:00
612370fc13 Fix the check for primary key of integer (to work for null primary keys, and to be inside the try-catch); tests on that 2024-01-31 16:16:14 -06:00
74d66d0fa5 Add Log for missing value in sourceKeyField 2024-01-31 11:14:50 -06:00
2a68478405 Fix how column-stats backend handles date-times, grouping by hour. update MemoryRecordStore to work for an aggregate with a DateTimeGroupBy, at least enough for test to pass. 2024-01-31 10:58:42 -06:00
459510bba4 CE-793 - make defineSavedViewTable public 2024-01-30 15:08:47 -06:00
18e1852ce4 CE-793 - rename saved-filter to saved-view in tests 2024-01-30 09:45:46 -06:00
0dd7f5e1d2 CE-793 - rename saved-filter to saved-view; add check for duplicate names (on insert & rename) in save process. 2024-01-30 09:34:28 -06:00
601c66ddff Merged dev into feature/CE-798-quick-filters 2024-01-23 20:34:18 -06:00
08e14ac346 CE-781 - remove unintended changes from last commit 2024-01-23 19:15:42 -06:00
0dd26b8f31 CE-781 - eliminate instance validation errors when using FilesystemImporterStep FIELD_IMPORT_SECURITY_VALUE_SUPPLIERs 2024-01-23 19:12:41 -06:00
7e0b7ddbf9 Merge pull request #61 from Kingsrook/feature/CE-781-fixes
Feature/ce 781 fixes
2024-01-23 15:18:43 -06:00
fb69c60e10 CE-781 - Add option to set secuirty key values in importFile & importRecord records dynamically through a QCodeReference to a Function 2024-01-23 14:44:10 -06:00
e7e93a6ab2 CE-781 - Rework api for adding automations (don't clobber if adding more than 1) 2024-01-23 14:41:43 -06:00
e1ca85c746 CE-798 - Add calls to supplementalTableMetaData.validate; move UnsafeLambda out of here to utils.lambdas package 2024-01-23 14:08:49 -06:00
1baade0449 Change insert & update actions to set default values for createDate & modifyDate based on FieldBehaviors instead of based on field names (though field names are used in Enricher to add those beavhiors); Some refactoring of FieldBehaviors. 2024-01-18 11:50:40 -06:00
0eb8356759 Remove unused import 2024-01-17 20:35:05 -06:00
6098e64934 Add warn instead of silent noop in setInputFieldDefaultValue, if field not found 2024-01-17 20:34:19 -06:00
dfb1e637a3 Updated afterEach method to package-private to quiet warning 2024-01-17 20:33:33 -06:00
ce28ce2e02 Add TableSyncProcess; remove previously built htmls & pdfs 2024-01-17 20:32:56 -06:00
7109cffa27 Merge branch 'wip/asciidoc' into dev 2024-01-17 20:29:17 -06:00
6f4d44df10 Merge pull request #59 from Kingsrook/feature/CE-781
Feature/ce 781
2024-01-17 20:27:44 -06:00
84eaa09932 CE-781 Feedback from code review 2024-01-17 19:39:00 -06:00
911978c74b CE-781 Feedback from code review 2024-01-17 19:09:19 -06:00
00a5b72bf3 added string util method for appending strings 2024-01-16 14:32:40 -06:00
a845ead466 Add option to exclude an enum possible value's fields from docs 2024-01-16 10:58:20 -06:00
3ebc567299 CE-781 Fix archivePath as field on table; set maxRows 100 on child-widget; always archive files; allow security name/value; significant tests on importer step 2024-01-16 10:33:59 -06:00
494f0242ac CE-781 Remove coverage ratios = 0 - as we might be good in here now!! 2024-01-15 20:29:14 -06:00
e6e7e3f9a7 Add overloaded constructor to SyncProcessConfig (defaults doInserts & doUpdates to true) 2024-01-15 20:22:41 -06:00
6dc7a8dde9 CE-781 Add qqq-backend-module-mongodb 2024-01-15 20:22:03 -06:00
dccbed87a7 CE-781 Add javadoc 2024-01-15 20:21:48 -06:00
7b141abcec CE-781 Add logQuery, queryStats, actionTimeouts to MongoDB; fix many query operators while adding test coverage 2024-01-15 20:21:16 -06:00
252c92913c CE-781 Do not assume recordIds are integers 2024-01-12 12:31:38 -06:00
f0150a3543 Remove debug system output from previous 2024-01-12 09:40:09 -06:00
16f0a8c3a7 Add src/main/resources to build as well 2024-01-12 09:06:26 -06:00
e5c35e90a6 Add some system outs to debug test fail 2024-01-12 08:57:40 -06:00
4286001b4d Turn on including src java files in jars 2024-01-12 08:40:46 -06:00
c1ce933d6c CE-781 Temp disable coverage ratios 2024-01-12 08:18:41 -06:00
f78d9a11b2 CE-781 javadoc syntax fix 2024-01-11 10:42:58 -06:00
d0233e839b CE-781 initial set of tets for mongodb 2024-01-11 10:28:59 -06:00
e4d7797bbe CE-781 Adding fake tests to ensure class-coverage on records... 2024-01-11 08:59:54 -06:00
f66f2d622a CE-781 Adding tests for new classes 2024-01-11 08:43:55 -06:00
624a723b54 CE-781 Initial checkin of filesystem importer meta-data template and process 2024-01-11 07:46:30 -06:00
b64883f34f CE-781 rename beforeEach and afterEach (to help avoid overwriting in sub-classes) 2024-01-10 19:59:40 -06:00
4b1bdebe44 CE-781 Move backend type (name) up to public static final constant 2024-01-10 19:59:11 -06:00
8d668d12ec CE-781 Get fields using getFields().containsKey/get, rather than getField(String) - to avoid it throwing, to cut down on exceptions (and warn if we get a real exception, vs., we'll expect non-fields sometimes, so be okay with that) 2024-01-10 19:58:26 -06:00
c27a2a986a CE-781 Add cases for LinkedHashMap and HashMap in deepCopySimpleMap 2024-01-10 19:57:20 -06:00
fed8cbbb45 CE-781 Make tie-break for sorting do backends earlier than everything else 2024-01-10 19:52:22 -06:00
5147a022fa CE-781 add sortOrder attribute to apps, for sorting them... 2024-01-10 19:51:44 -06:00
615ff6fce5 CE-781 more fluent methods in process meta data builders 2024-01-10 19:51:07 -06:00
f5c4c12388 CE-781 Initial build of mongodb backend module 2024-01-08 20:00:57 -06:00
68911190fa CE-781 Updates for compatibility with corresponding changes, refactoring, in backend-core 2024-01-08 16:40:56 -06:00
56a2949911 CE-781 Remove check for empty record list (has been moved up to core InsertAction) 2024-01-08 14:18:32 -06:00
96013878bc CE-781 Update some of the getValueAs methods to take Object instead of Serializable 2024-01-08 14:17:55 -06:00
f879575b32 CE-781 Gracefully ignore request to add null uniqueKey or recordSecurityLock 2024-01-08 14:16:59 -06:00
bab3c7b374 CE-781 Initial checkin 2024-01-08 14:15:34 -06:00
1c69784897 CE-781 Add method add(TopLevelMetaDataInterface) 2024-01-08 14:15:05 -06:00
8822c1bb99 CE-781 Add overload constructor that takes Collection of values 2024-01-08 14:14:47 -06:00
a5420bff4c CE-781 Add concept of sharded automations - schedule multiple instances of job, filter implicitly by shard value 2024-01-08 14:13:44 -06:00
06259041f8 CE-781 Update to work without a table specified (just getting field names from the json keys) 2024-01-08 12:39:43 -06:00
a00d4f3cbd CE-781 Refactoring this code out of RDBMS update, to be shared with MongoDB update 2024-01-08 12:37:38 -06:00
8473e11444 CE-781 Refactoring of backend actions - moving openTransaction out of insert-action only (up to backendModule); re-using the exit-early-if-0 and set-default-create-and-modify-date logics; 2024-01-08 12:37:22 -06:00
bc3f462d13 CE-781 log (once) & noop for tables w/o integer primary key, as that is required for auditing... 2024-01-08 12:31:37 -06:00
56a2099515 CE-781 Add option to treat CSV headers as field names (rather than working with a table's fields) 2024-01-08 12:30:43 -06:00
93dcee9f61 Add QRecord as a handled type inside deepCopySimpleMap (e.g., so copy constructor won't need to warn about it and do slow serialization-based cloning). 2024-01-04 18:11:05 -06:00
92b052fe59 CE-773 avoid s3 list requests that start with / if backend & table have no basePaths 2023-12-29 19:12:34 -06:00
3f431b39b9 Merge pull request #58 from Kingsrook/feature/CE-773-cartonization-playground
CE-773 Fixing globs for local filesystem by using Files.walkFileTree.…
2023-12-29 10:42:41 -06:00
688e221f9a CE-773 Fixing globs for local filesystem by using Files.walkFileTree. Refactored to share filter matching between s3 & local fs. 2023-12-29 08:20:38 -06:00
959f8c8041 Merge pull request #55 from Kingsrook/feature/CE-773-cartonization-playground
Feature/ce 773 cartonization playground
2023-12-28 18:45:30 -06:00
6e1ea5c8f1 CE-773 fix tables created in here, per new validationing! 2023-12-28 16:46:51 -06:00
872dec3177 CE-773 change fileNameFieldName and contentsFieldName to default as null - add validation to tableBackendDetails, specifically implemented in filesystem module 2023-12-28 16:38:40 -06:00
78d9ec87a2 Merge pull request #57 from Kingsrook/feature/basepull-subtract-seconds
Add option to move timestamps, e.g., to make overlapping windows
2023-12-28 16:24:17 -06:00
01c78534ef Add test for previous commit (Add option to move timestamps, e.g., to make overlapping windows) 2023-12-28 16:20:38 -06:00
cfab10c8e8 Add option to move timestamps, e.g., to make overlapping windows 2023-12-28 15:54:44 -06:00
2da6878e70 Make sure to always return an empty list rather than a null 2023-12-28 10:33:23 -06:00
345d8022c1 CE-773 Feedback from code review 2023-12-28 10:33:23 -06:00
aff4b43296 Merged dev into feature/CE-773-cartonization-playground 2023-12-27 20:20:08 -06:00
b805e7645b CE-773 Update for compat. with previous commit, but also, fix all generics and move inputStream into try-with-resources 2023-12-27 16:11:19 -06:00
940080bc86 CE-773 update to support listing/filtering filesystem tables with Cardinality.ONE (single-record per-file) 2023-12-27 16:10:45 -06:00
d624a42dac Checkpoint on qqq docs 2023-12-15 18:41:30 -06:00
184 changed files with 14482 additions and 17360 deletions

View File

@ -1,8 +1,176 @@
= Introduction
include::variables.adoc[]
QQQ is ...
QQQ is a Low-code Application Framework for Engineers.
Its purpose is to provide the basic structural elements of an application - things that every application needs - so that the engineers building an application on top of QQQ don't need to worry about those pieces, and can instead focus on the unique needs of the application that they are building.
- Framework
- Declarative
- Easy thing easy; Hard thing possible
- Customizable
== What makes QQQ special?
The scope of what QQQ provides is far-reaching, and most likely goes beyond what you may initially be thinking.
That is to say, QQQ includes code all the way from the backend of an application, through its middleware layer, and including its frontend.
For example, a common set of modules deployed in a QQQ application will provide:
* Backend RDBMS/Database connectivity and access.
* Frontend web UI (e.g., a React application)
* A java web server acting as middleware between the frontend web UI and the backend
That is to say - as an engineer deploying a QQQ application - you do not need to write a single line of code that is concerned with any of those things.
* You do not need to write code to connect to your database.
* You do not write any web UI code.
* You do not write any middleware code to tie together the frontend and backend.
Instead, QQQ includes *all* of these pieces.
QQQ knows how to connect to databases (and actually, several other kinds of backend systems - but ignore that for now).
Plus it knows how to do most of what an application needs to do with a database (single-record lookups, complex queries, joins, aggregates, bulk inserts, updates, deletes).
QQQ also knows how to present the data from a database - in table views, or single-record views, or exports, or reports or widgets.
And it knows how to present a powerful ad-hoc query interface to users, and how to show screens where users can create, update, and delete records.
It also provides the connective tissue (middleware) between those backend layers where data is stored, and frontend layers were users interact with data.
== What makes your application special?
I've said a lot about what does QQQ knows - but let's dig a little deeper.
What does QQQ know, and what does it not know?
Well - what it doesn't know is, it doesn't know the special or unique aspects of the application that you are building.
So, what makes your application unique?
Is your application unique because it needs to have screens where users can search for records in a table?
No!
QQQ assumes (as does the author of this document) that all applications (at least of the nature that QQQ supports) need what we call Query Screens.
So QQQ gives you a Query Screen for all of your tables - with zero code from you.
Is your application unique because you want users to be able to view, create, edit, and delete records from tables?
No!
QQQ assumes that all applications need these basic https://en.wikipedia.org/wiki/Create,_read,_update_and_delete[CRUD] capabilities.
So QQQ provides all of these UI screens - for view, create, edit, delete - along with the supporting middleware and backend code - all the way down to the SQL that selects & manages the data.
You get it all for free - zero code.
Is your application unique because you have a `fiz_bar` table, with 47 columns, and a `whoz_zat` table, with 42 columns of its own, that joins to `fiz_bar` on the `zizzy_ziz_id` field?
Yes!
OK - we found some of it - what makes your application unique is the data that you're working with.
Your tables - their fields - the connection info for your database.
QQQ doesn't know those details.
So - that's your first job as a QQQ application engineer - to describe your data to QQQ.
For the example above - you need to tell QQQ that you have a `fiz_bar` table, and that you have a `whoz_zat` table - and you need to tell QQQ what the fields or columns in thsoe tables are.
You can even tell QQQ how to join those tables (on that `zizzy_ziz_id` field).
And then that's it.
Once QQQ has this {link-table} meta data, it can then provide its Query screens, and full CRUD screens to your tables, in your database, with your fields.
And at the risk of repeating myself - you can do this (get a full Query & CRUD application) with zero lines of actual procedural code.
You only need to supply meta-data (which, at the time of this writing, is done in Java, but it's just creating objects - and in the future could be done in YAML files, for example).
== Beyond Basics
Going beyond the basic wiring as described above, QQQ also provides some of the more advanced elements needed in a modern data-driven web application, including:
* Authentication & Authorization
* ad-hoc Query engine for access to data tables
* Full CRUD (Create, Read, Update, Delete) capabilities
* Multistep custom workflows ("Processes" in QQQ parlance)
* Scheduled jobs
* Enterprise Service Bus
So what do we mean by all of this?
We said that basically every application needs, for example, Authentication & Authorization.
Login screens.
User & Role tables.
Permissions.
So, when it's time for you to build a new application for your _Big Tall Floor Lamp_ manufacturing business, do you need to start by writing a login screen?
And a Permissions scheme?
And throwing HTTP 401 errors?
And managing user-role relationships?
And then having a bug in the check permission logic on the _Light Bulb Inventory Edit_ screen, so Jim is always keying in bad quantities, even though he isn't supposed to have permission there?
No!
All of the (really important, even though application developers hate doing it) aspects of security - you don't need to write ANY code for dealing with that.
Just tell QQQ what Authentication provider you want to use (e.g., https://auth0.com/[Auth0]), and - to paraphrase the old https://www.youtube.com/watch?v=YHzM4avGrKI[iMac ad] - there's no step 2.
QQQ just does it.
''''
QQQ can provide this type of application using a variety and/or combination of backend data storage types.
And, whichever type of backend is used, QQQ gives a common interface (both user-facing and programmer-facing).
Backend types include:
* Relational Databases (RDBMS)
* File Systems
* Web APIs
* NoSQL/Document Databases (_Future_)
In addition, out-of-the-box, QQQ also goes beyond these basics, delivering:
* Bulk versions of all CRUD operations.
* Automatically generated JSON APIs.
* Auditing of data changes.
* End-user (e.g., non-engineer) customization via dynamic scripting capabilities
#todo say much more#
== QQQ Architecture
Like a house!
== Developing a QQQ Application
In developing an application with QQQ, engineers will generally have to define two types of code:
. *Meta Data* - This is the code that you use to tell QQQ the shape of your application - your unique Tables, Processes, Apps, Reports, Widgets, etc.
In general, this code is 100% declarative in nature (as opposed to procedural or functional).
That is to say - it has no logic.
It is just a definition of what exists - but it has no instructions, algorithms, or business logic.
* _In a future version of QQQ, we anticipate being able to define meta-data in a format such as YAML or JSON, or to even load it from a relational or document database.
This speaks to the fact that this "code" is not executable code - but rather is a simple declaration of (meta) data._
* A key function of QQQ then is to drive all of its layers of functionality - frontend UIs, middleware, and core backend actions (e.g., ORM operations) - based on this meta-data.
** For example:
... You define the meta-data for a table in your application - including its fields and their data types, as well as what backend system the table exists within.
... Then, the QQQ Frontend Material Dashboard UI's Query Screen loads that table's meta-data, and uses it to control the screen that is presented. Including:
**** The data grid shown on the screen will have columns for each field in the table.
**** The Filter button in the Query Screen will present a menu listing all fields from the table for the user to build ad-hoc queries against the table.
The data-types specified for the fields (in the meta-data) dictate what operators QQQ allows the user to use against fields (e.g., Strings offer "contains" vs Numbers offer "greater than").
**** Values for records from the table will be formatted for presentation based on the meta-data (such as a numeric field being shown with commas if it represents a quantity, or formatted as currency).
...
[start=2]
. *Meta Data* - declarative code - java object instances (potentially which could be read from `.yaml` files or other data sources in a future version of QQQ), which tell QQQ about the backend systems, tables, processes, reports, widgets, etc, that make up the application.
For example:
* Details about the database you are using, and how to connect to it.
* A database table's name, fields, their types, its keys, and basic business rules (required fields, read-only fields, field lengths).
* The description of web API - its URL and authentication mechanism.
* A table/path within a web API, and the fields returned in the JSON at that endpoint.
* The specification of a custom workflow (process), including what screens are needed, with input & output values, and references to the custom application code for processing the data.
* Details about a chart that summarizes data from a table for presentation as a dashboard widget.
// the section below is kinda dumb. like, it says you have to write application code, but
// then it just talks about how your app code gets for-free the same shit that QQQ does.
// it should instead say more about what your custom app code is or does.
// 2. *Application code* - to customize beyond what the framework does out-of-the box, and to provide application-specific business-logic.
// QQQ provides its programmers the same classes that it internally uses for record access, resulting in a unified application model.
// For example:
// * The same record-security model that is enforced for ad-hoc user queries through the frontend is applied to custom application code.
// ** So if your table has a security key defined, which says that users can only see Order records that are associated with the user's assigned Store, then QQQ's order Query Screen will enforce that rule.
// ** And at the same time - any custom processes ran by a user will have the same security applied to any queries that they run against the Order table.
// ** And any custom dashboard widgets - will only include data that the user is allowed to see.
// * Record audits are performed in custom code the same as they are in framework-driven actions.
// ** So if a custom process edits a record, details of the changed fields show up in the record's audit, the same as if the record was edited using the standard QQQ edit action.
// * Changed records are sent through the ESB automatically regardless of whether they are updated by custom application code or standard framework code.
// ** Meaning record automations are triggered regardless of how a record is created or edited - without you, as an application engineering, needing to send records through the bus.
// * The multi-threaded, paged producer/consumer pattern used in standard framework actions is how all custom application actions are also invoked.
// ** For example, the standard QQQ Bulk Edit action uses the same streamed-ETL process that custom application processes can use.
// Meaning your custom processes can take full advantage of the same complex frontend, middleware, and backend structural pieces, and you can just focus on your unique busines logic needs.
2. *Application code* - to customize beyond what the QQQ framework does out-of-the box, and to provide application-specific business-logic.
QQQ provides its programmers the same classes that it internally uses for record access, resulting in a unified application model.
For example:
== Lifecycle?
* define meta data
** enrichment
** validation
* start application
* for dev - hotSwap

File diff suppressed because it is too large Load Diff

View File

@ -1,34 +1,45 @@
== QueryAction
include::../variables.adoc[]
The `*QueryAction*` is the basic action that is used to get records from a {link-table}.
The `*QueryAction*` is the basic action that is used to get records from a {link-table}, generally according to a <<QQueryFilter,Filter>>.
In SQL/RDBMS terms, it is analogous to a `SELECT` statement, where 0 or more records may be found and returned.
=== Examples
==== Basic Form
[source,java]
----
QueryInput input = new QueryInput(qInstance);
input.setSession(session);
QueryInput input = new QueryInput();
input.setTableName("orders");
input.setFilter(new QQueryFilter()
.withCriteria(new QFilterCriteria("total", GREATER_THAN, new BigDecimal("3.50")))
.withOrderBy(new QFilterOrderBy("orderDate", false))
);
.withOrderBy(new QFilterOrderBy("orderDate", false)));
QueryOutput output = new QueryAction.execute(input);
List<QRecord> records = output.getRecords();
----
=== Details
`QueryAction`, in general, can be called in two different modes:
. The most common use-case case, and default, fetches all records synchronously, does any post-processing (as requested in the <<QueryInput>>), and returns all records as a list in the <<QueryOutput>>).
. The alternative use-case is meant for larger operations, where one wouldn't want all records matching a query in-memory.
For this scenario, a `RecordPipe` object can be passed in to the <<QueryInput>>.
This causes `QueryAction` to run its post-processing action on records as they are placed into the pipe, and to potentially block (per the pipe's settings).
This method of usage needs to be done on a separate thread from another thread which would be consuming records from the pipe.
QQQ's `AsyncRecordPipeLoop` class provides an implementation of doing such a dual-threaded job.
If the {link-table} has a `POST_QUERY_CUSTOMIZER` defined, then after records are fetched from the backend, that code is executed on the records before they leave the `QueryAction` (either through its `QueryOutput` or `RecordPipe`).
=== QueryInput
* `table` - *String, Required* - Name of the table being queried against.
* `filter` - *QQueryFilter object* - Specification for what records should be returned, based on *QFilterCriteria* objects, and how they should be sorted, based on *QFilterOrderBy* objects.
* `filter` - *<<QQueryFilter>> object* - Specification for what records should be returned, based on *<<QFilterCriteria>>* objects, and how they should be sorted, based on *<<QFilterOrderBy>>* objects.
If a `filter` is not given, then all rows in the table will be returned by the query.
* `skip` - *Integer* - Optional number of records to be skipped at the beginning of the result set.
e.g., for implementing pagination.
* `limit` - *Integer* - Optional maximum number of records to be returned by the query.
* `transaction` - *QBackendTransaction object* - Optional transaction object.
** Behavior for this object is backend-dependant.
In an RDBMS backend, this object is generally needed if you want your query to see data that may have been modified within the same transaction.
* `recordPipe` - *RecordPipe object* - Optional object that records are placed into, for asynchronous processing.
* `recordPipe` - *RecordPipe object* - Optional pipe object that records are placed into, for asynchronous processing.
** If a *recordPipe* is used, then records cannot be retrieved from the *QueryOutput*.
Rather, such records must be read from the pipe's `consumeAvailableRecords()` method.
** A *recordPipe* should only be used when a *QueryAction* is running in a separate Thread from the record's consumer.
@ -36,18 +47,21 @@ Rather, such records must be read from the pipe's `consumeAvailableRecords()` me
(e.g., to provide text translations in the generated records' `displayValues` map).
** For example, if running a query to present results to a user, this would generally need to be *true*.
But if running a query to provide data as part of a process, then this can generally be left as *false*.
* `shouldGenerateDisplayValues` - *boolean, default: false* - Controls whether if field level *displayFormats* should be used to populate the generated records' `displayValues` map.
* `shouldGenerateDisplayValues` - *boolean, default: false* - Controls whether field level *displayFormats* should be used to populate the generated records' `displayValues` map.
** For example, if running a query to present results to a user, this would generally need to be *true*.
But if running a query to provide data as part of a process, then this can generally be left as *false*.
* `queryJoins` - *List of QueryJoin objects* - Optional list of tables to be joined with the main *table* specified in the *QueryInput*.
* `shouldFetchHeavyFields` - *boolean, default: true* - Controls whether or not fields marked as `isHeavy` should be fetched & returned or not.
* `shouldOmitHiddenFields` - *boolean, default: true* - Controls whether or not fields marked as `isHidden` should be included in the result or not.
* `shouldMaskPassword` - *boolean, default: true* - Controls whether or not fields with `type` = `PASSWORD` should be masked, or if their actual values should be returned.
* `queryJoins` - *List of <<QueryJoin>> objects* - Optional list of tables to be joined with the main table being queried.
See QueryJoin below for further details.
==== QQueryFilter
A key component of *QueryInput*, a *QQueryFilter* defines both what records should be included in a query's results (e.g., an SQL `WHERE`), as well as how those results should be sorted (SQL `ORDER BY`).
A key component of *<<QueryInput>>*, a *QQueryFilter* defines both what records should be included in a query's results (e.g., an SQL `WHERE`), as well as how those results should be sorted (SQL `ORDER BY`).
* `criteria` - *List of QFilterCriteria* - Individual conditions or clauses to filter records.
* `criteria` - *List of <<QFilterCriteria>>* - Individual conditions or clauses to filter records.
They are combined using the *booleanOperator* specified in the *QQueryFilter*. See below for further details.
* `orderBys` - *List of QFilterOrderBy* - List of fields (and directions) to control the sorting of query results.
* `orderBys` - *List of <<QFilterOrderBy>>* - List of fields (and directions) to control the sorting of query results.
In general, multiple *orderBys* can be given (depending on backend implementations).
* `booleanOperator` - *Enum of AND, OR, default: AND* - Specifies the logical joining operator used among individual criteria.
* `subFilters` - *List of QQueryFilter* - To build arbitrarily complex queries, with nested boolean logic, 0 or more *subFilters* may be provided.
@ -69,7 +83,7 @@ In general, multiple *orderBys* can be given (depending on backend implementatio
)));
// which would generate the following WHERE clause in an RDBMS backend:
WHERE (first_name='James' AND last_name='Maes') OR (first_name='Darin' AND last_name='Kelkhoff')
// WHERE (first_name='James' AND last_name='Maes') OR (first_name='Darin' AND last_name='Kelkhoff')
----
===== QFilterCriteria
@ -79,19 +93,19 @@ In general, multiple *orderBys* can be given (depending on backend implementatio
* `operator` - *Enum of QCriteriaOperator, required* - Comparison operation to be applied to the field specified as *fieldName* and the *values* or *otherFieldName*.
** e.g., `EQUALS`, `NOT_IN`, `GREATER_THAN`, `BETWEEN`, `IS_BLANK`, etc.
* `values` - *List of values, conditional* - Provides the value(s) that the field is compared against.
The number of values (0, 1, 2, or more) be driven based on the *operator* being used.
The number of values (0, 1, 2, or more) required are based on the *operator* being used.
If an *otherFieldName* is given, and the *operator* expects 1 value, then *values* is ignored, and *otherFieldName* is used.
* `otherFieldName` - *String, conditional* - Specifies that the *fieldName* should be compared against another field in the records, rather than the values in the *values* property.
Only used for *operators* that expect 1 value (e.g., `EQUALS` or `LESS_THAN_OR_EQUALS` - not `IS_NOT_BLANK` or `IN`).
QFilterCriteria definition examples:
[source,java]
.QFilterCriteria definition examples:
----
// one-liners, via constructors that take (List<Serializable> values) or (Serializable... values) in 3rd position
new QFilterCriteria("id", IN, List.of(1, 2, 3))
// in-line, via constructors that take (List<Serializable> values) or (Serializable... values) as 3rd arg
new QFilterCriteria("id", IN, 1, 2, 3)
new QFilterCriteria("name", IS_BLANK)
new QFilterCriteria("orderNo", IN, orderNoList)
new QFilterCriteria("state", EQUALS, "MO");
new QFilterCriteria("state", EQUALS, "MO")
// long-form, with fluent setters
new QFilterCriteria()
@ -105,7 +119,7 @@ new QFilterCriteria()
.withOpeartor(QCriteriaOperator.EQUALS)
.withOtherFieldName("lastName");
// using otherFieldName to build a criterion that looks at two fields from join tables
// using otherFieldName to build a criterion that looks at two fields from two different join tables
new QFilterCriteria()
.withFieldName("billToCustomer.lastName")
.withOpeartor(QCriteriaOperator.NOT_EQUALS)
@ -118,9 +132,9 @@ new QFilterCriteria()
** Or, in the case of a query with *queryJoins*, a qualified name of a field from a join-table (where the qualifier would be the joined table's name or alias, followed by a dot)
* `isAscending` - *boolean, default: true* - Specify if the sort is ascending or descending.
QFilterCriteria definition examples:
[source,java]
.QFilterOrderBy definition examples:
----
// short-form, via constructors
new QFilterOrderBy("id") // isAscending defaults to true.
@ -129,7 +143,7 @@ new QFilterOrderBy("name", false)
// long-form, with fluent setters
new QFilterOrderBy()
.withFieldName("birthDate")
.withIsAscending(true);
.withIsAscending(false);
----
==== QueryJoin
@ -147,9 +161,8 @@ If given, must be used as the part before the dot in field name specifications t
If *true*, then the `QRecord` objects returned by this query will have values with corresponding to the (table-or-alias `.` field-name) form.
* `type` - *Enum of INNER, LEFT, RIGHT, FULL, default: INNER* - specifies the SQL-style type of join being performed.
QueryJoin definition examples:
[source,java]
.QueryJoin definition examples:
----
// selecting from an "orderLine" table - then join to its corresponding "order" table
queryInput.withTableName("orderLine");

View File

@ -1,27 +1,6 @@
<!--
~ QQQ - Low-code Application Framework for Engineers.
~ Copyright (C) 2021-2022. Kingsrook, LLC
~ 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
~ contact@kingsrook.com
~ https://github.com/Kingsrook/
~
~ This program is free software: you can redistribute it and/or modify
~ it under the terms of the GNU Affero General Public License as
~ published by the Free Software Foundation, either version 3 of the
~ License, 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 Affero General Public License for more details.
~
~ You should have received a copy of the GNU Affero General Public License
~ along with this program. If not, see <https://www.gnu.org/licenses/>.
-->
<style>
pre
.sect2 + .sect2
{
white-space: pre;
border-top: 1px solid #e7e7e9;
}
</style>

View File

@ -0,0 +1,406 @@
== TableSyncProcess
include::../variables.adoc[]
The `TableSyncProcess` is designed to help solve the common use-case where you have a set of records in one table,
you want to apply a transformation to them, and then you want them to result in records in a different table.
=== Sample Scenario
For example, you may be receiving an import file feed from a partner - say, a CSV file of order records
- that you need to synchronize into your local database's orders table.
=== High Level Steps
At a high-level, the steps of this task are:
1. Get the records from the partner's feed.
2. Decide Insert/Update - e.g., if you already have any of these orders in your database table, in which case, they need updated, versus ones
you don't have, which need inserted.
3. Map fields from the partner's order record to your own fields.
4. Store the necessary records in your database (insert or update).
=== What you need to tell QQQ
`TableSyncProcess`, as defined by QQQ, knows how to do everything for a job like this, other than the part that's unique to your business.
Those unique parts that you need to tell QQQ are:
* What are the source & destination tables?
* What are the criteria to identify source records to be processed?
* What are the key fields are that "link" together records from the source & destination tables?
** For the example above, imagine you have a "partnerOrderNo" field in your database's order table - then you'd need
to tell QQQ what field in the partner's table provides the value for that field in your table.
* How do fields / values from the source table map to fields & values in the destination table?
=== Detailed Steps
To get more specific, in a QQQ `TableSyncProcess`, here's what happens for each of the high-level steps given above:
* Getting records from the partner's feed (done by QQQ):
** Records from the source will be fetched via an Extract step, which runs a query to find the records that need processing.
** Depending on your use-case, you may use an `ExtractViaQueryStep` (maybe with a Table Automation) or `ExtractViaBasepullQueryStep`
(e.g., if you are polling a remote data source).
* Deciding Insert/Update (done by QQQ):
** Given a set of records from the source table (e.g., output of the Extract step mentioned above), get values from the "key" field in that table.
** Do a lookup in the destination table, where its corresponding "key" field has the values extracted from the source records.
** For each source record, if its "key" was found in the destination table, then plan an update to that existing corresponding
destination record; else, plan to insert a new record in the destination table.
* Mapping values (done by your custom Application code):
** Specifically, mapping is done in a subclass of `AbstractTableSyncTransformStep`, in the `populateRecordToStore` method.
Of particular interest are these two parameters to that method:
*** `QRecord destinationRecord` - as determined by the insert/update logic above, this will either be a
new empty record (e.g., for inserting), or a fully populated record from the destination table (for updating).
*** `QRecord sourceRecord` - this is the record being processed, from the source table.
** This method is responsible for setting values in the `destinationRecord`, and returning that record
(unless it has decided that for some reason the record should _not_ be stored, in which case it may return `null`).
* Storing the records (done by QQQ):
** This is typically done with the `LoadViaInsertOrUpdateStep`, though it is customizable if additional work is needed (e.g., via a
subclass of `LoadViaInsertOrUpdateStep`, or a more custom subclass of `AbstractLoadStep`).
=== Bare-bones Example
For this example, let's assume we're setting up a partner-order-feed as described above, with the following details:
* We have records from a partner in a table named `"partnerOrderImport"` (let's assume the records may have been created
using the QQQ `FilesystemImporter` process).
These records have the following fields:
** `orderNo, date, city, state, postal, whseNo`
* We need to synchronize those records with table in our database named `"order"`, with the following fields corresponding to those from the partner:
** `partnerOrderNo, orderDate, shipToCity, shipToState, shipToZipCode, warehouseId`
* The same conceptual order may appear in the `"partnerOrderImport"` multiple times, e.g., if they update some data on the order and re-transmit it to us.
Meaning, we need to update our `"order"` records when we receive a new version an existing order.
To use `*TableSyncProcess*` for solving this use-case, we'll need to create 2 things:
1. A `QProcessMetaData` object, which we can create using the builder object provided by class `TableSyncProcess`.
Note that this type of process is specialization of the standard QQQ `StreamedETLWithFrontendProcess`, as described elsewhere in this documentation.
2. A subclass of `AbstractTableSyncTransformStep`, where we implement our mapping logic.
Again, note that `AbstractTableSyncTransformStep` is a subclass of `AbstractTransformStep`, as used by `StreamedETLWithFrontendProcess`.
And to be good programmers, we'll actually create a 3rd thing:
[start=3]
. A unit test for our Transform step.
Here are examples of these pieces of code:
[source,java]
.Example of building process using the TableSyncProcess builder:
----
// the false argument below tells the build we are not a basepull-style process
QProcessMetaData processMetaData = TableSyncProcess.processMetaDataBuilder(false)
// give our process a unique name within our QInstance
.withName("partnerOrderToLocalOrderProcess")
// tell the process to what class to use for transforming records from source to destination
.withSyncTransformStepClass(PartnerOrderToOrderTransformStep.class)
.getProcessMetaData();
----
[source,java]
.Example implementation of an AbstractTableSyncTransformStep
----
public class PartnerOrderToOrderTransformStep extends AbstractTableSyncTransformStep
{
@Override
protected SyncProcessConfig getSyncProcessConfig()
{
return (new SyncProcessConfig(
"partnerOrderImport", // source tableName
"orderNo", // source table key fieldName
"order", // destination tableName
"partnerOrderNo" // destination table foreign key fieldName
));
}
@Override
public QRecord populateRecordToStore(RunBackendStepInput runBackendStepInput, QRecord destinationRecord, QRecord sourceRecord) throws QException
{
// map simple values from source table to destination table
destinationRecord.setValue("orderDate", sourceRecord.get("date"));
destinationRecord.setValue("shipToAddressCity", sourceRecord.get("city"));
destinationRecord.setValue("shipToAddressState", sourceRecord.get("state"));
destinationRecord.setValue("shipToAddressZipCode", sourceRecord.get("postal"));
return (destinationRecord);
}
}
----
[source,java]
.Example Unit Test for a transform step
----
@Test
void testTransformStep()
{
// insert 1 test order, that will be updated by the transform step
Integer existingId = new InsertAction().execute(new InsertInput("order").withRecords(List.of(
new QRecord().withValue("partnerOrderNo", 101).withValue("shipToState", "IL")
))).getRecords().get(0).getValueInteger("id");
// set up input for the step - a list of 2 of the partner's orders
RunBackendStepInput input = new RunBackendStepInput();
input.setRecords(List.of(
new QRecord().withValue("orderNo", 101).withValue("state", "NY"), // will update the order above
new QRecord().withValue("orderNo", 102).withValue("state", "CA") // will insert a new order
));
RunBackendStepOutput output = new RunBackendStepOutput();
// run the code under test - our transform step
new PartnerOrderToOrderTransformStep().run(input, output);
// Note that by just running the transform step, no records have been stored.
// We can assert against the output of this step.
assertEquals(existingId, output.getRecords().get(0).getValue("id"));
assertEquals(101, output.getRecords().get(0).getValue("partnerOrderNo"));
assertEquals("NY", output.getRecords().get(0).getValue("shipToState"));
assertNull(output.getRecords().get(1).getValue("id"));
assertEquals(102, output.getRecords().get(1).getValue("partnerOrderNo"));
assertEquals("CA", output.getRecords().get(1).getValue("shipToState"));
}
@Test
void testFullProcess()
{
// todo! :)
}
----
=== Pseudocode process flow
Now that we've seen the bare-bones example, let's see an even more detailed breakdown of how a full `TableSyncProcess` works,
by looking at its 3 "ETL" steps in pseudocode:
==== ExtractStep (Producer Thread)
* Queries source table for records
** Often based on Table Automations (e.g., for all newly inserted records) or Basepull pattern (polling for new/updated records).
==== TransformStep (Consumer Thread)
* Receives pages of records from `ExtractStep` in the `run` method.
* Makes `sourceKeyList` by getting `sourceTableKeyField` values from the records.
* Calls `initializeRecordLookupHelper(runBackendStepInput, sourceRecordList)`
** Calls `getLookupsToPreLoad` to control which lookups are performed.
* Calls `getExistingRecordsByForeignKey(runBackendStepInput, destinationTableForeignKeyField, destinationTableName, sourceKeyList);`
** Calls `getExistingRecordQueryFilter(runBackendStepInput, sourceKeyList)` as part of querying the `destinationTable`
** Returns the output of `buildExistingRecordsMap(destinationTableForeignKeyField, queryOutput.getRecords())`
* foreach input record (from `sourceTable`):
** Calls `getExistingRecord(existingRecordsByForeignKey, destinationForeignKeyField, sourceKeyValue)`
** if an existing record was returned (and if the syncConfig says `performUpdates`), this record is set as `recordToStore`
** else if no existing record was returned (and if the syncConfig says `performInserts`), a new record is set as `recordToStore`
** else continue the foreach.
** call `populateRecordToStore(runBackendStepInput, recordToStore, sourceRecord)`
** if a record is returned it is added to the process step output (to be stored in the LoadStep)
==== LoadStep (Consumer Thread)
* Receives records from the output of the `TransformStep`.
* Inserts and/or Updates `destinationTable`, with records returned by `populateRecordToStore`
=== Additional Process Configuration Examples
The following examples show how to use additional settings in the `TableSyncProcess` builder.
==== UI
While a `TableSyncProcess` will often run via a schedule and/or automation, we may also want to allow users
to manually run it in a UI.
[source,java]
.Making our process available for a UI
----
QProcessMetaData processMetaData = TableSyncProcess.processMetaDataBuilder(true)
.withName("partnerOrderToLocalOrderProcess")
.withSyncTransformStepClass(PartnerOrderToOrderTransformStep.class)
// attach our process to its source table, to show up in UI
.withTableName("partnerOrderImport")
// add some fields to display on the review screen, in UI
.withReviewStepRecordFields(List.of(
new QFieldMetaData("clientId", QFieldType.STRING).withLabel("Client"),
new QFieldMetaData("warehouseId", QFieldType.STRING).withLabel("Warehouse"),
new QFieldMetaData("partnerOrderNo", QFieldType.STRING)))
.getProcessMetaData();
----
==== Basepull
The previous example would work as a Table Automation (e.g., where the list of records identified in the
Extract step were determined by the Automation system).
However, a second common pattern is to use `Basepull` (e.g., if polling for updated records from a partner API endpoint).
[source,java]
.Configuring our process as a Basepull
----
// the true argument below tells the build we ARE a basepull-style process
// this changes the default extract-step.
QProcessMetaData processMetaData = TableSyncProcess.processMetaDataBuilder(false)
.withName("partnerOrderToLocalOrderProcess")
.withSyncTransformStepClass(PartnerOrderToOrderTransformStep.class)
// See Basepull documentation for details
.withBasepullConfiguration(new BasepullConfiguration())
// schedule our process to run automatically every minute
.withSchedule(new QScheduleMetaData().withRepeatSeconds(60))
.getProcessMetaData();
----
=== Additional Options in the Transform Step
==== Specifying to not perform Inserts or not perform Updates
We may have a scenario where we want our sync process to never update records if the key is already found in the destination table.
We can configure this with an additional optional parameter to the `SyncProcessConfig` constructor:
[source,java]
.Specifying to not do updates in a TableSyncProcess
----
@Override
protected SyncProcessConfig getSyncProcessConfig()
{
return (new SyncProcessConfig("partnerOrderImport", "orderNo", "order", "partnerOrderNo",
true, // performInserts
false // performUpdates
));
}
----
Similarly, we may want to disallow inserts from a particular sync process.
The `performInserts` argument to the `SyncProcessConfig` constructor lets us do that:
[source,java]
.Specifying to not do inserts in a TableSyncProcess
----
@Override
protected SyncProcessConfig getSyncProcessConfig()
{
return (new SyncProcessConfig("partnerOrderImport", "orderNo", "order", "partnerOrderNo",
false, // performInserts
true // performUpdates
));
}
----
==== Customizing the query for existing records
In some cases, a specific Table Sync process may need to refine the query filter that is used
to lookup existing records in the destination table (e.g. for determining insert vs. update).
For example, in our orders-from-a-partner scenario, if we have more than 1 partner sending us orders,
where there could be overlapping orderNo values among them - we may have an additional field in our
orders table to identify which partner an order came from.
So then when we're looking up orders by `partnerOrderNo`, we would need to also include the `partnerId` field
in our query, so that we only update orders from the specific partner that we're dealing with.
To do this (to customize the existing record query filter), we need can just override the method `getExistingRecordQueryFilter`.
Generally we would start by calling the `super` version of the method, and then add to it additional criteria.
[source,java]
.Customizing the query filter used to look for existing records
----
/*******************************************************************************
** Define the query filter to find existing records. e.g., for determining
** insert vs. update. Subclasses may override this to customize the behavior,
** e.g., in case an additional field is needed in the query.
*******************************************************************************/
protected QQueryFilter getExistingRecordQueryFilter(RunBackendStepInput runBackendStepInput, List<Serializable> sourceKeyList)
{
QQueryFilter filter = super.getExistingRecordQueryFilter(runBackendStepInput, sourceKeyList);
filter.addCriteria(new QFilterCriteria("partnerId", EQUALS, PARTNER_ID));
return (filter);
}
----
==== More efficient additional record lookups
It is a common use-case to need to map various ids from a partner's system to ids in your own system.
For the orders example, we might need to know what warehouse the order is shipping from.
The customer may send their identifier for the warehouse, and we may need to map those identifiers to our own warehouse ids.
The QQQ-provided class `RecordLookupHelper` exists to help with performing lookups like this,
and in particular, it can be used to execute one query to fetch a full table, storing records
by a key field, then returning those records without performing additional queries.
`AbstractTableSyncTransformStep` has a protected `recordLookupHelper` member.
If we override the method `getLookupsToPreLoad()`, then this object is
populated by calling its `preloadRecords` method with each specified pair of tableNames and fieldNames.
[source,java]
.Specifying tables to pre-load using a RecordLookupHelper
----
/*******************************************************************************
** Specify a list of tableName/keyColumnName pairs to run through
** the preloadRecords method of the recordLookupHelper.
*******************************************************************************/
@Override
protected List<Pair<String, String>> getLookupsToPreLoad()
{
return (List.of(
Pair.of("warehouse", "partnerWarehouseNo")
));
}
----
If we have preloaded some lookups, we can then use them in our `populateRecordToStore` method as follows:
[source,java]
.Using the recordLookupHelper in populateRecordToStore
----
// lookup warehouse with partnerWarehouseNo=whseNo from partner, and use our id in destination record
String partnerWarehouseNo = sourceRecord.getValue("whseNo");
Integer warehouseId = recordLookupHelper.getRecordId("warehouse", "partnerWarehouseNo", whseNo, Integer.class);
destinationRecord.setValue("warehouseId", warehouseId);
----
==== Additional override points
There are more methods which can be overridden in your `AbstractTableSyncTransformStep` subclass,
to provide further customizations of behaviors, specifically in the area of dealing with existing
records (e.g., the insert/update use-case).
[source,java]
.Additional AbstractTableSyncTransformStep overrides
----
/*******************************************************************************
** Run the existingRecordQueryFilter - to look in the destinationTable for
** any records that may need an update (rather than an insert).
**
** Generally returns a Map, keyed by a Pair of the destinationTableForeignKeyField
** and the value in that field. But, for more complex use-cases, one can override
** the buildExistingRecordsMap method, to make different keys (e.g., if there are
** two possible destinationTableForeignKeyFields).
*******************************************************************************/
protected Map<Pair<String, Serializable>, QRecord> getExistingRecordsByForeignKey
(
RunBackendStepInput runBackendStepInput,
String destinationTableForeignKeyField,
String destinationTableName,
List<Serializable> sourceKeyList
) throws QException;
/*******************************************************************************
** Overridable point where you can, for example, keys in the existingRecordsMap
** with different fieldNames from the destinationTable.
**
** Note, if you're overriding this method, you'll likely also want & need to
** override getExistingRecord.
*******************************************************************************/
protected Map<Pair<String, Serializable>, QRecord> buildExistingRecordsMap
(
String destinationTableForeignKeyField,
List<QRecord> existingRecordList
);
/*******************************************************************************
** Given the map of existingRecordsByForeignKey (as built by
** getExistingRecordsByForeignKey which calls buildExistingRecordsMap),
** get one record from that map, for a given key-value from a source record.
**
** The destinationForeignKeyField is given as advice if needed (e.g., to see its type)
*******************************************************************************/
protected QRecord getExistingRecord
(
Map<Pair<String, Serializable>, QRecord> existingRecordsByForeignKey,
QFieldMetaData destinationForeignKeyField,
Serializable sourceKeyValue
);
----

View File

@ -1,17 +1,63 @@
= QQQ
:doctype: book
:doctype: article
:toc: left
:toclevels: 2
:source-highlighter: coderay
include::Introduction.adoc[leveloffset=+1]
== Meta Data
include::metaData/Tables.adoc[leveloffset=+1]
''''
include::metaData/Reports.adoc[leveloffset=+1]
// Organizational units
include::metaData/QInstance.adoc[leveloffset=+1]
include::metaData/Backends.adoc[leveloffset=+1]
include::metaData/Apps.adoc[leveloffset=+1]
== Actions
// Primary meta-data types
include::metaData/Tables.adoc[leveloffset=+1]
include::metaData/Processes.adoc[leveloffset=+1]
include::metaData/Widgets.adoc[leveloffset=+1]
// Helper meta-data types
include::metaData/Fields.adoc[leveloffset=+1]
include::metaData/PossibleValueSources.adoc[leveloffset=+1]
include::metaData/Joins.adoc[leveloffset=+1]
include::metaData/SecurtiyKeyTypes.adoc[leveloffset=+1]
include::metaData/Reports.adoc[leveloffset=+1]
include::metaData/Icons.adoc[leveloffset=+1]
include::metaData/PermissionRules.adoc[leveloffset=+1]
== Custom Application Code
include::misc/QContext.adoc[leveloffset=+1]
include::misc/QRecords.adoc[leveloffset=+1]
include::misc/QRecordEntities.adoc[leveloffset=+1]
include::misc/ProcessBackendSteps.adoc[leveloffset=+1]
=== Table Customizers
#todo#
== QQQ Core Actions
include::actions/QueryAction.adoc[leveloffset=+1]
''''
include::actions/RenderTemplateAction.adoc[leveloffset=+1]
''''
include::actions/GetAction.adoc[leveloffset=+1]
=== CountAction
#todo#
=== AggregateAction
#todo#
include::actions/InsertAction.adoc[leveloffset=+1]
=== UpdateAction
#todo#
=== DeleteAction
#todo#
=== AuditAction
#todo#
== QQQ Default Implementations
include::implementations/TableSync.adoc[leveloffset=+1]
// later... include::actions/RenderTemplateAction.adoc[leveloffset=+1]

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

92
docs/metaData/Apps.adoc Normal file
View File

@ -0,0 +1,92 @@
[#Apps]
== Apps
include::../variables.adoc[]
QQQ User Interfaces (e.g., Material Dashboard) generally organize their contents via *Apps*.
Apps are a lightweight construct in QQQ - basically just containers for other objects.
Specifically, Apps can contain:
* {link-widgets}
* {link-tables}
* {link-process}
* {link-reports}
* Other {link-apps} - to create a multi-tiered navigational hierarchy.
=== QAppMetaData
Apps are defined in a QQQ Instance in `*QAppMetaData*` objects. Apps must consist of either 1 or more {link-widgets}, or 1 or more *Sections*, which are expected to contain 1 or more {link-tables}, {link-processes}, or {link-reports}.
*QAppMetaData Properties:*
* `name` - *String, Required* - Unique name for the app within the QQQ Instance.
* `label` - *String* - User-facing label for the app, presented in User Interfaces.
Inferred from `name` if not set.
* `permissionRules` - *QPermissionRules* - Permissions to apply to the app. See {link-permissionRules} for details.
* `children` - *List of QAppChildMetaData* - Objects contained within the app. These can be {link-tables}, {link-processes}, {link-reports} or other {link-apps}.
** See the example below for some common patterns for how these child-meta data objects are added to an App.
* `parentAppName` - *String* - For an app which is a child of another app, the parent app's name is referenced in this field.
** Note that this is generally automatically set when the child is added to its parent, in the `addChild` method.
* `icon` - *QIcon* - An icon to display in a UI for the app. See {link-icons}.
* `widgets` - *List of String* - A list of names of {link-widgets} to include in the app.
* `sections` - *List of <<QAppSection>>* - A list of `QAppSection` objects, to create organizational subdivisions within the app.
** As shown in the example below, the method `withSectionOfChildren` can be used to fluently add a new `QAppSection`, along with its child objects, to both an app and a section all at once.
==== QAppSection
A `QAppSection` is an organizational subsection of a {link-app}.
* `name` - *String, Required* - Unique name for the section within its app.
* `label` - *String* - User-facing label for the section, presented in User Interfaces.
Inferred from `name` if not set.
* `icon` - *QIcon* - An icon to display in a UI for the section. See {link-icons}.
* `tables` - *List of String* - A list of names of {link-tables} to include in the section.
* `processes` - *List of String* - A list of names of {link-processes} to include in the section.
* `reports` - *List of String* - A list of names of {link-reports} to include in the section.
*Examples*
[source,java]
----
/*******************************************************************************
** Full example of constructing a QAppMetaData object.
*******************************************************************************/
public class ExampleAppMetaDataProducer extends MetaDataProducer<QAppMetaData>
{
/*******************************************************************************
** Produce the QAppMetaData
*******************************************************************************/
@Override
public QAppMetaData produce(QInstance qInstance) throws QException
{
return (new QAppMetaData()
.withName("sample")
.withLabel("My Sample App")
.withIcon(new QIcon().withName("thumb_up"))
.withWidgets(List.of(
UserWelcomeWidget.NAME,
SystemHealthLineChartWidget.NAME))
.withSectionOfChildren(new QAppSection().withName("peoplePlacesAndThings"),
qInstance.getTable(People.TABLE_NAME),
qInstance.getTable(Places.TABLE_NAME),
qInstance.getTable(Things.TABLE_NAME),
qInstance.getProcess(AssociatePeopleWithPlacesProcess.NAME))
.withSectionOfChildren(new QAppSection().withName("math").withLabel("Mathematics"),
qInstance.getProcess(ComputePiProcess.NAME),
qInstance.getReport(PrimeNumbersReport.NAME),
qInstance.getReport(PolygonReport.NAME)));
}
/*******************************************************************************
** Since this meta-data producer expects to find other meta-data objects in the
** QInstance, give it a sortOrder higher than the default (which we'll expect
** the other objects used).
*******************************************************************************/
@Override
public int getSortOrder()
{
return (Integer.MAX_VALUE);
}
}
----

150
docs/metaData/Backends.adoc Normal file
View File

@ -0,0 +1,150 @@
[#Backends]
== Backends
include::../variables.adoc[]
A key component of QQQ is its ability to connect to various backend data stores, while providing the same interfaces to those backends - both User Interfaces, and Programming Interfaces.
For example, out-of-the-box, QQQ can connect to:
* <<RDBMSBackendMetaData,RDBMS>> (Relational Database Management Systems, such as MySQL)
* File Systems (<<S3BackendMetaData,Amazon S3>> or <<FilesystemBackendMetaData,local disk>>)
* <<APIBackendMetaData,JSON Web APIs>> (_using a custom mapping class per-API backend_).
* In-Memory data stores
All {link-tables} in a QQQ instance must belong to a backend. As such, any instance using tables (which would be almost all instances) must define 1 or more backends.
=== QBackendMetaData
Backends are defined in a QQQ Instance in a `*QBackendMetaData*` object.
These objects will have some common attributes, but many different attributes based on the type of backend being used.
*QBackendMetaData Properties:*
* `name` - *String, Required* - Unique name for the backend within the QQQ Instance.
* `backendType` - *String, Required* - Identifier for the backend type being defined.
** This attribute is typically set in the constructor of a `QBackendMetaData` subclass, and as such does not need to be set when defining a backend meta data object.
* `enabledCapabilities` and `disabledCapability` - *Sets*, containing *Capability* enum values.
Basic rules that apply to all tables in the backend, describing what actions (such as Delete, or Count) are supported in the backend.
** By default, QQQ assumes that a backend supports _most_ capabilities, with one exception being `QUERY_STATS`.
** #TODO# fully explain rules here
* `usesVariants` - *Boolean, default false* - Control whether or not the backend supports the concept of "Variants".
** Supporting variants means that tables within the backend can exist in alternative "variants" of the backend.
For example, this might mean a sharded or multi-tenant database backend (perhaps a different server or database name per-client).
Or this might mean using more than one set of credentials for connecting to an API backend - each of those credential sets would be a "variant".
** A backend that uses variants requires additional properties to be set. #TODO complete variant documentation#
In a QQQ application, one will typically not create an instance of `QBackendMetaData` directly, but instead will create an instance of one of its subclasses, specific to the type of backend being used.
The currently available list of such classes are:
==== RDBMSBackendMetaData
The meta data required for working with tables in an RDBMS (relational database) backend are defined in an instance of the `*RDBMSBackendMetaData*` class.
*RDBMSBackendMetaData Properties:*
* `vendor` - *String, Required* - Database vendor. Currently supported values are: `aurora`, `mysql`, `h2`.
* `jdbcUrl` - *String, Optional* - Full JDBC URL for connecting to the database.
** If this property is provided, then following properties (which are the components of a JDBC URL) are ignored.
In other words, you can either provide the `jdbcUrl`, or the individual components that make it up.
* `hostName` - *String, Conditionally Required* - Hostname or ip address of the RDBMS server.
* `port` - *Integer, Conditionally Required* - Port used to connect to the RDBMS server.
* `databaseName` - *String, Conditionally Required* - Name of the database being connected to, within the RDBMS server.
* `username` - *String, Conditionally Required* - Username for authenticating in the database server.
* `password` - *String, Conditionally Required* - Password for authenticating in the database server.
*Examples*
[source,java]
----
/*******************************************************************************
** Full example of constructing an RDBMSBackendMetaData
*******************************************************************************/
public class ExampleDatabaseBackendMetaDataProducer extends MetaDataProducer<QBackendMetaData>
{
public static final String NAME = "rdbmsBackend";
/*******************************************************************************
** Produce the QBackendMetaData
*******************************************************************************/
@Override
public QBackendMetaData produce(QInstance qInstance)
{
///////////////////////////////////////////////////////////////////////
// read settings from either a .env file or the system's environment //
///////////////////////////////////////////////////////////////////////
QMetaDataVariableInterpreter interpreter = new QMetaDataVariableInterpreter();
String vendor = interpreter.interpret("${env.RDBMS_VENDOR}");
String hostname = interpreter.interpret("${env.RDBMS_HOSTNAME}");
String port = interpreter.interpret("${env.RDBMS_PORT}");
String databaseName = interpreter.interpret("${env.RDBMS_DATABASE_NAME}");
String username = interpreter.interpret("${env.RDBMS_USERNAME}");
String password = interpreter.interpret("${env.RDBMS_PASSWORD}");
return (new RDBMSBackendMetaData()
.withName(NAME)
.withVendor(vendor)
.withHostName(hostname)
.withPort(ValueUtils.getValueAsInteger(port))
.withDatabaseName(databaseName)
.withUsername(username)
.withPassword(password)
.withCapability(Capability.QUERY_STATS));
}
}
----
==== S3BackendMetaData
The meta data required for working with tables in an Amazon S3 backend are defined in an instance of the `*S3BackendMetaData*` class.
*S3BackendMetaData Properties:*
* `bucketName` - *String, Required* - Bucket name to connect to inside AWS S3.
* `accessKey` - *String, Required* - Access key for connecting to S3 inside AWS S3.
* `secretKey` - *String, Required* - Secret key for connecting to S3 inside AWS S3.
* `region` - *String, Required* - AWS region containing the Bucket in S3.
* `basePath` - *String, Required* - Base path to the files within the S3 bucket.
==== FilesystemBackendMetaData
The meta data required for working with tables in a (local) filesystem backend are defined in an instance of the `*FilesystemBackendMetaData*` class.
*FilesystemBackendMetaData Properties:*
* `basePath` - *String, Required* - Base path to the backend's files.
==== APIBackendMetaData
The meta data required for working with tables in a web API are defined in an instance of the `*APIBackendMetaData*` class.
QQQ provides a minimal, reasonable default implementation for working with web APIs, making assumptions such as using `POST` to insert records, and `GET` with a primary key in the URL to get a single record.
However, in our experience, almost all APIs are implemented differently enough, that a layer of custom code is required.
For example, query/search endpoints are almost always unique in how they take their search parameters, and how they wrap their output.
To deal with this, a QQQ API Backend can define a custom class in the `actionUtil` property of the backend meta-data, as a subclass of `BaseAPIActionUtil`, which ideally can override methods at the level where unique functionality is needed.
For example, an application need not define the full method for executing a Query against an API backend (which would need to make the HTTP request (actually multiple, to deal with pagination)).
Instead, one can just override the `buildQueryStringForGet` method, where the unique details of making the request are defined, and maybe the `jsonObjectToRecord` method, where records are mapped from the API's response to a QRecord.
#todo - full reference and examples for `BaseAPIActionUtil`#
*APIBackendMetaData Properties:*
* `baseUrl` - *String, Required* - Base URL for connecting to the API.
* `contentType` - *String, Required* - value of `Content-type` header included in all requests to the API.
* `actionUtil` - *QCodeReference, Required* - Reference to a class that extends `BaseAPIActionUtil`, where custom code for working with this API backend is defined.
* `customValues` - *Map of String → Serializable* - Application-defined additional name=value pairs that can
* `authorizationType` - *Enum, Required* - Specifies how authentication is provided for the API.
The value here, dictates which other authentication-related properties are required.
Possible values are:
** `API_KEY_HEADER` - Uses the `apiKey` property in an HTTP header named `API-Key`.
_In the future, when needed, QQQ will add a property, tentatively named `apiKeyHeaderName`, to allow customization of this header name._
** `API_TOKEN` - Uses the `apiKey` property in an `Authroization` header, as: `"Token " + apiKey`
** `BASIC_AUTH_API_KEY` - Uses the `apiKey` property, Base64-encoded, in an `Authroization` header, as `"Basic " + base64(apiKey)`
** `BASIC_AUTH_USERNAME_PASSWORD` - Combines the `username` and `password` properties, Base64-encoded, in an `Authroization` header, as `"Basic " + base64(username + ":" + password)`
** `OAUTH2` - Implements an OAuth2 client credentials token grant flow, using the properties `clientId` and `clientSecret`.
By default, the id & secret are sent as query-string parameters to the API's `oauth/token` endpoint.
Alternatively, if the meta-data has a `customValue` of `setCredentialsInHeader=true`, then the id & secret are posted in an `Authorization` header (base-64 encoded, and concatenated with `":"`).
** `API_KEY_QUERY_PARAM` - Uses the `apiKey` property as a query-string parameter, with its name taken from the `apiKeyQueryParamName` property.
** `CUSTOM` - Has a no-op implementation at the QQQ layer.
Assumes that an override of `protected void handleCustomAuthorization(HttpRequestBase request)` be implemented in the backend's `actionUtil` class.
This would be
* `apiKey` - *String, Conditional* - See `authorizationType` above for details.
* `clientId` - *String, Conditional* - See `authorizationType` above for details.
* `clientSecret` - *String, Conditional* - See `authorizationType` above for details.
* `username` - *String, Conditional* - See `authorizationType` above for details.
* `password` - *String, Conditional* - See `authorizationType` above for details.
* `apiKeyQueryParamName` - *String, Conditional* - See `authorizationType` above for details.

View File

@ -1,4 +1,5 @@
== QQQ Fields
[#Fields]
== Fields
include::../variables.adoc[]
QQQ Fields define

17
docs/metaData/Joins.adoc Normal file
View File

@ -0,0 +1,17 @@
[#Joins]
== Joins
include::../variables.adoc[]
#TODO#
=== QJoinMetaData
Joins are defined in a QQQ Instance in a `*QJoinMetaData*` object.
#TODO#
*QJoinMetaData Properties:*
* `name` - *String, Required* - Unique name for the join within the QQQ Instance. #todo infererences or conventions?#
#TODO#

View File

@ -0,0 +1,17 @@
[#PossibleValueSources]
== Possible Value Sources
include::../variables.adoc[]
#TODO#
=== QPossibleValueSource
A Possible Value Source is defined in a QQQ Instance in a `*QPossibleValueSource*` object.
#TODO#
*QPossibleValueSource Properties:*
* `name` - *String, Required* - Unique name for the possible value source within the QQQ Instance.
#TODO#

View File

@ -0,0 +1,216 @@
[#Processes]
== Processes
include::../variables.adoc[]
Besides {link-tables}, the other most common type of object in a QQQ Instance is the Process.
Processes are "custom" actions (e.g., defined by the application developers, rather than QQQ) that users and/or the system can execute against records.
Processes generally are made up of two types of sub-objects:
* *Screens* - i.e., User Interfaces (e.g., for gathering input and/or showing output).
* *BackendSteps* - Java classes (of type `BackendStep`) that execute the logic of the process.
=== QProcessMetaData
Processes are defined in a QQQ Instance in a `*QProcessMetaData*` object.
In addition to directly building a `QProcessMetaData` object setting its properties directly, there are a few common process patterns that provide *Builder* objects for ease-of-use.
See StreamedETLWithFrontendProcess below for a common example
*QProcessMetaData Properties:*
* `name` - *String, Required* - Unique name for the process within the QQQ Instance.
* `label` - *String* - User-facing label for the process, presented in User Interfaces.
Inferred from `name` if not set.
* `icon` - *QIcon* - Icon associated with this process in certain user interfaces.
See {link-icons}.
* `tableName` - *String* - Name of a {link-table} that the process is associated with in User Interfaces (e.g., Action menu).
* `isHidden` - *Boolean, default false* - Option to hide the process from all User Interfaces.
* `basepullConfiguration` - *<<BasepullConfiguration>>* - config for the common "Basepull" pattern, of identifying records with a timestamp greater than the last time the process was ran.
See below for details.
* `permissionRules` - *QPermissionRules object* - define the permission/access rules for the process.
See {link-permissionRules} for details.
* `steps` and `stepList` - *Map of String → <<QStepMetaData>>* and *List of QStepMetaData* - Defines the <<QFrontendStepMetaData,screens>> and <<QBackendStepMetaData,backend code>> that makes up the process.
** `stepList` is the list of steps in the order that they will by default be executed.
** `steps` is a map, including all steps from `stepList`, but which may also include steps which can used by the process if its backend steps make the decision to do so, at run-time.
** A process's steps are normally defined in one of two was:
*** 1) by a single call to `.withStepList(List<QStepMetaData>)`, which internally adds each step into the `steps` map.
*** 2) by multiple calls to `.addStep(QStepMetaData)`, which adds a step to both the `stepList` and `steps` map.
** If a process also needs optional steps, they should be added by a call to `.addOptionalStep(QStepMetaData)`, which only places them in the `steps` map.
* `schedule` - *<<QScheduleMetaData>>* - set up the process to run automatically on the specified schedule.
See below for details.
* `minInputRecords` - *Integer* - #not used...#
* `maxInputRecords` - *Integer* - #not used...#
#todo: supplementalMetaData (API)#
==== QStepMetaData
This is the base class for the two types of steps in a process - <<QFrontendStepMetaData,screens>> and <<QBackendStepMetaData,backend code>>.
There are some shared attributes of both of them, defined here.
*QStepMetaData Properties:*
* `name` - *String, Required* - Unique name for the step within the process.
* `label` - *String* - User-facing label for the step, presented in User Interfaces.
Inferred from `name` if not set.
* `stepType` - *String* - _Deprecated._
==== QFrontendStepMetaData
For processes with a user-interface, they must define one or more "screens" in the form of `QFrontendStepMetaData` objects.
*QFrontendStepMetaData Properties:*
* `components` - *List of <<QFrontendComponentMetaData>>* - a list of components to be rendered on the screen.
* `formFields` - *List of String* - list of field names used by the screen as form-inputs.
* `viewFields` - *List of String* - list of field names used by the screen as visible outputs.
* `recordListFields` - *List of String* - list of field names used by the screen in a record listing.
==== QFrontendComponentMetaData
A screen in a process may consist of multiple "components" - e.g., help text, and a form, and a list of records.
Each of these components are defined in a `QFrontendComponentMetaData`.
*QFrontendComponentMetaData Properties:*
* `type` - *enum, Required* - The type of component to display.
Each component type works with different keys in the `values` map.
Possible values for `type` are:
** `EDIT_FORM` - Displays a list of fields for editing, similar to a record edit screen.
Requires that `formFields` be populated in the step.
** `VIEW_FORM` - Displays a list of fields for viewing (not editing), similar to a record view screen.
Requires that `viewFields` be populated in the step.
** `HELP_TEXT` - Block of help text to be display on the screen.
Requires an entry in the component's `values` map named `"text"`.
** `HTML` - Block of custom HTML, generated by the process backend.
Expects a process value named `html`.
** `DOWNLOAD_FORM` - Presentation of a link to download a file generated by the process.
Expects process values named `downloadFileName` and `serverFilePath`.
** `GOOGLE_DRIVE_SELECT_FOLDER` - Special form that presents a UI from Google Drive, where the user can select a folder (e.g., as a target for uploading files in a subsequent backend step).
** `BULK_EDIT_FORM` - For use by the standard QQQ Bulk Edit process.
** `VALIDATION_REVIEW_SCREEN` - For use by the QQQ Streamed ETL With Frontend process family of processes.
Displays a component prompting the user to run full validation or to skip it, or, if full validation has been ran, then showing the results of that validation.
** `PROCESS_SUMMARY_RESULTS` - For use by the QQQ Streamed ETL With Frontend process family of processes.
Displays the summary results of running the process.
** `RECORD_LIST` - _Deprecated.
Showed a grid with a list of records as populated by the process._
* `values` - *Map of String → Serializable* - Key=value pairs, with different expectations based on the component's `type`.
See above for details.
==== QBackendStepMetaData
Process Backend Steps are where custom (at this time, Java, but in the future, potentially, from any supported language) code is executed, to provide the logic of the process.
QQQ comes with several common backend steps, such as for extracting lists of records, storing lists of records, etc.
*QBackendStepMetaData Properties:*
* `code` - *QCodeReference, Required* - Reference to the code to be executed for the step.
The referenced code must implement the `BackendStep` interface.
* `inputMetaData` - *QFunctionInputMetaData* - Definition of the data that the backend step expects and/or requires.
Sub-properties are:
** `fieldList` - *List of {link-fields}* - Optional list of fields used by the process step.
In general, a process does not _have to_ specify the fields that its steps use.
It can be used, however, for example, to cause a `defaultValue` to be applied to a field if it isn't specified in the process's input.
It can also be used to cause the process to throw an error, if a field is marked as `isRequired`, but a value is not present.
** `recordListMetaData` - *RecordListMetaData object* - _Not used at this time._
==== BasepullConfiguration
A "Basepull" process is a common pattern where an application needs to perform some action on all new (or updated) records from a particular data source.
To implement this pattern, one needs to store the timestamp of when the action runs, then query the source for records where a date-time field is after that timestamp.
QQQ helps facilitate this pattern by automatically retrieving and updating that timestamp field, and by building a default query filter based on that timestamp.
This is done by adding a `BasepullConfiguration` object to a process's meta-data.
*BasepullConfiguration Properties:*
* `tableName` - *String, Required* - Name of a {link-table} in the QQQ Instance where the basepull timestamps are stored.
* `keyField` - *String, Required* - Name of a {link-field} in the basepull table that stores a unique identifier for the process.
* `keyValue` - *String* - Optional value to be stored in the `keyField` of the basepull table as the unique identifier for the process.
If not set, then the process's `name` is used.
* `lastRunTimeFieldName` - *String, Required* - Name of a {link-field} in the basepull table that stores the last-run time for the process.
* `hoursBackForInitialTimestamp` - *Integer* - Optional number of hours to go back in time (from `now`) for the first time that the process is executed (i.e., if there is no timestamp stored in the basepull table).
* `timestampField` - *String, Required* - Name of a {link-field} in the table being queried against the last-run timestamp.
==== QScheduleMetaData
QQQ can automatically run processes using an internal scheduler, if they are configured with a `QScheduleMetaData` object.
*QScheduleMetaData Properties*
* `repeatSeconds` - *Integer, Conditional* - How often the process should be executed, in seconds.
* `repeatMillis` - *Integer, Conditional* - How often the process should be executed, in milliseconds.
Mutually exclusive with `repeatSeconds`.
* `initialDelaySeconds` - *Integer, Conditional* - How long between when the scheduler starts and the process should first run, in seconds.
* `initialDelayMillis` - *Integer, Conditional* - How long between when the scheduler starts and the process should first run, in milliseconds.
Mutually exclusive with `initialDelaySeconds`.
* `variantRunStrategory` - *enum, Conditional* - For processes than run against {link-tables} that use a {link-backend} with Variants enabled, this property controls if the various instances of the process should run in `PARALLEL` or in `SERIAL`.
* `variantBackend` - *enum, Conditional* - For processes than run against {link-tables} that use a {link-backend} with Variants enabled, this property specifies the name of the {link-backend}.
==== StreamedETLWithFrontendProcess
A common pattern for QQQ processes to exhibit is called the "Streamed ETL With Frontend" process pattern.
This pattern is to do an "Extract, Transform, Load" job on a potentially large set of records.
The records are Streamed through the process's steps, meaning, QQQ runs multiple threads - a producer, which is selecting records, and a consumer, which is processing records.
As such, in general, an unlimited number of records can be processed by a process, without worrying about exhausting server resources (e.g., OutOfMemory).
These processes also have a standard user-interface for displaying a summary of what the process will do (and has done), with a small number of records as a preview.
The goal of the summary is to give the user the big-picture of what the process will do (e.g., X records will be inserted; Y records will be updated), along with a small view of some details on the records that will be stored (e.g., on record A field B will be set to C).
This type of process uses 3 backend steps, and 2 frontend steps, as follows:
* *preview* (backend) - does just a little work (limited # of rows), to give the user a preview of what the final result will be - e.g., some data to seed the review screen.
* *review* (frontend) - a review screen, which after the preview step does not have a full process summary, but can generally tell the user how many records are input to the process, and can show a preview of a small number of the records.
* *validate* (backend) - optionally (per input on review screen), does like the preview step, but does it for all records from the extract step.
* *review* (frontend) - a second view of the review screen, if the validate step was executed.
Now that the full validation was performed, a full process summary can be shown, along with a some preview records.
* *execute* (backend) - processes all the rows - does all the work - stores data in the backend.
* *result* (frontend) - a result screen, showing a "past-tense" version of the process summary.
These backend steps are defined within QQQ, meaning they themselves do not execute any application-defined custom code.
Instead, these steps use the following secondary <<QBackendStepMetaData,backend steps>>:
* *Extract* - Fetch the rows to be processed.
Used by preview (but only for a limited number of rows), validate (without limit), and execute (without limit).
* *Transform* - Do whatever transformation is needed to the rows.
Done on preview, validate, and execute.
Always works with a page of records at a time.
Since it is called on the preview & validate steps, it should *NOT* ever store any data (unless it does a specific check to confirm that it is being used on an *execute* step).
* *Load* - Store the records into the backend, as appropriate.
Only called by the execute step.
Always works with a page of records at a time.
The meta-data for a `StreamedETLWithFrontendProcess` uses several input fields on its steps.
As such, it can be somewhat clumsy and error-prone to fully define a `StreamedETLWithFrontendProcess`.
To improve this programmer-interface, an inner `Builder` class exists within `StreamedETLWithFrontendProcess` (generated by a call to `StreamedETLWithFrontendProcess.processMetaDataBuilder()`).
*StreamedETLWithFrontendProcess.Builder methods:*
* `withName(String name) - Set the name for the process.
* `withLabel(String label) - Set the label for the process.
* `withIcon(QIcon icon)` - Set an {link-icon} to be display with the process in the UI.
* `withExtractStepClass(Class<? extends AbstractExtractStep>)` - Define the Extract step for the process.
If no special extraction logic is needed, `ExtractViaQuery.class` is often a reasonable default.
In other cases, `ExtractViaQuery` can be a reasonable class to extend for a custom extract step.
* `withTransformStepClass(Class<? extends AbstractTransformStep>)` - Define the Transform step for the process.
If no transformation logic is needed, `NoopTransformStep.class` can be used (though this is not very common).
* `withLoadStepClass(Class<? extends AbstractLoadStep>)` - Define the Load step for the process.
Several standard implementations exist, such as: `LoadViaInsertStep.class`, `LoadViaUpdateStep.class`, and `LoadViaDeleteStep.class`.
* `withTableName(String tableName)` - Specify the name of the {link-table} that the process should be associated with in the UI.
* `withSourceTable(String sourceTable)` - Specify the name of the {link-table} to be used as the source of records for the process.
* `withDestinationTable(String destinationTable)` - Specify the name of the {link-table} to be used as the destination for records from the process.
* `withSupportsFullValidation(Boolean supportsFullValidation)` - By default, all StreamedETLWithFrontendProcesses do allow the user to choose to run the full validation step.
However, in case cases it may not make sense to do so - so this method can be used to turn off that option.
* `withDoFullValidation(Boolean doFullValidation)` - By default, all StreamedETLWithFrontendProcesses will prompt the user if they want to run the full validation step or not.
However, in case cases you may want to enforce that the validation step always be executed.
Calling this method will remove the option from the user, and always run a full validation.
* `withTransactionLevelAutoCommit()`, `withTransactionLevelPage()`, and `withTransactionLevelProcess()` - Change the transaction-level used by the process.
By default, these processes are ran with a single transaction for all pages of their execute step.
But for some cases, doing page-level transactions can reduce long-transactions and locking within the system.
* `withPreviewMessage(String previewMessage)` - Sets the message shown on the validation review screen(s) above the preview records.
* `withReviewStepRecordFields(List<QFieldMetaData> fieldList)` -
* `withFields(List<QFieldMetaData> fieldList)` - Adds additional input fields to the preview step of the process.
* `withBasepullConfiguration(BasepullConfiguration basepullConfiguration)` - Add a <<BasepullConfiguration>> to the process.
* `withSchedule(QScheduleMetaData schedule)` - Add a <<QScheduleMetaData>> to the process.

View File

@ -1,4 +1,5 @@
== QQQ Reports
[#Reports]
== Reports
include::../variables.adoc[]
QQQ can generate reports based on {link-tables} defined within a QQQ Instance.

View File

@ -0,0 +1,17 @@
[#SecurityKeyTypes]
== Security Key Types
include::../variables.adoc[]
#TODO#
=== QSecurityKeyType
A Security Key Type is defined in a QQQ Instance in a `*QSecurityKeyType*` object.
#TODO#
*QSecurityKeyType Properties:*
* `name` - *String, Required* - Unique name for the security key type within the QQQ Instance.
#TODO#

View File

@ -1,15 +1,16 @@
== QQQ Tables
[#Tables]
== Tables
include::../variables.adoc[]
The core type of object in a QQQ Instance is the Table.
One of the most common types of object in a QQQ Instance is the Table.
In the most common use-case, a QQQ Table may be the in-app representation of a Database table.
That is, it is a collection of records (or rows) of data, each of which has a set of fields (or columns).
QQQ also allows other types of data sources ({link-backends}) to be used as tables, such as File systems, API's, Java enums or objects, etc.
QQQ also allows other types of data sources ({link-backends}) to be used as tables, such as File systems, API's, etc.
All of these backend types present the same interfaces (both user-interfaces, and application programming interfaces), regardless of their backend type.
=== QTableMetaData
Tables are defined in a QQQ Instance in a `*QTableMetaData*` object.
Tables are defined in a QQQ Instance in `*QTableMetaData*` objects.
All tables must reference a {link-backend}, a list of fields that define the shape of records in the table, and additional data to describe how to work with the table within its backend.
*QTableMetaData Properties:*
@ -19,14 +20,37 @@ All tables must reference a {link-backend}, a list of fields that define the sha
Inferred from `name` if not set.
* `backendName` - *String, Required* - Name of a {link-backend} in which this table's data is managed.
* `fields` - *Map of String → {link-field}, Required* - The columns of data that make up all records in this table.
* `primaryKeyField` - *String, Conditional* - Name of a {link-field} that serves as the primary key (e.g., unique identifier) for records in this table.
* `uniqueKeys` - *List of UniqueKey* - Definition of additional unique constraints (from an RDBMS point of view) from the table.
* `primaryKeyField` - *String, Conditional* - Name of a {link-field} that serves as the primary key (unique identifier) for records in this table.
** Whether a primary key field is required or not depends on the backend type that the table belongs to.
* `uniqueKeys` - *List of UniqueKey* - Definition of additional unique keys or constraints (from an RDBMS point of view) from the table.
e.g., sets of columns which must have unique values for each record in the table.
The properties of the `UniqueKey` object are:
** `fieldNames` - *List of String, Required* - List of field names from this table.
** `label` - *String* - Optional label to be shown to users with error messages (e.g., for violation of this unique key).
* `backendDetails` - *QTableBackendDetails or subclass* - Additional data to configure the table within its {link-backend}.
* `automationDetails` - *QTableAutomationDetails* - Configuration of automated jobs that run against records in the table, e.g., upon insert or update.
** For example, for an RDBMS-type backend, the name of the table within the database.
** vs. a FileSystem backend, this may be the sub-path where files for the table are stored.
** #todo - details on these#
* `automationDetails` - *<<QTableAutomationDetails>>* - Configuration of automated jobs that run against records in the table, e.g., upon insert or update.
* `customizers` - *Map of String → QCodeReference* - References to custom code that are injected into standard table actions, that allow applications to customize certain parts of how the table works.
** Allowed values for keys in this map come from the `role` property of the `TableCustomizers` enum.
** Based on the key in this map, the `QCodeReference` used as the value must be of the appropriate java type, as specified in the `expectedType` property of the `TableCustomizers` enum value corresponding to the key.
** Example:
[source,java]
----
// in defining a QTableMetaData, a customizer can be added as:
.withCustomizer(TableCustomizers.PRE_INSERT_RECORD, new QCodeReference(MyPreInsCustomizer.class))
// where MyPreInsCustomizer would be defined as:
public class MyPreInsCustomizer extends AbstractPreInsertCustomizer
----
* `isHidden` - *Boolean, default false* - Option to hide the table from all User Interfaces.
* `parentAppName` - *String* - Name of a {link-app} that this table exists within.
* `icon` - *QIcon* - Icon associated with this table in certain user interfaces.
** This field generally does not need to be set on the table when it is defined, but rather, is set when the table gets placed within an app.
* `icon` - *QIcon* - Icon associated with this table in certain user interfaces. See {link-icons}.
* `recordLabelFormat` - *String* - Java Format String, used with `recordLabelFields` to produce a label shown for records from the table.
* `recordLabelFields` - *List of String, Conditional* - Used with `recordLabelFormat` to provide values for any format specifiers in the format string.
These strings must be field names within the table.
@ -42,8 +66,181 @@ new QFieldMetaData("birthDate", QFieldType.DATE)
.withRecordLabelFormat("%s (%s)")
.withRecordLabelFields(List.of("name", "birthDate"))
----
* `sections` - *List of QFieldSection* - Mechanism to organize fields within user interfaces, into logical sections.
* `sections` - *List of <<QFieldSection>>* - Mechanism to organize fields within user interfaces, into logical sections.
If any sections are present in the table meta data, then all fields in the table must be listed in exactly 1 section.
If no sections are defined, then instance enrichment will define default sections.
* `associatedScripts` - *List of AssociatedScript* - Definition of user-defined scripts that can be associated with records within the table.
* `associatedScripts` - *List of <<AssociatedScript>>* - Definition of user-defined scripts that can be associated with records within the table.
* `enabledCapabilities` and `disabledCapabilities` - *Set of Capability enum values* - Overrides from the backend level, for capabilities that this table does or does not possess.
* `associations` - *List of <<Association>>* - tables whose records can be managed along with records from this table. See below for details.
* `recordSecurityLocks` - *List of <<RecordSecurityLock>>* - locks that apply to records in the table - e.g., to control what users can or cannot access records in the table.
See RecordSecurityLock below for details.
* `permissionRules` - *QPermissionRules object* - define the permission/access rules for the table.
See {link-permissionRules} for details.
* `auditRules` - *<<QAuditRules>> object* - define the audit rules for the table.
See QAuditRules below for details.
* `cacheOf` - *<<CacheOf>> object* - specify that this table serves as a "cache of" another table.
See CacheOf object below for details.
* `exposedJoins` - *List of <<ExposedJoin>> objects* - optional list of joined tables that are to be exposed in User Interfaces.
See ExposedJoin object below for details.
#todo: supplementalMetaData (API)#
==== QFieldSection
When users view records from a QQQ Table in a UI, fields are organized on the screen based on the `QFieldSection` objects in the table's meta-data.
*QFieldSection Properties:*
* `name` - *String, Required* - unique identifier for the section within its table.
* `label` - *String* - User-facing label for the section, presented in User Interfaces.
Inferred from `name` if not set.
* `tier` - *enum* - importance of the fields in section for the table.
Different tiers may be presented differently in UI's.
Only a single `T1` section is allowed per-table. Possible values are: `T1`, `T2`, and `T3`.
* `icon` - *QIcon* - Icon associated with this section in certain user interfaces. See {link-icons}.
* `isHidden` - *Boolean, default false* - Option to hide the table from all User Interfaces.
* `gridColumns` - *Integer* - Option to specify how many columns in a grid layout the section should use.
For the Material-Dashboard frontend, this is a grid of 12.
* `fieldNames` - *List of String, Conditional* - List of names of {link-fields} from this table to be included in this section.
* `widgetName` - *String, Conditional* - Name of a {link-widget} to be displayed in this section.
** Note that exactly one of `fieldNames` or `widgetName` must be used.
==== QTableAutomationDetails
Records in QQQ can have application-defined custom actions automatically asynchronously executed against them after they are inserted or updated.
The configuration to enable this functionality is assigned to a table in a `QTableAutomationDetails` object.
*QTableAutomationDetails Properties:*
* `statusTracking` - *AutomationStatusTracking object, Required* - define how QQQ should keep track, per record, its status (e.g., pending-insert-automations, running-update-automations, etc).
Properties of `AutomationStatusTracking` object are:
** `type` - *enum, Required* - what type of tracking is used for the table.
Possible values are:
*** `FIELD_IN_TABLE` - specifies that the table has a field which stores an `AutomationStatus` id.
*** _Additional types may be defined in the future, such as ONE_TO_ONE_TABLE or SHARED_TABLE._
** `fieldName` - *String, Conditional* - for `type=FIELD_IN_TABLE`, this property specifies the name of the {link-field} in the table that stores the `AutomationStatus` id.
* `providerName` - *String, Required* - name of an Automation Provider within the QQQ Instance, which is responsible for running the automations on this table.
* `overrideBatchSize` - *Integer* - optional control over how many records from the table are processed in a single batch/page.
For tables with "slow" actions (e.g., one that may need to make an API call per-record), using a smaller batch size (say, 50) may be required to avoid timeout errors.
* `actions` - *List of TableAutomationAction* - list of the actions to perform on new and updated records in the table.
Properties are:
** `name` - *String, Required* - unique identifier for the action within its table.
** `triggerEvent` - *enum, Required* - indicate which event type (`POST_INSERT`, `POST_UPDATE`, or `PRE_DELETE` (which is not yet implemented)) the action applies to.
** `priority` - *Integer, default 500* - mechanism to control the order in which actions on a table are executed, if there are more than one.
Actions with a smaller value for `priority` are executed first. Ties are broken in an undefined manner.
** `filter` - *QQueryFilter* - optional filter that gets applied to records when they match the `triggerEvent`, to control which records have the action ran against them.
** `includeRecordAssociations` - *Boolean, default false* - for tables that have associations, control whether or not a record's associated records are loaded when records are fetched and passed into the action's custom code.
** `values` - *Map of String → Serializable* - optional application-defined map of name=value pairs that can be passed into the action's custom code.
** `processName` - *String, Conditional* - name of a {link-processes} in the QQQ Instance which is executed as the custom-code of the action.
** `codeReference` - *QCodeReference, Conditional* - reference to a class that extends `RecordAutomationHandler`, to be executed as the custom-code of the action.
*** Note, exactly one of `processName` or `codeReference` must be provided.
==== Association
An `Association` is a way to define a relationship between tables, that facilitates, for example, a parent record having a list of its child records included in it when it is returned from a Query.
Similarly, associated records can automatically be inserted/updated/deleted if they are included in a parent record when it is stored.
*Association Properties:*
* `name` - *String, Required* - unique name for the association within this table.
Used as the key in the `associatedRecords` map within `QRecord` objects for this table.
* `associatedTableName` - *String, Required* - name of a {link-table}, which is the associated table.
* `joinName` - *String, Required* - name of a {link-join} in the instance, which defines how the tables are joined.
==== RecordSecurityLock
A `RecordSecurityLock` is the mechanism through which users can be allowed or denied access to read and/or write records, based on values in the record, and values in the user's session.
Record security locks must correspond to a {link-securityKeyType}.
For example:
* An instance may have a security key type called `clientId`.
* Users may have 1 or more `clientId` values in their Session, or, they may have an "All Clients" key in their session (e.g., for internal/admin users).
* For some tables, it may be required to limit visibility to records based on a user's `clientId` key.
To do this. a *RecordSecurityLock* would be applied to the table, specifying the `clientId` field corresponds to the `clientId` security key.
* With these settings in place, QQQ will prevent users from viewing records from this table that do not have a matching key, and will similarly prevent users from writing records with an invalid key value.
** For example, in an RDBMS backend, all `SELECT` statements generated against such a table will have an implicit filter, such as `AND client_id = ?` based on the user's security key values.
*RecordSecurityLock Properties:*
* `securityKeyType` - *String, Required* - name of a {link-securityKeyType} in the Instance.
* `fieldName` - *String, Required* - name of a {link-field} in this table (or a joined table, if `joinNameChain` is set), where the value for the lock is stored.
* `joinNameChain` - *List of String* - if the lock value is not stored in this table, but rather comes from a joined table, then this property defines the path of joins from this table to the table with the lock field.
* `nullValueBehavior` - *enum, default: DENY* - control how records with a `null` value in the lock field should behave.
Possible values are:
** `DENY` - deny all users access to a record with a `null` value in the lock field (unless the user has an all-access key - see {link-securityKeyType})
** `ALLOW` - allow all users access to a record with a `null` value in the lock field.
** `ALLOW_WRITE_ONLY` - allow all users to write records with `null` in the lock field, but deny reads on records with `null` in the lock field (also excepted by all-access keys).
* `lockScope` - *enum, default: READ_AND_WRITE* - control what types of operations the lock applies to.
Possible values are:
** `READ_AND_WRITE` - control both reading and writing records based on the user having an appropriate security key.
** `WRITE` - allow all users to read the record, but limit writes to users with an appropriate security key.
==== QAuditRules
The audit rules on a table define the level of detail that is automatically stored in the audit table (if any) for DML actions (Insert, Update, Delete).
*QAuditRules Properties:*
* `auditLevel` - *enum, Required* - level of details that are audited.
Possible values are:
** `NONE` - no automatic audits are stored for the table.
** `RECORD` - only record-level audits are stored for the table (e.g., a message such as "record was edited", but without field-level details)
** `FIELD` - full field-level audits are stored (e.g., including all old & new values as audit details).
==== CacheOf
One QQQ Table can be defined as a "cache of" another QQQ Table by assigning a `CacheOf` object to the table which will function as the cache.
_Note, at this time, only limited use-cases are supported._
*CacheOf Properties:*
* `sourceTable` - *String, Required* - name of the other QQQ Table that is the source of data in this cache.
* `expirationSeconds` - *Integer* - optional number of seconds that a cached record is allowed to exist before it is considered expired, and must be re-fetched from the source table.
* `cachedDateFieldName` - *String, Conditional* - used with `expirationSeconds` to define the field in this table that is used for storing the timestamp for when the record was cached.
* `useCases` - *List of CacheUseCase* - what caching use-cases are to be implemented.
Properties of *CacheUseCase* are:
* `type` - *Enum, Required* - the type of use-case. Possible values are:
** `PRIMARY_KEY_TO_PRIMARY_KEY` - the primary key in the cache table equals the primary key in the source table.
** `UNIQUE_KEY_TO_PRIMARY_KEY` - a unique key in the cache table equals the primary key in the source table.
** `UNIQUE_KEY_TO_UNIQUE_KEY` - a unique key in the cache table equals a unique key in the source table.
* `cacheSourceMisses` - *Boolean, default false* - whether or not, if a "miss" happens in the source, if that fact gets cached.
* `cacheUniqueKey` - *UniqueKey, conditional* - define the fields in the cache table that define the unique key being used as the cache key.
* `sourceUniqueKey` - *UniqueKey, conditional* - define the fields in the source table that define the unique key being used as the cache key.
* `doCopySourcePrimaryKeyToCache` - *Boolean, default false* - specify whether or not the value of the primary key in the source table should be copied into records built in the cache table.
* `excludeRecordsMatching` - *List of QQueryFilter* - optional filter to be applied to records before they are cached.
If a record matches the filter, then it will not be cached.
==== ExposedJoin
Query screens in QQQ applications can potentially allow users to both display fields from joined tables, and filter by fields from joined tables, for any {link-join} explicitly defined as an *Exposed Join*.
_The reasoning why not all joins are implicitly exposed is that in many applications, the full join-graph can sometimes be overwhelming, surprisingly broad, and not necessarily practically useful.
This could be subject to change in the future, e.g., given a UI that allowed users to more explicitly add additional join tables..._
*ExposedJoin Properties:*
* `label` - *String, Required* - how the joined table should be presented in the UI.
* `joinTable` - *String, Required* - name of the QQQ Table that is joined to this table, and is being exposed as a join in the UI.
* `joinPath` - *List of String, Required* - names of 1 or more QQQ Joins that describe how to get from this table to the join table.
==== AssociatedScript
A QQQ Table can have end-user defined Script records associated with individual records in the table by use of the `associatedScripts` property of the table's meta-data.
The "types" of these scripts (e.g., how they are used in an application) are wholly application-designed & managed.
QQQ provides the mechanism for UI's to present and manage such scripts (e.g., the *Developer Mode* screen in the Material Dashboard), as well as an interface to load & execute such scripts `RunAssociatedScriptAction`).
*AssociatedScript Properties:*
* `fieldName` - *String, Required* - name of a {link-field} in the table which stores the id of the associated script record.
* `scriptTypeId` - *Serializable (typically Integer), Required* - primary key value from the `"scriptType"` table in the instance, to designate the type of the Script.
* `scriptTester` - *QCodeReference* - reference to a class which implements `TestScriptActionInterface`, that can be used by UI's for running an associated script to test it.

View File

@ -0,0 +1,17 @@
[#Widgets]
== Widgets
include::../variables.adoc[]
#TODO#
=== QWidgetMetaData
A Widget is defined in a QQQ Instance in a `*QWidgetMetaData*` object.
#TODO#
*QWidgetMetaData Properties:*
* `name` - *String, Required* - Unique name for the widget within the QQQ Instance.
#TODO#

View File

@ -1,13 +1,25 @@
ifdef::env-name[:relfilesuffix: .adoc]
:link-backend: link:Backends{relfilesuffix}[QQQ Backend]
:link-backends: link:Backends{relfilesuffix}[QQQ Backends]
:link-table: link:Tables{relfilesuffix}[QQQ Table]
:link-tables: link:Tables{relfilesuffix}[QQQ Tables]
:link-join: link:Joins{relfilesuffix}[QQQ Join]
:link-joins: link:Joins{relfilesuffix}[QQQ Joins]
:link-field: link:Fields{relfilesuffix}[QQQ Field]
:link-fields: link:Fields{relfilesuffix}[QQQ Fields]
:link-process: link:Processes{relfilesuffix}[QQQ Process]
:link-processes: link:Processes{relfilesuffix}[QQQ Processes]
:link-app: link:Apps{relfilesuffix}[QQQ App]
:link-apps: link:Apps{relfilesuffix}[QQQ Apps]
:link-app: <<Apps,QQQ App>>
:link-apps: <<Apps,QQQ Apps>>
:link-backend: <<Backends,QQQ Backend>>
:link-backends: <<Backends,QQQ Backends>>
:link-field: <<Fields,QQQ Field>>
:link-fields: <<Fields,QQQ Fields>>
:link-icon: <<Icons,Icon>>
:link-icons: <<Icons,Icons>>
:link-instance: <<QInstance,QInstance>>
:link-join: <<Joins,QQQ Join>>
:link-joins: <<Joins,QQQ Joins>>
:link-permissionRule: <<PermissionRules,Permission Rule>>
:link-permissionRules: <<PermissionRules,Permission Rules>>
:link-possibleValueSource: <<PossibleValueSources,QQQ Possible Value Source>>
:link-possibleValueSources: <<PossibleValueSources,QQQ Possible Value Sources>>
:link-process: <<Processes,QQQ Process>>
:link-processes: <<Processes,QQQ Processes>>
:link-report: <<Reports,QQQ Report>>
:link-reports: <<Reports,QQQ Reports>>
:link-securityKeyType: <<SecurityKeyTypes,Security Key Type>>
:link-securityKeyTypes: <<SecurityKeyTypes,Security Key Types>>
:link-table: <<Tables,QQQ Table>>
:link-tables: <<Tables,QQQ Tables>>
:link-widget: <<Widgets,QQQ Widget>>
:link-widgets: <<Widgets,QQQ Widgets>>

37
pom.xml
View File

@ -33,6 +33,7 @@
<module>qqq-backend-module-api</module>
<module>qqq-backend-module-filesystem</module>
<module>qqq-backend-module-rdbms</module>
<module>qqq-backend-module-mongodb</module>
<module>qqq-language-support-javascript</module>
<module>qqq-middleware-picocli</module>
<module>qqq-middleware-javalin</module>
@ -108,6 +109,16 @@
</dependencyManagement>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<!-- plugins specifically for this module -->
<!-- none at this time -->
@ -317,6 +328,32 @@ fi
</plugins>
</build>
<!-- mvn javadoc:aggregate -->
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.6.2</version>
<reportSets>
<reportSet>
<id>aggregate</id>
<inherited>false</inherited>
<reports>
<report>aggregate</report>
</reports>
</reportSet>
<reportSet>
<id>default</id>
<reports>
<report>javadoc</report>
</reports>
</reportSet>
</reportSets>
</plugin>
</plugins>
</reporting>
<repositories>
<repository>
<id>github-qqq-maven-registry</id>

View File

@ -23,6 +23,9 @@ package com.kingsrook.qqq.backend.core.actions;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.AbstractTableActionInput;
import com.kingsrook.qqq.backend.core.modules.backend.QBackendModuleDispatcher;
import com.kingsrook.qqq.backend.core.modules.backend.QBackendModuleInterface;
/*******************************************************************************
@ -30,12 +33,26 @@ import com.kingsrook.qqq.backend.core.exceptions.QException;
** part of a transaction.
**
** Most obvious use-case would be a JDBC Connection. See subclass in rdbms module.
** Ditto MongoDB.
**
** Note: One would imagine that this class shouldn't ever implement Serializable...
*******************************************************************************/
public class QBackendTransaction
{
/*******************************************************************************
**
*******************************************************************************/
public static QBackendTransaction openFor(AbstractTableActionInput input) throws QException
{
QBackendModuleDispatcher qBackendModuleDispatcher = new QBackendModuleDispatcher();
QBackendModuleInterface qModule = qBackendModuleDispatcher.getQBackendModule(input.getBackend());
QBackendTransaction transaction = qModule.openTransaction(input);
return (transaction);
}
/*******************************************************************************
** Commit the transaction.
*******************************************************************************/

View File

@ -30,10 +30,12 @@ import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import com.kingsrook.qqq.backend.core.actions.AbstractQActionFunction;
import com.kingsrook.qqq.backend.core.actions.values.QPossibleValueTranslator;
import com.kingsrook.qqq.backend.core.actions.values.QValueFormatter;
@ -73,6 +75,8 @@ public class DMLAuditAction extends AbstractQActionFunction<DMLAuditInput, DMLAu
public static final String AUDIT_CONTEXT_FIELD_NAME = "auditContext";
private static Set<String> loggedUnauditableTableNames = new HashSet<>();
/*******************************************************************************
@ -102,6 +106,21 @@ public class DMLAuditAction extends AbstractQActionFunction<DMLAuditInput, DMLAu
return (output);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
// currently, the table's primary key must be integer... so, log (once) and return early if not that //
// (or, if no primary key!) //
///////////////////////////////////////////////////////////////////////////////////////////////////////
QFieldMetaData field = table.getFields().get(table.getPrimaryKeyField());
if(field == null || !QFieldType.INTEGER.equals(field.getType()))
{
if(!loggedUnauditableTableNames.contains(table.getName()))
{
LOG.info("Cannot audit table without integer as its primary key", logPair("tableName", table.getName()));
loggedUnauditableTableNames.add(table.getName());
}
return (output);
}
String contextSuffix = getContentSuffix(input);
AuditInput auditInput = new AuditInput();
@ -192,6 +211,19 @@ public class DMLAuditAction extends AbstractQActionFunction<DMLAuditInput, DMLAu
contextSuffix.append(" ").append(input.getAuditContext());
}
//////////////////////////////////////////////////////////////
// look for a context value place directly into the session //
//////////////////////////////////////////////////////////////
QSession qSession = QContext.getQSession();
if(qSession != null)
{
String sessionContext = qSession.getValue(AUDIT_CONTEXT_FIELD_NAME);
if(StringUtils.hasContent(sessionContext))
{
contextSuffix.append(" ").append(sessionContext);
}
}
/////////////////////////////////////////////////////////////////////////////////////
// note process label (and a possible context from the process's state) if present //
/////////////////////////////////////////////////////////////////////////////////////
@ -215,17 +247,20 @@ public class DMLAuditAction extends AbstractQActionFunction<DMLAuditInput, DMLAu
///////////////////////////////////////////////////
// use api label & version if present in session //
///////////////////////////////////////////////////
QSession qSession = QContext.getQSession();
String apiVersion = qSession.getValue("apiVersion");
if(apiVersion != null)
if(qSession != null)
{
String apiLabel = qSession.getValue("apiLabel");
if(!StringUtils.hasContent(apiLabel))
String apiVersion = qSession.getValue("apiVersion");
if(apiVersion != null)
{
apiLabel = "API";
String apiLabel = qSession.getValue("apiLabel");
if(!StringUtils.hasContent(apiLabel))
{
apiLabel = "API";
}
contextSuffix.append(" via ").append(apiLabel).append(" Version: ").append(apiVersion);
}
contextSuffix.append(" via ").append(apiLabel).append(" Version: ").append(apiVersion);
}
return (contextSuffix.toString());
}

View File

@ -22,6 +22,7 @@
package com.kingsrook.qqq.backend.core.actions.automation;
import java.util.Objects;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.PossibleValueEnum;
@ -55,6 +56,30 @@ public enum AutomationStatus implements PossibleValueEnum<Integer>
/*******************************************************************************
** Get instance by id
**
*******************************************************************************/
public static AutomationStatus getById(Integer id)
{
if(id == null)
{
return (null);
}
for(AutomationStatus value : AutomationStatus.values())
{
if(Objects.equals(value.id, id))
{
return (value);
}
}
return (null);
}
/*******************************************************************************
** Getter for id
**
@ -106,10 +131,10 @@ public enum AutomationStatus implements PossibleValueEnum<Integer>
public String getInsertOrUpdate()
{
return switch(this)
{
case PENDING_INSERT_AUTOMATIONS, RUNNING_INSERT_AUTOMATIONS, FAILED_INSERT_AUTOMATIONS -> "Insert";
case PENDING_UPDATE_AUTOMATIONS, RUNNING_UPDATE_AUTOMATIONS, FAILED_UPDATE_AUTOMATIONS -> "Update";
case OK -> "";
};
{
case PENDING_INSERT_AUTOMATIONS, RUNNING_INSERT_AUTOMATIONS, FAILED_INSERT_AUTOMATIONS -> "Insert";
case PENDING_UPDATE_AUTOMATIONS, RUNNING_UPDATE_AUTOMATIONS, FAILED_UPDATE_AUTOMATIONS -> "Update";
case OK -> "";
};
}
}

View File

@ -22,30 +22,40 @@
package com.kingsrook.qqq.backend.core.actions.automation;
import java.io.Serializable;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import com.kingsrook.qqq.backend.core.actions.QBackendTransaction;
import com.kingsrook.qqq.backend.core.actions.tables.CountAction;
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.instances.QMetaDataVariableInterpreter;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.tables.count.CountInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.count.CountOutput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.automation.TableTrigger;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.AutomationStatusTrackingType;
import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.QTableAutomationDetails;
import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.TableAutomationAction;
import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.TriggerEvent;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.backend.core.utils.memoization.Memoization;
import org.apache.commons.lang.NotImplementedException;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
@ -55,19 +65,37 @@ public class RecordAutomationStatusUpdater
{
private static final QLogger LOG = QLogger.getLogger(RecordAutomationStatusUpdater.class);
///////////////////////////////////////////////////////////////////////////////////////////////////////
// feature flag - by default, will be true - before setting records to PENDING_UPDATE_AUTOMATIONS, //
// we will fetch them (if we didn't take them in from the caller, which, UpdateAction does if its //
// backend supports it), to check their current automationStatus - and if they are currently PENDING //
// or RUNNING inserts or updates, we won't update them. //
///////////////////////////////////////////////////////////////////////////////////////////////////////
private static boolean allowPreUpdateFetch = new QMetaDataVariableInterpreter().getBooleanFromPropertyOrEnvironment("qqq.recordAutomationStatusUpdater.allowPreUpdateFetch", "QQQ_RECORD_AUTOMATION_STATUS_UPDATER_ALLOW_PRE_UPDATE_FETCH", true);
///////////////////////////////////////////////////////////////////////////////////////////////
// feature flag - by default, we'll memoize the check for triggers - but we can turn it off. //
///////////////////////////////////////////////////////////////////////////////////////////////
private static boolean memoizeCheckForTriggers = new QMetaDataVariableInterpreter().getBooleanFromPropertyOrEnvironment("qqq.recordAutomationStatusUpdater.memoizeCheckForTriggers", "QQQ_RECORD_AUTOMATION_STATUS_UPDATER_MEMOIZE_CHECK_FOR_TRIGGERS", true);
private static Memoization<Key, Boolean> areThereTableTriggersForTableMemoization = new Memoization<Key, Boolean>().withTimeout(Duration.of(60, ChronoUnit.SECONDS));
/*******************************************************************************
** for a list of records from a table, set their automation status - based on
** how the table is configured.
*******************************************************************************/
public static boolean setAutomationStatusInRecords(QSession session, QTableMetaData table, List<QRecord> records, AutomationStatus automationStatus)
public static boolean setAutomationStatusInRecords(QTableMetaData table, List<QRecord> records, AutomationStatus automationStatus, QBackendTransaction transaction, List<QRecord> oldRecordList)
{
if(table == null || table.getAutomationDetails() == null || CollectionUtils.nullSafeIsEmpty(records))
{
return (false);
}
QTableAutomationDetails automationDetails = table.getAutomationDetails();
Set<Serializable> pkeysWeMayNotUpdate = new HashSet<>();
///////////////////////////////////////////////////////////////////////////////////////////////////
// In case an automation is running, and it updates records - don't let those records be marked //
// as PENDING_UPDATE_AUTOMATIONS... this is meant to avoid having a record's automation update //
@ -81,12 +109,60 @@ public class RecordAutomationStatusUpdater
for(StackTraceElement stackTraceElement : e.getStackTrace())
{
String className = stackTraceElement.getClassName();
if(className.contains("com.kingsrook.qqq.backend.core.actions.automation") && !className.equals(RecordAutomationStatusUpdater.class.getName()) && !className.endsWith("Test"))
if(className.contains(RecordAutomationStatusUpdater.class.getPackageName()) && !className.equals(RecordAutomationStatusUpdater.class.getName()) && !className.endsWith("Test") && !className.contains("Test$"))
{
LOG.debug("Avoiding re-setting automation status to PENDING_UPDATE while running an automation");
return (false);
}
}
///////////////////////////////////////////////////////////////////////////////
// if table uses field-in-table status tracking, then check the old records, //
// before we set them to pending-updates, to avoid losing other pending or //
// running status information. We will allow moving from OK or the 2 //
// failed statuses into pending-updates - which seems right. //
// This is added to fix cases where an update that comes in before insert //
// -automations have run, will cause the pending-insert status to be missed. //
///////////////////////////////////////////////////////////////////////////////
if(automationDetails.getStatusTracking() != null && AutomationStatusTrackingType.FIELD_IN_TABLE.equals(automationDetails.getStatusTracking().getType()))
{
try
{
if(CollectionUtils.nullSafeIsEmpty(oldRecordList))
{
///////////////////////////////////////////////////////////////////////////////////////////////
// if we didn't get the oldRecordList as input (though UpdateAction should usually pass it?) //
// then check feature-flag if we're allowed to do a lookup here & now. If so, then do. //
///////////////////////////////////////////////////////////////////////////////////////////////
if(allowPreUpdateFetch)
{
List<Serializable> pkeysToLookup = records.stream().map(r -> r.getValue(table.getPrimaryKeyField())).toList();
oldRecordList = new QueryAction().execute(new QueryInput(table.getName())
.withFilter(new QQueryFilter(new QFilterCriteria(table.getPrimaryKeyField(), QCriteriaOperator.IN, pkeysToLookup)))
.withTransaction(transaction)
).getRecords();
}
}
for(QRecord freshRecord : CollectionUtils.nonNullList(oldRecordList))
{
Serializable recordStatus = freshRecord.getValue(automationDetails.getStatusTracking().getFieldName());
if(AutomationStatus.PENDING_INSERT_AUTOMATIONS.getId().equals(recordStatus)
|| AutomationStatus.PENDING_UPDATE_AUTOMATIONS.getId().equals(recordStatus)
|| AutomationStatus.RUNNING_INSERT_AUTOMATIONS.getId().equals(recordStatus)
|| AutomationStatus.RUNNING_UPDATE_AUTOMATIONS.getId().equals(recordStatus))
{
Serializable primaryKey = freshRecord.getValue(table.getPrimaryKeyField());
LOG.debug("May not update automation status", logPair("table", table.getName()), logPair("id", primaryKey), logPair("currentStatus", recordStatus), logPair("requestedStatus", automationStatus.getId()));
pkeysWeMayNotUpdate.add(primaryKey);
}
}
}
catch(QException qe)
{
LOG.error("Error checking existing automation status before setting new automation status - more records will be updated than maybe should be...", qe);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@ -98,19 +174,15 @@ public class RecordAutomationStatusUpdater
automationStatus = AutomationStatus.OK;
}
QTableAutomationDetails automationDetails = table.getAutomationDetails();
if(automationDetails.getStatusTracking() != null && AutomationStatusTrackingType.FIELD_IN_TABLE.equals(automationDetails.getStatusTracking().getType()))
{
for(QRecord record : records)
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// todo - seems like there's some case here, where if an order was in PENDING_INSERT, but then some other job updated the record, that we'd //
// lose that pending status, which would be a Bad Thing™... //
// problem is - we may not have the full record in here, so we can't necessarily check the record to see what status it's currently in... //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
record.setValue(automationDetails.getStatusTracking().getFieldName(), automationStatus.getId());
// todo - another field - for the automation timestamp??
if(!pkeysWeMayNotUpdate.contains(record.getValue(table.getPrimaryKeyField())))
{
record.setValue(automationDetails.getStatusTracking().getFieldName(), automationStatus.getId());
// todo - another field - for the automation timestamp??
}
}
}
@ -188,11 +260,29 @@ public class RecordAutomationStatusUpdater
return (false);
}
if(memoizeCheckForTriggers)
{
///////////////////////////////////////////////////////////////////////////////////////
// as within the lookup method, error on the side of "yes, maybe there are triggers" //
///////////////////////////////////////////////////////////////////////////////////////
Optional<Boolean> result = areThereTableTriggersForTableMemoization.getResult(new Key(table, triggerEvent), key -> lookupIfThereAreTriggersForTable(table, triggerEvent));
return result.orElse(true);
}
else
{
return lookupIfThereAreTriggersForTable(table, triggerEvent);
}
}
/*******************************************************************************
**
*******************************************************************************/
private static Boolean lookupIfThereAreTriggersForTable(QTableMetaData table, TriggerEvent triggerEvent)
{
try
{
///////////////////
// todo - cache? //
///////////////////
CountInput countInput = new CountInput();
countInput.setTableName(TableTrigger.TABLE_NAME);
countInput.setFilter(new QQueryFilter(
@ -207,6 +297,7 @@ public class RecordAutomationStatusUpdater
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// if the count query failed, we're a bit safer to err on the side of "yeah, there might be automations" //
///////////////////////////////////////////////////////////////////////////////////////////////////////////
LOG.warn("Error looking if there are triggers for table", e, logPair("tableName", table.getName()));
return (true);
}
}
@ -217,12 +308,12 @@ public class RecordAutomationStatusUpdater
** for a list of records, update their automation status and actually Update the
** backend as well.
*******************************************************************************/
public static void setAutomationStatusInRecordsAndUpdate(QInstance instance, QSession session, QTableMetaData table, List<QRecord> records, AutomationStatus automationStatus) throws QException
public static void setAutomationStatusInRecordsAndUpdate(QTableMetaData table, List<QRecord> records, AutomationStatus automationStatus, QBackendTransaction transaction) throws QException
{
QTableAutomationDetails automationDetails = table.getAutomationDetails();
if(automationDetails != null && AutomationStatusTrackingType.FIELD_IN_TABLE.equals(automationDetails.getStatusTracking().getType()))
{
boolean didSetStatusField = setAutomationStatusInRecords(session, table, records, automationStatus);
boolean didSetStatusField = setAutomationStatusInRecords(table, records, automationStatus, transaction, null);
if(didSetStatusField)
{
UpdateInput updateInput = new UpdateInput();
@ -237,6 +328,7 @@ public class RecordAutomationStatusUpdater
.withValue(table.getPrimaryKeyField(), r.getValue(table.getPrimaryKeyField()))
.withValue(automationDetails.getStatusTracking().getFieldName(), r.getValue(automationDetails.getStatusTracking().getFieldName()))).toList());
updateInput.setAreAllValuesBeingUpdatedTheSame(true);
updateInput.setTransaction(transaction);
updateInput.setOmitDmlAudit(true);
new UpdateAction().execute(updateInput);
@ -250,4 +342,8 @@ public class RecordAutomationStatusUpdater
}
}
private record Key(QTableMetaData table, TriggerEvent triggerEvent) {}
}

View File

@ -43,6 +43,7 @@ import com.kingsrook.qqq.backend.core.actions.tables.GetAction;
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.LogPair;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunProcessInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunProcessOutput;
@ -64,13 +65,14 @@ import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.Automatio
import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.QTableAutomationDetails;
import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.TableAutomationAction;
import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.TriggerEvent;
import com.kingsrook.qqq.backend.core.model.savedfilters.SavedFilter;
import com.kingsrook.qqq.backend.core.model.savedviews.SavedView;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import com.kingsrook.qqq.backend.core.utils.collections.MapBuilder;
import org.apache.commons.lang.NotImplementedException;
import org.json.JSONObject;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
@ -87,8 +89,9 @@ public class PollingAutomationPerTableRunner implements Runnable
{
private static final QLogger LOG = QLogger.getLogger(PollingAutomationPerTableRunner.class);
private final TableActions tableActions;
private final String name;
private final TableActionsInterface tableActions;
private String name;
private QInstance instance;
private Supplier<QSession> sessionSupplier;
@ -116,10 +119,51 @@ public class PollingAutomationPerTableRunner implements Runnable
/*******************************************************************************
**
** Interface to be used by 2 records in this class - normal TableActions, and
** ShardedTableActions.
*******************************************************************************/
public record TableActions(String tableName, AutomationStatus status)
public interface TableActionsInterface
{
/*******************************************************************************
**
*******************************************************************************/
String tableName();
/*******************************************************************************
**
*******************************************************************************/
AutomationStatus status();
}
/*******************************************************************************
** Wrapper for a pair of (tableName, automationStatus)
*******************************************************************************/
public record TableActions(String tableName, AutomationStatus status) implements TableActionsInterface
{
/*******************************************************************************
**
*******************************************************************************/
public void noopToFakeTestCoverage()
{
}
}
/*******************************************************************************
** extended version of TableAction, for sharding use-case - adds the shard
** details.
*******************************************************************************/
public record ShardedTableActions(String tableName, AutomationStatus status, String shardByFieldName, Serializable shardValue, String shardLabel) implements TableActionsInterface
{
/*******************************************************************************
**
*******************************************************************************/
public void noopToFakeTestCoverage()
{
}
}
@ -128,16 +172,46 @@ public class PollingAutomationPerTableRunner implements Runnable
** basically just get a list of tables which at least *could* have automations
** run - either meta-data automations, or table-triggers (data/user defined).
*******************************************************************************/
public static List<TableActions> getTableActions(QInstance instance, String providerName)
public static List<TableActionsInterface> getTableActions(QInstance instance, String providerName)
{
List<TableActions> tableActionList = new ArrayList<>();
List<TableActionsInterface> tableActionList = new ArrayList<>();
for(QTableMetaData table : instance.getTables().values())
{
if(table.getAutomationDetails() != null && providerName.equals(table.getAutomationDetails().getProviderName()))
QTableAutomationDetails automationDetails = table.getAutomationDetails();
if(automationDetails != null && providerName.equals(automationDetails.getProviderName()))
{
tableActionList.add(new TableActions(table.getName(), AutomationStatus.PENDING_INSERT_AUTOMATIONS));
tableActionList.add(new TableActions(table.getName(), AutomationStatus.PENDING_UPDATE_AUTOMATIONS));
if(StringUtils.hasContent(automationDetails.getShardByFieldName()))
{
//////////////////////////////////////////////////////////////////////////////////////////////
// for sharded automations, add a tableAction (of the sharded subtype) for each shard-value //
//////////////////////////////////////////////////////////////////////////////////////////////
try
{
QueryInput queryInput = new QueryInput();
queryInput.setTableName(automationDetails.getShardSourceTableName());
QueryOutput queryOutput = new QueryAction().execute(queryInput);
for(QRecord record : queryOutput.getRecords())
{
Serializable shardId = record.getValue(automationDetails.getShardIdFieldName());
String label = record.getValueString(automationDetails.getShardLabelFieldName());
tableActionList.add(new ShardedTableActions(table.getName(), AutomationStatus.PENDING_INSERT_AUTOMATIONS, automationDetails.getShardByFieldName(), shardId, label));
tableActionList.add(new ShardedTableActions(table.getName(), AutomationStatus.PENDING_UPDATE_AUTOMATIONS, automationDetails.getShardByFieldName(), shardId, label));
}
}
catch(Exception e)
{
LOG.error("Error getting sharded table automation actions for a table", e, new LogPair("tableName", table.getName()));
}
}
else
{
///////////////////////////////////////////////////////////////////
// for non-sharded, we just need tabler name & automation status //
///////////////////////////////////////////////////////////////////
tableActionList.add(new TableActions(table.getName(), AutomationStatus.PENDING_INSERT_AUTOMATIONS));
tableActionList.add(new TableActions(table.getName(), AutomationStatus.PENDING_UPDATE_AUTOMATIONS));
}
}
}
@ -149,12 +223,17 @@ public class PollingAutomationPerTableRunner implements Runnable
/*******************************************************************************
**
*******************************************************************************/
public PollingAutomationPerTableRunner(QInstance instance, String providerName, Supplier<QSession> sessionSupplier, TableActions tableActions)
public PollingAutomationPerTableRunner(QInstance instance, String providerName, Supplier<QSession> sessionSupplier, TableActionsInterface tableActions)
{
this.instance = instance;
this.sessionSupplier = sessionSupplier;
this.tableActions = tableActions;
this.name = providerName + ">" + tableActions.tableName() + ">" + tableActions.status().getInsertOrUpdate();
if(tableActions instanceof ShardedTableActions shardedTableActions)
{
this.name += ":" + shardedTableActions.shardLabel();
}
}
@ -173,8 +252,7 @@ public class PollingAutomationPerTableRunner implements Runnable
try
{
QSession session = sessionSupplier != null ? sessionSupplier.get() : new QSession();
processTableInsertOrUpdate(instance.getTable(tableActions.tableName()), session, tableActions.status());
processTableInsertOrUpdate(instance.getTable(tableActions.tableName()), tableActions.status());
}
catch(Exception e)
{
@ -192,7 +270,7 @@ public class PollingAutomationPerTableRunner implements Runnable
/*******************************************************************************
** Query for and process records that have a PENDING_INSERT or PENDING_UPDATE status on a given table.
*******************************************************************************/
public void processTableInsertOrUpdate(QTableMetaData table, QSession session, AutomationStatus automationStatus) throws QException
public void processTableInsertOrUpdate(QTableMetaData table, AutomationStatus automationStatus) throws QException
{
/////////////////////////////////////////////////////////////////////////
// get the actions to run against this table in this automation status //
@ -229,12 +307,21 @@ public class PollingAutomationPerTableRunner implements Runnable
throw (new NotImplementedException("Automation Status Tracking type [" + statusTrackingType + "] is not yet implemented in here."));
}
if(tableActions instanceof ShardedTableActions shardedTableActions)
{
//////////////////////////////////////////////////////////////
// for sharded actions, add the shardBy field as a criteria //
//////////////////////////////////////////////////////////////
QQueryFilter filter = queryInput.getFilter();
filter.addCriteria(new QFilterCriteria(shardedTableActions.shardByFieldName(), QCriteriaOperator.EQUALS, shardedTableActions.shardValue()));
}
queryInput.setRecordPipe(recordPipe);
return (new QueryAction().execute(queryInput));
}, () ->
{
List<QRecord> records = recordPipe.consumeAvailableRecords();
applyActionsToRecords(session, table, records, actions, automationStatus);
applyActionsToRecords(table, records, actions, automationStatus);
return (records.size());
}
);
@ -258,7 +345,23 @@ public class PollingAutomationPerTableRunner implements Runnable
{
if(action.getTriggerEvent().equals(triggerEvent))
{
rs.add(action);
///////////////////////////////////////////////////////////
// for sharded configs, only run if the shard id matches //
///////////////////////////////////////////////////////////
if(tableActions instanceof ShardedTableActions shardedTableActions)
{
if(shardedTableActions.shardValue().equals(action.getShardId()))
{
rs.add(action);
}
}
else
{
////////////////////////////////////////////
// for non-sharded, always add the action //
////////////////////////////////////////////
rs.add(action);
}
}
}
@ -285,13 +388,15 @@ public class PollingAutomationPerTableRunner implements Runnable
if(filterId != null)
{
GetInput getInput = new GetInput();
getInput.setTableName(SavedFilter.TABLE_NAME);
getInput.setTableName(SavedView.TABLE_NAME);
getInput.setPrimaryKey(filterId);
GetOutput getOutput = new GetAction().execute(getInput);
if(getOutput.getRecord() != null)
{
SavedFilter savedFilter = new SavedFilter(getOutput.getRecord());
filter = JsonUtils.toObject(savedFilter.getFilterJson(), QQueryFilter.class);
SavedView savedView = new SavedView(getOutput.getRecord());
JSONObject viewJson = new JSONObject(savedView.getViewJson());
JSONObject queryFilter = viewJson.getJSONObject("queryFilter");
filter = JsonUtils.toObject(queryFilter.toString(), QQueryFilter.class);
}
}
@ -324,7 +429,7 @@ public class PollingAutomationPerTableRunner implements Runnable
** table's actions against them - IF they are found to match the action's filter
** (assuming it has one - if it doesn't, then all records match).
*******************************************************************************/
private void applyActionsToRecords(QSession session, QTableMetaData table, List<QRecord> records, List<TableAutomationAction> actions, AutomationStatus automationStatus) throws QException
private void applyActionsToRecords(QTableMetaData table, List<QRecord> records, List<TableAutomationAction> actions, AutomationStatus automationStatus) throws QException
{
if(CollectionUtils.nullSafeIsEmpty(records))
{
@ -334,7 +439,7 @@ public class PollingAutomationPerTableRunner implements Runnable
///////////////////////////////////////////////////
// mark the records as RUNNING their automations //
///////////////////////////////////////////////////
RecordAutomationStatusUpdater.setAutomationStatusInRecordsAndUpdate(instance, session, table, records, pendingToRunningStatusMap.get(automationStatus));
RecordAutomationStatusUpdater.setAutomationStatusInRecordsAndUpdate(table, records, pendingToRunningStatusMap.get(automationStatus), null);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// foreach action - run it against the records (but only if they match the action's filter, if there is one) //
@ -354,11 +459,11 @@ public class PollingAutomationPerTableRunner implements Runnable
////////////////////////////////////////
if(anyActionsFailed)
{
RecordAutomationStatusUpdater.setAutomationStatusInRecordsAndUpdate(instance, session, table, records, pendingToFailedStatusMap.get(automationStatus));
RecordAutomationStatusUpdater.setAutomationStatusInRecordsAndUpdate(table, records, pendingToFailedStatusMap.get(automationStatus), null);
}
else
{
RecordAutomationStatusUpdater.setAutomationStatusInRecordsAndUpdate(instance, session, table, records, AutomationStatus.OK);
RecordAutomationStatusUpdater.setAutomationStatusInRecordsAndUpdate(table, records, AutomationStatus.OK, null);
}
}
@ -471,7 +576,7 @@ public class PollingAutomationPerTableRunner implements Runnable
@Override
public QQueryFilter getQueryFilter()
{
List<Serializable> recordIds = records.stream().map(r -> r.getValueInteger(table.getPrimaryKeyField())).collect(Collectors.toList());
List<Serializable> recordIds = records.stream().map(r -> r.getValue(table.getPrimaryKeyField())).collect(Collectors.toList());
return (new QQueryFilter().withCriteria(new QFilterCriteria(table.getPrimaryKeyField(), QCriteriaOperator.IN, recordIds)));
}
});

View File

@ -297,4 +297,21 @@ public enum DateTimeGroupBy
ZonedDateTime zoned = instant.atZone(zoneId);
return (zoned.plus(noOfChronoUnitsToAdd, chronoUnitToAdd).toInstant());
}
/*******************************************************************************
**
*******************************************************************************/
public static DateTimeFormatter sqlDateFormatToSelectedDateTimeFormatter(String sqlDateFormat)
{
for(DateTimeGroupBy value : values())
{
if(value.sqlDateFormat.equals(sqlDateFormat))
{
return (value.selectedStringFormatter);
}
}
return null;
}
}

View File

@ -31,7 +31,7 @@ import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertOutput;
** Interface for the Insert action.
**
*******************************************************************************/
public interface InsertInterface extends QActionInterface
public interface InsertInterface
{
/*******************************************************************************
**

View File

@ -23,6 +23,7 @@ package com.kingsrook.qqq.backend.core.actions.metadata;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@ -150,14 +151,21 @@ public class MetaDataAction
}
metaDataOutput.setWidgets(widgets);
///////////////////////////////////////////////////////
// sort apps - by sortOrder (integer), then by label //
///////////////////////////////////////////////////////
List<QAppMetaData> sortedApps = metaDataInput.getInstance().getApps().values().stream()
.sorted(Comparator.comparing((QAppMetaData a) -> a.getSortOrder())
.thenComparing((QAppMetaData a) -> a.getLabel()))
.toList();
///////////////////////////////////
// map apps to frontend metadata //
///////////////////////////////////
Map<String, QFrontendAppMetaData> apps = new LinkedHashMap<>();
for(Map.Entry<String, QAppMetaData> entry : metaDataInput.getInstance().getApps().entrySet())
for(QAppMetaData app : sortedApps)
{
String appName = entry.getKey();
QAppMetaData app = entry.getValue();
String appName = app.getName();
PermissionCheckResult permissionResult = PermissionsHelper.getPermissionCheckResult(metaDataInput, app);
if(permissionResult.equals(PermissionCheckResult.DENY_HIDE))
@ -191,7 +199,7 @@ public class MetaDataAction
// organize app tree nodes by their hierarchy //
////////////////////////////////////////////////
List<AppTreeNode> appTree = new ArrayList<>();
for(QAppMetaData appMetaData : metaDataInput.getInstance().getApps().values())
for(QAppMetaData appMetaData : sortedApps)
{
if(appMetaData.getParentAppName() == null)
{

View File

@ -0,0 +1,68 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2024. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.kingsrook.qqq.backend.core.actions.processes;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
/*******************************************************************************
** Constructor for commonly used QProcessCallback's
*******************************************************************************/
public class QProcessCallbackFactory
{
/*******************************************************************************
**
*******************************************************************************/
public static QProcessCallback forFilter(QQueryFilter filter)
{
return new QProcessCallback()
{
/*******************************************************************************
**
*******************************************************************************/
@Override
public QQueryFilter getQueryFilter()
{
return (filter);
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public Map<String, Serializable> getFieldValues(List<QFieldMetaData> fields)
{
return (Collections.emptyMap());
}
};
}
}

View File

@ -72,7 +72,7 @@ import org.apache.commons.lang.BooleanUtils;
/*******************************************************************************
** Action handler for running q-processes (which are a sequence of q-functions).
** Action handler for running q-processes (which are a sequence of q-steps).
*
*******************************************************************************/
public class RunProcessAction
@ -82,6 +82,7 @@ public class RunProcessAction
public static final String BASEPULL_THIS_RUNTIME_KEY = "basepullThisRuntimeKey";
public static final String BASEPULL_LAST_RUNTIME_KEY = "basepullLastRuntimeKey";
public static final String BASEPULL_TIMESTAMP_FIELD = "basepullTimestampField";
public static final String BASEPULL_CONFIGURATION = "basepullConfiguration";
////////////////////////////////////////////////////////////////////////////////////////////////
// indicator that the timestamp field should be updated - e.g., the execute step is finished. //
@ -633,5 +634,6 @@ public class RunProcessAction
runProcessInput.getValues().put(BASEPULL_LAST_RUNTIME_KEY, lastRunTime);
runProcessInput.getValues().put(BASEPULL_TIMESTAMP_FIELD, basepullConfiguration.getTimestampField());
runProcessInput.getValues().put(BASEPULL_CONFIGURATION, basepullConfiguration);
}
}

View File

@ -30,6 +30,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.kingsrook.qqq.backend.core.actions.ActionHelper;
import com.kingsrook.qqq.backend.core.actions.audits.DMLAuditAction;
import com.kingsrook.qqq.backend.core.actions.tables.GetAction;
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
import com.kingsrook.qqq.backend.core.context.QContext;
@ -47,12 +48,14 @@ import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryJoin;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryOutput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.code.AdHocScriptCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.model.scripts.Script;
import com.kingsrook.qqq.backend.core.model.scripts.ScriptRevision;
import com.kingsrook.qqq.backend.core.model.scripts.ScriptsMetaDataProvider;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.backend.core.utils.memoization.Memoization;
/*******************************************************************************
@ -65,6 +68,8 @@ public class RunAdHocRecordScriptAction
private Map<Integer, ScriptRevision> scriptRevisionCacheByScriptRevisionId = new HashMap<>();
private Map<Integer, ScriptRevision> scriptRevisionCacheByScriptId = new HashMap<>();
private static Memoization<Integer, Script> scriptMemoizationById = new Memoization<>();
/*******************************************************************************
@ -85,6 +90,12 @@ public class RunAdHocRecordScriptAction
throw (new QException("Script revision was not found."));
}
Optional<Script> script = getScript(scriptRevision);
QContext.getQSession().setValue(DMLAuditAction.AUDIT_CONTEXT_FIELD_NAME, script.isPresent()
? "via Script \"%s\"".formatted(script.get().getName())
: "via Script id " + scriptRevision.getScriptId());
////////////////////////////
// figure out the records //
////////////////////////////
@ -124,6 +135,10 @@ public class RunAdHocRecordScriptAction
{
output.setException(Optional.of(e));
}
finally
{
QContext.getQSession().removeValue(DMLAuditAction.AUDIT_CONTEXT_FIELD_NAME);
}
}
@ -217,4 +232,44 @@ public class RunAdHocRecordScriptAction
throw (new QException("Code reference did not contain a scriptRevision, scriptRevisionId, or scriptId"));
}
/*******************************************************************************
**
*******************************************************************************/
private Optional<Script> getScript(ScriptRevision scriptRevision)
{
if(scriptRevision == null || scriptRevision.getScriptId() == null)
{
return (Optional.empty());
}
try
{
return scriptMemoizationById.getResult(scriptRevision.getScriptId(), scriptId ->
{
try
{
QRecord scriptRecord = new GetAction().executeForRecord(new GetInput(Script.TABLE_NAME).withPrimaryKey(scriptRevision.getScriptId()));
if(scriptRecord != null)
{
Script script = new Script(scriptRecord);
scriptMemoizationById.storeResult(scriptRevision.getScriptId(), script);
return (script);
}
}
catch(Exception e)
{
LOG.info("");
}
return (null);
});
}
catch(Exception e)
{
return (Optional.empty());
}
}
}

View File

@ -52,6 +52,7 @@ import com.kingsrook.qqq.backend.core.model.actions.audits.DMLAuditInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertOutput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QBackendMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.joins.JoinOn;
@ -116,21 +117,24 @@ public class InsertAction extends AbstractQActionFunction<InsertInput, InsertOut
setAutomationStatusField(insertInput);
//////////////////////////////////////////////////////
// load the backend module and its insert interface //
//////////////////////////////////////////////////////
QBackendModuleInterface qModule = getBackendModuleInterface(insertInput);
InsertInterface insertInterface = qModule.getInsertInterface();
/////////////////////////////
// run standard validators //
/////////////////////////////
performValidations(insertInput, false);
////////////////////////////////////
// have the backend do the insert //
////////////////////////////////////
InsertOutput insertOutput = insertInterface.execute(insertInput);
//////////////////////////////////////////////////////
// use the backend module to actually do the insert //
//////////////////////////////////////////////////////
InsertOutput insertOutput = runInsertInBackend(insertInput);
if(insertOutput.getRecords() == null)
{
////////////////////////////////////////////////////////////////////////////////////
// in case the module failed to set record in the output, put an empty list there //
// to avoid so many downstream NPE's //
////////////////////////////////////////////////////////////////////////////////////
insertOutput.setRecords(new ArrayList<>());
}
//////////////////////////////
// log if there were errors //
@ -186,6 +190,37 @@ public class InsertAction extends AbstractQActionFunction<InsertInput, InsertOut
/*******************************************************************************
**
*******************************************************************************/
private InsertOutput runInsertInBackend(InsertInput insertInput) throws QException
{
///////////////////////////////////
// exit early if 0 input records //
///////////////////////////////////
if(CollectionUtils.nullSafeIsEmpty(insertInput.getRecords()))
{
LOG.debug("Insert request called with 0 records. Returning with no-op", logPair("tableName", insertInput.getTableName()));
InsertOutput rs = new InsertOutput();
rs.setRecords(new ArrayList<>());
return (rs);
}
//////////////////////////////////////////////////////
// load the backend module and its insert interface //
//////////////////////////////////////////////////////
QBackendModuleInterface qModule = getBackendModuleInterface(insertInput.getBackend());
InsertInterface insertInterface = qModule.getInsertInterface();
////////////////////////////////////
// have the backend do the insert //
////////////////////////////////////
InsertOutput insertOutput = insertInterface.execute(insertInput);
return insertOutput;
}
/*******************************************************************************
**
*******************************************************************************/
@ -207,7 +242,7 @@ public class InsertAction extends AbstractQActionFunction<InsertInput, InsertOut
setDefaultValuesInRecords(table, insertInput.getRecords());
ValueBehaviorApplier.applyFieldBehaviors(insertInput.getInstance(), table, insertInput.getRecords());
ValueBehaviorApplier.applyFieldBehaviors(ValueBehaviorApplier.Action.INSERT, insertInput.getInstance(), table, insertInput.getRecords());
runPreInsertCustomizerIfItIsTime(insertInput, preInsertCustomizer, AbstractPreInsertCustomizer.WhenToRun.BEFORE_UNIQUE_KEY_CHECKS);
setErrorsIfUniqueKeyErrors(insertInput, table);
@ -409,7 +444,7 @@ public class InsertAction extends AbstractQActionFunction<InsertInput, InsertOut
*******************************************************************************/
private void setAutomationStatusField(InsertInput insertInput)
{
RecordAutomationStatusUpdater.setAutomationStatusInRecords(insertInput.getSession(), insertInput.getTable(), insertInput.getRecords(), AutomationStatus.PENDING_INSERT_AUTOMATIONS);
RecordAutomationStatusUpdater.setAutomationStatusInRecords(insertInput.getTable(), insertInput.getRecords(), AutomationStatus.PENDING_INSERT_AUTOMATIONS, insertInput.getTransaction(), null);
}
@ -417,23 +452,11 @@ public class InsertAction extends AbstractQActionFunction<InsertInput, InsertOut
/*******************************************************************************
**
*******************************************************************************/
private QBackendModuleInterface getBackendModuleInterface(InsertInput insertInput) throws QException
private QBackendModuleInterface getBackendModuleInterface(QBackendMetaData backend) throws QException
{
ActionHelper.validateSession(insertInput);
QBackendModuleDispatcher qBackendModuleDispatcher = new QBackendModuleDispatcher();
QBackendModuleInterface qModule = qBackendModuleDispatcher.getQBackendModule(insertInput.getBackend());
QBackendModuleInterface qModule = qBackendModuleDispatcher.getQBackendModule(backend);
return (qModule);
}
/*******************************************************************************
**
*******************************************************************************/
public QBackendTransaction openTransaction(InsertInput insertInput) throws QException
{
QBackendModuleInterface qModule = getBackendModuleInterface(insertInput);
return (qModule.getInsertInterface().openTransaction(insertInput));
}
}

View File

@ -84,9 +84,7 @@ public class ReplaceAction extends AbstractQActionFunction<ReplaceInput, Replace
String primaryKeyField = table.getPrimaryKeyField();
if(transaction == null)
{
InsertInput insertInput = new InsertInput();
insertInput.setTableName(input.getTableName());
transaction = new InsertAction().openTransaction(insertInput);
transaction = QBackendTransaction.openFor(new InsertInput(input.getTableName()));
weOwnTheTransaction = true;
}

View File

@ -113,7 +113,6 @@ public class UpdateAction
public UpdateOutput execute(UpdateInput updateInput) throws QException
{
ActionHelper.validateSession(updateInput);
setAutomationStatusField(updateInput);
QTableMetaData table = updateInput.getTable();
@ -130,12 +129,31 @@ public class UpdateAction
////////////////////////////////////////////////////////////////////////////////
Optional<List<QRecord>> oldRecordList = fetchOldRecords(updateInput, updateInterface);
///////////////////////////////////////////////////////////////////////////////////////
// allow caller to specify that we don't want to trigger automations. this isn't //
// isn't expected to be used much - by design, only for the process that is meant to //
// heal automation status, so that it can force us into status=Pending-inserts //
///////////////////////////////////////////////////////////////////////////////////////
if(!updateInput.getOmitTriggeringAutomations())
{
setAutomationStatusField(updateInput, oldRecordList);
}
performValidations(updateInput, oldRecordList, false);
////////////////////////////////////
// have the backend do the update //
////////////////////////////////////
UpdateOutput updateOutput = updateInterface.execute(updateInput);
UpdateOutput updateOutput = runUpdateInBackend(updateInput, updateInterface);
if(updateOutput.getRecords() == null)
{
////////////////////////////////////////////////////////////////////////////////////
// in case the module failed to set record in the output, put an empty list there //
// to avoid so many downstream NPE's //
////////////////////////////////////////////////////////////////////////////////////
updateOutput.setRecords(new ArrayList<>());
}
//////////////////////////////
// log if there were errors //
@ -194,6 +212,28 @@ public class UpdateAction
/*******************************************************************************
**
*******************************************************************************/
private UpdateOutput runUpdateInBackend(UpdateInput updateInput, UpdateInterface updateInterface) throws QException
{
///////////////////////////////////
// exit early if 0 input records //
///////////////////////////////////
if(CollectionUtils.nullSafeIsEmpty(updateInput.getRecords()))
{
LOG.debug("Update request called with 0 records. Returning with no-op", logPair("tableName", updateInput.getTableName()));
UpdateOutput rs = new UpdateOutput();
rs.setRecords(new ArrayList<>());
return (rs);
}
UpdateOutput updateOutput = updateInterface.execute(updateInput);
return updateOutput;
}
/*******************************************************************************
**
*******************************************************************************/
@ -204,7 +244,7 @@ public class UpdateAction
/////////////////////////////
// run standard validators //
/////////////////////////////
ValueBehaviorApplier.applyFieldBehaviors(updateInput.getInstance(), table, updateInput.getRecords());
ValueBehaviorApplier.applyFieldBehaviors(ValueBehaviorApplier.Action.UPDATE, updateInput.getInstance(), table, updateInput.getRecords());
validatePrimaryKeysAreGiven(updateInput);
if(oldRecordList.isPresent())
@ -530,9 +570,9 @@ public class UpdateAction
/*******************************************************************************
** If the table being updated uses an automation-status field, populate it now.
*******************************************************************************/
private void setAutomationStatusField(UpdateInput updateInput)
private void setAutomationStatusField(UpdateInput updateInput, Optional<List<QRecord>> oldRecordList)
{
RecordAutomationStatusUpdater.setAutomationStatusInRecords(updateInput.getSession(), updateInput.getTable(), updateInput.getRecords(), AutomationStatus.PENDING_UPDATE_AUTOMATIONS);
RecordAutomationStatusUpdater.setAutomationStatusInRecords(updateInput.getTable(), updateInput.getRecords(), AutomationStatus.PENDING_UPDATE_AUTOMATIONS, updateInput.getTransaction(), oldRecordList.orElse(null));
}
}

View File

@ -0,0 +1,174 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2024. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.kingsrook.qqq.backend.core.actions.tables.helpers;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.backend.core.utils.ListingHash;
/*******************************************************************************
** Helper for backends that want to do their updates on records grouped by the
** set of fields that are being changed, and/or by the values those fields are
** being set to.
**
** e.g., RDBMS, for n records where some sub-set of fields are all having values
** set the same (say, a status=x), we can do that as 1 query where id in (?,?,...,?).
*******************************************************************************/
public class UpdateActionRecordSplitHelper
{
private ListingHash<List<String>, QRecord> recordsByFieldBeingUpdated = new ListingHash<>();
private boolean haveAnyWithoutErrors = false;
private List<QRecord> outputRecords = new ArrayList<>();
/*******************************************************************************
**
*******************************************************************************/
public void init(UpdateInput updateInput)
{
QTableMetaData table = updateInput.getTable();
Instant now = Instant.now();
for(QRecord record : updateInput.getRecords())
{
List<String> updatableFields = table.getFields().values().stream()
.map(QFieldMetaData::getName)
// todo - intent here is to avoid non-updateable fields - but this
// should be like based on field.isUpdatable once that attribute exists
.filter(name -> !name.equals("id"))
.filter(name -> record.getValues().containsKey(name))
.toList();
recordsByFieldBeingUpdated.add(updatableFields, record);
if(CollectionUtils.nullSafeIsEmpty(record.getErrors()))
{
haveAnyWithoutErrors = true;
}
//////////////////////////////////////////////////////////////////////////////
// go ahead and put the record into the output list at this point in time, //
// so that the output list's order matches the input list order //
// note that if we want to capture updated values (like modify dates), then //
// we may want a map of primary key to output record, for easy updating. //
//////////////////////////////////////////////////////////////////////////////
QRecord outputRecord = new QRecord(record);
outputRecords.add(outputRecord);
}
}
/*******************************************************************************
**
*******************************************************************************/
public static boolean areAllValuesBeingUpdatedTheSame(UpdateInput updateInput, List<QRecord> recordList, List<String> fieldsBeingUpdated)
{
if(updateInput.getAreAllValuesBeingUpdatedTheSame() != null)
{
////////////////////////////////////////////////////////////
// if input told us what value to use here, then trust it //
////////////////////////////////////////////////////////////
return (updateInput.getAreAllValuesBeingUpdatedTheSame());
}
else
{
if(recordList.size() == 1)
{
//////////////////////////////////////////////////////
// if a single record, then yes, that always counts //
//////////////////////////////////////////////////////
return (true);
}
///////////////////////////////////////////////////////////////////////
// else iterate over the records, comparing them to the first record //
// return a false if any diffs are found. if no diffs, return true. //
///////////////////////////////////////////////////////////////////////
QRecord firstRecord = recordList.get(0);
for(int i = 1; i < recordList.size(); i++)
{
QRecord record = recordList.get(i);
if(CollectionUtils.nullSafeHasContents(record.getErrors()))
{
///////////////////////////////////////////////////////
// skip records w/ errors (that we won't be updating //
///////////////////////////////////////////////////////
continue;
}
for(String fieldName : fieldsBeingUpdated)
{
if(!Objects.equals(firstRecord.getValue(fieldName), record.getValue(fieldName)))
{
return (false);
}
}
}
return (true);
}
}
/*******************************************************************************
** Getter for haveAnyWithoutErrors
**
*******************************************************************************/
public boolean getHaveAnyWithoutErrors()
{
return haveAnyWithoutErrors;
}
/*******************************************************************************
** Getter for recordsByFieldBeingUpdated
**
*******************************************************************************/
public ListingHash<List<String>, QRecord> getRecordsByFieldBeingUpdated()
{
return recordsByFieldBeingUpdated;
}
/*******************************************************************************
** Getter for outputRecords
**
*******************************************************************************/
public List<QRecord> getOutputRecords()
{
return outputRecords;
}
}

View File

@ -34,7 +34,6 @@ import java.util.Objects;
import java.util.Set;
import com.kingsrook.qqq.backend.core.actions.QBackendTransaction;
import com.kingsrook.qqq.backend.core.actions.customizers.QCodeLoader;
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QValueException;
@ -104,7 +103,7 @@ public class QPossibleValueTranslator
{
if(!transactionsPerTable.containsKey(tableName))
{
transactionsPerTable.put(tableName, new InsertAction().openTransaction(new InsertInput(tableName)));
transactionsPerTable.put(tableName, QBackendTransaction.openFor(new InsertInput(tableName)));
}
return (transactionsPerTable.get(tableName));

View File

@ -334,24 +334,34 @@ public class QValueFormatter
if(exposedJoin.getJoinTable().equals(nameParts[0]))
{
QTableMetaData joinTable = QContext.getQInstance().getTable(nameParts[0]);
fieldMap.put(fieldName, joinTable.getField(nameParts[1]));
if(joinTable.getFields().containsKey(nameParts[1]))
{
fieldMap.put(fieldName, joinTable.getField(nameParts[1]));
}
}
}
}
else
{
fieldMap.put(fieldName, table.getField(fieldName));
if(table.getFields().containsKey(fieldName))
{
fieldMap.put(fieldName, table.getField(fieldName));
}
}
}
catch(Exception e)
{
///////////////////////////////////////////////////////////
// put an empty field in - so no formatting will be done //
///////////////////////////////////////////////////////////
LOG.info("Error getting field for setting display value", e, logPair("fieldName", fieldName), logPair("tableName", table.getName()));
fieldMap.put(fieldName, new QFieldMetaData());
LOG.warn("Error getting field for setting display value", e, logPair("fieldName", fieldName), logPair("tableName", table.getName()));
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// if we didn't find the field definition, put an empty field in the map, so no formatting will be done //
//////////////////////////////////////////////////////////////////////////////////////////////////////////
if(!fieldMap.containsKey(fieldName))
{
fieldMap.put(fieldName, new QFieldMetaData());
}
}
setDisplayValuesInRecord(fieldMap, record);

View File

@ -25,12 +25,10 @@ package com.kingsrook.qqq.backend.core.actions.values;
import java.util.List;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.fields.FieldBehavior;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.model.statusmessages.BadInputStatusMessage;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
/*******************************************************************************
@ -42,16 +40,10 @@ public class ValueBehaviorApplier
/*******************************************************************************
**
*******************************************************************************/
public static void applyFieldBehaviors(QInstance instance, QTableMetaData table, List<QRecord> recordList)
public enum Action
{
for(QFieldMetaData field : table.getFields().values())
{
String fieldName = field.getName();
if(field.getType().equals(QFieldType.STRING) && field.getMaxLength() != null)
{
applyValueTooLongBehavior(instance, recordList, field, fieldName);
}
}
INSERT,
UPDATE
}
@ -59,31 +51,18 @@ public class ValueBehaviorApplier
/*******************************************************************************
**
*******************************************************************************/
private static void applyValueTooLongBehavior(QInstance instance, List<QRecord> recordList, QFieldMetaData field, String fieldName)
public static void applyFieldBehaviors(Action action, QInstance instance, QTableMetaData table, List<QRecord> recordList)
{
ValueTooLongBehavior valueTooLongBehavior = field.getBehavior(instance, ValueTooLongBehavior.class);
////////////////////////////////////////////////////////////////////////////////////////////////////
// don't process PASS_THROUGH - so we don't have to iterate over the whole record list to do noop //
////////////////////////////////////////////////////////////////////////////////////////////////////
if(valueTooLongBehavior != null && !valueTooLongBehavior.equals(ValueTooLongBehavior.PASS_THROUGH))
if(CollectionUtils.nullSafeIsEmpty(recordList))
{
for(QRecord record : recordList)
return;
}
for(QFieldMetaData field : table.getFields().values())
{
for(FieldBehavior<?> fieldBehavior : CollectionUtils.nonNullCollection(field.getBehaviors()))
{
String value = record.getValueString(fieldName);
if(value != null && value.length() > field.getMaxLength())
{
switch(valueTooLongBehavior)
{
case TRUNCATE -> record.setValue(fieldName, StringUtils.safeTruncate(value, field.getMaxLength()));
case TRUNCATE_ELLIPSIS -> record.setValue(fieldName, StringUtils.safeTruncate(value, field.getMaxLength(), "..."));
case ERROR -> record.addError(new BadInputStatusMessage("The value for " + field.getLabel() + " is too long (max allowed length=" + field.getMaxLength() + ")"));
case PASS_THROUGH ->
{
}
default -> throw new IllegalStateException("Unexpected valueTooLongBehavior: " + valueTooLongBehavior);
}
}
fieldBehavior.apply(action, recordList, instance, table, field);
}
}
}

View File

@ -35,6 +35,7 @@ import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.shared.mapping.AbstractQFieldMapping;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.model.statusmessages.BadInputStatusMessage;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
@ -133,11 +134,17 @@ public class CsvToQRecordAdapter
CSVFormat.DEFAULT
.withFirstRecordAsHeader()
.withIgnoreHeaderCase()
.withIgnoreEmptyLines()
.withTrim());
List<String> headers = csvParser.getHeaderNames();
headers = makeHeadersUnique(headers);
////////////////////////////////////////
// used by csv-headers-as-field-names //
////////////////////////////////////////
Map<String, QFieldMetaData> csvHeaderFieldMapping = buildCsvHeaderFieldMappingIfNeeded(inputWrapper, headers);
Iterator<CSVRecord> csvIterator = csvParser.iterator();
int recordCount = 0;
while(csvIterator.hasNext())
@ -160,11 +167,27 @@ public class CsvToQRecordAdapter
QRecord qRecord = new QRecord();
try
{
for(QFieldMetaData field : table.getFields().values())
if(inputWrapper.getCsvHeadersAsFieldNames())
{
String fieldSource = mapping == null ? field.getName() : String.valueOf(mapping.getFieldSource(field.getName()));
fieldSource = adjustHeaderCase(fieldSource, inputWrapper);
setValue(inputWrapper, qRecord, field, csvValues.get(fieldSource));
/////////////////////////////////////////////////////////////////////////////////////////
// in csv-headers-as-field-names mode, don't mess with table, and don't do any mapping //
/////////////////////////////////////////////////////////////////////////////////////////
for(Map.Entry<String, String> entry : csvValues.entrySet())
{
setValue(inputWrapper, qRecord, csvHeaderFieldMapping.get(entry.getKey()), entry.getValue());
}
}
else
{
///////////////////////////////////////
// otherwise, fields come from table //
///////////////////////////////////////
for(QFieldMetaData field : table.getFields().values())
{
String fieldSource = mapping == null ? field.getName() : String.valueOf(mapping.getFieldSource(field.getName()));
fieldSource = adjustHeaderCase(fieldSource, inputWrapper);
setValue(inputWrapper, qRecord, field, csvValues.get(fieldSource));
}
}
runRecordCustomizer(recordCustomizer, qRecord);
@ -247,6 +270,26 @@ public class CsvToQRecordAdapter
/*******************************************************************************
**
*******************************************************************************/
private Map<String, QFieldMetaData> buildCsvHeaderFieldMappingIfNeeded(InputWrapper inputWrapper, List<String> headers)
{
Map<String, QFieldMetaData> csvHeaderFieldMapping = null;
if(inputWrapper.getCsvHeadersAsFieldNames())
{
csvHeaderFieldMapping = new HashMap<>();
for(String header : headers)
{
header = adjustHeaderCase(header, inputWrapper);
csvHeaderFieldMapping.put(header, new QFieldMetaData(header, QFieldType.STRING));
}
}
return csvHeaderFieldMapping;
}
/*******************************************************************************
**
*******************************************************************************/
@ -376,7 +419,8 @@ public class CsvToQRecordAdapter
private Integer limit;
private boolean doCorrectValueTypes = false;
private boolean caseSensitiveHeaders = false;
private boolean caseSensitiveHeaders = false;
private boolean csvHeadersAsFieldNames = false;
@ -618,6 +662,40 @@ public class CsvToQRecordAdapter
/*******************************************************************************
** Getter for csvHeadersAsFieldNames
**
*******************************************************************************/
public boolean getCsvHeadersAsFieldNames()
{
return csvHeadersAsFieldNames;
}
/*******************************************************************************
** Setter for csvHeadersAsFieldNames
**
*******************************************************************************/
public void setCsvHeadersAsFieldNames(boolean csvHeadersAsFieldNames)
{
this.csvHeadersAsFieldNames = csvHeadersAsFieldNames;
}
/*******************************************************************************
** Fluent setter for csvHeadersAsFieldNames
**
*******************************************************************************/
public InputWrapper withCsvHeadersAsFieldNames(boolean csvHeadersAsFieldNames)
{
this.csvHeadersAsFieldNames = csvHeadersAsFieldNames;
return (this);
}
/*******************************************************************************
** Getter for doCorrectValueTypes
**

View File

@ -103,13 +103,23 @@ public class JsonToQRecordAdapter
{
QRecord record = new QRecord();
for(QFieldMetaData field : table.getFields().values())
if(table == null)
{
String fieldSource = mapping == null ? field.getName() : String.valueOf(mapping.getFieldSource(field.getName()));
// todo - so if the mapping didn't say how to map this field, does that mean we should use the default name for the field?
if(jsonObject.has(fieldSource))
jsonObject.keys().forEachRemaining(key ->
{
record.setValue(field.getName(), (Serializable) jsonObject.get(fieldSource));
record.setValue(key, jsonObject.optString(key));
});
}
else
{
for(QFieldMetaData field : table.getFields().values())
{
String fieldSource = mapping == null ? field.getName() : String.valueOf(mapping.getFieldSource(field.getName()));
// todo - so if the mapping didn't say how to map this field, does that mean we should use the default name for the field?
if(jsonObject.has(fieldSource))
{
record.setValue(field.getName(), (Serializable) jsonObject.get(fieldSource));
}
}
}

View File

@ -42,6 +42,7 @@ import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaDataInterface;
import com.kingsrook.qqq.backend.core.model.metadata.fields.AdornmentType;
import com.kingsrook.qqq.backend.core.model.metadata.fields.DynamicDefaultValueBehavior;
import com.kingsrook.qqq.backend.core.model.metadata.fields.FieldAdornment;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
@ -94,10 +95,8 @@ public class QInstanceEnricher
private JoinGraph joinGraph;
//////////////////////////////////////////////////////////
// todo - come up w/ a way for app devs to set configs! //
//////////////////////////////////////////////////////////
private boolean configRemoveIdFromNameWhenCreatingPossibleValueFieldLabels = true;
private boolean configRemoveIdFromNameWhenCreatingPossibleValueFieldLabels = true;
private boolean configAddDynamicDefaultValuesToFieldsNamedCreateDateAndModifyDate = true;
//////////////////////////////////////////////////////////////////////////////////////////////////
// let an instance define mappings to be applied during name-to-label enrichments, //
@ -464,6 +463,22 @@ public class QInstanceEnricher
}
}
}
/////////////////////////////////////////////////////////////////////////
// add field behaviors for create date & modify date, if so configured //
/////////////////////////////////////////////////////////////////////////
if(configAddDynamicDefaultValuesToFieldsNamedCreateDateAndModifyDate)
{
if("createDate".equals(field.getName()) && field.getBehaviorOnlyIfSet(DynamicDefaultValueBehavior.class) == null)
{
field.withBehavior(DynamicDefaultValueBehavior.CREATE_DATE);
}
if("modifyDate".equals(field.getName()) && field.getBehaviorOnlyIfSet(DynamicDefaultValueBehavior.class) == null)
{
field.withBehavior(DynamicDefaultValueBehavior.MODIFY_DATE);
}
}
}
@ -1220,4 +1235,66 @@ public class QInstanceEnricher
labelMappings.clear();
}
/*******************************************************************************
** Getter for configRemoveIdFromNameWhenCreatingPossibleValueFieldLabels
*******************************************************************************/
public boolean getConfigRemoveIdFromNameWhenCreatingPossibleValueFieldLabels()
{
return (this.configRemoveIdFromNameWhenCreatingPossibleValueFieldLabels);
}
/*******************************************************************************
** Setter for configRemoveIdFromNameWhenCreatingPossibleValueFieldLabels
*******************************************************************************/
public void setConfigRemoveIdFromNameWhenCreatingPossibleValueFieldLabels(boolean configRemoveIdFromNameWhenCreatingPossibleValueFieldLabels)
{
this.configRemoveIdFromNameWhenCreatingPossibleValueFieldLabels = configRemoveIdFromNameWhenCreatingPossibleValueFieldLabels;
}
/*******************************************************************************
** Fluent setter for configRemoveIdFromNameWhenCreatingPossibleValueFieldLabels
*******************************************************************************/
public QInstanceEnricher withConfigRemoveIdFromNameWhenCreatingPossibleValueFieldLabels(boolean configRemoveIdFromNameWhenCreatingPossibleValueFieldLabels)
{
this.configRemoveIdFromNameWhenCreatingPossibleValueFieldLabels = configRemoveIdFromNameWhenCreatingPossibleValueFieldLabels;
return (this);
}
/*******************************************************************************
** Getter for configAddDynamicDefaultValuesToFieldsNamedCreateDateAndModifyDate
*******************************************************************************/
public boolean getConfigAddDynamicDefaultValuesToFieldsNamedCreateDateAndModifyDate()
{
return (this.configAddDynamicDefaultValuesToFieldsNamedCreateDateAndModifyDate);
}
/*******************************************************************************
** Setter for configAddDynamicDefaultValuesToFieldsNamedCreateDateAndModifyDate
*******************************************************************************/
public void setConfigAddDynamicDefaultValuesToFieldsNamedCreateDateAndModifyDate(boolean configAddDynamicDefaultValuesToFieldsNamedCreateDateAndModifyDate)
{
this.configAddDynamicDefaultValuesToFieldsNamedCreateDateAndModifyDate = configAddDynamicDefaultValuesToFieldsNamedCreateDateAndModifyDate;
}
/*******************************************************************************
** Fluent setter for configAddDynamicDefaultValuesToFieldsNamedCreateDateAndModifyDate
*******************************************************************************/
public QInstanceEnricher withConfigAddDynamicDefaultValuesToFieldsNamedCreateDateAndModifyDate(boolean configAddDynamicDefaultValuesToFieldsNamedCreateDateAndModifyDate)
{
this.configAddDynamicDefaultValuesToFieldsNamedCreateDateAndModifyDate = configAddDynamicDefaultValuesToFieldsNamedCreateDateAndModifyDate;
return (this);
}
}

View File

@ -31,6 +31,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Stream;
@ -75,6 +76,7 @@ import com.kingsrook.qqq.backend.core.model.metadata.tables.AssociatedScript;
import com.kingsrook.qqq.backend.core.model.metadata.tables.Association;
import com.kingsrook.qqq.backend.core.model.metadata.tables.ExposedJoin;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QFieldSection;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QSupplementalTableMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.Tier;
import com.kingsrook.qqq.backend.core.model.metadata.tables.UniqueKey;
@ -86,6 +88,7 @@ import com.kingsrook.qqq.backend.core.model.metadata.tables.cache.CacheUseCase;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import com.kingsrook.qqq.backend.core.utils.ValueUtils;
import com.kingsrook.qqq.backend.core.utils.lambdas.UnsafeLambda;
/*******************************************************************************
@ -480,6 +483,11 @@ public class QInstanceValidator
validateTableCustomizer(tableName, entry.getKey(), entry.getValue());
}
if(table.getBackendDetails() != null)
{
table.getBackendDetails().validate(qInstance, table, this);
}
validateTableAutomationDetails(qInstance, table);
validateTableUniqueKeys(table);
validateAssociatedScripts(table);
@ -487,6 +495,11 @@ public class QInstanceValidator
validateTableRecordSecurityLocks(qInstance, table);
validateTableAssociations(qInstance, table);
validateExposedJoins(qInstance, joinGraph, table);
for(QSupplementalTableMetaData supplementalTableMetaData : CollectionUtils.nonNullMap(table.getSupplementalMetaData()).values())
{
supplementalTableMetaData.validate(qInstance, table, this);
}
});
}
}
@ -686,7 +699,7 @@ public class QInstanceValidator
String prefix = "Field " + fieldName + " in table " + tableName + " ";
ValueTooLongBehavior behavior = field.getBehavior(qInstance, ValueTooLongBehavior.class);
ValueTooLongBehavior behavior = field.getBehaviorOrDefault(qInstance, ValueTooLongBehavior.class);
if(behavior != null && !behavior.equals(ValueTooLongBehavior.PASS_THROUGH))
{
assertCondition(field.getMaxLength() != null, prefix + "specifies a ValueTooLongBehavior, but not a maxLength.");
@ -1239,7 +1252,25 @@ public class QInstanceValidator
{
if(fieldMetaData.getDefaultValue() != null && fieldMetaData.getDefaultValue() instanceof QCodeReference codeReference)
{
validateSimpleCodeReference("Process " + processName + " backend step code reference: ", codeReference, BackendStep.class);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// by default, assume that any process field which is a QCodeReference should be a reference to a BackendStep... //
// but... allow a secondary field name to be set, to tell us what class to *actually* expect here... //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Class<?> expectedClass = BackendStep.class;
try
{
Optional<QFieldMetaData> expectedTypeField = backendStepMetaData.getInputMetaData().getField(fieldMetaData.getName() + "_expectedType");
if(expectedTypeField.isPresent() && expectedTypeField.get().getDefaultValue() != null)
{
expectedClass = Class.forName(ValueUtils.getValueAsString(expectedTypeField.get().getDefaultValue()));
}
}
catch(Exception e)
{
warn("Error loading expectedType for field [" + fieldMetaData.getName() + "] in process [" + processName + "]: " + e.getMessage());
}
validateSimpleCodeReference("Process " + processName + " code reference: ", codeReference, expectedClass);
}
}
}
@ -1760,20 +1791,6 @@ public class QInstanceValidator
/*******************************************************************************
**
*******************************************************************************/
@FunctionalInterface
interface UnsafeLambda
{
/*******************************************************************************
**
*******************************************************************************/
void run() throws Exception;
}
/*******************************************************************************
**
*******************************************************************************/

View File

@ -25,6 +25,7 @@ package com.kingsrook.qqq.backend.core.model.actions.tables.query;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.kingsrook.qqq.backend.core.logging.QLogger;
@ -42,7 +43,7 @@ public class QFilterCriteria implements Serializable, Cloneable
{
private static final QLogger LOG = QLogger.getLogger(QFilterCriteria.class);
private String fieldName;
private String fieldName;
private QCriteriaOperator operator;
private List<Serializable> values;
@ -93,11 +94,37 @@ public class QFilterCriteria implements Serializable, Cloneable
/*******************************************************************************
**
*******************************************************************************/
public QFilterCriteria(String fieldName, QCriteriaOperator operator, List<Serializable> values)
@SuppressWarnings("unchecked")
public QFilterCriteria(String fieldName, QCriteriaOperator operator, List<? extends Serializable> values)
{
this.fieldName = fieldName;
this.operator = operator;
this.values = values == null ? new ArrayList<>() : values;
this.values = values == null ? new ArrayList<>() : (List<Serializable>) values;
}
/*******************************************************************************
**
*******************************************************************************/
@SuppressWarnings({ "rawtypes", "unchecked" })
public QFilterCriteria(String fieldName, QCriteriaOperator operator, Collection<? extends Serializable> values)
{
this.fieldName = fieldName;
this.operator = operator;
if(values == null)
{
this.values = new ArrayList<>();
}
else if(values instanceof List list)
{
this.values = list;
}
else
{
this.values = new ArrayList<>(values);
}
}

View File

@ -323,6 +323,18 @@ public class QQueryFilter implements Serializable, Cloneable
/*******************************************************************************
** Fluent setter for adding a single subFilter
**
*******************************************************************************/
public QQueryFilter withSubFilter(QQueryFilter subFilter)
{
addSubFilter(subFilter);
return (this);
}
/*******************************************************************************
**
*******************************************************************************/

View File

@ -51,6 +51,7 @@ public class UpdateInput extends AbstractTableActionInput
////////////////////////////////////////////////////////////////////////////////////////////
private Boolean areAllValuesBeingUpdatedTheSame = null;
private boolean omitTriggeringAutomations = false;
private boolean omitDmlAudit = false;
private String auditContext = null;
@ -321,4 +322,35 @@ public class UpdateInput extends AbstractTableActionInput
return (this);
}
/*******************************************************************************
** Getter for omitTriggeringAutomations
*******************************************************************************/
public boolean getOmitTriggeringAutomations()
{
return (this.omitTriggeringAutomations);
}
/*******************************************************************************
** Setter for omitTriggeringAutomations
*******************************************************************************/
public void setOmitTriggeringAutomations(boolean omitTriggeringAutomations)
{
this.omitTriggeringAutomations = omitTriggeringAutomations;
}
/*******************************************************************************
** Fluent setter for omitTriggeringAutomations
*******************************************************************************/
public UpdateInput withOmitTriggeringAutomations(boolean omitTriggeringAutomations)
{
this.omitTriggeringAutomations = omitTriggeringAutomations;
return (this);
}
}

View File

@ -28,7 +28,7 @@ import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.tables.TablesPossibleValueSourceMetaDataProvider;
import com.kingsrook.qqq.backend.core.model.savedfilters.SavedFilter;
import com.kingsrook.qqq.backend.core.model.savedviews.SavedView;
import com.kingsrook.qqq.backend.core.model.scripts.Script;
@ -51,7 +51,7 @@ public class TableTrigger extends QRecordEntity
@QField(possibleValueSourceName = TablesPossibleValueSourceMetaDataProvider.NAME)
private String tableName;
@QField(possibleValueSourceName = SavedFilter.TABLE_NAME)
@QField(possibleValueSourceName = SavedView.TABLE_NAME)
private Integer filterId;
@QField(possibleValueSourceName = Script.TABLE_NAME)

View File

@ -32,6 +32,7 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.kingsrook.qqq.backend.core.exceptions.QException;
@ -108,7 +109,7 @@ public class QRecord implements Serializable
/*******************************************************************************
** Copy constructor.
** Copy constructor. Makes a deep clone.
**
*******************************************************************************/
public QRecord(QRecord record)
@ -120,10 +121,10 @@ public class QRecord implements Serializable
this.displayValues = deepCopySimpleMap(record.displayValues);
this.backendDetails = deepCopySimpleMap(record.backendDetails);
this.associatedRecords = deepCopyAssociatedRecords(record.associatedRecords);
this.errors = record.errors == null ? null : new ArrayList<>(record.errors);
this.warnings = record.warnings == null ? null : new ArrayList<>(record.warnings);
this.associatedRecords = deepCopyAssociatedRecords(record.associatedRecords);
}
@ -143,17 +144,17 @@ public class QRecord implements Serializable
** todo - move to a cloning utils maybe?
*******************************************************************************/
@SuppressWarnings({ "unchecked" })
private <K, V> Map<K, V> deepCopySimpleMap(Map<K, V> map)
private <V extends Serializable> Map<String, V> deepCopySimpleMap(Map<String, V> map)
{
if(map == null)
{
return (null);
}
Map<K, V> clone = new LinkedHashMap<>();
for(Map.Entry<K, V> entry : map.entrySet())
Map<String, V> clone = new LinkedHashMap<>();
for(Map.Entry<String, V> entry : map.entrySet())
{
V value = entry.getValue();
Serializable value = entry.getValue();
//////////////////////////////////////////////////////////////////////////
// not sure from where/how java.sql.Date objects are getting in here... //
@ -167,15 +168,32 @@ public class QRecord implements Serializable
ArrayList<?> cloneList = new ArrayList<>(arrayList);
clone.put(entry.getKey(), (V) cloneList);
}
else if(entry.getValue() instanceof Serializable serializableValue)
else if(entry.getValue() instanceof LinkedList<?> linkedList)
{
LOG.info("Non-primitive serializable value in QRecord - calling SerializationUtils.clone...", logPair("key", entry.getKey()), logPair("type", value.getClass()));
clone.put(entry.getKey(), (V) SerializationUtils.clone(serializableValue));
LinkedList<?> cloneList = new LinkedList<>(linkedList);
clone.put(entry.getKey(), (V) cloneList);
}
else if(entry.getValue() instanceof LinkedHashMap<?, ?> linkedHashMap)
{
LinkedHashMap<?, ?> cloneMap = new LinkedHashMap<>(linkedHashMap);
clone.put(entry.getKey(), (V) cloneMap);
}
else if(entry.getValue() instanceof HashMap<?, ?> hashMap)
{
HashMap<?, ?> cloneMap = new HashMap<>(hashMap);
clone.put(entry.getKey(), (V) cloneMap);
}
else if(entry.getValue() instanceof QRecord otherQRecord)
{
clone.put(entry.getKey(), (V) new QRecord(otherQRecord));
}
else
{
LOG.warn("Non-serializable value in QRecord...", logPair("key", entry.getKey()), logPair("type", value.getClass()));
clone.put(entry.getKey(), entry.getValue());
//////////////////////////////////////////////////////////////////////////////
// we know entry is serializable at this point, based on type param's bound //
//////////////////////////////////////////////////////////////////////////////
LOG.debug("Non-primitive serializable value in QRecord - calling SerializationUtils.clone...", logPair("key", entry.getKey()), logPair("type", value.getClass()));
clone.put(entry.getKey(), (V) SerializationUtils.clone(entry.getValue()));
}
}
return (clone);

View File

@ -95,6 +95,7 @@ public class MetaDataProducerHelper
////////////////////////////////////////////////////////////////////////////////////////////
// sort them by sort order, then by the type that they return - specifically - doing apps //
// after all other types (as apps often try to get other types from the instance) //
// also - do backends earlier than others (e.g., tables may expect backends to exist) //
////////////////////////////////////////////////////////////////////////////////////////////
producers.sort(Comparator
.comparing((MetaDataProducerInterface<?> p) -> p.getSortOrder())
@ -105,11 +106,15 @@ public class MetaDataProducerHelper
Class<?> outputType = p.getClass().getMethod("produce", QInstance.class).getReturnType();
if(outputType.equals(QAppMetaData.class))
{
return (1);
return (2);
}
else if(outputType.equals(QBackendMetaData.class))
{
return (0);
}
else
{
return (0);
return (1);
}
}
catch(Exception e)

View File

@ -746,12 +746,22 @@ public class QInstance
/*******************************************************************************
** Setter for hasBeenValidated
** If pass a QInstanceValidationKey (which can only be instantiated by the validator),
** then the hasBeenValidated field will be set to true.
**
** Else, if passed a null, hasBeenValidated will be reset to false - e.g., to
** re-trigger validation (can be useful in tests).
*******************************************************************************/
public void setHasBeenValidated(QInstanceValidationKey key)
{
this.hasBeenValidated = true;
if(key == null)
{
this.hasBeenValidated = false;
}
else
{
this.hasBeenValidated = true;
}
}
@ -1198,4 +1208,14 @@ public class QInstance
return (this);
}
/*******************************************************************************
**
*******************************************************************************/
public void add(TopLevelMetaDataInterface metaData)
{
metaData.addSelfToInstance(this);
}
}

View File

@ -51,6 +51,7 @@ public class HtmlWrapper implements Serializable
public static final String STYLE_INDENT_2 = "padding-left: 2rem; ";
public static final String STYLE_FLOAT_RIGHT = "float: right; ";
public static final String STYLE_RED = "color: red; ";
public static final String STYLE_YELLOW = "color: #bfb743; ";

View File

@ -0,0 +1,164 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2022. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.kingsrook.qqq.backend.core.model.metadata.fields;
import java.io.Serializable;
import java.time.Instant;
import java.time.LocalDate;
import java.util.List;
import com.kingsrook.qqq.backend.core.actions.values.ValueBehaviorApplier;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** Field behavior that sets a default value for a field dynamically.
** e.g., create-date fields get set to 'now' on insert.
** e.g., modify-date fields get set to 'now' on insert and on update.
*******************************************************************************/
public enum DynamicDefaultValueBehavior implements FieldBehavior<DynamicDefaultValueBehavior>
{
CREATE_DATE,
MODIFY_DATE,
NONE;
private static final QLogger LOG = QLogger.getLogger(ValueTooLongBehavior.class);
/*******************************************************************************
**
*******************************************************************************/
@Override
public DynamicDefaultValueBehavior getDefault()
{
return (NONE);
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void apply(ValueBehaviorApplier.Action action, List<QRecord> recordList, QInstance instance, QTableMetaData table, QFieldMetaData field)
{
if(this.equals(NONE))
{
return;
}
switch(this)
{
case CREATE_DATE -> applyCreateDate(action, recordList, table, field);
case MODIFY_DATE -> applyModifyDate(action, recordList, table, field);
default -> throw new IllegalStateException("Unexpected enum value: " + this);
}
}
/*******************************************************************************
**
*******************************************************************************/
private void applyCreateDate(ValueBehaviorApplier.Action action, List<QRecord> recordList, QTableMetaData table, QFieldMetaData field)
{
if(!ValueBehaviorApplier.Action.INSERT.equals(action))
{
return;
}
setCreateDateOrModifyDateOnList(recordList, table, field);
}
/*******************************************************************************
**
*******************************************************************************/
private void applyModifyDate(ValueBehaviorApplier.Action action, List<QRecord> recordList, QTableMetaData table, QFieldMetaData field)
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// check both of these (even though they're the only 2 values at the time of this writing), just in case more enum values are added in the future //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(!ValueBehaviorApplier.Action.INSERT.equals(action) && !ValueBehaviorApplier.Action.UPDATE.equals(action))
{
return;
}
setCreateDateOrModifyDateOnList(recordList, table, field);
}
/*******************************************************************************
**
*******************************************************************************/
private void setCreateDateOrModifyDateOnList(List<QRecord> recordList, QTableMetaData table, QFieldMetaData field)
{
String fieldName = field.getName();
Serializable value = getNow(table, field);
for(QRecord record : CollectionUtils.nonNullList(recordList))
{
record.setValue(fieldName, value);
}
}
/*******************************************************************************
**
*******************************************************************************/
private Serializable getNow(QTableMetaData table, QFieldMetaData field)
{
if(QFieldType.DATE_TIME.equals(field.getType()))
{
return (Instant.now());
}
else if(QFieldType.DATE.equals(field.getType()))
{
return (LocalDate.now());
}
else
{
LOG.debug("Request to apply a " + this.name() + " DynamicDefaultValueBehavior to a non-date or date-time field", logPair("table", table.getName()), logPair("field", field.getName()));
return (null);
}
}
/*******************************************************************************
**
*******************************************************************************/
private void noop()
{
}
}

View File

@ -22,10 +22,41 @@
package com.kingsrook.qqq.backend.core.model.metadata.fields;
import java.util.List;
import com.kingsrook.qqq.backend.core.actions.values.ValueBehaviorApplier;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
/*******************************************************************************
** Interface for (expected to be?) enums which define behaviors that get applied
** to fields.
**
** At the present, these behaviors get applied before a field is stored (insert
** or update), through the ValueBehaviorApplier class.
**
*******************************************************************************/
public interface FieldBehavior
public interface FieldBehavior<T extends FieldBehavior<T>>
{
/*******************************************************************************
** In case a behavior of this type wasn't set on the field, what should the
** default of this type be?
*******************************************************************************/
T getDefault();
/*******************************************************************************
** Apply this behavior to a list of records
*******************************************************************************/
void apply(ValueBehaviorApplier.Action action, List<QRecord> recordList, QInstance instance, QTableMetaData table, QFieldMetaData field);
/*******************************************************************************
** control if multiple behaviors of this type should be allowed together on a field.
*******************************************************************************/
default boolean allowMultipleBehaviorsOfThisType()
{
return (false);
}
}

View File

@ -35,6 +35,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.github.hervian.reflection.Fun;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.instances.QInstanceHelpContentManager;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
@ -44,6 +45,7 @@ import com.kingsrook.qqq.backend.core.model.metadata.help.QHelpContent;
import com.kingsrook.qqq.backend.core.model.metadata.security.FieldSecurityLock;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
@ -52,6 +54,8 @@ import com.kingsrook.qqq.backend.core.utils.StringUtils;
*******************************************************************************/
public class QFieldMetaData implements Cloneable
{
private static final QLogger LOG = QLogger.getLogger(QFieldMetaData.class);
private String name;
private String label;
private String backendName;
@ -73,8 +77,8 @@ public class QFieldMetaData implements Cloneable
private String possibleValueSourceName;
private QQueryFilter possibleValueSourceFilter;
private Integer maxLength;
private Set<FieldBehavior> behaviors;
private Integer maxLength;
private Set<FieldBehavior<?>> behaviors;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// w/ longer-term vision for FieldBehaviors //
@ -674,7 +678,7 @@ public class QFieldMetaData implements Cloneable
** Getter for behaviors
**
*******************************************************************************/
public Set<FieldBehavior> getBehaviors()
public Set<FieldBehavior<?>> getBehaviors()
{
return behaviors;
}
@ -682,11 +686,12 @@ public class QFieldMetaData implements Cloneable
/*******************************************************************************
**
** Get the FieldBehavior object of a given behaviorType (class) - but - if one
** isn't set, then use the default from that type.
*******************************************************************************/
public <T extends FieldBehavior> T getBehavior(QInstance instance, Class<T> behaviorType)
public <T extends FieldBehavior<T>> T getBehaviorOrDefault(QInstance instance, Class<T> behaviorType)
{
for(FieldBehavior fieldBehavior : CollectionUtils.nonNullCollection(behaviors))
for(FieldBehavior<?> fieldBehavior : CollectionUtils.nonNullCollection(behaviors))
{
if(behaviorType.isInstance(fieldBehavior))
{
@ -701,9 +706,33 @@ public class QFieldMetaData implements Cloneable
///////////////////////////////////////////
// return default behavior for this type //
///////////////////////////////////////////
if(behaviorType.equals(ValueTooLongBehavior.class))
if(behaviorType.isEnum())
{
return behaviorType.cast(ValueTooLongBehavior.getDefault());
return (behaviorType.getEnumConstants()[0].getDefault());
}
return (null);
}
/*******************************************************************************
** Get the FieldBehavior object of a given behaviorType (class) - and if one
** isn't set, then return null.
*******************************************************************************/
public <T extends FieldBehavior<T>> T getBehaviorOnlyIfSet(Class<T> behaviorType)
{
if(behaviors == null)
{
return (null);
}
for(FieldBehavior<?> fieldBehavior : CollectionUtils.nonNullCollection(behaviors))
{
if(behaviorType.isInstance(fieldBehavior))
{
return (behaviorType.cast(fieldBehavior));
}
}
return (null);
@ -715,7 +744,7 @@ public class QFieldMetaData implements Cloneable
** Setter for behaviors
**
*******************************************************************************/
public void setBehaviors(Set<FieldBehavior> behaviors)
public void setBehaviors(Set<FieldBehavior<?>> behaviors)
{
this.behaviors = behaviors;
}
@ -726,7 +755,7 @@ public class QFieldMetaData implements Cloneable
** Fluent setter for behaviors
**
*******************************************************************************/
public QFieldMetaData withBehaviors(Set<FieldBehavior> behaviors)
public QFieldMetaData withBehaviors(Set<FieldBehavior<?>> behaviors)
{
this.behaviors = behaviors;
return (this);
@ -738,12 +767,30 @@ public class QFieldMetaData implements Cloneable
** Fluent setter for behaviors
**
*******************************************************************************/
public QFieldMetaData withBehavior(FieldBehavior behavior)
public QFieldMetaData withBehavior(FieldBehavior<?> behavior)
{
if(behavior == null)
{
LOG.debug("Skipping request to add null behavior", logPair("fieldName", getName()));
return (this);
}
if(behaviors == null)
{
behaviors = new HashSet<>();
}
if(!behavior.allowMultipleBehaviorsOfThisType())
{
@SuppressWarnings("unchecked")
FieldBehavior<?> existingBehaviorOfThisType = getBehaviorOnlyIfSet(behavior.getClass());
if(existingBehaviorOfThisType != null)
{
LOG.debug("Replacing a field behavior", logPair("fieldName", getName()), logPair("oldBehavior", existingBehaviorOfThisType), logPair("newBehavior", behavior));
this.behaviors.remove(existingBehaviorOfThisType);
}
}
this.behaviors.add(behavior);
return (this);
}

View File

@ -22,23 +22,85 @@
package com.kingsrook.qqq.backend.core.model.metadata.fields;
import java.util.List;
import com.kingsrook.qqq.backend.core.actions.values.ValueBehaviorApplier;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.model.statusmessages.BadInputStatusMessage;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** Behaviors for string fields, if their value is too long.
**
** Note: This was the first implementation of a FieldBehavior, so its test
** coverage is provided in ValueBehaviorApplierTest.
*******************************************************************************/
public enum ValueTooLongBehavior implements FieldBehavior
public enum ValueTooLongBehavior implements FieldBehavior<ValueTooLongBehavior>
{
TRUNCATE,
TRUNCATE_ELLIPSIS,
ERROR,
PASS_THROUGH;
private static final QLogger LOG = QLogger.getLogger(ValueTooLongBehavior.class);
/*******************************************************************************
**
*******************************************************************************/
public static FieldBehavior getDefault()
@Override
public ValueTooLongBehavior getDefault()
{
return PASS_THROUGH;
return (PASS_THROUGH);
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void apply(ValueBehaviorApplier.Action action, List<QRecord> recordList, QInstance instance, QTableMetaData table, QFieldMetaData field)
{
if(this.equals(PASS_THROUGH))
{
return;
}
String fieldName = field.getName();
if(!QFieldType.STRING.equals(field.getType()))
{
LOG.debug("Request to apply a ValueTooLongBehavior to a non-string field", logPair("table", table.getName()), logPair("field", fieldName));
return;
}
if(field.getMaxLength() == null)
{
LOG.debug("Request to apply a ValueTooLongBehavior to string field without a maxLength", logPair("table", table.getName()), logPair("field", fieldName));
return;
}
for(QRecord record : recordList)
{
String value = record.getValueString(fieldName);
if(value != null && value.length() > field.getMaxLength())
{
switch(this)
{
case TRUNCATE -> record.setValue(fieldName, StringUtils.safeTruncate(value, field.getMaxLength()));
case TRUNCATE_ELLIPSIS -> record.setValue(fieldName, StringUtils.safeTruncate(value, field.getMaxLength(), "..."));
case ERROR -> record.addError(new BadInputStatusMessage("The value for " + field.getLabel() + " is too long (max allowed length=" + field.getMaxLength() + ")"));
///////////////////////////////////
// PASS_THROUGH is handled above //
///////////////////////////////////
default -> throw new IllegalStateException("Unexpected enum value: " + this);
}
}
}
}
}

View File

@ -43,6 +43,8 @@ public class QAppMetaData implements QAppChildMetaData, MetaDataWithPermissionRu
private String name;
private String label;
private Integer sortOrder = 500;
private QPermissionRules permissionRules;
private List<QAppChildMetaData> children;
@ -426,4 +428,36 @@ public class QAppMetaData implements QAppChildMetaData, MetaDataWithPermissionRu
{
qInstance.addApp(this);
}
/*******************************************************************************
** Getter for sortOrder
*******************************************************************************/
public Integer getSortOrder()
{
return (this.sortOrder);
}
/*******************************************************************************
** Setter for sortOrder
*******************************************************************************/
public void setSortOrder(Integer sortOrder)
{
this.sortOrder = sortOrder;
}
/*******************************************************************************
** Fluent setter for sortOrder
*******************************************************************************/
public QAppMetaData withSortOrder(Integer sortOrder)
{
this.sortOrder = sortOrder;
return (this);
}
}

View File

@ -23,8 +23,11 @@ package com.kingsrook.qqq.backend.core.model.metadata.processes;
import java.io.Serializable;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QIcon;
import com.kingsrook.qqq.backend.core.model.metadata.scheduleing.QScheduleMetaData;
import com.kingsrook.qqq.backend.core.processes.implementations.basepull.BasepullConfiguration;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
@ -32,6 +35,8 @@ import com.kingsrook.qqq.backend.core.processes.implementations.basepull.Basepul
*******************************************************************************/
public class AbstractProcessMetaDataBuilder
{
private static final QLogger LOG = QLogger.getLogger(AbstractProcessMetaDataBuilder.class);
protected QProcessMetaData processMetaData;
@ -58,6 +63,54 @@ public class AbstractProcessMetaDataBuilder
/*******************************************************************************
** Fluent setter for name
**
*******************************************************************************/
public AbstractProcessMetaDataBuilder withName(String name)
{
processMetaData.setName(name);
return (this);
}
/*******************************************************************************
** Fluent setter for label
**
*******************************************************************************/
public AbstractProcessMetaDataBuilder withLabel(String name)
{
processMetaData.setLabel(name);
return (this);
}
/*******************************************************************************
** Fluent setter for tableName
**
*******************************************************************************/
public AbstractProcessMetaDataBuilder withTableName(String tableName)
{
processMetaData.setTableName(tableName);
return (this);
}
/*******************************************************************************
** Fluent setter for icon
**
*******************************************************************************/
public AbstractProcessMetaDataBuilder withIcon(QIcon icon)
{
processMetaData.setIcon(icon);
return (this);
}
/*******************************************************************************
**
*******************************************************************************/
@ -65,7 +118,8 @@ public class AbstractProcessMetaDataBuilder
{
processMetaData.getInputFields().stream()
.filter(f -> f.getName().equals(fieldName)).findFirst()
.ifPresent(f -> f.setDefaultValue(value));
.ifPresentOrElse(f -> f.setDefaultValue(value),
() -> LOG.warn("Could not find process input field for setting default value", logPair("processName", () -> processMetaData.getName()), logPair("fieldName", fieldName)));
}

View File

@ -22,6 +22,7 @@
package com.kingsrook.qqq.backend.core.model.metadata.tables;
import com.kingsrook.qqq.backend.core.instances.QInstanceValidator;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
@ -69,4 +70,16 @@ public abstract class QSupplementalTableMetaData
// noop in base class //
////////////////////////
}
/*******************************************************************************
**
*******************************************************************************/
public void validate(QInstance qInstance, QTableMetaData tableMetaData, QInstanceValidator qInstanceValidator)
{
////////////////////////
// noop in base class //
////////////////////////
}
}

View File

@ -23,6 +23,9 @@ package com.kingsrook.qqq.backend.core.model.metadata.tables;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.kingsrook.qqq.backend.core.instances.QInstanceValidator;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.serialization.QTableBackendDetailsDeserializer;
import com.kingsrook.qqq.backend.core.modules.backend.QBackendModuleInterface;
@ -100,4 +103,16 @@ public abstract class QTableBackendDetails
return (this);
}
/*******************************************************************************
**
*******************************************************************************/
public void validate(QInstance qInstance, QTableMetaData table, QInstanceValidator qInstanceValidator)
{
////////////////////////
// noop in base class //
////////////////////////
}
}

View File

@ -34,6 +34,7 @@ import java.util.Optional;
import java.util.Set;
import com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizers;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntityField;
import com.kingsrook.qqq.backend.core.model.metadata.QBackendMetaData;
@ -49,6 +50,7 @@ import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRule
import com.kingsrook.qqq.backend.core.model.metadata.security.RecordSecurityLock;
import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.QTableAutomationDetails;
import com.kingsrook.qqq.backend.core.model.metadata.tables.cache.CacheOf;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
@ -57,6 +59,8 @@ import com.kingsrook.qqq.backend.core.model.metadata.tables.cache.CacheOf;
*******************************************************************************/
public class QTableMetaData implements QAppChildMetaData, Serializable, MetaDataWithPermissionRules, TopLevelMetaDataInterface
{
private static final QLogger LOG = QLogger.getLogger(QTableMetaData.class);
private String name;
private String label;
@ -813,6 +817,15 @@ public class QTableMetaData implements QAppChildMetaData, Serializable, MetaData
*******************************************************************************/
public QTableMetaData withUniqueKey(UniqueKey uniqueKey)
{
////////////////////////////////////////////////////////////////////////////////////
// you can't add a null key, so, if someone tried, just gracefully return w/ noop //
////////////////////////////////////////////////////////////////////////////////////
if(uniqueKey == null)
{
LOG.debug("Skipping request to add null uniqueKey", logPair("tableName", name));
return (this);
}
if(this.uniqueKeys == null)
{
this.uniqueKeys = new ArrayList<>();
@ -1130,6 +1143,15 @@ public class QTableMetaData implements QAppChildMetaData, Serializable, MetaData
*******************************************************************************/
public QTableMetaData withRecordSecurityLock(RecordSecurityLock recordSecurityLock)
{
/////////////////////////////////////////////////////////////////////////////////////
// you can't add a null lock, so, if someone tried, just gracefully return w/ noop //
/////////////////////////////////////////////////////////////////////////////////////
if(recordSecurityLock == null)
{
LOG.debug("Skipping request to add null recordSecurityLock", logPair("tableName", name));
return (this);
}
if(this.recordSecurityLocks == null)
{
this.recordSecurityLocks = new ArrayList<>();

View File

@ -37,6 +37,11 @@ public class QTableAutomationDetails
private Integer overrideBatchSize;
private String shardByFieldName; // field in "this" table, to use for sharding
private String shardSourceTableName; // name of the table where the shards are defined as rows
private String shardLabelFieldName; // field in shard-source-table to use for labeling shards
private String shardIdFieldName; // field in shard-source-table to identify shards (e.g., joins to this table's shardByFieldName)
/*******************************************************************************
@ -188,4 +193,128 @@ public class QTableAutomationDetails
return (this);
}
/*******************************************************************************
** Getter for shardByFieldName
*******************************************************************************/
public String getShardByFieldName()
{
return (this.shardByFieldName);
}
/*******************************************************************************
** Setter for shardByFieldName
*******************************************************************************/
public void setShardByFieldName(String shardByFieldName)
{
this.shardByFieldName = shardByFieldName;
}
/*******************************************************************************
** Fluent setter for shardByFieldName
*******************************************************************************/
public QTableAutomationDetails withShardByFieldName(String shardByFieldName)
{
this.shardByFieldName = shardByFieldName;
return (this);
}
/*******************************************************************************
** Getter for shardSourceTableName
*******************************************************************************/
public String getShardSourceTableName()
{
return (this.shardSourceTableName);
}
/*******************************************************************************
** Setter for shardSourceTableName
*******************************************************************************/
public void setShardSourceTableName(String shardSourceTableName)
{
this.shardSourceTableName = shardSourceTableName;
}
/*******************************************************************************
** Fluent setter for shardSourceTableName
*******************************************************************************/
public QTableAutomationDetails withShardSourceTableName(String shardSourceTableName)
{
this.shardSourceTableName = shardSourceTableName;
return (this);
}
/*******************************************************************************
** Getter for shardLabelFieldName
*******************************************************************************/
public String getShardLabelFieldName()
{
return (this.shardLabelFieldName);
}
/*******************************************************************************
** Setter for shardLabelFieldName
*******************************************************************************/
public void setShardLabelFieldName(String shardLabelFieldName)
{
this.shardLabelFieldName = shardLabelFieldName;
}
/*******************************************************************************
** Fluent setter for shardLabelFieldName
*******************************************************************************/
public QTableAutomationDetails withShardLabelFieldName(String shardLabelFieldName)
{
this.shardLabelFieldName = shardLabelFieldName;
return (this);
}
/*******************************************************************************
** Getter for shardIdFieldName
*******************************************************************************/
public String getShardIdFieldName()
{
return (this.shardIdFieldName);
}
/*******************************************************************************
** Setter for shardIdFieldName
*******************************************************************************/
public void setShardIdFieldName(String shardIdFieldName)
{
this.shardIdFieldName = shardIdFieldName;
}
/*******************************************************************************
** Fluent setter for shardIdFieldName
*******************************************************************************/
public QTableAutomationDetails withShardIdFieldName(String shardIdFieldName)
{
this.shardIdFieldName = shardIdFieldName;
return (this);
}
}

View File

@ -37,6 +37,7 @@ public class TableAutomationAction
private TriggerEvent triggerEvent;
private Integer priority = 500;
private QQueryFilter filter;
private Serializable shardId;
////////////////////////////////////////////////////////////////////////
// flag that will cause the records to cause their associations to be //
@ -329,4 +330,35 @@ public class TableAutomationAction
return (this);
}
/*******************************************************************************
** Getter for shardId
*******************************************************************************/
public Serializable getShardId()
{
return (this.shardId);
}
/*******************************************************************************
** Setter for shardId
*******************************************************************************/
public void setShardId(Serializable shardId)
{
this.shardId = shardId;
}
/*******************************************************************************
** Fluent setter for shardId
*******************************************************************************/
public TableAutomationAction withShardId(Serializable shardId)
{
this.shardId = shardId;
return (this);
}
}

View File

@ -1,6 +1,6 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2023. Kingsrook, LLC
* Copyright (C) 2021-2024. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
@ -19,7 +19,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.kingsrook.qqq.backend.core.model.savedfilters;
package com.kingsrook.qqq.backend.core.model.savedviews;
import java.time.Instant;
@ -32,9 +32,9 @@ import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
/*******************************************************************************
** Entity bean for the saved filter table
*******************************************************************************/
public class SavedFilter extends QRecordEntity
public class SavedView extends QRecordEntity
{
public static final String TABLE_NAME = "savedFilter";
public static final String TABLE_NAME = "savedView";
@QField(isEditable = false)
private Integer id;
@ -55,7 +55,7 @@ public class SavedFilter extends QRecordEntity
private String userId;
@QField(isEditable = false)
private String filterJson;
private String viewJson;
@ -63,7 +63,7 @@ public class SavedFilter extends QRecordEntity
** Constructor
**
*******************************************************************************/
public SavedFilter()
public SavedView()
{
}
@ -73,7 +73,7 @@ public class SavedFilter extends QRecordEntity
** Constructor
**
*******************************************************************************/
public SavedFilter(QRecord qRecord) throws QException
public SavedView(QRecord qRecord) throws QException
{
populateFromQRecord(qRecord);
}
@ -172,7 +172,7 @@ public class SavedFilter extends QRecordEntity
** Fluent setter for label
**
*******************************************************************************/
public SavedFilter withLabel(String label)
public SavedView withLabel(String label)
{
this.label = label;
return (this);
@ -206,7 +206,7 @@ public class SavedFilter extends QRecordEntity
** Fluent setter for tableName
**
*******************************************************************************/
public SavedFilter withTableName(String tableName)
public SavedView withTableName(String tableName)
{
this.tableName = tableName;
return (this);
@ -240,7 +240,7 @@ public class SavedFilter extends QRecordEntity
** Fluent setter for userId
**
*******************************************************************************/
public SavedFilter withUserId(String userId)
public SavedView withUserId(String userId)
{
this.userId = userId;
return (this);
@ -249,34 +249,31 @@ public class SavedFilter extends QRecordEntity
/*******************************************************************************
** Getter for filterJson
**
** Getter for viewJson
*******************************************************************************/
public String getFilterJson()
public String getViewJson()
{
return filterJson;
return (this.viewJson);
}
/*******************************************************************************
** Setter for filterJson
**
** Setter for viewJson
*******************************************************************************/
public void setFilterJson(String filterJson)
public void setViewJson(String viewJson)
{
this.filterJson = filterJson;
this.viewJson = viewJson;
}
/*******************************************************************************
** Fluent setter for filterJson
**
** Fluent setter for viewJson
*******************************************************************************/
public SavedFilter withFilterJson(String filterJson)
public SavedView withViewJson(String viewJson)
{
this.filterJson = filterJson;
this.viewJson = viewJson;
return (this);
}

View File

@ -1,6 +1,6 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2022. Kingsrook, LLC
* Copyright (C) 2021-2024. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
@ -19,25 +19,31 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.kingsrook.qqq.backend.core.model.savedfilters;
package com.kingsrook.qqq.backend.core.model.savedviews;
import java.util.List;
import java.util.function.Consumer;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.fields.AdornmentType;
import com.kingsrook.qqq.backend.core.model.metadata.fields.FieldAdornment;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QIcon;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.PVSValueFormatAndFields;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSource;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSourceType;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QFieldSection;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.processes.implementations.savedfilters.DeleteSavedFilterProcess;
import com.kingsrook.qqq.backend.core.processes.implementations.savedfilters.QuerySavedFilterProcess;
import com.kingsrook.qqq.backend.core.processes.implementations.savedfilters.StoreSavedFilterProcess;
import com.kingsrook.qqq.backend.core.model.metadata.tables.Tier;
import com.kingsrook.qqq.backend.core.processes.implementations.savedviews.DeleteSavedViewProcess;
import com.kingsrook.qqq.backend.core.processes.implementations.savedviews.QuerySavedViewProcess;
import com.kingsrook.qqq.backend.core.processes.implementations.savedviews.StoreSavedViewProcess;
/*******************************************************************************
**
*******************************************************************************/
public class SavedFiltersMetaDataProvider
public class SavedViewsMetaDataProvider
{
@ -46,11 +52,11 @@ public class SavedFiltersMetaDataProvider
*******************************************************************************/
public void defineAll(QInstance instance, String backendName, Consumer<QTableMetaData> backendDetailEnricher) throws QException
{
instance.addTable(defineSavedFilterTable(backendName, backendDetailEnricher));
instance.addPossibleValueSource(defineSavedFilterPossibleValueSource());
instance.addProcess(QuerySavedFilterProcess.getProcessMetaData());
instance.addProcess(StoreSavedFilterProcess.getProcessMetaData());
instance.addProcess(DeleteSavedFilterProcess.getProcessMetaData());
instance.addTable(defineSavedViewTable(backendName, backendDetailEnricher));
instance.addPossibleValueSource(defineSavedViewPossibleValueSource());
instance.addProcess(QuerySavedViewProcess.getProcessMetaData());
instance.addProcess(StoreSavedViewProcess.getProcessMetaData());
instance.addProcess(DeleteSavedViewProcess.getProcessMetaData());
}
@ -58,16 +64,21 @@ public class SavedFiltersMetaDataProvider
/*******************************************************************************
**
*******************************************************************************/
private QTableMetaData defineSavedFilterTable(String backendName, Consumer<QTableMetaData> backendDetailEnricher) throws QException
public QTableMetaData defineSavedViewTable(String backendName, Consumer<QTableMetaData> backendDetailEnricher) throws QException
{
QTableMetaData table = new QTableMetaData()
.withName(SavedFilter.TABLE_NAME)
.withLabel("Saved Filter")
.withName(SavedView.TABLE_NAME)
.withLabel("Saved View")
.withRecordLabelFormat("%s")
.withRecordLabelFields("label")
.withBackendName(backendName)
.withPrimaryKeyField("id")
.withFieldsFromEntity(SavedFilter.class);
.withFieldsFromEntity(SavedView.class)
.withSection(new QFieldSection("identity", new QIcon().withName("badge"), Tier.T1, List.of("id", "label")))
.withSection(new QFieldSection("data", new QIcon().withName("text_snippet"), Tier.T2, List.of("userId", "tableName", "viewJson")))
.withSection(new QFieldSection("dates", new QIcon().withName("calendar_month"), Tier.T3, List.of("createDate", "modifyDate")));
table.getField("viewJson").withFieldAdornment(new FieldAdornment(AdornmentType.CODE_EDITOR).withValue(AdornmentType.CodeEditorValues.languageMode("json")));
if(backendDetailEnricher != null)
{
@ -82,12 +93,12 @@ public class SavedFiltersMetaDataProvider
/*******************************************************************************
**
*******************************************************************************/
private QPossibleValueSource defineSavedFilterPossibleValueSource()
private QPossibleValueSource defineSavedViewPossibleValueSource()
{
return new QPossibleValueSource()
.withName(SavedFilter.TABLE_NAME)
.withName(SavedView.TABLE_NAME)
.withType(QPossibleValueSourceType.TABLE)
.withTableName(SavedFilter.TABLE_NAME)
.withTableName(SavedView.TABLE_NAME)
.withValueFormatAndFields(PVSValueFormatAndFields.LABEL_ONLY)
.withOrderByField("label");
}

View File

@ -142,6 +142,19 @@ public class QSession implements Serializable
/*******************************************************************************
**
*******************************************************************************/
public void removeValue(String key)
{
if(values != null)
{
values.remove(key);
}
}
/*******************************************************************************
**
*******************************************************************************/

View File

@ -176,7 +176,7 @@ public class Auth0AuthenticationModule implements QAuthenticationModuleInterface
// process a sessionUUID - looks up userSession record - cannot create token this way. //
/////////////////////////////////////////////////////////////////////////////////////////
String sessionUUID = context.get(SESSION_UUID_KEY);
LOG.info("Creating session from sessionUUID (userSession)", logPair("sessionUUID", maskForLog(sessionUUID)));
LOG.debug("Creating session from sessionUUID (userSession)", logPair("sessionUUID", maskForLog(sessionUUID)));
if(sessionUUID != null)
{
accessToken = getAccessTokenFromSessionUUID(metaData, sessionUUID);

View File

@ -22,6 +22,7 @@
package com.kingsrook.qqq.backend.core.modules.backend;
import com.kingsrook.qqq.backend.core.actions.QBackendTransaction;
import com.kingsrook.qqq.backend.core.actions.interfaces.AggregateInterface;
import com.kingsrook.qqq.backend.core.actions.interfaces.CountInterface;
import com.kingsrook.qqq.backend.core.actions.interfaces.DeleteInterface;
@ -29,6 +30,8 @@ import com.kingsrook.qqq.backend.core.actions.interfaces.GetInterface;
import com.kingsrook.qqq.backend.core.actions.interfaces.InsertInterface;
import com.kingsrook.qqq.backend.core.actions.interfaces.QueryInterface;
import com.kingsrook.qqq.backend.core.actions.interfaces.UpdateInterface;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.AbstractTableActionInput;
import com.kingsrook.qqq.backend.core.model.metadata.QBackendMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableBackendDetails;
@ -126,6 +129,14 @@ public interface QBackendModuleInterface
return null;
}
/*******************************************************************************
**
*******************************************************************************/
default QBackendTransaction openTransaction(AbstractTableActionInput input) throws QException
{
return (new QBackendTransaction());
}
/*******************************************************************************
**
*******************************************************************************/

View File

@ -23,7 +23,6 @@ package com.kingsrook.qqq.backend.core.modules.backend.implementations.memory;
import java.io.Serializable;
import com.kingsrook.qqq.backend.core.actions.interfaces.QActionInterface;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
@ -32,7 +31,7 @@ import com.kingsrook.qqq.backend.core.utils.StringUtils;
/*******************************************************************************
** Base class for all core actions in the Memory backend module.
*******************************************************************************/
public abstract class AbstractMemoryAction implements QActionInterface
public abstract class AbstractMemoryAction
{
/*******************************************************************************

View File

@ -22,13 +22,10 @@
package com.kingsrook.qqq.backend.core.modules.backend.implementations.memory;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.actions.interfaces.InsertInterface;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertOutput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
/*******************************************************************************
@ -45,18 +42,6 @@ public class MemoryInsertAction extends AbstractMemoryAction implements InsertIn
{
try
{
QTableMetaData table = insertInput.getTable();
Instant now = Instant.now();
for(QRecord record : insertInput.getRecords())
{
///////////////////////////////////////////
// todo .. better (not hard-coded names) //
///////////////////////////////////////////
setValueIfTableHasField(record, table, "createDate", now, false);
setValueIfTableHasField(record, table, "modifyDate", now, false);
}
InsertOutput insertOutput = new InsertOutput();
insertOutput.setRecords(MemoryRecordStore.getInstance().insert(insertInput, true));
return (insertOutput);

View File

@ -24,6 +24,10 @@ package com.kingsrook.qqq.backend.core.modules.backend.implementations.memory;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@ -35,6 +39,7 @@ import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.kingsrook.qqq.backend.core.actions.dashboard.widgets.DateTimeGroupBy;
import com.kingsrook.qqq.backend.core.actions.tables.helpers.ValidateRecordSecurityLockHelper;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
@ -66,6 +71,7 @@ import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.modules.backend.implementations.utils.BackendQueryFilterUtils;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.backend.core.utils.ListingHash;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import com.kingsrook.qqq.backend.core.utils.ValueUtils;
@ -577,7 +583,11 @@ public class MemoryRecordStore
for(GroupBy groupBy : groupBys)
{
Serializable groupByValue = record.getValue(groupBy.getFieldName());
if(groupBy.getType() != null)
if(StringUtils.hasContent(groupBy.getFormatString()))
{
groupByValue = applyFormatString(groupByValue, groupBy);
}
else if(groupBy.getType() != null)
{
groupByValue = ValueUtils.getValueAsFieldType(groupBy.getType(), groupByValue);
}
@ -629,7 +639,9 @@ public class MemoryRecordStore
/////////////////////
if(aggregateInput.getFilter() != null && CollectionUtils.nullSafeHasContents(aggregateInput.getFilter().getOrderBys()))
{
Comparator<AggregateResult> comparator = null;
/////////////////////////////////////////////////////////////////////////////////////
// lambda to compare 2 serializables, as we'll assume (& cast) them to Comparables //
/////////////////////////////////////////////////////////////////////////////////////
Comparator<Serializable> serializableComparator = (Serializable a, Serializable b) ->
{
if(a == null && b == null)
@ -647,9 +659,15 @@ public class MemoryRecordStore
return ((Comparable) a).compareTo(b);
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// reverse of the lambda above (we had some errors calling .reversed() on the comparator we were building, so this seemed simpler & worked) //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Comparator<Serializable> reverseSerializableComparator = (Serializable a, Serializable b) -> -serializableComparator.compare(a, b);
////////////////////////////////////////////////
// build a comparator out of all the orderBys //
////////////////////////////////////////////////
Comparator<AggregateResult> comparator = null;
for(QFilterOrderBy orderBy : aggregateInput.getFilter().getOrderBys())
{
Function<AggregateResult, Serializable> keyExtractor = aggregateResult ->
@ -670,16 +688,11 @@ public class MemoryRecordStore
if(comparator == null)
{
comparator = Comparator.comparing(keyExtractor, serializableComparator);
comparator = Comparator.comparing(keyExtractor, orderBy.getIsAscending() ? serializableComparator : reverseSerializableComparator);
}
else
{
comparator = comparator.thenComparing(keyExtractor, serializableComparator);
}
if(!orderBy.getIsAscending())
{
comparator = comparator.reversed();
comparator = comparator.thenComparing(keyExtractor, orderBy.getIsAscending() ? serializableComparator : reverseSerializableComparator);
}
}
@ -696,6 +709,57 @@ public class MemoryRecordStore
/*******************************************************************************
**
*******************************************************************************/
private Serializable applyFormatString(Serializable value, GroupBy groupBy) throws QException
{
if(value == null)
{
return (null);
}
String formatString = groupBy.getFormatString();
try
{
if(formatString.startsWith("DATE_FORMAT"))
{
/////////////////////////////////////////////////////////////////////////////
// one known-use case we have here looks like this: //
// DATE_FORMAT(CONVERT_TZ(%s, 'UTC', 'UTC'), '%%Y-%%m-%%dT%%H') //
// ... for now, let's just try to support the formatting bit at the end... //
// todo - support the CONVERT_TZ bit too! //
/////////////////////////////////////////////////////////////////////////////
String sqlDateTimeFormat = formatString.replaceFirst(".*'%%", "%%").replaceFirst("'.*", "");
DateTimeFormatter dateTimeFormatter = DateTimeGroupBy.sqlDateFormatToSelectedDateTimeFormatter(sqlDateTimeFormat);
if(dateTimeFormatter == null)
{
throw (new QException("Unsupported sql dateTime format string [" + sqlDateTimeFormat + "] for MemoryRecordStore"));
}
String valueAsString = ValueUtils.getValueAsString(value);
Instant valueAsInstant = ValueUtils.getValueAsInstant(valueAsString);
ZonedDateTime zonedDateTime = valueAsInstant.atZone(ZoneId.systemDefault());
return (dateTimeFormatter.format(zonedDateTime));
}
else
{
throw (new QException("Unsupported group-by format string [" + formatString + "] for MemoryRecordStore"));
}
}
catch(QException qe)
{
throw (qe);
}
catch(Exception e)
{
throw (new QException("Error applying format string [" + formatString + "] to group by value [" + value + "]", e));
}
}
/*******************************************************************************
**
*******************************************************************************/

View File

@ -22,13 +22,10 @@
package com.kingsrook.qqq.backend.core.modules.backend.implementations.memory;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.actions.interfaces.UpdateInterface;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateOutput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
/*******************************************************************************
@ -45,17 +42,6 @@ public class MemoryUpdateAction extends AbstractMemoryAction implements UpdateIn
{
try
{
QTableMetaData table = updateInput.getTable();
Instant now = Instant.now();
for(QRecord record : updateInput.getRecords())
{
///////////////////////////////////////////
// todo .. better (not hard-coded names) //
///////////////////////////////////////////
setValueIfTableHasField(record, table, "modifyDate", now, false);
}
UpdateOutput updateOutput = new UpdateOutput();
updateOutput.setRecords(MemoryRecordStore.getInstance().update(updateInput, true));
return (updateOutput);

View File

@ -0,0 +1,298 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2024. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.kingsrook.qqq.backend.core.processes.implementations.automation;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import com.kingsrook.qqq.backend.core.actions.automation.AutomationStatus;
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.MetaDataProducerInterface;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryOutput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.expressions.NowWithOffset;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.nocode.HtmlWrapper;
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.nocode.WidgetHtmlLine;
import com.kingsrook.qqq.backend.core.model.metadata.fields.DisplayFormat;
import com.kingsrook.qqq.backend.core.model.metadata.fields.DynamicDefaultValueBehavior;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.processes.NoCodeWidgetFrontendComponentMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QComponentType;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFrontendComponentMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFrontendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.TablesPossibleValueSourceMetaDataProvider;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.backend.core.utils.ExceptionUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import com.kingsrook.qqq.backend.core.utils.collections.MultiLevelMapHelper;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** Process to find records with a bad automation status, and repair them.
**
** Bad status are defined as:
** - failed insert or updates.
** - running insert or updates for more than X minutes (see input field value).
**
** Repair in this case means resetting their status to the corresponding (e.g.,
** insert/update) pending status.
**
*******************************************************************************/
public class HealBadRecordAutomationStatusesProcessStep implements BackendStep, MetaDataProducerInterface<QProcessMetaData>
{
public static final String NAME = "HealBadRecordAutomationStatusesProcess";
private static final QLogger LOG = QLogger.getLogger(HealBadRecordAutomationStatusesProcessStep.class);
private static final Map<Integer, Integer> statusUpdateMap = Map.of(
AutomationStatus.FAILED_INSERT_AUTOMATIONS.getId(), AutomationStatus.PENDING_INSERT_AUTOMATIONS.getId(),
AutomationStatus.RUNNING_INSERT_AUTOMATIONS.getId(), AutomationStatus.PENDING_INSERT_AUTOMATIONS.getId(),
AutomationStatus.FAILED_UPDATE_AUTOMATIONS.getId(), AutomationStatus.PENDING_UPDATE_AUTOMATIONS.getId(),
AutomationStatus.RUNNING_UPDATE_AUTOMATIONS.getId(), AutomationStatus.PENDING_UPDATE_AUTOMATIONS.getId()
);
/*******************************************************************************
**
*******************************************************************************/
@Override
public QProcessMetaData produce(QInstance qInstance) throws QException
{
QProcessMetaData processMetaData = new QProcessMetaData()
.withName(NAME)
.withStepList(List.of(
new QFrontendStepMetaData()
.withName("input")
.withComponent(new QFrontendComponentMetaData().withType(QComponentType.EDIT_FORM))
.withFormField(new QFieldMetaData("tableName", QFieldType.STRING).withPossibleValueSourceName(TablesPossibleValueSourceMetaDataProvider.NAME))
.withFormField(new QFieldMetaData("minutesOldLimit", QFieldType.INTEGER).withDefaultValue(60)),
new QBackendStepMetaData()
.withName("run")
.withCode(new QCodeReference(getClass())),
new QFrontendStepMetaData()
.withName("output")
.withComponent(new NoCodeWidgetFrontendComponentMetaData()
.withOutput(new WidgetHtmlLine()
.withCondition(new QFilterCriteria("warningCount", QCriteriaOperator.GREATER_THAN, 0))
.withWrapper(HtmlWrapper.divWithStyles(HtmlWrapper.STYLE_YELLOW))
.withVelocityTemplate("<b>Warning:</b>"))
.withOutput(new WidgetHtmlLine()
.withCondition(new QFilterCriteria("warningCount", QCriteriaOperator.GREATER_THAN, 0))
.withWrapper(HtmlWrapper.divWithStyles(HtmlWrapper.STYLE_INDENT_1))
.withWrapper(HtmlWrapper.divWithStyles(HtmlWrapper.STYLE_YELLOW))
.withVelocityTemplate("""
<ul>
#foreach($string in $warnings)
<li>$string</li>
#end
</ul>
""")))
.withComponent(new QFrontendComponentMetaData().withType(QComponentType.VIEW_FORM))
.withViewField(new QFieldMetaData("totalRecordsUpdated", QFieldType.INTEGER) /* todo - didn't display commas... .withDisplayFormat(DisplayFormat.COMMAS) */)
.withComponent(new QFrontendComponentMetaData().withType(QComponentType.RECORD_LIST))
.withRecordListField(new QFieldMetaData("tableName", QFieldType.STRING))
.withRecordListField(new QFieldMetaData("badStatus", QFieldType.STRING))
.withRecordListField(new QFieldMetaData("count", QFieldType.INTEGER).withDisplayFormat(DisplayFormat.COMMAS) /* todo - didn't display commas... */)
));
return (processMetaData);
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void run(RunBackendStepInput runBackendStepInput, RunBackendStepOutput runBackendStepOutput) throws QException
{
int recordsUpdated = 0;
////////////////////////////////////////////////////////////////////////
// if a table name is given, validate it, and run for just that table //
////////////////////////////////////////////////////////////////////////
String tableName = runBackendStepInput.getValueString("tableName");
ArrayList<String> warnings = new ArrayList<>();
if(StringUtils.hasContent(tableName))
{
if(!QContext.getQInstance().getTables().containsKey(tableName))
{
throw (new QException("Unrecognized table name: " + tableName));
}
recordsUpdated += processTable(tableName, runBackendStepInput, runBackendStepOutput, warnings);
}
else
{
//////////////////////////////////////////////////////////////////////////
// else, try to run for all tables that have an automation status field //
//////////////////////////////////////////////////////////////////////////
for(QTableMetaData table : QContext.getQInstance().getTables().values())
{
recordsUpdated += processTable(table.getName(), runBackendStepInput, runBackendStepOutput, warnings);
}
}
runBackendStepOutput.addValue("totalRecordsUpdated", recordsUpdated);
runBackendStepOutput.addValue("warnings", warnings);
runBackendStepOutput.addValue("warningCount", warnings.size());
if(CollectionUtils.nullSafeIsEmpty(runBackendStepOutput.getRecords()))
{
runBackendStepOutput.addRecord(new QRecord()
.withValue("tableName", "--")
.withValue("badStatus", "--")
.withValue("count", "0"));
}
}
/*******************************************************************************
**
*******************************************************************************/
private int processTable(String tableName, RunBackendStepInput runBackendStepInput, RunBackendStepOutput runBackendStepOutput, List<String> warnings)
{
try
{
Integer minutesOldLimit = Objects.requireNonNullElse(runBackendStepInput.getValueInteger("minutesOldLimit"), 60);
QTableMetaData table = QContext.getQInstance().getTable(tableName);
//////////////////////////////////////////////////////////////////////////
// only process tables w/ automation details w/ a status tracking field //
//////////////////////////////////////////////////////////////////////////
if(table != null && table.getAutomationDetails() != null && table.getAutomationDetails().getStatusTracking() != null && StringUtils.hasContent(table.getAutomationDetails().getStatusTracking().getFieldName()))
{
String automationStatusFieldName = table.getAutomationDetails().getStatusTracking().getFieldName();
/////////////////////////////////////////////
// find the modify-date field on the table //
/////////////////////////////////////////////
String modifyDateFieldName = null;
for(QFieldMetaData field : table.getFields().values())
{
if(DynamicDefaultValueBehavior.MODIFY_DATE.equals(field.getBehaviorOnlyIfSet(DynamicDefaultValueBehavior.class)))
{
modifyDateFieldName = field.getName();
break;
}
}
if(modifyDateFieldName == null)
{
warnings.add("Could not find a Modify Date field on table: " + tableName);
LOG.info("Couldn't find a MODIFY_DATE field on table", logPair("tableName", tableName));
return 0;
}
////////////////////////////////////////////////////////////////////////
// query for records either FAILED, or RUNNING w/ modify date too old //
////////////////////////////////////////////////////////////////////////
QueryInput queryInput = new QueryInput();
queryInput.setTableName(tableName);
queryInput.setFilter(new QQueryFilter().withBooleanOperator(QQueryFilter.BooleanOperator.OR)
.withSubFilter(new QQueryFilter()
.withCriteria(new QFilterCriteria(automationStatusFieldName, QCriteriaOperator.IN, AutomationStatus.FAILED_INSERT_AUTOMATIONS.getId(), AutomationStatus.FAILED_UPDATE_AUTOMATIONS.getId())))
.withSubFilter(new QQueryFilter()
.withCriteria(new QFilterCriteria(automationStatusFieldName, QCriteriaOperator.IN, AutomationStatus.RUNNING_INSERT_AUTOMATIONS.getId(), AutomationStatus.RUNNING_UPDATE_AUTOMATIONS.getId()))
.withCriteria(new QFilterCriteria(modifyDateFieldName, QCriteriaOperator.LESS_THAN, NowWithOffset.minus(minutesOldLimit, ChronoUnit.MINUTES))))
);
QueryOutput queryOutput = new QueryAction().execute(queryInput);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// foreach record found, add it to list of records to be updated - mapping status to appropriate pending status //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
List<QRecord> recordsToUpdate = new ArrayList<>();
Map<String, Integer> countByStatus = new HashMap<>();
for(QRecord record : queryOutput.getRecords())
{
Integer badAutomationStatusId = record.getValueInteger(automationStatusFieldName);
Integer updateStatus = statusUpdateMap.get(badAutomationStatusId);
if(updateStatus != null)
{
AutomationStatus badStatus = AutomationStatus.getById(badAutomationStatusId);
if(badStatus != null)
{
MultiLevelMapHelper.getOrPutAndIncrement(countByStatus, badStatus.getLabel());
}
recordsToUpdate.add(new QRecord()
.withValue(table.getPrimaryKeyField(), record.getValue(table.getPrimaryKeyField()))
.withValue(automationStatusFieldName, updateStatus));
}
}
if(!recordsToUpdate.isEmpty())
{
LOG.info("Healing bad record automation statuses", logPair("tableName", tableName), logPair("count", recordsToUpdate.size()));
new UpdateAction().execute(new UpdateInput(tableName).withRecords(recordsToUpdate).withOmitTriggeringAutomations(true));
}
for(Map.Entry<String, Integer> entry : countByStatus.entrySet())
{
runBackendStepOutput.addRecord(new QRecord()
.withValue("tableName", tableName)
.withValue("badStatus", entry.getKey())
.withValue("count", entry.getValue()));
}
return (recordsToUpdate.size());
}
}
catch(Exception e)
{
warnings.add("Error processing table: " + tableName + ": " + ExceptionUtils.getTopAndBottomMessages(e));
LOG.warn("Error processing table for bad automation statuses", e, logPair("tableName, name"));
}
return 0;
}
}

View File

@ -0,0 +1,149 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2024. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.kingsrook.qqq.backend.core.processes.implementations.automation;
import java.util.List;
import java.util.Map;
import com.kingsrook.qqq.backend.core.actions.automation.polling.PollingAutomationPerTableRunner;
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.MetaDataProducerInterface;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.automation.QAutomationProviderMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QComponentType;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFrontendComponentMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFrontendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.TablesPossibleValueSourceMetaDataProvider;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
/*******************************************************************************
** Process to manually run table automations, for a table.
**
** Useful, maybe, for an e2e test. Or, if you don't want jobs to be running,
** but want to run automations by-hand, for some reason.
**
** In the future, this class could take a param to only do inserts or updates.
**
** Also, right now, only records that are Pending automations will be run -
** again, that could be changed, presumably (take a list of records, always run, etc...)
*******************************************************************************/
public class RunTableAutomationsProcessStep implements BackendStep, MetaDataProducerInterface<QProcessMetaData>
{
public static final String NAME = "RunTableAutomationsProcess";
/*******************************************************************************
**
*******************************************************************************/
@Override
public QProcessMetaData produce(QInstance qInstance) throws QException
{
QProcessMetaData processMetaData = new QProcessMetaData()
.withName(NAME)
.withStepList(List.of(
new QFrontendStepMetaData()
.withName("input")
.withComponent(new QFrontendComponentMetaData().withType(QComponentType.EDIT_FORM))
.withFormField(new QFieldMetaData("tableName", QFieldType.STRING).withIsRequired(true).withPossibleValueSourceName(TablesPossibleValueSourceMetaDataProvider.NAME))
.withFormField(new QFieldMetaData("automationProviderName", QFieldType.STRING)),
new QBackendStepMetaData()
.withName("run")
.withCode(new QCodeReference(getClass())),
new QFrontendStepMetaData()
.withName("output")
.withComponent(new QFrontendComponentMetaData().withType(QComponentType.VIEW_FORM))
.withViewField(new QFieldMetaData("ok", QFieldType.STRING))
));
return (processMetaData);
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void run(RunBackendStepInput runBackendStepInput, RunBackendStepOutput runBackendStepOutput) throws QException
{
QInstance qInstance = QContext.getQInstance();
////////////////////////////////////////////////////////////////////
// get tableName param (since this process is not table-specific) //
////////////////////////////////////////////////////////////////////
String tableName = runBackendStepInput.getValueString("tableName");
if(!StringUtils.hasContent(tableName))
{
throw (new QException("Missing required input value: tableName"));
}
if(!QContext.getQInstance().getTables().containsKey(tableName))
{
throw (new QException("Unrecognized table name: " + tableName));
}
////////////////////////////////////////////////////////////////////////////////////////////////
// get the automation provider name to use - either as the only-one-in-instance, or via param //
////////////////////////////////////////////////////////////////////////////////////////////////
String automationProviderName = runBackendStepInput.getValueString("automationProviderName");
if(!StringUtils.hasContent(automationProviderName))
{
Map<String, QAutomationProviderMetaData> automationProviders = CollectionUtils.nonNullMap(qInstance.getAutomationProviders());
if(automationProviders.size() == 1)
{
automationProviderName = automationProviders.keySet().iterator().next();
}
else
{
throw (new QException("Missing required input value: automationProviderName (and there is not exactly 1 in the active instance)"));
}
}
/////////////////////////////////////////////
// run automations for the requested table //
/////////////////////////////////////////////
List<PollingAutomationPerTableRunner.TableActionsInterface> tableActions = PollingAutomationPerTableRunner.getTableActions(qInstance, automationProviderName);
for(PollingAutomationPerTableRunner.TableActionsInterface tableAction : tableActions)
{
if(tableName.equals(tableAction.tableName()))
{
PollingAutomationPerTableRunner pollingAutomationPerTableRunner = new PollingAutomationPerTableRunner(qInstance, automationProviderName, () -> QContext.getQSession(), tableAction);
pollingAutomationPerTableRunner.processTableInsertOrUpdate(qInstance.getTable(tableAction.tableName()), tableAction.status());
}
}
runBackendStepOutput.addValue("ok", "true");
}
}

View File

@ -40,6 +40,9 @@ public class BasepullConfiguration implements Serializable
private String timestampField; // the name of the field in the table being queried against the last-run timestamp.
private Integer secondsToSubtractFromLastRunTimeForTimestampQuery; // option to adjust the query's start-time (based on last run time) by a number of seconds.
private Integer secondsToSubtractFromThisRunTimeForTimestampQuery; // option to adjust the query's end-time (based on this run time) by a number of seconds.
/*******************************************************************************
@ -244,4 +247,66 @@ public class BasepullConfiguration implements Serializable
return (this);
}
/*******************************************************************************
** Getter for secondsToSubtractFromLastRunTimeForTimestampQuery
*******************************************************************************/
public Integer getSecondsToSubtractFromLastRunTimeForTimestampQuery()
{
return (this.secondsToSubtractFromLastRunTimeForTimestampQuery);
}
/*******************************************************************************
** Setter for secondsToSubtractFromLastRunTimeForTimestampQuery
*******************************************************************************/
public void setSecondsToSubtractFromLastRunTimeForTimestampQuery(Integer secondsToSubtractFromLastRunTimeForTimestampQuery)
{
this.secondsToSubtractFromLastRunTimeForTimestampQuery = secondsToSubtractFromLastRunTimeForTimestampQuery;
}
/*******************************************************************************
** Fluent setter for secondsToSubtractFromLastRunTimeForTimestampQuery
*******************************************************************************/
public BasepullConfiguration withSecondsToSubtractFromLastRunTimeForTimestampQuery(Integer secondsToSubtractFromLastRunTimeForTimestampQuery)
{
this.secondsToSubtractFromLastRunTimeForTimestampQuery = secondsToSubtractFromLastRunTimeForTimestampQuery;
return (this);
}
/*******************************************************************************
** Getter for secondsToSubtractFromThisRunTimeForTimestampQuery
*******************************************************************************/
public Integer getSecondsToSubtractFromThisRunTimeForTimestampQuery()
{
return (this.secondsToSubtractFromThisRunTimeForTimestampQuery);
}
/*******************************************************************************
** Setter for secondsToSubtractFromThisRunTimeForTimestampQuery
*******************************************************************************/
public void setSecondsToSubtractFromThisRunTimeForTimestampQuery(Integer secondsToSubtractFromThisRunTimeForTimestampQuery)
{
this.secondsToSubtractFromThisRunTimeForTimestampQuery = secondsToSubtractFromThisRunTimeForTimestampQuery;
}
/*******************************************************************************
** Fluent setter for secondsToSubtractFromThisRunTimeForTimestampQuery
*******************************************************************************/
public BasepullConfiguration withSecondsToSubtractFromThisRunTimeForTimestampQuery(Integer secondsToSubtractFromThisRunTimeForTimestampQuery)
{
this.secondsToSubtractFromThisRunTimeForTimestampQuery = secondsToSubtractFromThisRunTimeForTimestampQuery;
return (this);
}
}

View File

@ -22,6 +22,8 @@
package com.kingsrook.qqq.backend.core.processes.implementations.basepull;
import java.io.Serializable;
import java.time.Instant;
import java.util.List;
import com.kingsrook.qqq.backend.core.actions.processes.RunProcessAction;
import com.kingsrook.qqq.backend.core.exceptions.QException;
@ -122,7 +124,21 @@ public class ExtractViaBasepullQueryStep extends ExtractViaQueryStep
*******************************************************************************/
protected String getLastRunTimeString(RunBackendStepInput runBackendStepInput) throws QException
{
return (runBackendStepInput.getBasepullLastRunTime().toString());
Instant lastRunTime = runBackendStepInput.getBasepullLastRunTime();
//////////////////////////////////////////////////////////////////////////////////////////////
// allow the timestamps to be adjusted by the specified number of seconds. //
// normally this would be a positive value, to move to an earlier time - but it could also //
// be a negative value, if you wanted (for some reason) to move forward in time //
// this is useful to provide overlapping windows of time, in case records are being missed. //
//////////////////////////////////////////////////////////////////////////////////////////////
Serializable basepullConfigurationValue = runBackendStepInput.getValue(RunProcessAction.BASEPULL_CONFIGURATION);
if(basepullConfigurationValue instanceof BasepullConfiguration basepullConfiguration && basepullConfiguration.getSecondsToSubtractFromLastRunTimeForTimestampQuery() != null)
{
lastRunTime = lastRunTime.minusSeconds(basepullConfiguration.getSecondsToSubtractFromLastRunTimeForTimestampQuery());
}
return (lastRunTime.toString());
}
@ -132,6 +148,14 @@ public class ExtractViaBasepullQueryStep extends ExtractViaQueryStep
*******************************************************************************/
protected String getThisRunTimeString(RunBackendStepInput runBackendStepInput) throws QException
{
return (runBackendStepInput.getValueInstant(RunProcessAction.BASEPULL_THIS_RUNTIME_KEY).toString());
Instant thisRunTime = runBackendStepInput.getValueInstant(RunProcessAction.BASEPULL_THIS_RUNTIME_KEY);
Serializable basepullConfigurationValue = runBackendStepInput.getValue(RunProcessAction.BASEPULL_CONFIGURATION);
if(basepullConfigurationValue instanceof BasepullConfiguration basepullConfiguration && basepullConfiguration.getSecondsToSubtractFromThisRunTimeForTimestampQuery() != null)
{
thisRunTime = thisRunTime.minusSeconds(basepullConfiguration.getSecondsToSubtractFromThisRunTimeForTimestampQuery());
}
return (thisRunTime.toString());
}
}

View File

@ -25,6 +25,8 @@ package com.kingsrook.qqq.backend.core.processes.implementations.columnstats;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
@ -173,11 +175,10 @@ public class ColumnStatsStep implements BackendStep
Aggregate aggregate = new Aggregate(table.getPrimaryKeyField(), AggregateOperator.COUNT).withFieldType(QFieldType.DECIMAL);
GroupBy groupBy = new GroupBy(field.getType(), fieldName);
// todo - something here about "by-date, not time"
// todo - something here about an input param to specify how you want dates & date-times grouped
if(field.getType().equals(QFieldType.DATE_TIME))
{
// groupBy = new GroupBy(field.getType(), fieldName, "DATE(%s)");
String sqlExpression = DateTimeGroupBy.HOUR.getSqlExpression();
String sqlExpression = DateTimeGroupBy.HOUR.getSqlExpression(ZoneId.systemDefault());
groupBy = new GroupBy(QFieldType.STRING, fieldName, sqlExpression);
}
@ -230,6 +231,12 @@ public class ColumnStatsStep implements BackendStep
for(AggregateResult result : aggregateOutput.getResults())
{
Serializable value = result.getGroupByValue(groupBy);
if(field.getType().equals(QFieldType.DATE_TIME) && value != null)
{
value = Instant.parse(value + ":00:00Z");
}
Integer count = ValueUtils.getValueAsInteger(result.getAggregateValue(aggregate));
valueCounts.add(new QRecord().withValue(fieldName, value).withValue("count", count));
}

View File

@ -27,7 +27,6 @@ import com.kingsrook.qqq.backend.core.actions.QBackendTransaction;
import com.kingsrook.qqq.backend.core.actions.async.AsyncRecordPipeLoop;
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
import com.kingsrook.qqq.backend.core.actions.reporting.RecordPipe;
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
@ -116,7 +115,7 @@ public class StreamedETLBackendStep implements BackendStep
insertInput.setTableName(runBackendStepInput.getValueString(BasicETLProcess.FIELD_DESTINATION_TABLE));
return new InsertAction().openTransaction(insertInput);
return QBackendTransaction.openFor(insertInput);
}

View File

@ -26,7 +26,6 @@ import java.util.Optional;
import java.util.stream.Collectors;
import com.kingsrook.qqq.backend.core.actions.QBackendTransaction;
import com.kingsrook.qqq.backend.core.actions.tables.DeleteAction;
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
@ -34,7 +33,6 @@ import com.kingsrook.qqq.backend.core.model.actions.tables.InputSource;
import com.kingsrook.qqq.backend.core.model.actions.tables.QInputSource;
import com.kingsrook.qqq.backend.core.model.actions.tables.delete.DeleteInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.delete.DeleteOutput;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
@ -87,9 +85,8 @@ public class LoadViaDeleteStep extends AbstractLoadStep
@Override
public Optional<QBackendTransaction> openTransaction(RunBackendStepInput runBackendStepInput) throws QException
{
InsertInput insertInput = new InsertInput();
insertInput.setTableName(runBackendStepInput.getValueString(FIELD_DESTINATION_TABLE));
return (Optional.of(new InsertAction().openTransaction(insertInput)));
DeleteInput deleteInput = new DeleteInput();
deleteInput.setTableName(runBackendStepInput.getValueString(FIELD_DESTINATION_TABLE));
return (Optional.of(QBackendTransaction.openFor(deleteInput)));
}
}

View File

@ -129,8 +129,7 @@ public class LoadViaInsertOrUpdateStep extends AbstractLoadStep
{
InsertInput insertInput = new InsertInput();
insertInput.setTableName(runBackendStepInput.getValueString(FIELD_DESTINATION_TABLE));
return (Optional.of(new InsertAction().openTransaction(insertInput)));
return (Optional.of(QBackendTransaction.openFor(insertInput)));
}

View File

@ -88,7 +88,6 @@ public class LoadViaInsertStep extends AbstractLoadStep
{
InsertInput insertInput = new InsertInput();
insertInput.setTableName(runBackendStepInput.getValueString(FIELD_DESTINATION_TABLE));
return (Optional.of(new InsertAction().openTransaction(insertInput)));
return (Optional.of(QBackendTransaction.openFor(insertInput)));
}
}

View File

@ -24,14 +24,12 @@ package com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwit
import java.util.Optional;
import com.kingsrook.qqq.backend.core.actions.QBackendTransaction;
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
import com.kingsrook.qqq.backend.core.model.actions.tables.InputSource;
import com.kingsrook.qqq.backend.core.model.actions.tables.QInputSource;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateOutput;
@ -81,9 +79,8 @@ public class LoadViaUpdateStep extends AbstractLoadStep
@Override
public Optional<QBackendTransaction> openTransaction(RunBackendStepInput runBackendStepInput) throws QException
{
InsertInput insertInput = new InsertInput();
insertInput.setTableName(runBackendStepInput.getValueString(FIELD_DESTINATION_TABLE));
return (Optional.of(new InsertAction().openTransaction(insertInput)));
UpdateInput updateInput = new UpdateInput();
updateInput.setTableName(runBackendStepInput.getValueString(FIELD_DESTINATION_TABLE));
return (Optional.of(QBackendTransaction.openFor(updateInput)));
}
}

View File

@ -34,7 +34,6 @@ import com.kingsrook.qqq.backend.core.actions.reporting.RecordPipe;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.audits.AuditInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLine;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLineInterface;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;

View File

@ -1,6 +1,6 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2023. Kingsrook, LLC
* Copyright (C) 2021-2024. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
@ -19,7 +19,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.kingsrook.qqq.backend.core.processes.implementations.savedfilters;
package com.kingsrook.qqq.backend.core.processes.implementations.savedviews;
import java.util.List;
@ -34,15 +34,15 @@ import com.kingsrook.qqq.backend.core.model.actions.tables.delete.DeleteInput;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.savedfilters.SavedFilter;
import com.kingsrook.qqq.backend.core.model.savedviews.SavedView;
/*******************************************************************************
** Process used by the delete filter dialog
** Process used by the delete view dialog
*******************************************************************************/
public class DeleteSavedFilterProcess implements BackendStep
public class DeleteSavedViewProcess implements BackendStep
{
private static final QLogger LOG = QLogger.getLogger(DeleteSavedFilterProcess.class);
private static final QLogger LOG = QLogger.getLogger(DeleteSavedViewProcess.class);
@ -52,10 +52,10 @@ public class DeleteSavedFilterProcess implements BackendStep
public static QProcessMetaData getProcessMetaData()
{
return (new QProcessMetaData()
.withName("deleteSavedFilter")
.withName("deleteSavedView")
.withStepList(List.of(
new QBackendStepMetaData()
.withCode(new QCodeReference(DeleteSavedFilterProcess.class))
.withCode(new QCodeReference(DeleteSavedViewProcess.class))
.withName("delete")
)));
}
@ -72,16 +72,16 @@ public class DeleteSavedFilterProcess implements BackendStep
try
{
Integer savedFilterId = runBackendStepInput.getValueInteger("id");
Integer savedViewId = runBackendStepInput.getValueInteger("id");
DeleteInput input = new DeleteInput();
input.setTableName(SavedFilter.TABLE_NAME);
input.setPrimaryKeys(List.of(savedFilterId));
input.setTableName(SavedView.TABLE_NAME);
input.setPrimaryKeys(List.of(savedViewId));
new DeleteAction().execute(input);
}
catch(Exception e)
{
LOG.warn("Error deleting saved filter", e);
LOG.warn("Error deleting saved view", e);
throw (e);
}
}

View File

@ -1,6 +1,6 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2023. Kingsrook, LLC
* Copyright (C) 2021-2024. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
@ -19,7 +19,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.kingsrook.qqq.backend.core.processes.implementations.savedfilters;
package com.kingsrook.qqq.backend.core.processes.implementations.savedviews;
import java.io.Serializable;
@ -43,15 +43,15 @@ import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryOutput;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.savedfilters.SavedFilter;
import com.kingsrook.qqq.backend.core.model.savedviews.SavedView;
/*******************************************************************************
** Process used by the saved filter dialogs
** Process used by the saved view dialogs
*******************************************************************************/
public class QuerySavedFilterProcess implements BackendStep
public class QuerySavedViewProcess implements BackendStep
{
private static final QLogger LOG = QLogger.getLogger(QuerySavedFilterProcess.class);
private static final QLogger LOG = QLogger.getLogger(QuerySavedViewProcess.class);
@ -61,10 +61,10 @@ public class QuerySavedFilterProcess implements BackendStep
public static QProcessMetaData getProcessMetaData()
{
return (new QProcessMetaData()
.withName("querySavedFilter")
.withName("querySavedView")
.withStepList(List.of(
new QBackendStepMetaData()
.withCode(new QCodeReference(QuerySavedFilterProcess.class))
.withCode(new QCodeReference(QuerySavedViewProcess.class))
.withName("query")
)));
}
@ -81,36 +81,36 @@ public class QuerySavedFilterProcess implements BackendStep
try
{
Integer savedFilterId = runBackendStepInput.getValueInteger("id");
if(savedFilterId != null)
Integer savedViewId = runBackendStepInput.getValueInteger("id");
if(savedViewId != null)
{
GetInput input = new GetInput();
input.setTableName(SavedFilter.TABLE_NAME);
input.setPrimaryKey(savedFilterId);
input.setTableName(SavedView.TABLE_NAME);
input.setPrimaryKey(savedViewId);
GetOutput output = new GetAction().execute(input);
runBackendStepOutput.addRecord(output.getRecord());
runBackendStepOutput.addValue("savedFilter", output.getRecord());
runBackendStepOutput.addValue("savedFilterList", (Serializable) List.of(output.getRecord()));
runBackendStepOutput.addValue("savedView", output.getRecord());
runBackendStepOutput.addValue("savedViewList", (Serializable) List.of(output.getRecord()));
}
else
{
String tableName = runBackendStepInput.getValueString("tableName");
QueryInput input = new QueryInput();
input.setTableName(SavedFilter.TABLE_NAME);
input.setTableName(SavedView.TABLE_NAME);
input.setFilter(new QQueryFilter()
.withCriteria(new QFilterCriteria("tableName", QCriteriaOperator.EQUALS, tableName))
.withOrderBy(new QFilterOrderBy("label")));
QueryOutput output = new QueryAction().execute(input);
runBackendStepOutput.setRecords(output.getRecords());
runBackendStepOutput.addValue("savedFilterList", (Serializable) output.getRecords());
runBackendStepOutput.addValue("savedViewList", (Serializable) output.getRecords());
}
}
catch(Exception e)
{
LOG.warn("Error deleting saved filter", e);
LOG.warn("Error querying for saved views", e);
throw (e);
}
}

View File

@ -1,6 +1,6 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2023. Kingsrook, LLC
* Copyright (C) 2021-2024. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
@ -19,37 +19,45 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.kingsrook.qqq.backend.core.processes.implementations.savedfilters;
package com.kingsrook.qqq.backend.core.processes.implementations.savedviews;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.kingsrook.qqq.backend.core.actions.ActionHelper;
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QUserFacingException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertOutput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryOutput;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateOutput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.savedfilters.SavedFilter;
import com.kingsrook.qqq.backend.core.model.savedviews.SavedView;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
/*******************************************************************************
** Process used by the saved filter dialog
** Process used by the saved view dialog
*******************************************************************************/
public class StoreSavedFilterProcess implements BackendStep
public class StoreSavedViewProcess implements BackendStep
{
private static final QLogger LOG = QLogger.getLogger(StoreSavedFilterProcess.class);
private static final QLogger LOG = QLogger.getLogger(StoreSavedViewProcess.class);
@ -59,10 +67,10 @@ public class StoreSavedFilterProcess implements BackendStep
public static QProcessMetaData getProcessMetaData()
{
return (new QProcessMetaData()
.withName("storeSavedFilter")
.withName("storeSavedView")
.withStepList(List.of(
new QBackendStepMetaData()
.withCode(new QCodeReference(StoreSavedFilterProcess.class))
.withCode(new QCodeReference(StoreSavedViewProcess.class))
.withName("store")
)));
}
@ -79,39 +87,73 @@ public class StoreSavedFilterProcess implements BackendStep
try
{
String userId = QContext.getQSession().getUser().getIdReference();
String tableName = runBackendStepInput.getValueString("tableName");
String label = runBackendStepInput.getValueString("label");
QRecord qRecord = new QRecord()
.withValue("id", runBackendStepInput.getValueInteger("id"))
.withValue("label", runBackendStepInput.getValueString("label"))
.withValue("tableName", runBackendStepInput.getValueString("tableName"))
.withValue("filterJson", runBackendStepInput.getValueString("filterJson"))
.withValue("userId", runBackendStepInput.getSession().getUser().getIdReference());
.withValue("viewJson", runBackendStepInput.getValueString("viewJson"))
.withValue("label", label)
.withValue("tableName", tableName)
.withValue("userId", userId);
List<QRecord> savedFilterList = new ArrayList<>();
List<QRecord> savedViewList;
if(qRecord.getValueInteger("id") == null)
{
checkForDuplicates(userId, tableName, label, null);
InsertInput input = new InsertInput();
input.setTableName(SavedFilter.TABLE_NAME);
input.setTableName(SavedView.TABLE_NAME);
input.setRecords(List.of(qRecord));
InsertOutput output = new InsertAction().execute(input);
savedFilterList = output.getRecords();
savedViewList = output.getRecords();
}
else
{
checkForDuplicates(userId, tableName, label, qRecord.getValueInteger("id"));
UpdateInput input = new UpdateInput();
input.setTableName(SavedFilter.TABLE_NAME);
input.setTableName(SavedView.TABLE_NAME);
input.setRecords(List.of(qRecord));
UpdateOutput output = new UpdateAction().execute(input);
savedFilterList = output.getRecords();
savedViewList = output.getRecords();
}
runBackendStepOutput.addValue("savedFilterList", (Serializable) savedFilterList);
runBackendStepOutput.addValue("savedViewList", (Serializable) savedViewList);
}
catch(Exception e)
{
LOG.warn("Error storing data saved filter", e);
LOG.warn("Error storing saved view", e);
throw (e);
}
}
/*******************************************************************************
**
*******************************************************************************/
private static void checkForDuplicates(String userId, String tableName, String label, Integer id) throws QException
{
QueryInput queryInput = new QueryInput();
queryInput.setTableName(SavedView.TABLE_NAME);
queryInput.setFilter(new QQueryFilter(
new QFilterCriteria("userId", QCriteriaOperator.EQUALS, userId),
new QFilterCriteria("tableName", QCriteriaOperator.EQUALS, tableName),
new QFilterCriteria("label", QCriteriaOperator.EQUALS, label)));
if(id != null)
{
queryInput.getFilter().addCriteria(new QFilterCriteria("id", QCriteriaOperator.NOT_EQUALS, id));
}
QueryOutput queryOutput = new QueryAction().execute(queryInput);
if(CollectionUtils.nullSafeHasContents(queryOutput.getRecords()))
{
throw (new QUserFacingException("You already have a saved view on this table with this name."));
}
}
}

View File

@ -26,7 +26,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.kingsrook.qqq.backend.core.actions.audits.AuditAction;
import com.kingsrook.qqq.backend.core.actions.audits.DMLAuditAction;
import com.kingsrook.qqq.backend.core.actions.scripts.RunAdHocRecordScriptAction;
import com.kingsrook.qqq.backend.core.actions.scripts.logging.StoreScriptLogAndScriptLogLineExecutionLogger;
import com.kingsrook.qqq.backend.core.actions.tables.GetAction;
@ -133,11 +132,6 @@ public class RunRecordScriptLoadStep extends AbstractLoadStep implements Process
throw (new QException("Could not find script by id: " + scriptId));
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// set an "audit context" - so any DML executed during the script will include the note of what script was running. //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
runBackendStepInput.addValue(DMLAuditAction.AUDIT_CONTEXT_FIELD_NAME, "via Script \"" + script.getValue("name") + "\"");
String tableName = script.getValueString("tableName");
RunAdHocRecordScriptInput input = new RunAdHocRecordScriptInput();

View File

@ -75,7 +75,7 @@ public class StoreScriptRevisionProcessStep implements BackendStep
InsertAction insertAction = new InsertAction();
InsertInput insertInput = new InsertInput();
insertInput.setTableName(ScriptRevision.TABLE_NAME);
QBackendTransaction transaction = insertAction.openTransaction(insertInput);
QBackendTransaction transaction = QBackendTransaction.openFor(insertInput);
insertInput.setTransaction(transaction);
try

View File

@ -182,6 +182,14 @@ public abstract class AbstractTableSyncTransformStep extends AbstractTransformSt
public record SyncProcessConfig(String sourceTable, String sourceTableKeyField, String destinationTable, String destinationTableForeignKey, boolean performInserts, boolean performUpdates)
{
/*******************************************************************************
** Overloaded constructor - defaults both performInserts & performUpdates to true.
*******************************************************************************/
public SyncProcessConfig(String sourceTable, String sourceTableKeyField, String destinationTable, String destinationTableForeignKey)
{
this(sourceTable, sourceTableKeyField, destinationTable, destinationTableForeignKey, true, true);
}
/*******************************************************************************
** artificial method, here to make jacoco see that this class is indeed
** included in test coverage...
@ -268,6 +276,7 @@ public abstract class AbstractTableSyncTransformStep extends AbstractTransformSt
if(sourceKeyValue == null || "".equals(sourceKeyValue))
{
LOG.debug("Skipping record without a value in the sourceKeyField", logPair("keyField", sourceTableKeyField));
errorMissingKeyField.incrementCountAndAddPrimaryKey(sourcePrimaryKey);
try

View File

@ -120,52 +120,68 @@ public class ScheduleManager
return;
}
for(QQueueProviderMetaData queueProvider : qInstance.getQueueProviders().values())
boolean needToClearContext = false;
try
{
startQueueProvider(queueProvider);
}
for(QAutomationProviderMetaData automationProvider : qInstance.getAutomationProviders().values())
{
startAutomationProviderPerTable(automationProvider);
}
for(QProcessMetaData process : qInstance.getProcesses().values())
{
if(process.getSchedule() != null && allowedToStart(process.getName()))
if(QContext.getQInstance() == null)
{
QScheduleMetaData scheduleMetaData = process.getSchedule();
if(process.getSchedule().getVariantBackend() == null || QScheduleMetaData.RunStrategy.SERIAL.equals(process.getSchedule().getVariantRunStrategy()))
needToClearContext = true;
QContext.init(qInstance, sessionSupplier.get());
}
for(QQueueProviderMetaData queueProvider : qInstance.getQueueProviders().values())
{
startQueueProvider(queueProvider);
}
for(QAutomationProviderMetaData automationProvider : qInstance.getAutomationProviders().values())
{
startAutomationProviderPerTable(automationProvider);
}
for(QProcessMetaData process : qInstance.getProcesses().values())
{
if(process.getSchedule() != null && allowedToStart(process.getName()))
{
///////////////////////////////////////////////
// if no variants, or variant is serial mode //
///////////////////////////////////////////////
startProcess(process, null);
}
else if(QScheduleMetaData.RunStrategy.PARALLEL.equals(process.getSchedule().getVariantRunStrategy()))
{
/////////////////////////////////////////////////////////////////////////////////////////////////////
// if this a "parallel", which for example means we want to have a thread for each backend variant //
// running at the same time, get the variant records and schedule each separately //
/////////////////////////////////////////////////////////////////////////////////////////////////////
QContext.init(qInstance, sessionSupplier.get());
QBackendMetaData backendMetaData = qInstance.getBackend(scheduleMetaData.getVariantBackend());
for(QRecord qRecord : CollectionUtils.nonNullList(getBackendVariantFilteredRecords(process)))
QScheduleMetaData scheduleMetaData = process.getSchedule();
if(process.getSchedule().getVariantBackend() == null || QScheduleMetaData.RunStrategy.SERIAL.equals(process.getSchedule().getVariantRunStrategy()))
{
try
///////////////////////////////////////////////
// if no variants, or variant is serial mode //
///////////////////////////////////////////////
startProcess(process, null);
}
else if(QScheduleMetaData.RunStrategy.PARALLEL.equals(process.getSchedule().getVariantRunStrategy()))
{
/////////////////////////////////////////////////////////////////////////////////////////////////////
// if this a "parallel", which for example means we want to have a thread for each backend variant //
// running at the same time, get the variant records and schedule each separately //
/////////////////////////////////////////////////////////////////////////////////////////////////////
QBackendMetaData backendMetaData = qInstance.getBackend(scheduleMetaData.getVariantBackend());
for(QRecord qRecord : CollectionUtils.nonNullList(getBackendVariantFilteredRecords(process)))
{
startProcess(process, MapBuilder.of(backendMetaData.getVariantOptionsTableTypeValue(), qRecord.getValue(backendMetaData.getVariantOptionsTableIdField())));
}
catch(Exception e)
{
LOG.error("An error starting process [" + process.getLabel() + "], with backend variant data.", e, new LogPair("variantQRecord", qRecord));
try
{
startProcess(process, MapBuilder.of(backendMetaData.getVariantOptionsTableTypeValue(), qRecord.getValue(backendMetaData.getVariantOptionsTableIdField())));
}
catch(Exception e)
{
LOG.error("An error starting process [" + process.getLabel() + "], with backend variant data.", e, new LogPair("variantQRecord", qRecord));
}
}
}
else
{
LOG.error("Unsupported Schedule Run Strategy [" + process.getSchedule().getVariantRunStrategy() + "] was provided.");
}
}
else
{
LOG.error("Unsupported Schedule Run Strategy [" + process.getSchedule().getVariantRunStrategy() + "] was provided.");
}
}
}
finally
{
if(needToClearContext)
{
QContext.clear();
}
}
}
@ -210,8 +226,8 @@ public class ScheduleManager
// ask the PollingAutomationPerTableRunner how many threads of itself need setup //
// then start a scheduled executor foreach one //
///////////////////////////////////////////////////////////////////////////////////
List<PollingAutomationPerTableRunner.TableActions> tableActions = PollingAutomationPerTableRunner.getTableActions(qInstance, automationProvider.getName());
for(PollingAutomationPerTableRunner.TableActions tableAction : tableActions)
List<PollingAutomationPerTableRunner.TableActionsInterface> tableActions = PollingAutomationPerTableRunner.getTableActions(qInstance, automationProvider.getName());
for(PollingAutomationPerTableRunner.TableActionsInterface tableAction : tableActions)
{
if(allowedToStart(tableAction.tableName()))
{

View File

@ -164,4 +164,23 @@ public class ExceptionUtils
return (StringUtils.join("; ", messages));
}
/*******************************************************************************
** Get the messages from the top & bottoms (root) of an exception.
**
** If there's no root, just return the top (e.g., parameter)'s message.
** If they are both found, put ": " between them.
*******************************************************************************/
public static String getTopAndBottomMessages(Exception e)
{
String rs = e.getMessage();
Throwable rootException = getRootException(e);
if(rootException != e)
{
rs += ": " + rootException.getMessage();
}
return (rs);
}
}

View File

@ -176,6 +176,19 @@ public class StringUtils
/*******************************************************************************
** safely appends a string to another, changing empty string if either value is null
**
*******************************************************************************/
public static String safeAppend(String input, String contentToAppend)
{
input = input != null ? input : "";
contentToAppend = contentToAppend != null ? contentToAppend : "";
return input + contentToAppend;
}
/*******************************************************************************
** returns input if not null, or nullOutput if input == null (as in SQL NVL)
**

View File

@ -574,7 +574,7 @@ public class ValueUtils
/*******************************************************************************
**
*******************************************************************************/
public static LocalTime getValueAsLocalTime(Serializable value)
public static LocalTime getValueAsLocalTime(Object value)
{
try
{
@ -615,7 +615,7 @@ public class ValueUtils
/*******************************************************************************
**
*******************************************************************************/
public static byte[] getValueAsByteArray(Serializable value)
public static byte[] getValueAsByteArray(Object value)
{
if(value == null)
{
@ -641,7 +641,7 @@ public class ValueUtils
**
*******************************************************************************/
@SuppressWarnings("unchecked")
public static <T extends Serializable> T getValueAsType(Class<T> type, Serializable value)
public static <T extends Serializable> T getValueAsType(Class<T> type, Object value)
{
if(type.equals(Integer.class))
{
@ -687,7 +687,7 @@ public class ValueUtils
**
*******************************************************************************/
@SuppressWarnings("checkstyle:indentation")
public static Serializable getValueAsFieldType(QFieldType type, Serializable value)
public static Serializable getValueAsFieldType(QFieldType type, Object value)
{
return switch(type)
{

View File

@ -19,26 +19,19 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.kingsrook.qqq.backend.core.actions.interfaces;
import com.kingsrook.qqq.backend.core.actions.QBackendTransaction;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.AbstractTableActionInput;
package com.kingsrook.qqq.backend.core.utils.lambdas;
/*******************************************************************************
**
*******************************************************************************/
public interface QActionInterface
@FunctionalInterface
public interface UnsafeLambda
{
/*******************************************************************************
**
*******************************************************************************/
default QBackendTransaction openTransaction(AbstractTableActionInput input) throws QException
{
return (new QBackendTransaction());
}
void run() throws Exception;
}

View File

@ -30,6 +30,7 @@ import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.utils.lambdas.UnsafeFunction;
/*******************************************************************************
@ -58,8 +59,16 @@ public class Memoization<K, V>
/*******************************************************************************
** Get the memoized Value for a given input Key.
**
** But note, this looks the same to the caller, whether the key just wasn't in
** the internal map (e.g., had never been looked up), or if it was previously looked
** up, and that returned null. In either case, the optional will be empty.
**
** See getMemoizedResult for where we can tell the difference (and we would
** generally want to call that.
*******************************************************************************/
@Deprecated
public Optional<V> getResult(K key)
{
MemoizedResult<V> result = map.get(key);
@ -77,7 +86,57 @@ public class Memoization<K, V>
/*******************************************************************************
** Get the memoized Value for a given input Key - computing it if it wasn't previously
** memoized (or expired).
**
** In here, if the optional is empty, it means the value is null (whether that
** came form memoization, or from the lookupFunction, you don't care - the answer
** is null).
*******************************************************************************/
public Optional<V> getResult(K key, UnsafeFunction<K, V, ?> lookupFunction)
{
MemoizedResult<V> result = map.get(key);
if(result != null)
{
if(result.getTime().isAfter(Instant.now().minus(timeout)))
{
//////////////////////////////////////////////////////////////////////////////
// ok, we have a memoized value, and it's not expired, so we can return it. //
// of course, it might be a memoized null, so we use .ofNullable. //
//////////////////////////////////////////////////////////////////////////////
return (Optional.ofNullable(result.getResult()));
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
// ok - either we never memoized this key, or it's expired, so, apply the lookup function, //
// store the result, and then return the value (in an Optional.ofNullable) //
/////////////////////////////////////////////////////////////////////////////////////////////
try
{
V value = lookupFunction.apply(key);
storeResult(key, value);
return (Optional.ofNullable(value));
}
catch(Exception e)
{
LOG.warn("Uncaught Exception while executing a Memoization lookupFunction (to avoid this log, add a catch in the lookupFunction)", e);
storeResult(key, null);
return (Optional.empty());
}
}
/*******************************************************************************
** Get a memoized result, optionally containing a Value, for a given input Key.
**
** In this method (contrasted with getResult), if the returned Optional is empty,
** it means that we haven't ever looked up or memoized the key (or it's expired).
**
** If the returned Optional is not empty, then it means we've memoized something
** (and it's not expired) - so if the Value from the MemoizedResult is null,
** then null is the proper memoized value.
*******************************************************************************/
public Optional<MemoizedResult<V>> getMemoizedResult(K key)
{
@ -86,7 +145,7 @@ public class Memoization<K, V>
{
if(result.getTime().isAfter(Instant.now().minus(timeout)))
{
return (Optional.ofNullable(result));
return (Optional.of(result));
}
}
@ -181,4 +240,47 @@ public class Memoization<K, V>
{
return map;
}
/*******************************************************************************
** Getter for timeout
*******************************************************************************/
public Duration getTimeout()
{
return (this.timeout);
}
/*******************************************************************************
** Fluent setter for timeout
*******************************************************************************/
public Memoization<K, V> withTimeout(Duration timeout)
{
this.timeout = timeout;
return (this);
}
/*******************************************************************************
** Getter for maxSize
*******************************************************************************/
public Integer getMaxSize()
{
return (this.maxSize);
}
/*******************************************************************************
** Fluent setter for maxSize
*******************************************************************************/
public Memoization<K, V> withMaxSize(Integer maxSize)
{
this.maxSize = maxSize;
return (this);
}
}

View File

@ -400,4 +400,49 @@ class DMLAuditActionTest extends BaseTest
QContext.popAction();
}
/*******************************************************************************
**
*******************************************************************************/
@Test
void testTableWithoutIntegerPrimaryKey() throws QException
{
QInstance qInstance = QContext.getQInstance();
new AuditsMetaDataProvider().defineAll(qInstance, TestUtils.MEMORY_BACKEND_NAME, null);
////////////////////////////////////////////////////////////////////////////////////////////////////
// we used to throw if table had no primary key. first, assert that we do not throw in that case //
////////////////////////////////////////////////////////////////////////////////////////////////////
QContext.getQInstance().addTable(
new QTableMetaData()
.withName("nullPkey")
.withField(new QFieldMetaData("foo", QFieldType.STRING))
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD)));
new DMLAuditAction().execute(new DMLAuditInput()
.withTableActionInput(new InsertInput("nullPkey"))
.withRecordList(List.of(new QRecord())));
//////////////////////////////////////////////////////////////////////////////////////////////
// next, make sure we don't throw (and don't record anything) if table's pkey isn't integer //
//////////////////////////////////////////////////////////////////////////////////////////////
QContext.getQInstance().addTable(
new QTableMetaData()
.withName("stringPkey")
.withField(new QFieldMetaData("idString", QFieldType.STRING))
.withPrimaryKeyField("idString")
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD)));
new DMLAuditAction().execute(new DMLAuditInput()
.withTableActionInput(new InsertInput("stringPkey"))
.withRecordList(List.of(new QRecord())));
//////////////////////////////////
// make sure no audits happened //
//////////////////////////////////
List<QRecord> auditList = TestUtils.queryTable("audit");
assertTrue(auditList.isEmpty());
}
}

View File

@ -0,0 +1,220 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2024. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.kingsrook.qqq.backend.core.actions.automation.polling;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import com.kingsrook.qqq.backend.core.BaseTest;
import com.kingsrook.qqq.backend.core.actions.automation.AutomationStatus;
import com.kingsrook.qqq.backend.core.actions.automation.RecordAutomationHandler;
import com.kingsrook.qqq.backend.core.actions.tables.GetAction;
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
import com.kingsrook.qqq.backend.core.context.CapturedContext;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.get.GetInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.automation.RecordAutomationInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.TableAutomationAction;
import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.TriggerEvent;
import com.kingsrook.qqq.backend.core.utils.TestUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static com.kingsrook.qqq.backend.core.actions.automation.polling.PollingAutomationPerTableRunnerTest.runAllTableActions;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
/*******************************************************************************
** Test for the case where:
** - inserting into a main table and a child table, and the child table has a
** post-insert customizer, which mo
*******************************************************************************/
public class PollingAutomationPerTableRunnerAutomtationUpdatingSelfAvoidInfiniteLoopTest extends BaseTest
{
private static boolean didFailInThread = false;
static
{
///////////////////////////////////////////////////////////////////////////////////////////////////
// we can set this property to revert to the behavior that existed before this test was written. //
///////////////////////////////////////////////////////////////////////////////////////////////////
// System.setProperty("qqq.recordAutomationStatusUpdater.skipPreUpdateFetch", "true");
}
/*******************************************************************************
**
*******************************************************************************/
@BeforeEach
void beforeEach()
{
didFailInThread = false;
}
/*******************************************************************************
**
*******************************************************************************/
@Test
void test() throws QException
{
////////////////////////////////////
// add automations to order table //
////////////////////////////////////
QContext.getQInstance().getTable(TestUtils.TABLE_NAME_ORDER)
.withField(TestUtils.standardQqqAutomationStatusField())
.withAutomationDetails(TestUtils.defineStandardAutomationDetails()
.withAction(new TableAutomationAction()
.withName("orderPostInsertAction")
.withTriggerEvent(TriggerEvent.POST_INSERT)
.withCodeReference(new QCodeReference(OrderPostInsertAndUpdateAction.class)))
.withAction(new TableAutomationAction()
.withName("orderPostUpdateAction")
.withTriggerEvent(TriggerEvent.POST_UPDATE)
.withCodeReference(new QCodeReference(OrderPostInsertAndUpdateAction.class))));
QContext.getQSession().withSecurityKeyValue(TestUtils.SECURITY_KEY_TYPE_STORE_ALL_ACCESS, true);
InsertInput insertInput = new InsertInput();
insertInput.setTableName(TestUtils.TABLE_NAME_ORDER);
insertInput.setRecords(List.of(new QRecord().withValue("orderNo", "10101").withValue("total", new BigDecimal(1))));
new InsertAction().execute(insertInput);
//////////////////////////////////////////////////////
// make sure the order is in pending-inserts status //
//////////////////////////////////////////////////////
{
QRecord order = new GetAction().executeForRecord(new GetInput(TestUtils.TABLE_NAME_ORDER).withPrimaryKey(1));
assertEquals(AutomationStatus.PENDING_INSERT_AUTOMATIONS.getId(), order.getValue(TestUtils.standardQqqAutomationStatusField().getName()));
assertEquals(new BigDecimal(1), order.getValueBigDecimal("total"));
}
////////////////////////////////////////////////////////////////////////////////////////////////
// run automations - that should update the order via the automation - but leave status as OK //
////////////////////////////////////////////////////////////////////////////////////////////////
runAllTableActions(QContext.getQInstance());
assertFalse(didFailInThread, "A failure condition happened in the automation sub-thread. Check System.out for message.");
{
QRecord order = new GetAction().executeForRecord(new GetInput(TestUtils.TABLE_NAME_ORDER).withPrimaryKey(1));
assertEquals(AutomationStatus.OK.getId(), order.getValue(TestUtils.standardQqqAutomationStatusField().getName()));
assertEquals(new BigDecimal(2), order.getValueBigDecimal("total"));
}
//////////////////////////////////////////////////////////////////
// now update the order, verify status moves to pending-updates //
//////////////////////////////////////////////////////////////////
new UpdateAction().execute(new UpdateInput(TestUtils.TABLE_NAME_ORDER).withRecord(new QRecord()
.withValue("id", 1)
.withValue("storeId", "x")));
{
QRecord order = new GetAction().executeForRecord(new GetInput(TestUtils.TABLE_NAME_ORDER).withPrimaryKey(1));
assertEquals(AutomationStatus.PENDING_UPDATE_AUTOMATIONS.getId(), order.getValue(TestUtils.standardQqqAutomationStatusField().getName()));
assertEquals(new BigDecimal(2), order.getValueBigDecimal("total"));
assertEquals("x", order.getValueString("storeId"));
}
////////////////////////////////////////////////////////////////////////////////////////////////
// run automations - that should update the order via the automation - but leave status as OK //
////////////////////////////////////////////////////////////////////////////////////////////////
runAllTableActions(QContext.getQInstance());
assertFalse(didFailInThread, "A failure condition happened in the automation sub-thread. Check System.out for message.");
{
QRecord order = new GetAction().executeForRecord(new GetInput(TestUtils.TABLE_NAME_ORDER).withPrimaryKey(1));
assertEquals(AutomationStatus.OK.getId(), order.getValue(TestUtils.standardQqqAutomationStatusField().getName()));
assertEquals(new BigDecimal(3), order.getValueBigDecimal("total"));
}
}
/*******************************************************************************
**
*******************************************************************************/
public static class OrderPostInsertAndUpdateAction extends RecordAutomationHandler
{
/*******************************************************************************
**
*******************************************************************************/
@Override
public void execute(RecordAutomationInput recordAutomationInput) throws QException
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// launch a new thread, to make sure we avoid the "stack contains automations" check in RecordAutomationStatusUpdater //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CapturedContext capturedContext = QContext.capture();
for(QRecord record : recordAutomationInput.getRecordList())
{
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
Future<?> submit = service.submit(() ->
{
QContext.init(capturedContext);
try
{
new UpdateAction().execute(new UpdateInput(TestUtils.TABLE_NAME_ORDER).withRecord(new QRecord()
.withValue("id", record.getValue("id"))
.withValue("total", record.getValueBigDecimal("total").add(new BigDecimal(1)))
));
///////////////////////////////////////////////////////////////////
// make sure that update action didn't change the order's status //
///////////////////////////////////////////////////////////////////
QRecord order = new GetAction().executeForRecord(new GetInput(TestUtils.TABLE_NAME_ORDER).withPrimaryKey(1));
if(Objects.equals(AutomationStatus.PENDING_UPDATE_AUTOMATIONS.getId(), order.getValue(TestUtils.standardQqqAutomationStatusField().getName())))
{
System.out.println("Failing test - expected status to not be [PENDING_UPDATE_AUTOMATIONS], but it was.");
didFailInThread = true;
}
assertNotEquals(AutomationStatus.PENDING_UPDATE_AUTOMATIONS.getId(), order.getValue(TestUtils.standardQqqAutomationStatusField().getName()));
}
catch(QException e)
{
e.printStackTrace();
}
finally
{
QContext.clear();
}
});
while(!submit.isDone())
{
}
}
}
}
}

View File

@ -0,0 +1,224 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2024. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.kingsrook.qqq.backend.core.actions.automation.polling;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import com.kingsrook.qqq.backend.core.BaseTest;
import com.kingsrook.qqq.backend.core.actions.automation.AutomationStatus;
import com.kingsrook.qqq.backend.core.actions.automation.RecordAutomationHandler;
import com.kingsrook.qqq.backend.core.actions.customizers.AbstractPostInsertCustomizer;
import com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizers;
import com.kingsrook.qqq.backend.core.actions.tables.AggregateAction;
import com.kingsrook.qqq.backend.core.actions.tables.GetAction;
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.Aggregate;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateOutput;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateResult;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.GroupBy;
import com.kingsrook.qqq.backend.core.model.actions.tables.get.GetInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertOutput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.automation.RecordAutomationInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.TableAutomationAction;
import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.TriggerEvent;
import com.kingsrook.qqq.backend.core.utils.TestUtils;
import com.kingsrook.qqq.backend.core.utils.ValueUtils;
import org.junit.jupiter.api.Test;
import static com.kingsrook.qqq.backend.core.actions.automation.polling.PollingAutomationPerTableRunnerTest.runAllTableActions;
import static org.junit.jupiter.api.Assertions.assertEquals;
/*******************************************************************************
** Test for the case where:
** - inserting into a main table and a child table, and the child table has a
** post-insert customizer, which mo
*******************************************************************************/
public class PollingAutomationPerTableRunnerChildPostInsertCustomizerTest extends BaseTest
{
static
{
///////////////////////////////////////////////////////////////////////////////////////////////////
// we can set this property to revert to the behavior that existed before this test was written. //
///////////////////////////////////////////////////////////////////////////////////////////////////
// System.setProperty("qqq.recordAutomationStatusUpdater.skipPreUpdateFetch", "true");
}
/*******************************************************************************
**
*******************************************************************************/
@Test
void test() throws QException
{
////////////////////////////////////
// add automations to order table //
////////////////////////////////////
QContext.getQInstance().getTable(TestUtils.TABLE_NAME_ORDER)
.withField(TestUtils.standardQqqAutomationStatusField())
.withAutomationDetails(TestUtils.defineStandardAutomationDetails()
.withAction(new TableAutomationAction()
.withName("orderPostInsertAction")
.withTriggerEvent(TriggerEvent.POST_INSERT)
.withCodeReference(new QCodeReference(OrderPostInsertAction.class))
));
///////////////////////////////////////////////////////////////////////////
// add a post-insert customizer to line-ite table (child of order table) //
///////////////////////////////////////////////////////////////////////////
QContext.getQInstance().getTable(TestUtils.TABLE_NAME_LINE_ITEM)
.withCustomizer(TableCustomizers.POST_INSERT_RECORD, new QCodeReference(LineItemPostInsertCustomizer.class));
QContext.getQSession().withSecurityKeyValue(TestUtils.SECURITY_KEY_TYPE_STORE_ALL_ACCESS, true);
InsertInput insertInput = new InsertInput();
insertInput.setTableName(TestUtils.TABLE_NAME_ORDER);
insertInput.setRecords(List.of(new QRecord()
.withValue("orderNo", "10101")
.withAssociatedRecord("orderLine", new QRecord()
.withValue("sku", "ABC")
.withValue("quantity", 1))));
InsertOutput insertOutput = new InsertAction().execute(insertInput);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// make sure the order is in pending-inserts status (at one time, a bug meant that it wouldn't have been...) //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
{
QRecord order = new GetAction().executeForRecord(new GetInput(TestUtils.TABLE_NAME_ORDER).withPrimaryKey(1));
assertEquals(AutomationStatus.PENDING_INSERT_AUTOMATIONS.getId(), order.getValue(TestUtils.standardQqqAutomationStatusField().getName()));
assertEquals(new BigDecimal(1), order.getValueBigDecimal("total"));
}
///////////////////////////////////////////////////////////////////////////////////////////////
// run automations - that should... insert a second line item, but should leave the order in //
// automation-status = OK, to avoid perpetual re-running //
// the line-item post-inserter should run a second time, making the order's total = 2 //
///////////////////////////////////////////////////////////////////////////////////////////////
runAllTableActions(QContext.getQInstance());
{
QRecord order = new GetAction().executeForRecord(new GetInput(TestUtils.TABLE_NAME_ORDER).withPrimaryKey(1));
assertEquals(AutomationStatus.OK.getId(), order.getValue(TestUtils.standardQqqAutomationStatusField().getName()));
assertEquals(new BigDecimal(2), order.getValueBigDecimal("total"));
}
}
/*******************************************************************************
**
*******************************************************************************/
public static class OrderPostInsertAction extends RecordAutomationHandler
{
/*******************************************************************************
**
*******************************************************************************/
@Override
public void execute(RecordAutomationInput recordAutomationInput) throws QException
{
///////////////////////////////////////
// add a new line item to the orders //
///////////////////////////////////////
List<QRecord> lineItemsToInsert = new ArrayList<>();
for(QRecord record : recordAutomationInput.getRecordList())
{
lineItemsToInsert.add(new QRecord()
.withValue("orderId", record.getValue("id"))
.withValue("sku", UUID.randomUUID())
.withValue("quantity", 1)
);
}
new InsertAction().execute(new InsertInput(TestUtils.TABLE_NAME_LINE_ITEM).withRecords(lineItemsToInsert));
}
}
/*******************************************************************************
**
*******************************************************************************/
public static class LineItemPostInsertCustomizer extends AbstractPostInsertCustomizer
{
@Override
public List<QRecord> apply(List<QRecord> records) throws QException
{
//////////////////////////////////
// count line items by order id //
//////////////////////////////////
Set<Serializable> orderIds = records.stream().map(r -> r.getValue("orderId")).collect(Collectors.toSet());
GroupBy groupByOrderId = new GroupBy(QFieldType.STRING, "orderId");
Aggregate countId = new Aggregate("id", AggregateOperator.COUNT);
AggregateInput aggregateInput = new AggregateInput();
aggregateInput.setTableName(TestUtils.TABLE_NAME_LINE_ITEM);
aggregateInput.setFilter(new QQueryFilter(new QFilterCriteria("orderId", QCriteriaOperator.IN, orderIds)));
aggregateInput.withGroupBy(groupByOrderId);
aggregateInput.withAggregate(countId);
AggregateOutput aggregateOutput = new AggregateAction().execute(aggregateInput);
Map<Integer, Integer> countByOrderId = new HashMap<>();
for(AggregateResult result : aggregateOutput.getResults())
{
countByOrderId.put(ValueUtils.getValueAsInteger(result.getGroupByValue(groupByOrderId)), ValueUtils.getValueAsInteger(result.getAggregateValue(countId)));
}
///////////////////////////////////
// update the order total fields //
// s/b in bulk, but, meh //
///////////////////////////////////
for(Integer orderId : countByOrderId.keySet())
{
UpdateInput updateInput = new UpdateInput();
updateInput.setTableName(TestUtils.TABLE_NAME_ORDER);
updateInput.setRecords(List.of(new QRecord()
.withValue("id", orderId)
.withValue("total", new BigDecimal(countByOrderId.get(orderId)))));
new UpdateAction().execute(updateInput);
}
return (records);
}
}
}

View File

@ -56,14 +56,11 @@ import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.QTableAut
import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.TableAutomationAction;
import com.kingsrook.qqq.backend.core.model.metadata.tables.automation.TriggerEvent;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryRecordStore;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.ExtractViaQueryStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.LoadViaInsertStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.StreamedETLWithFrontendProcess;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.StreamedETLWithFrontendProcessTest;
import com.kingsrook.qqq.backend.core.utils.TestUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@ -77,18 +74,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
class PollingAutomationPerTableRunnerTest extends BaseTest
{
/*******************************************************************************
**
*******************************************************************************/
@BeforeEach
@AfterEach
void beforeAndAfterEach()
{
MemoryRecordStore.getInstance().reset();
}
/*******************************************************************************
** Test a cycle that does an insert, some automations, then and an update, and more automations.
*******************************************************************************/
@ -200,17 +185,17 @@ class PollingAutomationPerTableRunnerTest extends BaseTest
/*******************************************************************************
**
*******************************************************************************/
private void runAllTableActions(QInstance qInstance) throws QException
static void runAllTableActions(QInstance qInstance) throws QException
{
List<PollingAutomationPerTableRunner.TableActions> tableActions = PollingAutomationPerTableRunner.getTableActions(qInstance, TestUtils.POLLING_AUTOMATION);
for(PollingAutomationPerTableRunner.TableActions tableAction : tableActions)
List<PollingAutomationPerTableRunner.TableActionsInterface> tableActions = PollingAutomationPerTableRunner.getTableActions(qInstance, TestUtils.POLLING_AUTOMATION);
for(PollingAutomationPerTableRunner.TableActionsInterface tableAction : tableActions)
{
PollingAutomationPerTableRunner pollingAutomationPerTableRunner = new PollingAutomationPerTableRunner(qInstance, TestUtils.POLLING_AUTOMATION, QSession::new, tableAction);
/////////////////////////////////////////////////////////////////////////////////////////////////////
// note - don't call run - it is meant to be called async - e.g., it sets & clears thread context. //
/////////////////////////////////////////////////////////////////////////////////////////////////////
pollingAutomationPerTableRunner.processTableInsertOrUpdate(qInstance.getTable(tableAction.tableName()), QContext.getQSession(), tableAction.status());
pollingAutomationPerTableRunner.processTableInsertOrUpdate(qInstance.getTable(tableAction.tableName()), tableAction.status());
}
}
@ -504,15 +489,15 @@ class PollingAutomationPerTableRunnerTest extends BaseTest
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
assertThatThrownBy(() ->
{
List<PollingAutomationPerTableRunner.TableActions> tableActions = PollingAutomationPerTableRunner.getTableActions(qInstance, TestUtils.POLLING_AUTOMATION);
for(PollingAutomationPerTableRunner.TableActions tableAction : tableActions)
List<PollingAutomationPerTableRunner.TableActionsInterface> tableActions = PollingAutomationPerTableRunner.getTableActions(qInstance, TestUtils.POLLING_AUTOMATION);
for(PollingAutomationPerTableRunner.TableActionsInterface tableAction : tableActions)
{
PollingAutomationPerTableRunner pollingAutomationPerTableRunner = new PollingAutomationPerTableRunnerThatShouldSimulateServerShutdownMidRun(qInstance, TestUtils.POLLING_AUTOMATION, QSession::new, tableAction);
/////////////////////////////////////////////////////////////////////////////////////////////////////
// note - don't call run - it is meant to be called async - e.g., it sets & clears thread context. //
/////////////////////////////////////////////////////////////////////////////////////////////////////
pollingAutomationPerTableRunner.processTableInsertOrUpdate(qInstance.getTable(tableAction.tableName()), QContext.getQSession(), tableAction.status());
pollingAutomationPerTableRunner.processTableInsertOrUpdate(qInstance.getTable(tableAction.tableName()), tableAction.status());
}
}).hasMessage(PollingAutomationPerTableRunnerThatShouldSimulateServerShutdownMidRun.EXCEPTION_MESSAGE);
@ -564,7 +549,7 @@ class PollingAutomationPerTableRunnerTest extends BaseTest
/*******************************************************************************
**
*******************************************************************************/
public PollingAutomationPerTableRunnerThatShouldSimulateServerShutdownMidRun(QInstance instance, String providerName, Supplier<QSession> sessionSupplier, TableActions tableActions)
public PollingAutomationPerTableRunnerThatShouldSimulateServerShutdownMidRun(QInstance instance, String providerName, Supplier<QSession> sessionSupplier, TableActionsInterface tableActions)
{
super(instance, providerName, sessionSupplier, tableActions);
}
@ -581,4 +566,16 @@ class PollingAutomationPerTableRunnerTest extends BaseTest
}
}
/*******************************************************************************
**
*******************************************************************************/
@Test
void testLoadingRecordTypesToEnsureClassCoverage()
{
new PollingAutomationPerTableRunner.TableActions(null, null).noopToFakeTestCoverage();
new PollingAutomationPerTableRunner.ShardedTableActions(null, null, null, null, null).noopToFakeTestCoverage();
}
}

View File

@ -186,9 +186,9 @@ class StandardScheduledExecutorTest extends BaseTest
*******************************************************************************/
private void runPollingAutomationExecutorForAwhile(QInstance qInstance, Supplier<QSession> sessionSupplier)
{
List<PollingAutomationPerTableRunner.TableActions> tableActions = PollingAutomationPerTableRunner.getTableActions(qInstance, TestUtils.POLLING_AUTOMATION);
List<PollingAutomationPerTableRunner.TableActionsInterface> tableActions = PollingAutomationPerTableRunner.getTableActions(qInstance, TestUtils.POLLING_AUTOMATION);
List<StandardScheduledExecutor> executors = new ArrayList<>();
for(PollingAutomationPerTableRunner.TableActions tableAction : tableActions)
for(PollingAutomationPerTableRunner.TableActionsInterface tableAction : tableActions)
{
PollingAutomationPerTableRunner pollingAutomationPerTableRunner = new PollingAutomationPerTableRunner(qInstance, TestUtils.POLLING_AUTOMATION, sessionSupplier, tableAction);
StandardScheduledExecutor pollingAutomationExecutor = new StandardScheduledExecutor(pollingAutomationPerTableRunner);

View File

@ -0,0 +1,58 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2024. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.kingsrook.qqq.backend.core.actions.processes;
import java.util.ArrayList;
import java.util.Collections;
import com.kingsrook.qqq.backend.core.BaseTest;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/*******************************************************************************
** Unit test for QProcessCallbackFactory
*******************************************************************************/
class QProcessCallbackFactoryTest extends BaseTest
{
/*******************************************************************************
**
*******************************************************************************/
@Test
void test()
{
QProcessCallback qProcessCallback = QProcessCallbackFactory.forFilter(new QQueryFilter(new QFilterCriteria("foo", QCriteriaOperator.EQUALS, "bar")));
QQueryFilter queryFilter = qProcessCallback.getQueryFilter();
assertEquals(1, queryFilter.getCriteria().size());
assertEquals("foo", queryFilter.getCriteria().get(0).getFieldName());
assertEquals(QCriteriaOperator.EQUALS, queryFilter.getCriteria().get(0).getOperator());
assertEquals("bar", queryFilter.getCriteria().get(0).getValues().get(0));
assertEquals(Collections.emptyMap(), qProcessCallback.getFieldValues(new ArrayList<>()));
}
}

View File

@ -156,10 +156,10 @@ class RunAssociatedScriptActionTest extends BaseTest
/////////////////////////////////////
assertEquals(N, TestUtils.queryTable(ScriptLog.TABLE_NAME).size());
////////////////////////////////////////////////////////////////////////////////////////
// and we should have just ran 2 inserts - for the log & logLines (even though empty) //
////////////////////////////////////////////////////////////////////////////////////////
assertEquals(2, MemoryRecordStore.getStatistics().get(MemoryRecordStore.STAT_INSERTS_RAN));
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// and we should have just ran 1 inserts - for the log (no longer run one for empty insert of 0 log-lines) //
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
assertEquals(1, MemoryRecordStore.getStatistics().get(MemoryRecordStore.STAT_INSERTS_RAN));
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// and we shouldn't have run N queries (which we would have (at least), if we would have built a new Action object inside the loop) //

Some files were not shown because too many files have changed in this diff Show More