|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require 'duckdb' |
| 4 | +require 'polars-df' |
| 5 | + |
| 6 | +df = Polars::DataFrame.new( |
| 7 | + { |
| 8 | + a: [1, 2, 3], |
| 9 | + b: %w[one two three] |
| 10 | + } |
| 11 | +) |
| 12 | + |
| 13 | +module DuckDB |
| 14 | + class TableFunction |
| 15 | + @table_adapters = {} |
| 16 | + class << self |
| 17 | + def add_table_adapter(klass, adapter) |
| 18 | + @table_adapters[klass] = adapter |
| 19 | + end |
| 20 | + |
| 21 | + def table_adapter_for(klass) |
| 22 | + @table_adapters[klass] |
| 23 | + end |
| 24 | + end |
| 25 | + end |
| 26 | + |
| 27 | + class Connection |
| 28 | + def create_table_function(object, name) |
| 29 | + adapter = TableFunction.table_adapter_for(object.class) |
| 30 | + raise ArgumentError, "No table adapter registered for #{object.class}" if adapter.nil? |
| 31 | + |
| 32 | + tf = adapter.call(object, name) |
| 33 | + register_table_function(tf) |
| 34 | + end |
| 35 | + end |
| 36 | + |
| 37 | + module Polars |
| 38 | + module DataFrame |
| 39 | + class TableAdapter |
| 40 | + def call(df, name) # rubocop:disable Metrics/MethodLength, Naming/MethodParameterName |
| 41 | + columns = df.columns.each_with_object({}) { |header, hash| hash[header] = LogicalType::VARCHAR } |
| 42 | + counter = 0 |
| 43 | + height = df.height |
| 44 | + width = df.columns.length |
| 45 | + |
| 46 | + DuckDB::TableFunction.create( |
| 47 | + name:, |
| 48 | + columns: |
| 49 | + ) do |_func_info, output| |
| 50 | + if counter < height |
| 51 | + width.times do |index| |
| 52 | + output.set_value(index, 0, df[counter, index]) |
| 53 | + end |
| 54 | + counter += 1 |
| 55 | + 1 |
| 56 | + else |
| 57 | + counter = 0 |
| 58 | + 0 |
| 59 | + end |
| 60 | + end |
| 61 | + end |
| 62 | + end |
| 63 | + end |
| 64 | + end |
| 65 | + TableFunction.add_table_adapter(::Polars::DataFrame, DuckDB::Polars::DataFrame::TableAdapter.new) |
| 66 | +end |
| 67 | + |
| 68 | +db = DuckDB::Database.open |
| 69 | + |
| 70 | +con = db.connect |
| 71 | +con.query('SET threads=1') |
| 72 | +con.create_table_function(df, 'polars_df') |
| 73 | +result = con.query('SELECT * FROM polars_df()').to_a |
| 74 | +p result |
| 75 | +puts result.first.first == '1' |
| 76 | + |
| 77 | +con.close |
| 78 | +db.close |
0 commit comments