In Beeketing, improve quality for a SQL's query is most of the important thing to do in a large scalable system with thousand records data have to return for a query. To help us can monitor for each of a query when they executed, we use tracking time by add hook operations into each a query. Basically, we will add more code to run before and after the query being executed.
Firstly, hook operations is a solution just help you implement two more methods will run before and after of a query when it is executed. They are Before() and After(). We will also implement a method called OnError() for handle error.
Secondly, we only focus on original SQL database drivers from Golang. So that, we will wrap/override some methods in SQL Drivers for use Hook.
In this tutorial, we only show you how to tracking time of a query, all code for implement hook operation is being shown below.
Source code: https://github.com/Beeketing/golang-sqlhooks
Beautiful day when we only use pure Golang, no framework, library.
Note: sqlhooks.go only focus to 3 methods: Before(), After(), OnError()
We will create loghooks.go to implement hook operations to tracking time for a query.
We would like to use context to help us save point of time when query start. And use time.Since() to get total time counted. All queries will be logged.
In this tutorial, we want to test with MySQL.
So, make connection configuration to MySql with connection.go.
We have already all weapons, lets create main.go to show the magic.
As you can see, we must wrap current MySql drivers to new one that we already implemented before with Hook operations by use sql.Register("driverName", hooks)
Before we going to run the main, we must to deploy a MySQL server. If you haven't ready MySQL on your machine. Let's open your terminal and use Docker with two simple command lines for good.
Create MySQL first.
docker run --name local-mysql -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.7.25
Create PhpMyAdmin to manage MySQL.
docker run --name myadmin -d --link local-mysql:db -p 8080:80 phpmyadmin/phpmyadmin
Finally, this is the magic:
You can see clearly the result that we have done!
Finally, thank you for watching. Please lets your comment here, I will help you.