CQL is a powerful library designed to simplify and enhance the management and execution of SQL queries in the Crystal programming language. It provides utilities for building, validating, and executing SQL statements, ensuring better performance and code maintainability.
u =AcmeDB.updateu.table(:users).set(name: "Jane Smith").where(id: 1).commit
5. Deleting Data
Delete records from the database:
d =AcmeDB.deleted.from(:users).where(id: 1).commit
6. Using the Repository Pattern
Utilize the repository pattern for organized data management:
user_repository =CQL::Repository(User,Int64).new(schema, :users)# Create a new useruser_repository.create(name: "Jane Doe", email: "jane@example.com")# Fetch all usersusers = user_repository.allusers.each { |user|puts user.name }# Find a user by IDuser = user_repository.find!(1)puts user.name# Update a user by IDuser_repository.update(1, name: "Jane Smith")
7. Active Record Pattern
Work with your data using the Active Record pattern:
structActor < CQL::Record(Int64) db_context AcmeDB2, :actorsgetter id :Int64?getter name :Stringdefinitialize(@name :String)endendstructMovie < CQL::Record(Int64) db_context AcmeDB2, :movies has_one :screenplay,Screenplay many_to_many :actors,Actor, join_through: :movies_actors has_many :directors,Director, foreign_key: :movie_idgetter id :Int64?getter title :Stringdefinitialize(@title :String)endendstructDirector < CQL::Record(Int64) db_context AcmeDB2, :directorsgetter id :Int64?getter name :String belongs_to :movie, foreign_key: :movie_iddefinitialize(@name :String)endendstructScreenplay < CQL::Record(Int64) db_context AcmeDB2, :screenplays belongs_to :movie, foreign_key: :movie_idgetter id :Int64?getter content :Stringdefinitialize(@movie_id :Int64, @content :String)endendstructMoviesActors < CQL::Record(Int64) db_context AcmeDB2, :movies_actorsgetter id :Int64?getter movie_id :Int64getter actor_id :Int64 has_many :actors,Actor, :actor_iddefinitialize(@movie_id :Int64, @actor_id :Int64)endend