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: support using pgvector #13

Merged
merged 3 commits into from
Sep 20, 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
2 changes: 1 addition & 1 deletion .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Metrics/MethodLength:
- 'method_call'

Metrics/ModuleLength:
Max: 100
Max: 150
CountAsOne:
- 'array'
- 'heredoc'
Expand Down
34 changes: 31 additions & 3 deletions lib/kirei/model/class_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,40 @@ def wrap_jsonb_non_primivitives!(attributes)
return unless App.config.db_extensions.include?(:pg_json)

attributes.each_pair do |key, value|
next unless value.is_a?(Hash) || value.is_a?(Array)

attributes[key] = T.unsafe(Sequel).pg_jsonb_wrap(value)
if vector_column?(key.to_s)
attributes[key] = cast_to_vector(value)
elsif value.is_a?(Hash) || value.is_a?(Array)
attributes[key] = T.unsafe(Sequel).pg_jsonb_wrap(value)
end
end
end

#
# install the gem "pgvector" if you need to use vector columns
# also add `:pgvector` to the `App.config.db_extensions` array
# and enable the vector extension on the database.
#
sig { params(column_name: String).returns(T::Boolean) }
def vector_column?(column_name)
_col_name, col_info = T.let(
db.schema(table_name.to_sym).find { _1[0] == column_name.to_sym },
[Symbol, T::Hash[Symbol, T.untyped]],
)
col_info.fetch(:db_type).match?(/vector\(\d+\)/)
end

# New method to cast an array to a vector
sig { params(value: T.any(T::Array[Numeric], Sequel::SQL::Expression)).returns(Sequel::SQL::Expression) }
def cast_to_vector(value)
return value if value.is_a?(Sequel::SQL::Expression) || value.is_a?(Sequel::SQL::PlaceholderLiteralString)

Kernel.raise("'pg_array' extension is not enabled") unless db.extension(:pg_array)

pg_array = T.unsafe(Sequel).pg_array(value)

Sequel.lit("?::vector", pg_array)
end

sig do
override.params(
hash: T::Hash[Symbol, T.untyped],
Expand Down