graph-ecs/tests/query-parser/query.test.js

83 lines
3.2 KiB
JavaScript

import util from 'node:util'
import { describe, it } from 'node:test'
import assert from '../assert.js'
import { query } from '../../src/query-parser/index.js'
import { Alias, Identifier, Match, ObjectPath, Property, Query, ReturnValues, SelectedGraph } from '../../src/query-parser/types.js'
import { makeNode, makeRelationship, makeRightEdge } from '../utils.js'
import { map } from '../../src/fn.js'
const path = (...args) => new ObjectPath(identifier(args[0]), ...args.slice(1).map(prop))
const prop = x => new Property(identifier(x))
const alias = (...x) => new Alias(...x)
const identifier = n => new Identifier(n)
const graph = n => new SelectedGraph(identifier(n))
const returnVals = (...x) => new ReturnValues(...x)
const matches = (...args) => map(x => new Match(x), args)
const q = (u, m, w, rv) => new Query(u, m, w, rv)
describe('query', () => {
it('should match a node', () => {
assert.parseOk(query, 'MATCH (node:Label) RETURN node', ([actual]) => {
const expected = q(
undefined, // no use clause
matches(makeNode('node', 'Label')),
[],
returnVals(identifier('node'))
)
assert.deepEqual(actual, expected)
})
})
it('should match a relationship', () => {
assert.parseOk(query, 'MATCH (rown:Creature)-[:Petpats]->(kbity:NetCat) RETURN rown, kbity', ([actual]) => {
const expected = q(
undefined, // no use clause
matches(makeRelationship(
makeNode('rown', 'Creature'),
makeRightEdge(undefined, 'Petpats'),
makeNode('kbity', 'NetCat'),
)),
[],
returnVals(identifier('rown'), identifier('kbity'))
)
assert.deepEqual(actual, expected)
})
})
it('should support the USE clause', () => {
assert.parseOk(query, 'USE aminals MATCH (kbity:Cat) RETURN kbity', ([actual]) => {
const expected = q(
graph('aminals'),
matches(makeNode('kbity', 'Cat')),
[],
returnVals(identifier('kbity'))
)
assert.deepEqual(actual, expected)
})
})
it('should support complex queries', () => {
assert.parseOk(query, 'USE aminals MATCH (kbity:Cat { type: "cute" })-[:Eats { schedule: "daily" }]->(snacc:Feesh { type: "vegan", weight: 0.7 }) RETURN kbity.name AS name, snacc AS food', ([actual]) => {
const expected = q(
graph('aminals'),
matches(makeRelationship(
makeNode('kbity', 'Cat', [['type', 'cute']]),
makeRightEdge(undefined, 'Eats', [['schedule', 'daily']]),
makeNode('snacc', 'Feesh', [['type', 'vegan'], ['weight', 0.7]])
)),
[],
returnVals(
alias(path('kbity', 'name'), identifier('name')),
alias(identifier('snacc'), identifier('food'))
)
)
console.log(util.inspect(actual, { depth: null }))
console.log(util.inspect(expected, { depth: null }))
assert.deepEqual(actual, expected)
})
})
})