Databases

Crystal ORM

Using ORMs

Crystal ORMs like Granite simplify database queries.

Introduction to Crystal ORMs

Object-Relational Mapping (ORM) is a technique that allows developers to interact with a database using an object-oriented paradigm. Crystal, a language known for its performance and efficiency, offers several ORM libraries, with Granite being one of the most popular choices. Granite simplifies database interactions by abstracting SQL queries into Crystal code, making it easier to perform CRUD operations.

Setting Up Granite ORM

To get started with Granite ORM in a Crystal application, you need to include it in your project dependencies. This can be done via the shard.yml file.

Configuring the Database Connection

After setting up Granite, the next step is to configure your database connection. This is typically done in a database.yml file, where you specify the adapter, host, username, password, and database name.

Defining Models in Granite

In Granite, each database table corresponds to a model class. Models define the structure and behavior of your data. Here’s how you can define a simple model in Granite:

Performing CRUD Operations

With models defined, performing CRUD (Create, Read, Update, Delete) operations becomes straightforward. Here’s how you can create a new user and query existing users:

Advanced Querying Techniques

Granite allows for more advanced querying techniques. You can filter, sort, and apply conditions to queries easily:

Conclusion

Granite ORM provides a powerful and intuitive interface for interacting with databases in Crystal applications. By abstracting the complexity of SQL, it allows developers to focus more on building application logic rather than database management, enhancing productivity and code clarity.