Connector interface abstracts away (hides) how MySQL connections are made and only returns
sql.Conn (new in Go 1.9). Code that uses a connection (let’s call it “database code”) does not and should not know how to connect to the database. The “how” is an implementation detail that should be hidden from database code. Furthermore, programs usually run in multiple environments: local (laptop), CI, staging, and production. The “how” can be different in all environments, but the database code should not. An interface like
Connector, which is a type of factory, is necessary.
sql.Conn is safe and has no drawbacks. It matches the developer’s expectation that “my connection is my connection”. Unless a developer reads the docs carefully, they are prone to using
sql.DB in correctly with potentially disastrous results. The benefit of the transparent connection pool in
sql.DB are outweighed by the consequences of its improper use. Luckily,
sql.Conn in Go 1.9 provide a safer and better alternative.
Human-friendly Error Handling
In production, it is common for MySQL connections to be dropped, lost, killed, etc. There are a suite of common errors that well-design production systems should handle but are not trivial to handle because it is not Go or the driver’s responsibility to make them obvious; it is the developer’s responsibility, but MySQL is a complicated system, so unless the de veloper also happens to be a MySQL expert, the errors ar
not running: 0: dial tcp <addr>: getsockopt: connection refused kill conn: 0: invalid connection crash: 0: invalid connection shutdown: 1053: Server shutdown in progress kill query: 1317: Query execution was interrupted read-only: 1290: The MySQL server is running with the --read-only (super) option so it cannot execute this statement dupe key: 1062: Duplicate entry '<value>' for key '<index name>' HOW DOES IT HANDLE UNDER OUTAGE PRESSURE? Need circuit breaker so new conns dont just stall -- fail quickly */