From cdfefd49267e06834d7707e32c25901c340363b6 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 | 15 ++++++++++++--- 2 files changed, 21 insertions(+), 3 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..c81fcf1 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" @@ -23,8 +23,17 @@ class MySql::Connection < DB::Connection else 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["socket"] + @socket = UNIXSocket.new(params["socket"]) + else + @socket = TCPSocket.new(host, port) + end + handshake = read_packet(Protocol::HandshakeV10) write_packet(1) do |packet|