Add sqlite database

This commit is contained in:
mikgor 2018-10-28 11:33:41 +01:00
parent 4264ff0bf6
commit 934983574e
6 changed files with 105 additions and 44 deletions

1
.gitignore vendored
View File

@ -12,3 +12,4 @@
*.out *.out
static/icons/* static/icons/*
*.db

33
db/db.go Normal file
View File

@ -0,0 +1,33 @@
package db
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
var Database *sql.DB
func DbConnect() {
Database, _ = sql.Open("sqlite3", "db.db")
}
func DbBuild() {
statement, _ := Database.Prepare("CREATE TABLE IF NOT EXISTS Category (id INTEGER PRIMARY KEY, name TEXT)")
statement.Exec()
statement, _ = Database.Prepare("CREATE TABLE IF NOT EXISTS Product (id INTEGER PRIMARY KEY, categoryId INTEGER, name TEXT, description TEXT, imgUrl TEXT, quantity INTEGER, price INTEGER)")
statement.Exec()
statement, _ = Database.Prepare("CREATE TABLE IF NOT EXISTS PurchasementProduct (id INTEGER PRIMARY KEY, purchasementId INTEGER, productId INTEGER, quantity INTEGER, priceTotal INTEGER)")
statement.Exec()
statement, _ = Database.Prepare("CREATE TABLE IF NOT EXISTS Purchasement (id INTEGER PRIMARY KEY, priceTotal TEXT, firstName TEXT, lastName TEXT, paymentMethod INTEGER, deliveryDate TEXT)")
statement.Exec()
}
func DbInsert(table, columns, values string) {
statement, _ := Database.Prepare("INSERT INTO "+ table +" ("+ columns +") VALUES ("+ values +")")
statement.Exec()
}
func DbSelect(table, columns string) *sql.Rows {
rows, _ := Database.Query("SELECT "+ columns +" FROM "+ table)
return rows
}

View File

@ -2,8 +2,11 @@ package initializers
import ( import (
"net/http" "net/http"
"database/sql"
"strconv"
. "Elektromarket/views" . "Elektromarket/views"
. "Elektromarket/models" . "Elektromarket/models"
. "Elektromarket/db"
) )
func initializePages() { func initializePages() {
@ -19,52 +22,68 @@ func initializePages() {
Pages["paymentDone"] = Page{"/paymentDone", "templates/paymentDone.html", map[string]interface{}{}, PaymentDoneView} Pages["paymentDone"] = Page{"/paymentDone", "templates/paymentDone.html", map[string]interface{}{}, PaymentDoneView}
} }
func initializeData() { func insertCategories() {
Categories = []Category { for i := range Categories {
{1, "Laptopy"}, DbInsert("Category", "name", "'"+Categories[i].Name+"'")
{2, "Komputery"},
{3, "Smartfony"},
{4, "Smartwatche"},
{5, "Monitory"},
{6, "Drukarki"},
{7, "Myszki"},
{8, "Klawiatury"},
{9, "Akcesoria"},
}
Products = []Product {
{
1,
GetCategoryByName("Laptopy"),
"Apple MacBook Air 128 GB",
"Procesor Intel Core i5 | Pamięć 8 GB | Dysk SSD M.2 PCIe 128 GB | Grafika Intel HD Graphics 6000 | Typ ekranu Błyszczący, LED | System macOS Sierra",
"https://cdn.x-kom.pl/i/setup/images/prod/big/product-big,apple-macbook-air-i58gb128gbhd-6000mac-os-368639,pr_2016_4_28_12_39_54_140.jpg",
11,
3999,
},
{
2,
GetCategoryByName("Laptopy"),
"Dell Inspiron 5370",
"Procesor Intel Core i5-8250U | Pamięć 8 GB | Dysk SSD M.2 256 GB | Grafika AMD Radeon 530, + Intel UHD Graphics 620 | Typ ekranu Matowy, LED | System Microsoft Windows 10 Home PL",
"https://cdn.x-kom.pl/i/setup/images/prod/big/product-big,dell-inspiron-5370-i5-8250u8gb256win10-r530-fhd-393456,2017/12/pr_2017_12_14_9_40_43_405_10.jpg",
5,
3249,
},
{
3,
GetCategoryByName("Komputery"),
"Dell Inspiron 3670",
"System Microsoft Windows 10 Home PL | Procesor Intel Core i7-8700 | Grafika NVIDIA GeForce GTX 1050Ti, + Intel UHD Graphics 630 | Pamięć RAM 8 GB | Dysk SSD PCIe 128 GB | Dysk HDD SATA 7200 obr. 1000 GB | Miejsce na dodatkowy wewnętrzny dysk SATA Możliwość montażu dwóch dysków SATA",
"https://cdn.x-kom.pl/i/setup/images/prod/big/product-big,dell-inspiron-3670-i7-87008gb1281000win10-gtx1050ti-447395,2018/9/pr_2018_9_20_15_45_5_770_00.jpg",
123,
4299,
},
} }
} }
func insertProducts() {
for i := range Products {
DbInsert("Product", "categoryId, name, description, imgUrl, quantity, price","'"+strconv.Itoa(Products[i].Category.Id)+"','"+Products[i].Name+"','"+Products[i].Description+"','"+Products[i].ImgUrl+"','"+strconv.Itoa(Products[i].Quantity)+"','"+strconv.Itoa(Products[i].Price)+"'")
}
}
func initializeCategories() {
var rows *sql.Rows = DbSelect("Category", "id, name")
var id int
var name string
for rows.Next() {
rows.Scan(&id, &name)
Categories = append(Categories, Category{id, name})
}
}
func initializeProducts() {
var rows *sql.Rows = DbSelect("Product", "id, categoryId, name, description, imgUrl, quantity, price")
var id, categoryId, quantity, price int
var name, description, imgUrl string
for rows.Next() {
rows.Scan(&id, &categoryId, &name, &description, &imgUrl, &quantity, &price)
Products = append(Products, Product{id, GetCategoryById(categoryId), name, description, imgUrl, quantity, price})
}
}
func initializePurchasements() {
var rows *sql.Rows = DbSelect("Purchasement", "id, priceTotal, firstName, lastName, paymentMethod, deliveryDate")
var rowsProducts *sql.Rows = DbSelect("PurchasementProduct", "id, purchasementId, productId, quantity, priceTotal")
var products map[int][]CartProduct
for rowsProducts.Next() {
var Pid, PpurchasementId, PproductId, Pquantity, PpriceTotal int
rows.Scan(&Pid, &PpurchasementId, &PproductId, &Pquantity, &PpriceTotal)
products[PpurchasementId] = append(products[PpurchasementId], CartProduct{GetProductById(PproductId), Pquantity, PpriceTotal})
}
for rows.Next() {
var purchasementproducts []CartProduct
var id, priceTotal, paymentMethod int
var firstName, lastName, deliveryDate string
rows.Scan(&id, &priceTotal, &firstName, &lastName, &paymentMethod, &deliveryDate)
for i := range products[id]{
purchasementproducts = append(purchasementproducts, products[id][i])
}
Purchasements = append(Purchasements, Purchasement{id, purchasementproducts, priceTotal, firstName, lastName, paymentMethod, deliveryDate})
if id > LastPurchasementId {
LastPurchasementId = id
}
}
}
func Initialize() { func Initialize() {
initializeData() DbConnect()
DbBuild()
initializeCategories()
initializeProducts()
initializePurchasements()
initializePages() initializePages()
for k := range Pages { for k := range Pages {
http.HandleFunc(Pages[k].Path, Pages[k].HandlePage) http.HandleFunc(Pages[k].Path, Pages[k].HandlePage)

View File

@ -43,6 +43,7 @@ type Cart struct {
} }
type Purchasement struct { type Purchasement struct {
Id int
Products []CartProduct Products []CartProduct
PriceTotal int PriceTotal int
FirstName string FirstName string
@ -66,6 +67,7 @@ var Categories []Category
var Products []Product var Products []Product
var ShoppingCart Cart var ShoppingCart Cart
var Purchasements []Purchasement var Purchasements []Purchasement
var LastPurchasementId int
func (p Product) Save() { func (p Product) Save() {
for i:= range Products { for i:= range Products {

View File

@ -9,7 +9,7 @@
</div> </div>
{{range $.purchasements}} {{range $.purchasements}}
<div class="cartItem"> <div class="cartItem">
<div class="cartItemColumn">1</div> <div class="cartItemColumn">{{.Id}}</div>
<div class="cartItemColumn">{{.FirstName}} {{.LastName}}</div> <div class="cartItemColumn">{{.FirstName}} {{.LastName}}</div>
<div class="cartItemColumn">{{.PriceTotal}} zł</div> <div class="cartItemColumn">{{.PriceTotal}} zł</div>
<div class="cartItemColumn">{{if eq .PaymentMethod 1}}Gotówka/ karta{{end}}{{if eq .PaymentMethod 2}}Raty 0% na 24 mies.{{end}}</div> <div class="cartItemColumn">{{if eq .PaymentMethod 1}}Gotówka/ karta{{end}}{{if eq .PaymentMethod 2}}Raty 0% na 24 mies.{{end}}</div>

View File

@ -5,6 +5,7 @@ import (
"strconv" "strconv"
"html/template" "html/template"
. "Elektromarket/models" . "Elektromarket/models"
. "Elektromarket/db"
) )
func ExecuteView(w http.ResponseWriter, r *http.Request, templateName string, data map[string]interface{}) { func ExecuteView(w http.ResponseWriter, r *http.Request, templateName string, data map[string]interface{}) {
@ -94,8 +95,13 @@ func PaymentDoneView(p Page, w http.ResponseWriter, r *http.Request) {
pm, err := strconv.Atoi(r.URL.Query()["pm"][0]) pm, err := strconv.Atoi(r.URL.Query()["pm"][0])
dd := r.URL.Query()["dd"][0] dd := r.URL.Query()["dd"][0]
if fn != "" && ln != "" && dd != "" && err == nil { if fn != "" && ln != "" && dd != "" && err == nil {
purchasement := Purchasement{ShoppingCart.Products, ShoppingCart.PriceTotal, fn, ln, pm, dd} LastPurchasementId+=1
purchasement := Purchasement{LastPurchasementId, ShoppingCart.Products, ShoppingCart.PriceTotal, fn, ln, pm, dd}
Purchasements = append(Purchasements, purchasement) Purchasements = append(Purchasements, purchasement)
DbInsert("Purchasement", "priceTotal, firstName, lastName, paymentMethod, deliveryDate", "'" +strconv.Itoa(purchasement.PriceTotal) +"','"+ purchasement.FirstName + "','" + purchasement.LastName + "','" + strconv.Itoa(purchasement.PaymentMethod) + "','" + purchasement.DeliveryDate +"'")
for i:= range purchasement.Products {
DbInsert("PurchasementProduct", "purchasementId, productId, quantity, priceTotal", "'" +strconv.Itoa(LastPurchasementId) + "','" + strconv.Itoa(purchasement.Products[i].Product.Id) + "','" + strconv.Itoa(purchasement.Products[i].Quantity) + "','" + strconv.Itoa(purchasement.Products[i].PriceTotal) + "'")
}
ShoppingCart.Products = nil ShoppingCart.Products = nil
ShoppingCart.Calculate() ShoppingCart.Calculate()
} }