A replacement for database sql
source link: https://medium.com/@rocketlaunchr.cloud/a-replacement-for-database-sql-f25d01fbe9b1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
A replacement for database/sql
Apr 13 ·2min read
Imagine if you had the power to rewrite the notorious database/sql
package so that it was friendlier, simpler and less verbose.
What would it look like?
It would look like the all-new dbq
package
. Version 2.2 was just released with so many bells and whistles that you’ll never directly use the database/sql
package again.
A small subset of the features are showcased below. Also read to the end to see the new direction of the package.
Zero boilerplate code
You can execute simple queries in 8 lines instead of 30. And it comes with built-in unmarshaling.
dbq vs database/sql
The contrast speaks for itself.
Flatten Query Args
You have a []string
with a list of query arguments that you want to inject into a query without SQL-injection issues. You can feel the irritation building up.
func (db *DB) Query(query string, args ...interface{})
Unfortunately, args
only accepts interface{}
so you need to superfluously iterate over the entire []string
to
copy
the values into a []interface{}
. It makes your code look like Wuhan 2 months back.
dbq
has your back.
All slices are flattened automatically . No questions asked.
Mission-critical queries
What if you have a query that HAS TO SUCCEED . Failure is not an option®.
dbq has built-in retry capabilities so it will continue to attempt your query with exponentially increasing intervals.
Transaction management
What about transactions? Got you covered.
dbq.Tx(ctx, db, func(tx interface{}, ..., txCommit dbq.TxCommit) { res, err := E(ctx, "exec statement") if err != nil { return // Automatic rollback } txCommit()})
You can have an arbitrarily complex database operation happening within a transaction without having to worry about rolling-back ON every SINGLE sad PATH. Just commit at the end.
Finally, THIS IS YOUR PACKAGE
The x
subpackage houses custom query helper functions that are general xor MySQL/PostgreSQL specific.
You are welcome to submit PR’s with whatever custom functions you want. As long as you leave the core package pristine, and your code compiles and is well documented, then it’ll be welcomed with open arms.
As a warm-up, I’ve included a BulkUpdate
function which allows you to update thousands of rows with 1 query without a transaction!
Stay safe boys and girls.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK