Ejemplo n.º 1
0
func TestNewCar(t *testing.T) {

	cars := []Car{
		{},
		{Manufacturer: "Volvo", Design: "v40", Style: "urban"},
	}
	for _, c := range cars {
		timeNow := time.Now().Format(time.UnixDate)
		NewCar(&c)

		createdAt := c.CreatedAt.Format(time.UnixDate)
		updatedAt := c.UpdatedAt.Format(time.UnixDate)

		if timeNow != createdAt {
			t.Errorf("Car created_at not have correct DateTime %q != %q", createdAt, timeNow)
		}

		if timeNow != updatedAt {
			t.Errorf("Car updated_at not have correct DateTime %q != %q", createdAt, timeNow)
		}
	}

	rows, _ := config.Db().Query("SELECT * FROM cars")

	var rowsCount int

	for rows.Next() {
		rowsCount += 1
	}

	if rowsCount != 2 {
		t.Errorf("Database does not have 2 records, it has %v records", rowsCount)
	}
}
Ejemplo n.º 2
0
func AllCars() *Cars {
	var cars Cars

	rows, err := config.Db().Query("SELECT * FROM cars")

	if err != nil {
		log.Fatal(err)
	}

	// Close rows after all readed
	defer rows.Close()

	for rows.Next() {
		var c Car

		err := rows.Scan(&c.Id, &c.Manufacturer, &c.Design, &c.Style, &c.Doors, &c.CreatedAt, &c.UpdatedAt)

		if err != nil {
			log.Fatal(err)
		}

		cars = append(cars, c)
	}

	return &cars
}
Ejemplo n.º 3
0
func DeleteCarById(id int) error {
	stmt, err := config.Db().Prepare("DELETE FROM cars WHERE id=$1;")

	if err != nil {
		log.Fatal(err)
	}

	_, err = stmt.Exec(id)

	return err
}
Ejemplo n.º 4
0
func FindCarById(id int) *Car {
	var car Car

	row := config.Db().QueryRow("SELECT * FROM cars WHERE id = $1;", id)
	err := row.Scan(&car.Id, &car.Manufacturer, &car.Design, &car.Style, &car.Doors, &car.CreatedAt, &car.UpdatedAt)

	if err != nil {
		log.Fatal(err)
	}

	return &car
}
Ejemplo n.º 5
0
func NewCar(c *Car) {
	if c == nil {
		log.Fatal(c)
	}
	c.CreatedAt = time.Now()
	c.UpdatedAt = time.Now()

	err := config.Db().QueryRow("INSERT INTO cars (manufacturer, design, style, doors, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6) RETURNING id;", c.Manufacturer, c.Design, c.Style, c.Doors, c.CreatedAt, c.UpdatedAt).Scan(&c.Id)

	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 6
0
func UpdateCar(car *Car) {
	car.UpdatedAt = time.Now()

	stmt, err := config.Db().Prepare("UPDATE cars SET manufacturer=$1, design=$2, style=$3, doors=$4, updated_at=$5 WHERE id=$6;")

	if err != nil {
		log.Fatal(err)
	}

	_, err = stmt.Exec(car.Manufacturer, car.Design, car.Style, car.Doors, car.UpdatedAt, car.Id)

	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 7
0
func ResetTableCars() {
	config.Db().Exec("DROP TABLE cars; CREATE TABLE IF NOT EXISTS cars(id serial,manufacturer varchar(20), design varchar(20), style varchar(20), doors int, created_at timestamp default NULL, updated_at timestamp default NULL, constraint pk primary key(id))")
}