When transitioning to Go from another language that relies heavily on a framework, it can quickly start to feel like Go is lacking. Like it just doesn’t have the power or the tools that you are accustomed to. The end result is the language can feel confusing and clunky. One example of this is database migration tooling. If you are coming from a framework like Rails, Django, Flask, Laravel, or really any web framework, you very likely have an idea of what I am talking about.
In Java, it is pretty common to see libraries that use method chaining (aka the builder pattern) to construct resources. For example, we might construct a user by doing something like: User user = new User.Builder() .name("Michael Scott") .email("email@example.com") .role("manager") .nickname("Best Boss") .build(); Builders are handy for a variety of reasons, but in the example above we are using a builder in order to define a subset of our User attributes before constructing the user object.
One of the most common change requests I get with my Web Development course is to stop using GORM, and instead use the database/sql package that is part of Go’s standard library. When I receive feedback like this I often respond asking, “Why?” Why do they feel the database/sql package would be better suited for their education? Why do they feel ORMs will be problematic long term? I don’t ask these questions to be snarky or because I don’t care; I ask because I truly want to understand a problem before I look for solutions, and oftentimes people will tell you their problem is X, when in reality X is only a symptom of a deeper problem.
Learn how to query for multiple records using Go's database/sql package by querying for several users in a users table.
In this article we cover how to query for a single record using Go's database/sql package, including handling the ErrNoRows error.
Learn how to update and delete records with the database/sql package in Go. We also cover how to verify how many records were altered and return data from those rows.
Jon Calhoun is a full stack web developer who teaches about Go, web development, algorithms, and anything programming. If you haven't already, you should totally check out his Go courses.
Previously, Jon worked at several statups including co-founding EasyPost, a shipping API used by several fortune 500 companies. Prior to that Jon worked at Google, competed at world finals in programming competitions, and has been programming since he was a child.
©2018 Jonathan Calhoun. All rights reserved.