tiny_tds and JSON

3 views
Skip to first unread message

cra...@gmail.com

unread,
Aug 2, 2021, 10:02:34 AMAug 2
to sequel-talk
Using Sequel and the tiny_tds client in a Sinatra application.

When I use the tiny_tds client in a controller directly, the dataset is converted to JSON as expected:

    before do
        content_type :json
    end

    get '/' do
        client = TinyTds::Client.new(:host =>'HOST', :database => 'DATABASE', :username => 'USER', :password => 'PASSWORD')
        query = 'SELECT * FROM MssqlTable'
        client.execute(query).each.to_json
    end

# results
[{
expected JSON object
}]

However, when I include Sequel:

class  MssqlTable  < Sequel::Model(: mssql_table  )
end

get '/' do
    Sequel.connect(adapter: :tinytds, host: 'HOST', port: 1433, database: 'DATABASE', user: 'USER', password: 'PASSWORD')
      MssqlTable.all.to_json

#      MssqlTable.all.each.to_json # "#<Enumerator:0x00007fdd400f43d8>"

#       @results.all.each do |r|
#           r.to_json  # undefined method `bytesize' for #
#       end

end

# results
["#<MssqlTable:0x00007effa80ed068>"]

What's the correct syntax to have <MssqlTable> converted to JSON?

Jeremy Evans

unread,
Aug 2, 2021, 11:08:34 AMAug 2
to seque...@googlegroups.com
There are a couple different issues here.  First, you should never create a Sequel::Database instance inside a route handling block.  Second, you probably want to use the json_serializer plugin:

DB = Sequel.connect(adapter: :tinytds, host: 'HOST', port: 1433, database: 'DATABASE', user: 'USER', password: 'PASSWORD')
class  MssqlTable  < Sequel::Model(: mssql_table  )
  plugin :json_serializer
end

get '/' do
    MssqlTable.to_json
end

Alternatively, you could try just returning hashes instead of model objects:

get '/' do
      MssqlTable.naked.all.to_json
end

Thanks,
Jeremy

cra...@gmail.com

unread,
Aug 2, 2021, 11:16:04 AMAug 2
to sequel-talk
>  There are a couple different issues here.  First, you should never create a Sequel::Database instance inside a route handling block. 
Agreed.  Done merely to reduce the complexity while I was trying to get this to work.

> Second, you probably want to use the json_serializer plugin:
Good idea.

Both approaches worked.  Thanks for the help.
Reply all
Reply to author
Forward
0 new messages