Elffuss BraidHub

kikocis/EDC public

main · 9.2 KiBRenderedRawPermalink
1# Issuing dynamic queries in SQL data stores
2
3## Introduction
4
5The Management API (DM API) offers a very open and unrestricted query feature: as long as it can be expressed as a
63-tuple in the form
7
8```
9<LEFT_OPERAND> <OPERATOR> <RIGHT_OPERAND>
10```
11
12it is a valid query. This abstract way of expressing a condition is called a `Criterion`. For example, API clients may
13specify a query to obtain a selection of `ContractNegotiation` objects that looks like this:
14
15```
16contractAgreement.assetId = myAssetId
17```
18
19In practice this would return `ContractNegotiation`s, that have a `ContractAgreement` which references an `Asset` with
20the ID `"myAssetId"`.
21
22This means, that the backing `SqlContractNegotiationStore` must be able to do the following things:
23
241. 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.
292. 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)`
313. substitute the values in the expression with placeholders for prepared statements (=`?`)
324. leverage DB-specific features, like querying a JSON-encoded field, which would only be available in Postgres
33
34The following section explains how all of these are achieved.
35
36## Preliminary: the canonical format
37
38Theoretically it is possible to map every schema onto every other schema, given that they are of equal cardinality. To
39achieve that, we introduce the notion of a _canonical format_, which is our internal working schema. In other words,
40this is the schema in which objects are represented internally. If in the future we support a wider variety of
41translation and transformation paths, everything would have to be transformed into that canonical format first.
42
43In actuality the _canonical format_ of an object is defined by the respective Java class and its field names. For
44instance, a query for contract negotiations must be specified using the field names of a `ContractNegotiation` object:
45
46```java
47public class ContractNegotiation {
48 // ...
49 private ContractAgreement contractAgreement;
50 // ...
51}
52
53public class ContractAgreement {
54 // ...
55 private final String assetId;
56}
57```
58
59Consequently, `contractAgreement.assetId` would be valid, whereas `contract_agreement.asset_id` would not. Or, the
60left-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
65In order to decouple the canonical format and the SQL schema (or any other schema) in terms of naming convention, a
66mapping scheme exists to map the canonical model onto the SQL model. The `TranslationMapping` is essentially a
67graph-like metamodel of the business objects: every Java class is represented by a mapping class that contains its field
68names and the associated SQL column names. The convention is to append `*Mapping` to the class name,
69e.g. `PolicyDefinitionMapping`.
70
71### Mapping primitive fields
72
73Primitive fields are stored directly in SQL columns (as opposed to JSON, foreign keys,...). Thus, mapping primitive data
74types is trivial: a simple mapping from one onto the other is necessary, for
75example, `ContractNegotiation.counterPartyAddress` would be represented in the metamodel as an entry
76
77```java
78"counterPartyAddress"->"counterparty_address"
79```
80
81When constructing `WHERE/AND` clauses, the canonical property must simply be replaced by the respective SQL column name.
82
83### Mapping complex objects
84
85For fields that are of complex type, such as the `ContractNegotiation.contractAgreement` field, it is necessary to
86accommodate this depending on how the EDM is defined. There are two basic variants that we use:
87
88#### Option 1: using foreign keys
89
90In 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
92would 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
96time._
97
98#### Option 2a: encoding the object in JSON
99
100Another way to store complex objects is to encode them in JSON and store them in a `VARCHAR` column. Some databases even
101have a special data type and dedicated operators and functions for that. Postgres is one of them. For example,
102the `TranferProcess` is stored in a table called `edc_transfer_process`, its `DataAddress` property is encoded in JSON
103and stored in a `JSON` field.
104
105For example querying for `TransferProcess` objects: when mapping the filter
106expression `contentDataAddress.properties.somekey=somevalue`, the `contentDataAddress` is represented as JSON, therefore
107in the `TransferProcessMapping` the `contentDataAddress` field maps to a `JsonFieldMapping`:
108
109```java
110public TransferProcessMapping(TransferProcessStoreStatements statements){
111 // ...
112 add(FIELD_CONTENTDATAADDRESS,new JsonFieldMapping(statements.getContentDataAddressColumn()));
113 // ...
114 }
115```
116
117which would then get translated to:
118
119```sql
120SELECT *
121FROM edc_transfer_process
122-- omit LEFT OUTER JOIN for readability
123WHERE 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
127possibilities._
128
129#### Option 2b: encoding lists/arrays in JSON
130
131Like accessing objects, accessing lists/arrays of objects is possible using special JSON operators. In this case the
132special Postgres function `json_array_elements()` is used. Please refer to
133the [official documentation](https://www.postgresql.org/docs/9.5/functions-json.html).
134
135For an example of how this is done, please look at how
136the [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)
137maps a `ResourceManifest`, which in turn contains a `List<ResourceDefinition>` using
138the [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`
140gets [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
145The first step of the translation, i.e. mapping from canonical format onto a target DSL, is handled by
146the `TranslationMapping` class and its implementors.
147
148The second and third steps involve interpreting the right-hand operand as scalar or list-type and substituting its
149values with the appropriate placeholders for SQL prepared statements. This is done by the `SqlConditionExpression`
150class, which validates the expression by checking the operator against a list of supported operators, and then converts
151the right-hand operand in to either a single, or a list of placeholders. In SQL this is either `?` or `(?,?,...?)`.
152
153The `SqlQueryStatement` wraps both these two steps (translation and substitution) and offers a convenient API.
154
155## Specific features for PostgreSQL
156
157As 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
159parts of the object graph are persisted as JSON rather than in a separate table referenced by foreign key.
160
161The condition of the`WHERE` clause is in fact contributed by the `*Mapping` class that is specific to Postgres.
162
163Notes:
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
171Currently 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
180In CosmosDB this translation is not necessary, as the domain object is wrapped in a `CosmosDocument` and directly
181serialized to JSON. In other words, the canonical format is congruent to the CosmosDB schema. However, CosmosDB uses a
182similar method to dynamically generate `SELECT` statements.