Cars in a specific range and order

Report a typo

Dominic keeps working with the in-memory SQLite database and the cars table that stores the specifications of all the cars he has raced against in street races:

sqlite3 database

Now he wants to retrieve all Car records from the cars table with a horsepower that is between 600 and 900, ordered by their model_name in descending order and then print the records using a for...range loop.

Dominic has already created the Car model struct and written the for...range loop that prints the retrieved records. Your task is to help him write the additional required code to retrieve the records using string conditions.

Write a program in Go
package main

import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"log"
)

type Car struct { // Model for the `cars` table
gorm.Model
Manufacturer string
ModelName string
TopSpeed float64
Horsepower float64
Torque float64
}

// nolint:gomnd // DO NOT delete this comment!
func main() {
db := createDB() // DO NOT delete this line! it creates the in-memory database

var cars []Car
// Write the code to retrieve all `Car` records using string conditions below:
result := ?
if result.Error != nil {
log.Fatalf("cannot retrieve cars: %v", result.Error)
}

// DO NOT delete the for...range loop — it prints the retrieved records!
for _, car := range cars {
fmt.Printf("%-2d | %-26s | %.2f | %.2f\n", car.ID, car.ModelName, car.TopSpeed, car.Torque)
}
}

// DO NOT delete the createDB() function — it is a helper function for creating the in-memory database!
func createDB() *gorm.DB {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
must(err)
must(db.AutoMigrate(&Car{}))
populateDatabase(db)
return db
}

// DO NOT delete the must() function — it is a helper function for error handling!
func must(err error) {
if err != nil {
log.Fatal(err)
}
}
___

Create a free account to access the full topic