Created
February 27, 2025 07:26
-
-
Save zxt-tzx/3b1a6af7529312bb9ddb8ab08a599ae4 to your computer and use it in GitHub Desktop.
Drizzle helper functions: typesafe cosineDistance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { SQL } from "drizzle-orm"; | |
import { sql } from "drizzle-orm"; | |
import type { AnyColumn } from "drizzle-orm/column"; | |
import type { TypedQueryBuilder } from "drizzle-orm/query-builders/query-builder"; | |
import type { SQLWrapper } from "drizzle-orm/sql"; | |
function toSql(value: number[] | string[]): string { | |
return JSON.stringify(value); | |
} | |
// copy from drizzle-orm/sql/functions/vector.ts | |
// BUT accept a type argument for type-safety | |
export function cosineDistance<T = unknown>( | |
column: SQLWrapper | AnyColumn, | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
value: number[] | string[] | TypedQueryBuilder<any> | string, | |
): SQL<T> { | |
if (Array.isArray(value)) { | |
return sql`${column} <=> ${toSql(value)}`; | |
} | |
return sql`${column} <=> ${value}`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment