Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Implement initial subquery implementation #49

Merged
merged 2 commits into from
Sep 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/storage/FindOptionsTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,18 @@ export interface FindOptionsWhere {
[k: string]: FindOptionsWhereField | undefined;
}

// Add these new types
export interface SubQuery {
select: Variable[];
where: FindOptionsWhere;
groupBy?: string[];
having?: FindOptionsWhere;
}

export interface FindAllOptions extends FindOneOptions {
offset?: number;
limit?: number;
subQueries?: SubQuery[];
}

export interface FindExistsOptions {
Expand Down
37 changes: 37 additions & 0 deletions src/storage/query-adapter/sparql/SparqlQueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import type {
Pattern,
ConstructQuery,
GraphPattern,
Grouping,
SelectQuery,
} from 'sparqljs';
import {
allTypesAndSuperTypesPath,
Expand Down Expand Up @@ -59,6 +61,7 @@ import type {
FindOptionsWhere,
FindOptionsWhereField,
IdFindOptionsWhereField,
SubQuery,
TypeFindOptionsWhereField,
ValueWhereFieldObject,
} from '../../FindOptionsTypes';
Expand Down Expand Up @@ -104,6 +107,7 @@ export interface SparqlQueryBuilderOptions {
select?: FindOptionsSelect;
order?: FindOptionsOrder;
relations?: FindOptionsRelations;
subQueries?: SubQuery[];
}

export class SparqlQueryBuilder {
Expand All @@ -121,6 +125,11 @@ export class SparqlQueryBuilder {
const whereQueryData = this.createWhereQueryData(subject, options?.where, true);
const orderQueryData = this.createOrderQueryData(subject, options?.order);
const relationsQueryData = this.createRelationsQueryData(subject, relations);
// Handle subqueries
if (options?.subQueries && options.subQueries.length > 0) {
const subQueryPatterns = this.createSubQueryPatterns(options.subQueries);
whereQueryData.values.unshift(...subQueryPatterns as ValuesPattern[]);
}
const patterns: Pattern[] = whereQueryData.values;
if (whereQueryData.triples.length === 0 && (
whereQueryData.filters.length > 0 ||
Expand Down Expand Up @@ -163,6 +172,34 @@ export class SparqlQueryBuilder {
};
}

private createSubQueryPatterns(subQueries: SubQuery[]): Pattern[] {
return subQueries.map((subQuery: SubQuery): Pattern => {
const subQueryWhere = this.createWhereQueryData(entityVariable, subQuery.where);
const queryGroup: Grouping[] = [];
if (subQuery.groupBy && Array.isArray(subQuery.groupBy)) {
subQuery.groupBy.forEach((group: string): void => {
queryGroup.push({
expression: DataFactory.variable(group),
});
});
}
const selectQuery: SelectQuery = {
type: 'query',
queryType: 'SELECT',
variables: subQuery.select,
where: this.createWherePatternsFromQueryData(
subQueryWhere.values,
subQueryWhere.triples,
subQueryWhere.filters,
),
group: queryGroup.length > 0 ? queryGroup : undefined,
having: subQuery.having ? this.createWhereQueryData(entityVariable, subQuery.having).filters : undefined,
prefixes: {},
};
return createSparqlSelectGroup([ selectQuery ]);
});
}

private createEntityGraphFilterPattern(subject: Variable): GraphPattern {
const entityFilterTriple = { subject, predicate: this.createVariable(), object: this.createVariable() };
return createSparqlGraphPattern(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -706,7 +706,7 @@ describe('a SparqlQueryAdapter', (): void => {
await adapter.findAll({
where: {
type: 'https://schema.org/Place',
'https://standardknowledge.com/ontologies/core/deduplicationGroup': '?deduplicationGroup'
'https://standardknowledge.com/ontologies/core/deduplicationGroup': '?deduplicationGroup',
},
group: DataFactory.variable('deduplicationGroup'),
entitySelectVariable: {
Expand Down Expand Up @@ -736,6 +736,46 @@ describe('a SparqlQueryAdapter', (): void => {
});
});

it('executes a subquery.', async(): Promise<void> => {
await adapter.findAll({
where: {
type: 'https://schema.org/Place',
},
subQueries: [
{
select: [ DataFactory.variable('deduplicationGroup'), {
variable: DataFactory.variable('entity'),
expression: {
type: 'aggregate',
aggregation: 'MIN',
expression: DataFactory.variable('entity'),
},
}],
where: {
'https://standardknowledge.com/ontologies/core/deduplicationGroup': '?deduplicationGroup',
},
groupBy: [ 'deduplicationGroup' ],
},
],
});
expect(select.mock.calls[0][0].split('\n')).toEqual([
'CONSTRUCT { ?subject ?predicate ?object. }',
'WHERE {',
' {',
' SELECT DISTINCT ?entity WHERE {',
' {',
' SELECT ?deduplicationGroup (MIN(?entity) AS ?entity) WHERE { ?entity <https://standardknowledge.com/ontologies/core/deduplicationGroup> ?deduplicationGroup. }',
' GROUP BY ?deduplicationGroup',
' }',
' ?entity (<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/(<http://www.w3.org/2000/01/rdf-schema#subClassOf>*)) <https://schema.org/Place>.',
' FILTER(EXISTS { GRAPH ?entity { ?entity ?c1 ?c2. } })',
' }',
' }',
' GRAPH ?entity { ?subject ?predicate ?object. }',
'}',
]);
});

describe('findAllBy', (): void => {
it('queries for entities and returns an empty array if there are no results.',
async(): Promise<void> => {
Expand Down
Loading