Skip to content

Instantly share code, notes, and snippets.

@crisward
Last active October 21, 2016 13:54
Show Gist options
  • Save crisward/cd6bd7ed6f5796add143419c66af83c0 to your computer and use it in GitHub Desktop.
Save crisward/cd6bd7ed6f5796add143419c66af83c0 to your computer and use it in GitHub Desktop.
kemal mysql
require "./mess/*"
require "kemal"
require "json"
require "mysql"
require "pool/connection"
db = ConnectionPool.new(capacity: 25, timeout: 0.01) do
DB.open(ENV["DATABASE_URL"])
end
class User
DB.mapping({
id: Int32,
first_name: {type: String, nilable: true},
surname: {type: String, nilable: true},
})
JSON.mapping({
id: Int32,
first_name: {type: String, nilable: true},
surname: {type: String, nilable: true},
})
end
get "/" do |env|
db.connection do |conn|
env.response.content_type = "application/json"
rs = conn.query("SELECT id,first_name,surname FROM users")
users = User.from_rs(rs)
rs.close #must do this to allow the connection to be reused
return users.to_json
end
end
Kemal.run
name: mess
version: 0.1.0
authors:
- Cris Ward
license: MIT
dependencies:
kemal:
github: sdogruyol/kemal
branch: master
mysql:
github: crystal-lang/crystal-mysql
branch: master
pool:
github: ysbaddaden/pool
branch: master
@rdp
Copy link

rdp commented Sep 28, 2016

for followers, DB.mapping is described here https://github.com/crystal-lang/crystal-db/blob/4f724475e0b929fe028186e7bce8a656fcb4f46d/src/db/mapping.cr and "from_rs" means "from result set" :|
You might be able to avoid having to call close on the resultset by putting it in a block.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment