| 1 | # Issuing dynamic queries in SQL data stores |
| 2 | |
| 3 | ## Introduction |
| 4 | |
| 5 | The Management API (DM API) offers a very open and unrestricted query feature: as long as it can be expressed as a |
| 6 | 3-tuple in the form |
| 7 | |
| 8 | ``` |
| 9 | <LEFT_OPERAND> <OPERATOR> <RIGHT_OPERAND> |
| 10 | ``` |
| 11 | |
| 12 | it is a valid query. This abstract way of expressing a condition is called a `Criterion`. For example, API clients may |
| 13 | specify a query to obtain a selection of `ContractNegotiation` objects that looks like this: |
| 14 | |
| 15 | ``` |
| 16 | contractAgreement.assetId = myAssetId |
| 17 | ``` |
| 18 | |
| 19 | In practice this would return `ContractNegotiation`s, that have a `ContractAgreement` which references an `Asset` with |
| 20 | the ID `"myAssetId"`. |
| 21 | |
| 22 | This means, that the backing `SqlContractNegotiationStore` must be able to do the following things: |
| 23 | |
| 24 | 1. dynamically map the expression onto it's internal DB schema: a mapping from the properties `contractAgreement` onto |
| 25 | the column name `contract_agreement` must be made. Furthermore, the store implementation must be able to determine |
| 26 | how to traverse from `ContractNegotiation` to `ContractAgreement` in the database, which in this case means |
| 27 | navigation ( |
| 28 | = `JOIN`-ing ) a foreign key. |
| 29 | 2. distinguish between a scalar or a collection right-hand operand: operators such as `IN` require the right-hand |
| 30 | operand to be a list, such as `...WHERE x IN (y1,y1)` |
| 31 | 3. substitute the values in the expression with placeholders for prepared statements (=`?`) |
| 32 | 4. leverage DB-specific features, like querying a JSON-encoded field, which would only be available in Postgres |
| 33 | |
| 34 | The following section explains how all of these are achieved. |
| 35 | |
| 36 | ## Preliminary: the canonical format |
| 37 | |
| 38 | Theoretically it is possible to map every schema onto every other schema, given that they are of equal cardinality. To |
| 39 | achieve that, we introduce the notion of a _canonical format_, which is our internal working schema. In other words, |
| 40 | this is the schema in which objects are represented internally. If in the future we support a wider variety of |
| 41 | translation and transformation paths, everything would have to be transformed into that canonical format first. |
| 42 | |
| 43 | In actuality the _canonical format_ of an object is defined by the respective Java class and its field names. For |
| 44 | instance, a query for contract negotiations must be specified using the field names of a `ContractNegotiation` object: |
| 45 | |
| 46 | ```java |
| 47 | public class ContractNegotiation { |
| 48 | // ... |
| 49 | private ContractAgreement contractAgreement; |
| 50 | // ... |
| 51 | } |
| 52 | |
| 53 | public class ContractAgreement { |
| 54 | // ... |
| 55 | private final String assetId; |
| 56 | } |
| 57 | ``` |
| 58 | |
| 59 | Consequently, `contractAgreement.assetId` would be valid, whereas `contract_agreement.asset_id` would not. Or, the |
| 60 | left-hand operand looks like as if we were traversing the Java object graph. This is what we call the _canonical format_ |
| 61 | . Note the omission of the root object `contractNegotiation`! |
| 62 | |
| 63 | ## Using `TranslationMapping` |
| 64 | |
| 65 | In order to decouple the canonical format and the SQL schema (or any other schema) in terms of naming convention, a |
| 66 | mapping scheme exists to map the canonical model onto the SQL model. The `TranslationMapping` is essentially a |
| 67 | graph-like metamodel of the business objects: every Java class is represented by a mapping class that contains its field |
| 68 | names and the associated SQL column names. The convention is to append `*Mapping` to the class name, |
| 69 | e.g. `PolicyDefinitionMapping`. |
| 70 | |
| 71 | ### Mapping primitive fields |
| 72 | |
| 73 | Primitive fields are stored directly in SQL columns (as opposed to JSON, foreign keys,...). Thus, mapping primitive data |
| 74 | types is trivial: a simple mapping from one onto the other is necessary, for |
| 75 | example, `ContractNegotiation.counterPartyAddress` would be represented in the metamodel as an entry |
| 76 | |
| 77 | ```java |
| 78 | "counterPartyAddress"->"counterparty_address" |
| 79 | ``` |
| 80 | |
| 81 | When constructing `WHERE/AND` clauses, the canonical property must simply be replaced by the respective SQL column name. |
| 82 | |
| 83 | ### Mapping complex objects |
| 84 | |
| 85 | For fields that are of complex type, such as the `ContractNegotiation.contractAgreement` field, it is necessary to |
| 86 | accommodate this depending on how the EDM is defined. There are two basic variants that we use: |
| 87 | |
| 88 | #### Option 1: using foreign keys |
| 89 | |
| 90 | In this case, the referenced object is stored in a separate table using a foreign key. Thus, the canonical property |
| 91 | (= `contractAgreement`) is mapped onto the SQL schema using yet another `*Mapping` class. In the given example this |
| 92 | would be the `ContractAgreementMapping`. When resolving a property in the canonical format (`contractAgreement.assetId`) |
| 93 | , this means we must recursively descend into the model graph and resolve the correct SQL expression. |
| 94 | |
| 95 | _Note: mapping and translating `one-to-many` relations (= arrays/lists) with foreign keys is not implemented at this |
| 96 | time._ |
| 97 | |
| 98 | #### Option 2a: encoding the object in JSON |
| 99 | |
| 100 | Another way to store complex objects is to encode them in JSON and store them in a `VARCHAR` column. Some databases even |
| 101 | have a special data type and dedicated operators and functions for that. Postgres is one of them. For example, |
| 102 | the `TranferProcess` is stored in a table called `edc_transfer_process`, its `DataAddress` property is encoded in JSON |
| 103 | and stored in a `JSON` field. |
| 104 | |
| 105 | For example querying for `TransferProcess` objects: when mapping the filter |
| 106 | expression `contentDataAddress.properties.somekey=somevalue`, the `contentDataAddress` is represented as JSON, therefore |
| 107 | in the `TransferProcessMapping` the `contentDataAddress` field maps to a `JsonFieldMapping`: |
| 108 | |
| 109 | ```java |
| 110 | public TransferProcessMapping(TransferProcessStoreStatements statements){ |
| 111 | // ... |
| 112 | add(FIELD_CONTENTDATAADDRESS,new JsonFieldMapping(statements.getContentDataAddressColumn())); |
| 113 | // ... |
| 114 | } |
| 115 | ``` |
| 116 | |
| 117 | which would then get translated to: |
| 118 | |
| 119 | ```sql |
| 120 | SELECT * |
| 121 | FROM edc_transfer_process |
| 122 | -- omit LEFT OUTER JOIN for readability |
| 123 | WHERE content_data_address -> 'properties' ->> 'key' = 'value' |
| 124 | ``` |
| 125 | |
| 126 | _Note this statement is only valid in the Postgres dialect! Other SQL databases may or may not have similar |
| 127 | possibilities._ |
| 128 | |
| 129 | #### Option 2b: encoding lists/arrays in JSON |
| 130 | |
| 131 | Like accessing objects, accessing lists/arrays of objects is possible using special JSON operators. In this case the |
| 132 | special Postgres function `json_array_elements()` is used. Please refer to |
| 133 | the [official documentation](https://www.postgresql.org/docs/9.5/functions-json.html). |
| 134 | |
| 135 | For an example of how this is done, please look at how |
| 136 | the [TransferProcessMapping](../../extensions/control-plane/store/sql/transfer-process-store-sql/src/main/java/org/eclipse/edc/connector/store/sql/transferprocess/store/schema/postgres/TransferProcessMapping.java) |
| 137 | maps a `ResourceManifest`, which in turn contains a `List<ResourceDefinition>` using |
| 138 | the [ResourceManifestMapping](../../extensions/control-plane/store/sql/transfer-process-store-sql/src/main/java/org/eclipse/edc/connector/store/sql/transferprocess/store/schema/postgres/ResourceManifestMapping.java) |
| 139 | . Finally, the `SqlQueryStatement` |
| 140 | gets [assembled using the aforementioned JSON array function](../../extensions/control-plane/store/sql/transfer-process-store-sql/src/main/java/org/eclipse/edc/connector/store/sql/transferprocess/store/schema/postgres/PostgresDialectStatements.java) |
| 141 | . |
| 142 | |
| 143 | ## Prepared statements using the `SqlQueryStatement` |
| 144 | |
| 145 | The first step of the translation, i.e. mapping from canonical format onto a target DSL, is handled by |
| 146 | the `TranslationMapping` class and its implementors. |
| 147 | |
| 148 | The second and third steps involve interpreting the right-hand operand as scalar or list-type and substituting its |
| 149 | values with the appropriate placeholders for SQL prepared statements. This is done by the `SqlConditionExpression` |
| 150 | class, which validates the expression by checking the operator against a list of supported operators, and then converts |
| 151 | the right-hand operand in to either a single, or a list of placeholders. In SQL this is either `?` or `(?,?,...?)`. |
| 152 | |
| 153 | The `SqlQueryStatement` wraps both these two steps (translation and substitution) and offers a convenient API. |
| 154 | |
| 155 | ## Specific features for PostgreSQL |
| 156 | |
| 157 | As mentioned before Postgres has data types and query operators specifically to store and query JSON structures |
| 158 | (see [official documentation](https://www.postgresql.org/docs/12/functions-json.html)). In order to leverage that, some |
| 159 | parts of the object graph are persisted as JSON rather than in a separate table referenced by foreign key. |
| 160 | |
| 161 | The condition of the`WHERE` clause is in fact contributed by the `*Mapping` class that is specific to Postgres. |
| 162 | |
| 163 | Notes: |
| 164 | |
| 165 | - Querying list/array types using Postgres' JSON features requires modifying the `SELECT` statement, as the cast to a |
| 166 | JSON array is done on the fly. Therefore, this has to be done _before_ constructing the `SqlQueryStatement`. |
| 167 | - in order to port this to another database dialect, the `Mapping` classes very likely will have to be reimplemented |
| 168 | |
| 169 | ## Supported query operators |
| 170 | |
| 171 | Currently we only support the following operators: |
| 172 | |
| 173 | - `=`: equality, right-hand operand is interpreted as literal |
| 174 | - `in`: "one-of", right hand operand must be an `Iterable` |
| 175 | - `like`: pattern matching, right-hand operand is interpreted |
| 176 | as [pattern string](https://www.w3schools.com/sql/sql_like.asp) |
| 177 | |
| 178 | ## Comparison with NoSQL databases (CosmosDB) |
| 179 | |
| 180 | In CosmosDB this translation is not necessary, as the domain object is wrapped in a `CosmosDocument` and directly |
| 181 | serialized to JSON. In other words, the canonical format is congruent to the CosmosDB schema. However, CosmosDB uses a |
| 182 | similar method to dynamically generate `SELECT` statements. |