From 0ba5ad6d49d57e0e9c2a04f789c1fbcea143f221 Mon Sep 17 00:00:00 2001 From: Erik Wrenholt Date: Sat, 27 Jun 2020 23:37:16 -0500 Subject: [PATCH] Add unix domain socket support and update readme --- README.md | 9 +++++++++ src/mysql/connection.cr | 13 +++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f8d8d32..9f02857 100644 --- a/README.md +++ b/README.md @@ -77,3 +77,12 @@ Then use the example above changing the `DB.open` line to ```crystal DB.open "mysql://test:yourpassword@localhost/test" do |db| ``` + +## Unix Domain Socket + +If you specify a socket path, it will override the hostname in the URI. + +```crystal +DB.open "mysql://root@localhost/test?socket=/tmp/mysql.sock" do |db| +end +``` diff --git a/src/mysql/connection.cr b/src/mysql/connection.cr index ee50db6..fbcca34 100644 --- a/src/mysql/connection.cr +++ b/src/mysql/connection.cr @@ -9,7 +9,7 @@ class MySql::Connection < DB::Connection def initialize(context : DB::ConnectionContext) super(context) - @socket = uninitialized TCPSocket + @socket = uninitialized TCPSocket | UNIXSocket begin host = context.uri.hostname || raise "no host provided" @@ -24,7 +24,16 @@ class MySql::Connection < DB::Connection initial_catalog = nil end - @socket = TCPSocket.new(host, port) + if !context.uri.query.nil? + params = HTTP::Params.parse(context.uri.query.to_s) + end + + if !params.nil? && params.has_key?("socket") + @socket = UNIXSocket.new(params["socket"]) + else + @socket = TCPSocket.new(host, port) + end + handshake = read_packet(Protocol::HandshakeV10) write_packet(1) do |packet|