Ostatnie, drobne zmiany. Serwer działa jak powinien.

This commit is contained in:
Marcel Grześ 2019-01-11 22:49:42 +01:00
parent 4e842c5406
commit 647211f92f
8 changed files with 207 additions and 105 deletions

View File

@ -10,7 +10,7 @@ type patient struct {
Name string Name string
Surname string Surname string
BirthDate time.Time BirthDate time.Time
PatientState sql.NullString PatientState nullString
PatientSex sex PatientSex sex
PatientEmail string PatientEmail string
} }
@ -35,24 +35,24 @@ type doctor struct {
type operation struct { type operation struct {
OperationID int64 OperationID int64
Name string Name string
averageTime NullTime AverageTime string
operationType operationTypes OperationType operationTypes
cost uint8 Cost float32
refoundation int64 Refoundation int64
} }
type room struct { type room struct {
RoomNumber int RoomNumber int
NumberOfBeds int NumberOfBeds int
IncrasedCare bool IncreasedCare bool
} }
type admission struct { type admission struct {
AdmissionID string AdmissionID int64
AdmissionDate time.Time AdmissionDate time.Time
EndDate NullTime EndDate NullTime
PatientPesel sql.NullString PatientPesel nullString
DiagnosisSymbol sql.NullString DiagnosisSymbol nullString
MainDoctor int64 MainDoctor int64
PlanedOperation int64 PlanedOperation int64
RoomNumber int64 RoomNumber int64

View File

@ -10,7 +10,7 @@ import (
_ "github.com/denisenkom/go-mssqldb" _ "github.com/denisenkom/go-mssqldb"
) )
var connectionString = "server=192.168.1.3;Port=1433;database=DB_s439397;trusted_connection=yes;encrypt=disable" var connectionString = "server=192.168.1.2;Port=1433;database=DB_s439397;trusted_connection=yes;encrypt=disable"
var db *sql.DB var db *sql.DB
var err error var err error
@ -32,11 +32,11 @@ func testConnection() {
type iHasValue interface{} type iHasValue interface{}
type values []iHasValue type values []iHasValue
func readDatabase(tableName string) (iDatabaseModels, error) { // ODCZYT Z BAZY DANYCH BEZ SORTOWANIA
func readDatabase(command string, tableName string) (iDatabaseModels, error) {
ctx := context.Background() ctx := context.Background()
checkIsDatabaseAlive() checkIsDatabaseAlive()
tsql := "SELECT * FROM " + tableName rows, _ := db.QueryContext(ctx, command)
rows, _ := db.QueryContext(ctx, tsql)
defer rows.Close() defer rows.Close()
var models iDatabaseModels var models iDatabaseModels
models = nil models = nil
@ -66,20 +66,35 @@ func updateRecord(tableName string, primaryKey string,
primaryKeyName string, fieldToUpdate string, valueToInsert string) string { primaryKeyName string, fieldToUpdate string, valueToInsert string) string {
ctx := context.Background() ctx := context.Background()
checkIsDatabaseAlive() checkIsDatabaseAlive()
tsql := "UPDATE " + tableName + " SET " + fieldToUpdate + " = '" + valueToInsert + if valueToInsert == "null" {
"' WHERE " + primaryKeyName + " = '" + primaryKey + "'" valueToInsert = "NULL"
result, _ := db.ExecContext(ctx, tsql) } else {
valueToInsert = "'" + valueToInsert + "'"
}
tsql := "UPDATE " + tableName + " SET " + fieldToUpdate + " = " + valueToInsert +
" WHERE " + primaryKeyName + " = '" + primaryKey + "'"
result, er := db.ExecContext(ctx, tsql)
if er == nil {
toReturn, _ := result.RowsAffected() toReturn, _ := result.RowsAffected()
return (strconv.FormatInt(toReturn, 10)) return (strconv.FormatInt(toReturn, 10))
} }
return "ERROR"
}
func insertRecord(command string) string { func insertRecord(command string) string {
ctx := context.Background() ctx := context.Background()
checkIsDatabaseAlive() checkIsDatabaseAlive()
/*tsql := "INSERT " + tableName + " VALUES '" + primaryKey + "'" result, er := db.ExecContext(ctx, command)
for i := 0; i<numberOfValues; i++ { if er == nil {
tsql = tsql + ", '" + valuesList[i] + "'" toReturn, _ := result.RowsAffected()
}*/ return (strconv.FormatInt(toReturn, 10))
}
return "ERROR"
}
func deleteRecord(command string) string {
ctx := context.Background()
checkIsDatabaseAlive()
result, _ := db.ExecContext(ctx, command) result, _ := db.ExecContext(ctx, command)
toReturn, _ := result.RowsAffected() toReturn, _ := result.RowsAffected()
return (strconv.FormatInt(toReturn, 10)) return (strconv.FormatInt(toReturn, 10))

View File

@ -18,3 +18,15 @@ func getColumnNames(tableName string) (string, error) {
} }
return toReturn, nil return toReturn, nil
} }
func getColumnTypes(tableName string) (string, error) {
ctx := context.Background()
checkIsDatabaseAlive()
tsql := "SELECT * FROM " + tableName
rows, _ := db.QueryContext(ctx, tsql)
collection, _ := rows.ColumnTypes()
var toReturn string
for _, element := range collection {
toReturn += element.DatabaseTypeName() + "."
}
return toReturn, nil
}

View File

@ -2,11 +2,9 @@ package main
import ( import (
"database/sql" "database/sql"
"database/sql/driver"
"time" "time"
) )
// DOCTOR:
func (doc doctors) readModels(rows *sql.Rows) iDatabaseModels { func (doc doctors) readModels(rows *sql.Rows) iDatabaseModels {
var models iDatabaseModels var models iDatabaseModels
for rows.Next() { for rows.Next() {
@ -21,33 +19,14 @@ func (doc doctors) readModels(rows *sql.Rows) iDatabaseModels {
return models return models
} }
//DO POPRAWY:
func (pat patients) readModels(rows *sql.Rows) iDatabaseModels { func (pat patients) readModels(rows *sql.Rows) iDatabaseModels {
var models iDatabaseModels var models iDatabaseModels
var pati patient var pati patient
for rows.Next() { for rows.Next() {
//var valueList [7]iHasValue
pati = patient{} pati = patient{}
rows.Scan(&pati.Pesel, &pati.Name, &pati.Surname, &pati.BirthDate, &pati.PatientState, rows.Scan(&pati.Pesel, &pati.Name, &pati.Surname, &pati.BirthDate, &pati.PatientState,
&pati.PatientSex) &pati.PatientSex)
/*rows.Scan(&valueList[0], &valueList[1], &valueList[2], &valueList[3], &valueList[4],
&valueList[5])*/
//var patientSta patientStates
models = append(models, pati) models = append(models, pati)
/*if valueList[4] == nil {
patientSta = patientStates("NULL")
} else {
patientSta = patientStates(valueList[4].(string))
}
var se sex
if valueList[5] == nil {
se = sex("M")
} else {
se = sex(valueList[5].(string))
}
models = append(models, patient{
valueList[0].(string), valueList[1].(string), valueList[2].(string), valueList[3].(time.Time),
patientSta, se, ""})*/
} }
return models return models
} }
@ -66,8 +45,8 @@ func (ope operations) readModels(rows *sql.Rows) iDatabaseModels {
var oper operation var oper operation
for rows.Next() { for rows.Next() {
oper = operation{} oper = operation{}
rows.Scan(&oper.OperationID, &oper.Name, &oper.averageTime, &oper.operationType, rows.Scan(&oper.OperationID, &oper.Name, &oper.AverageTime, &oper.OperationType,
&oper.cost, &oper.refoundation) &oper.Cost, &oper.Refoundation)
models = append(models, oper) models = append(models, oper)
} }
return models return models
@ -78,66 +57,20 @@ func (doc admissions) readModels(rows *sql.Rows) iDatabaseModels {
var admiss admission var admiss admission
for rows.Next() { for rows.Next() {
admiss = admission{} admiss = admission{}
//var dummy interface{}
/*var valueList [9]iHasValue
rows.Scan(&valueList[0], &valueList[1], &valueList[2], &valueList[3], &valueList[4],
&valueList[5], &valueList[6], &valueList[7], &valueList[8])
timex := NullTime{}
stri, strix := sql.NullString{}, sql.NullString{}
if valueList[2] == nil {
timex.Valid = false
} else {
timex.Time = valueList[2].(time.Time)
timex.Valid = true
}
if valueList[3] == nil {
strix.Valid = false
} else {
strix.String = valueList[4].(string)
strix.Valid = true
}
if valueList[4] == nil {
stri.Valid = false
} else {
stri.String = valueList[4].(string)
stri.Valid = true
}
models = append(models, admission{
valueList[0].(int64), valueList[1].(time.Time), timex, strix,
stri, valueList[5].(int64), valueList[6].(int64), valueList[7].(int64),
valueList[8].(bool)})*/
rows.Scan(&admiss.AdmissionID, &admiss.AdmissionDate, &admiss.EndDate, rows.Scan(&admiss.AdmissionID, &admiss.AdmissionDate, &admiss.EndDate,
&admiss.PatientPesel, &admiss.MainDoctor, &admiss.PlanedOperation, &admiss.PatientPesel, &admiss.DiagnosisSymbol, &admiss.MainDoctor, &admiss.PlanedOperation,
&admiss.RoomNumber, &admiss.IsPlanned) &admiss.RoomNumber, &admiss.IsPlanned)
models = append(models, admiss) models = append(models, admiss)
} }
return models return models
} }
type NullTime struct {
Time time.Time
Valid bool // Valid is true if Time is not NULL
}
// Scan implements the Scanner interface.
func (nt *NullTime) Scan(value interface{}) error {
nt.Time, nt.Valid = value.(time.Time)
return nil
}
// Value implements the driver Valuer interface.
func (nt NullTime) Value() (driver.Value, error) {
if !nt.Valid {
return nil, nil
}
return nt.Time, nil
}
func (ro rooms) readModels(rows *sql.Rows) iDatabaseModels { func (ro rooms) readModels(rows *sql.Rows) iDatabaseModels {
var models iDatabaseModels var models iDatabaseModels
var rom room var rom room
for rows.Next() { for rows.Next() {
rom = room{} rom = room{}
rows.Scan(&rom.RoomNumber, &rom.NumberOfBeds, &rom.IncrasedCare) rows.Scan(&rom.RoomNumber, &rom.NumberOfBeds, &rom.IncreasedCare)
models = append(models, rom) models = append(models, rom)
} }
return models return models

View File

@ -16,8 +16,38 @@ func index(w http.ResponseWriter, r *http.Request) {
func getAll(w http.ResponseWriter, r *http.Request) { func getAll(w http.ResponseWriter, r *http.Request) {
args := mux.Vars(r) args := mux.Vars(r)
table := args["tableName"] table := args["tableName"]
patientsList, _ := readDatabase(table) tsql := "SELECT * FROM " + table
patientsList, _ := readDatabase(tsql, table)
x, _ := json.Marshal(patientsList)
fmt.Fprintf(w, string(x), html.EscapeString(r.URL.Path))
//json.NewEncoder(w).Encode(x)
fmt.Println("POBRANO DANE" + table)
}
func sort(w http.ResponseWriter, r *http.Request) {
args := mux.Vars(r)
table := args["tableName"]
sortby := args["sortBy"]
sortType := args["type"]
tsql := "SELECT * FROM " + table
tsql += " ORDER BY " + sortby + " " + sortType
patientsList, _ := readDatabase(tsql, table)
json.NewEncoder(w).Encode(patientsList) json.NewEncoder(w).Encode(patientsList)
fmt.Println("POBRANO DANE" + table + " orderby " + sortby)
}
func search(w http.ResponseWriter, r *http.Request) {
args := mux.Vars(r)
table := args["tableName"]
sortby := args["sortBy"]
sortType := args["type"]
searchIn := args["columnName"]
searchVal := args["searchedValue"]
tsql := "SELECT * FROM " + table
tsql += " WHERE " + searchIn + " = '" + searchVal + "'"
tsql += " ORDER BY " + sortby + " " + sortType
patientsList, _ := readDatabase(tsql, table)
json.NewEncoder(w).Encode(patientsList)
fmt.Println("POBRANO DANE" + table + " orderby " + sortby)
} }
func update(w http.ResponseWriter, r *http.Request) { func update(w http.ResponseWriter, r *http.Request) {
args := mux.Vars(r) args := mux.Vars(r)
@ -26,30 +56,57 @@ func update(w http.ResponseWriter, r *http.Request) {
primaryKeyName := args["primaryKeyName"] primaryKeyName := args["primaryKeyName"]
fieldToUpdate := args["fieldToUpdate"] fieldToUpdate := args["fieldToUpdate"]
valueToInsert := args["valueToInsert"] valueToInsert := args["valueToInsert"]
rowsAffected := rowsAffected :=
updateRecord(tableName, primaryKey, primaryKeyName, fieldToUpdate, valueToInsert) updateRecord(tableName, primaryKey, primaryKeyName, fieldToUpdate, valueToInsert)
fmt.Fprint(w, rowsAffected) fmt.Fprint(w, rowsAffected)
fmt.Println("Zaktualizowano " + rowsAffected + " z " + tableName)
} }
func insert(w http.ResponseWriter, r *http.Request) { func insert(w http.ResponseWriter, r *http.Request) {
args := mux.Vars(r) args := mux.Vars(r)
// TODO: Dodac walidacje primary key // TODO: Dodac walidacje primary key
tsqlCommand := "INSERT INTO " + args["tableName"] + " VALUES ('" + args["primaryKey"] tsqlCommand := "INSERT INTO " + args["tableName"] + " VALUES ('" + args["primaryKey"] + "'"
max, _ := strconv.Atoi(args["count"]) max, _ := strconv.Atoi(args["count"])
for i := 1; i < max; i++ { for i := 1; i < max; i++ {
key := "val" + strconv.Itoa(i) key := "val" + strconv.Itoa(i)
tsqlCommand += "', '" + args[key] valueToInsert := args[key]
if valueToInsert == "null" {
valueToInsert = "NULL"
} else {
valueToInsert = "'" + valueToInsert + "'"
} }
tsqlCommand += "')" tsqlCommand += ", " + valueToInsert
}
tsqlCommand += ")"
rowsAffected := insertRecord(tsqlCommand) rowsAffected := insertRecord(tsqlCommand)
fmt.Fprint(w, rowsAffected) fmt.Fprint(w, rowsAffected)
fmt.Println("Dodano " + rowsAffected + " " + tsqlCommand)
}
func delete(w http.ResponseWriter, r *http.Request) {
args := mux.Vars(r)
tableName := args["tableName"]
primaryKey := args["primaryKey"]
primaryKeyName := args["primaryKeyName"]
tsqlCommand := "DELETE " + tableName + " WHERE " + primaryKeyName + " = '" + primaryKey + "'"
rowsAffected := deleteRecord(tsqlCommand)
fmt.Fprint(w, rowsAffected)
fmt.Println("Usunięto " + rowsAffected + " " + tsqlCommand)
} }
func columnNames(w http.ResponseWriter, r *http.Request) { func columnNames(w http.ResponseWriter, r *http.Request) {
args := mux.Vars(r) args := mux.Vars(r)
table := args["tableName"] table := args["tableName"]
colNames, _ := getColumnNames(table) colNames, _ := getColumnNames(table)
fmt.Fprint(w, colNames) //fmt.Fprint(w, colNames)
json.NewEncoder(w).Encode(colNames)
fmt.Println("POBRANO COLUMN NAMES " + table)
}
func columnTypes(w http.ResponseWriter, r *http.Request) {
args := mux.Vars(r)
table := args["tableName"]
colNames, _ := getColumnTypes(table)
//fmt.Fprint(w, colNames)
json.NewEncoder(w).Encode(colNames)
fmt.Println("POBRANO COLUMN TYPES " + table)
} }
func getIndex(w http.ResponseWriter, r *http.Request) { func getIndex(w http.ResponseWriter, r *http.Request) {
args := mux.Vars(r) args := mux.Vars(r)

View File

@ -10,10 +10,6 @@ import (
// Zrobione: // Zrobione:
// Podstawowy serwer; Podstawowe struktury modeli; niezbędne enumy; prosta refraktoryzacja; // Podstawowy serwer; Podstawowe struktury modeli; niezbędne enumy; prosta refraktoryzacja;
// Utworzenie połączenia z bazą danych; Funkcje modeli; łączenie z bazą danych; // Utworzenie połączenia z bazą danych; Funkcje modeli; łączenie z bazą danych;
// Do zrobienia:
// Rozne metody do tworzenia komend sql;
// Komunikacja z aplikacja desktopowa; Walidacja danych!! ;
func main() { func main() {
router := newRouter() router := newRouter()
testConnection() testConnection()

85
jsonNullValues.go Normal file
View File

@ -0,0 +1,85 @@
package main
import (
"database/sql"
"database/sql/driver"
"encoding/json"
"time"
)
// Źródło poniższych:
// https://stackoverflow.com/questions/33072172/how-can-i-work-with-sql-null-values-and-json-in-golang-in-a-good-way
type NullTime struct {
Time time.Time
Valid bool // Valid is true if Time is not NULL
}
// Scan implements the Scanner interface.
func (nt *NullTime) Scan(value interface{}) error {
nt.Time, nt.Valid = value.(time.Time)
return nil
}
// Value implements the driver Valuer interface.
func (nt NullTime) Value() (driver.Value, error) {
if !nt.Valid {
return nil, nil
}
return nt.Time, nil
}
func (nt NullTime) MarshalJSON() ([]byte, error) {
if nt.Valid {
return json.Marshal(nt.Time)
}
return json.Marshal(nil)
}
type nullTimeInHours struct {
NullTime
}
// Scan implements the Scanner interface.
func (nt *nullTimeInHours) Scan(value interface{}) error {
nt.Time = value.(time.Time)
return nil
}
// Value implements the driver Valuer interface.
func (nt nullTimeInHours) Value() (driver.Value, error) {
if !nt.Valid {
return nil, nil
}
return nt.Time, nil
}
func (nt nullTimeInHours) MarshalJSON() ([]byte, error) {
if nt.Valid {
t, _ := time.Parse("15:04:05", time.Time.String(nt.Time))
return json.Marshal(t)
}
return json.Marshal(nil)
}
type nullString struct {
sql.NullString
}
// Scan implements the Scanner interface.
func (nt *nullString) Scan(value interface{}) error {
nt.String, nt.Valid = value.(string)
return nil
}
// Value implements the driver Valuer interface.
func (nt nullString) Value() (driver.Value, error) {
if !nt.Valid {
return nil, nil
}
return nt.String, nil
}
func (nt nullString) MarshalJSON() ([]byte, error) {
if nt.Valid {
return json.Marshal(nt.String)
}
return json.Marshal("null")
}

View File

@ -23,7 +23,11 @@ var registredRoutes = routes{
update}, update},
route{"InsertRecord", "/insertrec/{tableName}/nr/{count}/pk/{primaryKey}/{val1}/{val2}/{val3}/{val4}/{val5}/{val6}/{val7}", route{"InsertRecord", "/insertrec/{tableName}/nr/{count}/pk/{primaryKey}/{val1}/{val2}/{val3}/{val4}/{val5}/{val6}/{val7}",
insert}, insert},
route{"DeleteRecord", "/deleterec/{tableName}/pk/{primaryKey}/pkn/{primaryKeyName}", delete},
route{"GetColumnNames", "/getcolumnnames/{tableName}", columnNames}, route{"GetColumnNames", "/getcolumnnames/{tableName}", columnNames},
route{"GetColumnTypes", "/getcolumntypes/{tableName}", columnTypes},
route{"Sort", "/sort/{tableName}/sortby/{sortBy}/sorttype/{type}", sort},
route{"Search", "/search/{tableName}/where/{columnName}/is/{searchedValue}/sortby/{sortBy}/sorttype/{type}", search},
} }
func newRouter() *mux.Router { func newRouter() *mux.Router {