feat: add IdentityDB core memory graph APIs
This commit is contained in:
55
src/queries/topics.ts
Normal file
55
src/queries/topics.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import type { Kysely, Transaction } from 'kysely';
|
||||
|
||||
import type { IdentityDatabaseSchema } from '../types/database';
|
||||
import type { TopicRecord } from '../types/domain';
|
||||
|
||||
export type DatabaseExecutor = Kysely<IdentityDatabaseSchema> | Transaction<IdentityDatabaseSchema>;
|
||||
|
||||
export interface ConnectedTopicRow extends TopicRecord {
|
||||
shared_fact_count: number;
|
||||
}
|
||||
|
||||
export async function findTopicRowByNormalizedName(
|
||||
executor: DatabaseExecutor,
|
||||
normalizedName: string,
|
||||
): Promise<TopicRecord | undefined> {
|
||||
return executor
|
||||
.selectFrom('topics')
|
||||
.selectAll()
|
||||
.where('normalized_name', '=', normalizedName)
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
export async function listTopicRows(
|
||||
executor: DatabaseExecutor,
|
||||
limit?: number,
|
||||
): Promise<TopicRecord[]> {
|
||||
let query = executor
|
||||
.selectFrom('topics')
|
||||
.selectAll()
|
||||
.orderBy('normalized_name', 'asc');
|
||||
|
||||
if (limit !== undefined) {
|
||||
query = query.limit(limit);
|
||||
}
|
||||
|
||||
return query.execute();
|
||||
}
|
||||
|
||||
export async function findConnectedTopicRows(
|
||||
executor: DatabaseExecutor,
|
||||
topicId: string,
|
||||
): Promise<ConnectedTopicRow[]> {
|
||||
return executor
|
||||
.selectFrom('fact_topics as source_link')
|
||||
.innerJoin('fact_topics as related_link', 'related_link.fact_id', 'source_link.fact_id')
|
||||
.innerJoin('topics', 'topics.id', 'related_link.topic_id')
|
||||
.selectAll('topics')
|
||||
.select((eb) => eb.fn.count<number>('related_link.fact_id').as('shared_fact_count'))
|
||||
.where('source_link.topic_id', '=', topicId)
|
||||
.whereRef('related_link.topic_id', '!=', 'source_link.topic_id')
|
||||
.groupBy('topics.id')
|
||||
.orderBy('shared_fact_count', 'desc')
|
||||
.orderBy('topics.normalized_name', 'asc')
|
||||
.execute() as Promise<ConnectedTopicRow[]>;
|
||||
}
|
||||
Reference in New Issue
Block a user