DEV Community

Tangpanqing
Tangpanqing

Posted on

Go is also able to use objects to operate databases. Many users have commented that this ensures robustness in the code

Hi, all my friends who are using go, happy new year.

Have you all tried using the Aorm library that I introduced before? It is, so far, the best database operation library I've seen in the go field.

Last year (in fact, half a month ago), I wrote an article introducing the Aorm's chain operation, showing its ease of use.

"You never know, go's database operation can be as smooth as php"

Many friends added me, expressing their support and making earnest requests. One of the requests was for the ability to use objects to operate on the database.

After half a month of research and effort, it's here now, it's here, it's come with devilish steps.

What is object-oriented database operation?

Many friends may not have heard of this, so I'll give a simple example in another language's code first.

$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->orderBy('name', 'desc')
->get();
Enter fullscreen mode Exit fullscreen mode

As shown above, in PHP code, a simple database query statement, familiar to PHP friends.

The users, id, and name that appear here are all strings and need to be manually coded in, and the disadvantages are obvious:

  1. During development, it is easy to produce spelling errors.

  2. When refactoring or when field and table names are changed, it can be a headache. Because they are distributed in various places in the project, you need to be extremely careful and find them correctly and then modify them. Missing one is like a timed bomb.

Let's take a look at how this problem is solved in .NET

dbContext
.Person
.GroupJoin(
     dbContext.Products, 
     person => person.Id, 
     product => product.Id, 
     (person, products) => new { Person = person, Products = products })
.SelectMany(
        combination => combination.Products.DefaultIfEmpty(), 
        (person, products) => new { 
            PersonId = person.Person.Id, 
            PersonName = person.Person.Name, 
            ProductsId = products.Id, 
            ProductsName = products.Product 
        }
    )
    .ToList();
Enter fullscreen mode Exit fullscreen mode

In the code you saw above, there are no manually written strings, they are all object types or object properties.

During development, you need to define objects and properties in advance, which is indeed more work than PHP development. But maintenance is super easy.

If you have a table or field that needs to be modified, just modify it and the editor will automatically prompt you which fields are missing, highlight and display them, not a single mistake, and not missing any.

If you do not modify it, it will not pass compilation. As a result, the robustness of your program is guaranteed. After development, you can also sleep soundly.

What is Aorm?

Aorm is a Go-based database operation library.

The project address is github.com/tangpanqing/aorm

Core advantages:

Support using structs (objects) to operate databases, making your system more robust

Support for MySQL, MsSQL, Postgres, Sqlite3 databases, making your system easier to expand

Support for chain operations, making your development more efficient

Support for null value queries or updates, making your development experience better

Support for migrating data structures, making your data migration more convenient

Currently, the number of stars on Github is not high, but the author is quite thoughtful and the documentation is still complete. If you are interested, you can take a look.

Aorm uses objects to operate databases

below is an example of association query that I found from Aorm's documentation.

aorm.Db(db).
        Table(&article).
        LeftJoin(
            &person,
            []builder.JoinCondition{
                builder.GenJoinCondition(&person.Id, builder.RawEq, &article.PersonId),
            },
        ).
        SelectAll(&article).
        SelectAs(&person.Name, &articleVO.PersonName).
        WhereEq(&article.Type, 0).
        WhereIn(&person.Age, []int{18, 20}).
        GetMany(&list2)
Enter fullscreen mode Exit fullscreen mode

It generates the following SQL statement:

    SELECT article.*,person.name as person_name 
    FROM article 
    LEFT JOIN person ON person.id=article.person_id 
    WHERE article.type = ? 
    AND article.age IN (?,?)

    0 18 20
Enter fullscreen mode Exit fullscreen mode

By comparing the code and the SQL, if you have a good understanding of SQL, you should be able to understand the function of each method in the code and what each parameter represents. As you can see, the &article in the code corresponds to the article table in the SQL, &person.Id corresponds to the person.id field in the SQL, and so on.

Once you understand the principle, you can look at the code again and see that there is no hard-coded field name or table name. Like the .NET example above, all operations are object-oriented, making your code more robust and making maintenance and refactoring more convenient.

End
through this article, we have briefly introduced using objects (structs) to operate databases in Go and provided some examples.

For more features or documentation on Aorm, you can check out the Aorm documentation at the project address

github.com/tangpanqing/aorm

I also strongly invite friends to use Aorm, if you encounter any problems during use, please feel free to contact me through various channels.

Top comments (0)