Repository: globocom/huskyCI
Pull request #422 (2019-11-04 15:49:09)

Implementation of functions for data inserts and retrieves in PostgreSQL DB
This P.R. assigns issue #392 .

This will allow that all functions related with data manipulation can interact with as Postgres DB.

 `GetMetricByType` is not supported yet. So it will not be able to use Postgres with dashboard.

The next steps are:
 - Generate a Postgres docker image with the required configurations;
 - Launch local environment with Postgres for tests;

carlosljr: Hi @rafaveira3!

Thanks for all the comments and the review!

I've done all the requested changes!

Please let me know if everything is ok now :)

Patch:
diff --git a/Makefile b/Makefile
index f126369..f190216 100644
--- a/Makefile
+++ b/Makefile
@@ -5,7 +5,7 @@ GO ?= go
 GOROOT ?= $(shell $(GO) env GOROOT)
 GOPATH ?= $(shell $(GO) env GOPATH)
 GOBIN ?= $(GOPATH)/bin
-GOCILINT ?= $(GOBIN)/golangci-lint
+GOCILINT ?= ./bin/golangci-lint
 GOLINT ?= $(GOBIN)/golint
 GOSEC ?= $(GOBIN)/gosec
 GINKGO ?= $(GOBIN)/ginkgo
@@ -99,7 +99,7 @@ get-gosec-deps:
 
 ## Gets all link dependencies
 get-lint-deps:
-	$(GO) get -u github.com/golangci/golangci-lint/cmd/golangci-lint
+	curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v1.21.0
 	$(GO) get -u golang.org/x/lint/golint
 
 ## Gets all go test dependencies
diff --git a/api/analysis/analysis.go b/api/analysis/analysis.go
index b3ebaf3..ec084df 100644
--- a/api/analysis/analysis.go
+++ b/api/analysis/analysis.go
@@ -95,6 +95,7 @@ func registerFinishedAnalysis(RID string, allScanResults *securitytest.RunAllInf
 			"finishedAt":     time.Now(),
 		},
 	}
+
 	if err := apiContext.APIConfiguration.DBInstance.UpdateOneDBAnalysisContainer(analysisQuery, updateAnalysisQuery); err != nil {
 		log.Error("registerFinishedAnalysis", logInfoAnalysis, 2011, err)
 		return err
diff --git a/api/context/context.go b/api/context/context.go
index 51831a8..3271276 100644
--- a/api/context/context.go
+++ b/api/context/context.go
@@ -11,6 +11,7 @@ import (
 	"time"
 
 	"github.com/globocom/huskyCI/api/db"
+	postgres "github.com/globocom/huskyCI/api/db/postgres"
 	"github.com/globocom/huskyCI/api/types"
 )
 
@@ -357,7 +358,19 @@ func (dF DefaultConfig) GetMaxContainersAllowed() int {
 func (dF DefaultConfig) GetDB() db.Requests {
 	dB := dF.Caller.GetEnvironmentVariable("HUSKYCI_DATABASE_TYPE")
 	if strings.EqualFold(dB, "postgres") {
-		return nil
+		postgresOperations := postgres.PostgresHandler{}
+		sqlConfig := postgres.SQLConfig{
+			Postgres: &postgresOperations,
+		}
+		jsonHandler := db.JSONCaller{}
+		sqlJSONRetriever := db.SQLJSONRetrieve{
+			Psql:        &sqlConfig,
+			JSONHandler: &jsonHandler,
+		}
+		postgres := db.PostgresRequests{
+			DataRetriever: &sqlJSONRetriever,
+		}
+		return &postgres
 	}
 	return &db.MongoRequests{}
 }
diff --git a/api/db/huskydb.go b/api/db/huskydb.go
index 0f4ec9e..e40818f 100644
--- a/api/db/huskydb.go
+++ b/api/db/huskydb.go
@@ -222,7 +222,7 @@ func (mR *MongoRequests) UpsertOneDBSecurityTest(mapParams map[string]interface{
 }
 
 // UpdateOneDBAnalysis checks if a given analysis is present into AnalysisCollection and update it.
-func (mR *MongoRequests) UpdateOneDBAnalysis(mapParams map[string]interface{}, updatedAnalysis types.Analysis) error {
+func (mR *MongoRequests) UpdateOneDBAnalysis(mapParams map[string]interface{}, updatedAnalysis map[string]interface{}) error {
 	analysisQuery := []bson.M{}
 	for k, v := range mapParams {
 		analysisQuery = append(analysisQuery, bson.M{k: v})
diff --git a/api/db/jsoncaller.go b/api/db/jsoncaller.go
new file mode 100644
index 0000000..866087e
--- /dev/null
+++ b/api/db/jsoncaller.go
@@ -0,0 +1,15 @@
+package db
+
+import (
+	"encoding/json"
+)
+
+// Marshal will call Marshal function from json struct.
+func (jCaller *JSONCaller) Marshal(v interface{}) ([]byte, error) {
+	return json.Marshal(v)
+}
+
+// Unmarshal will call Unmarshal function from json struct.
+func (jCaller *JSONCaller) Unmarshal(data []byte, v interface{}) error {
+	return json.Unmarshal(data, v)
+}
diff --git a/api/db/postgres.go b/api/db/postgres.go
new file mode 100644
index 0000000..5107230
--- /dev/null
+++ b/api/db/postgres.go
@@ -0,0 +1,607 @@
+package db
+
+import (
+	"errors"
+	"fmt"
+	"strings"
+	"time"
+
+	"github.com/globocom/huskyCI/api/types"
+)
+
+// ConnectDB will call Connect function
+// and try to establish a connection with
+// Postgres.
+func (pR *PostgresRequests) ConnectDB(
+	address string,
+	dbName string,
+	username string,
+	password string,
+	timeout time.Duration,
+	poolLimit int,
+	port int,
+	maxOpenConns int,
+	maxIdleConns int,
+	connMaxLifetime time.Duration) error {
+	return pR.DataRetriever.Connect(
+		address,
+		username,
+		password,
+		dbName,
+		maxOpenConns,
+		maxIdleConns,
+		connMaxLifetime)
+}
+
+// FindOneDBRepository checks if a given repository is present into repository table.
+func (pR *PostgresRequests) FindOneDBRepository(
+	mapParams map[string]interface{}) (types.Repository, error) {
+	repositoryResponse := []types.Repository{}
+	repository, ok := mapParams["repositoryURL"]
+	if !ok {
+		return types.Repository{}, errors.New("Could not find repository URL")
+	}
+	repositoryQuery := `SELECT 
+					repositoryURL,
+					createdAt
+				FROM
+					repository
+				WHERE
+					repositoryURL = $1`
+
+	if err := pR.DataRetriever.RetrieveFromDB(
+		repositoryQuery, &repositoryResponse, repository); err != nil {
+		return types.Repository{}, err
+	}
+	return repositoryResponse[0], nil
+}
+
+// FindOneDBSecurityTest checks if a given securityTest is present into securityTest table.
+func (pR *PostgresRequests) FindOneDBSecurityTest(
+	mapParams map[string]interface{}) (types.SecurityTest, error) {
+	securityTestResponse := []types.SecurityTest{}
+	securityTest, ok := mapParams["name"]
+	if !ok {
+		return types.SecurityTest{}, errors.New("Could not find securityTest name field")
+	}
+	securityTestQuery := `SELECT
+					name,
+					image,
+					imageTag,
+					cmd,
+					type,
+					language,
+					default,
+					timeOutSeconds
+				FROM
+					securityTest
+				WHERE
+					name = $1`
+	if err := pR.DataRetriever.RetrieveFromDB(
+		securityTestQuery, &securityTestResponse, securityTest); err != nil {
+		return types.SecurityTest{}, err
+	}
+	return securityTestResponse[0], nil
+}
+
+// FindOneDBAnalysis checks if a given analysis is present into analysis table.
+func (pR *PostgresRequests) FindOneDBAnalysis(
+	mapParams map[string]interface{}) (types.Analysis, error) {
+	analysisResponse := []types.Analysis{}
+	analysis, ok := mapParams["RID"]
+	if !ok {
+		return types.Analysis{}, errors.New("Could not find RID field")
+	}
+	analysisQuery := `SELECT
+					RID,
+					repositoryURL,
+					repositoryBranch,
+					commitAuthors,
+					status,
+					result,
+					errorFound,
+					containers,
+					startedAt,
+					finishedAt,
+					codes,
+					huskyciresults
+				FROM
+					analysis
+				WHERE
+					RID = $1`
+
+	if err := pR.DataRetriever.RetrieveFromDB(
+		analysisQuery, &analysisResponse, analysis); err != nil {
+		return types.Analysis{}, err
+	}
+	return analysisResponse[0], nil
+}
+
+// FindOneDBUser checks if a given user is present into user table.
+func (pR *PostgresRequests) FindOneDBUser(
+	mapParams map[string]interface{}) (types.User, error) {
+	userResponse := []types.User{}
+	user, ok := mapParams["username"]
+	if !ok {
+		return types.User{}, errors.New("Could not find user in DB")
+	}
+	userQuery := `SELECT
+					username,
+					password,
+					salt,
+					iterations,
+					keylen,
+					hashfunction
+				FROM
+					user
+				WHERE
+					username = $1`
+
+	if err := pR.DataRetriever.RetrieveFromDB(userQuery, &userResponse, user); err != nil {
+		return types.User{}, err
+	}
+	return userResponse[0], nil
+}
+
+// FindOneDBAccessToken checks if a given accessToken exists in accessToken table.
+func (pR *PostgresRequests) FindOneDBAccessToken(
+	mapParams map[string]interface{}) (types.DBToken, error) {
+	tokenResponse := []types.DBToken{}
+	token, ok := mapParams["uuid"]
+	if !ok {
+		return types.DBToken{}, errors.New("Could not find uuid parameter")
+	}
+	tokenQuery := `SELECT
+					huskytoken,
+					repositoryURL,
+					isValid,
+					createdAt,
+					salt,
+					uuid
+				FROM
+					accessToken
+				WHERE
+					uuid = $1`
+	if err := pR.DataRetriever.RetrieveFromDB(tokenQuery, &tokenResponse, token); err != nil {
+		return types.DBToken{}, err
+	}
+	return tokenResponse[0], nil
+}
+
+// FindAllDBRepository returns all Repository of a given query present into repository table.
+func (pR *PostgresRequests) FindAllDBRepository(
+	mapParams map[string]interface{}) ([]types.Repository, error) {
+	repositoryResponse := []types.Repository{}
+	query, params := ConfigureQuery(`SELECT * FROM repository`, mapParams)
+	if err := pR.DataRetriever.RetrieveFromDB(query, &repositoryResponse, params); err != nil {
+		return repositoryResponse, err
+	}
+	return repositoryResponse, nil
+}
+
+// FindAllDBSecurityTest returns all SecurityTests of a given query present
+// into security Test table.
+func (pR *PostgresRequests) FindAllDBSecurityTest(
+	mapParams map[string]interface{}) ([]types.SecurityTest, error) {
+	securityResponse := []types.SecurityTest{}
+	query, params := ConfigureQuery(`SELECT * FROM securityTest`, mapParams)
+	if err := pR.DataRetriever.RetrieveFromDB(query, &securityResponse, params); err != nil {
+		return securityResponse, err
+	}
+	return securityResponse, nil
+}
+
+// FindAllDBAnalysis returns all Analysis of a given query present into analysis table.
+func (pR *PostgresRequests) FindAllDBAnalysis(
+	mapParams map[string]interface{}) ([]types.Analysis, error) {
+	analysisResponse := []types.Analysis{}
+	query, params := ConfigureQuery(`SELECT * FROM analysis`, mapParams)
+	if err := pR.DataRetriever.RetrieveFromDB(query, &analysisResponse, params); err != nil {
+		return analysisResponse, err
+	}
+	return analysisResponse, nil
+}
+
+// InsertDBRepository inserts a new repository into repository table.
+func (pR *PostgresRequests) InsertDBRepository(repository types.Repository) error {
+	if (types.Repository{}) == repository {
+		return errors.New("Empty repository data")
+	}
+	repositoryMap := map[string]interface{}{
+		"repositoryURL": repository.URL,
+		"createdAt":     repository.CreatedAt,
+	}
+	finalQuery, values := ConfigureInsertQuery(
+		`INSERT into repository`, repositoryMap)
+	rowsAff, err := pR.DataRetriever.WriteInDB(finalQuery, values)
+	if err != nil {
+		return err
+	}
+	if rowsAff == int64(0) {
+		return errors.New("No data was inserted")
+	}
+	return nil
+}
+
+// InsertDBSecurityTest inserts a new securityTest into securityTest table.
+func (pR *PostgresRequests) InsertDBSecurityTest(securityTest types.SecurityTest) error {
+	if (types.SecurityTest{}) == securityTest {
+		return errors.New("Empty SecurityTest data")
+	}
+	securityTestMap := map[string]interface{}{
+		"name":           securityTest.Name,
+		"image":          securityTest.Image,
+		"imageTag":       securityTest.ImageTag,
+		"cmd":            securityTest.Cmd,
+		"language":       securityTest.Language,
+		"type":           securityTest.Type,
+		"default":        securityTest.Default,
+		"timeOutSeconds": securityTest.TimeOutInSeconds,
+	}
+	finalQuery, values := ConfigureInsertQuery(
+		`INSERT into securityTest`, securityTestMap)
+	rowsAff, err := pR.DataRetriever.WriteInDB(finalQuery, values)
+	if err != nil {
+		return err
+	}
+	if rowsAff == int64(0) {
+		return errors.New("No data was inserted")
+	}
+	return nil
+}
+
+// InsertDBAnalysis inserts a new analysis into analysis table.
+func (pR *PostgresRequests) InsertDBAnalysis(analysis types.Analysis) error {
+	if analysis.URL == "" {
+		return errors.New("Empty Analysis data")
+	}
+	analysisMap := map[string]interface{}{
+		"RID":              analysis.RID,
+		"repositoryURL":    analysis.URL,
+		"repositoryBranch": analysis.Branch,
+		"status":           analysis.Status,
+		"result":           analysis.Result,
+		"containers":       analysis.Containers,
+		"startedAt":        analysis.StartedAt,
+	}
+	finalQuery, values := ConfigureInsertQuery(
+		`INSERT into analysis`, analysisMap)
+	rowsAff, err := pR.DataRetriever.WriteInDB(finalQuery, values)
+	if err != nil {
+		return err
+	}
+	if rowsAff == int64(0) {
+		return errors.New("No data was inserted")
+	}
+	return nil
+}
+
+// InsertDBUser inserts a new user into user table.
+func (pR *PostgresRequests) InsertDBUser(user types.User) error {
+	if (types.User{}) == user {
+		return errors.New("Empty User data")
+	}
+	userMap := map[string]interface{}{
+		"username":     user.Username,
+		"password":     user.Password,
+		"salt":         user.Salt,
+		"iterations":   user.Iterations,
+		"keylen":       user.KeyLen,
+		"hashfunction": user.HashFunction,
+	}
+	finalQuery, values := ConfigureInsertQuery(
+		`INSERT into user`, userMap)
+	rowsAff, err := pR.DataRetriever.WriteInDB(finalQuery, values)
+	if err != nil {
+		return err
+	}
+	if rowsAff == int64(0) {
+		return errors.New("No data was inserted")
+	}
+	return nil
+}
+
+// InsertDBAccessToken inserts a new access into accessToken table.
+func (pR *PostgresRequests) InsertDBAccessToken(accessToken types.DBToken) error {
+	if (types.DBToken{}) == accessToken {
+		return errors.New("Empty DBToken data")
+	}
+	accessTokenMap := map[string]interface{}{
+		"huskytoken":    accessToken.HuskyToken,
+		"repositoryURL": accessToken.URL,
+		"isValid":       accessToken.IsValid,
+		"createdAt":     accessToken.CreatedAt,
+		"salt":          accessToken.Salt,
+		"uuid":          accessToken.UUID,
+	}
+	finalQuery, values := ConfigureInsertQuery(
+		`INSERT into accessToken`, accessTokenMap)
+	rowsAff, err := pR.DataRetriever.WriteInDB(finalQuery, values)
+	if err != nil {
+		return err
+	}
+	if rowsAff == int64(0) {
+		return errors.New("No data was inserted")
+	}
+	return nil
+}
+
+// UpdateOneDBRepository checks if a given repository is present into repository table
+// and update it.
+func (pR *PostgresRequests) UpdateOneDBRepository(
+	mapParams, updateQuery map[string]interface{}) error {
+	if len(updateQuery) == 0 {
+		return errors.New("Empty fields to be updated")
+	}
+	if len(mapParams) == 0 {
+		return errors.New("Empty fields to search")
+	}
+	finalQuery, values := ConfigureUpdateQuery(
+		`UPDATE repository`, mapParams, updateQuery)
+	rowsAff, err := pR.DataRetriever.WriteInDB(finalQuery, values)
+	if err != nil {
+		return err
+	}
+	if rowsAff == int64(0) {
+		return errors.New("No data was updated")
+	}
+	return nil
+}
+
+// UpsertOneDBSecurityTest checks if a given securityTest is present into securityTest
+// and update it. If not, it will insert a new entry.
+func (pR *PostgresRequests) UpsertOneDBSecurityTest(
+	mapParams map[string]interface{}, updatedSecurityTest types.SecurityTest) (interface{}, error) {
+	if (types.SecurityTest{}) == updatedSecurityTest {
+		return nil, errors.New("Empty fields to be updated")
+	}
+	if len(mapParams) == 0 {
+		return nil, errors.New("Empty fields to search")
+	}
+	updatedSecurityMap := map[string]interface{}{
+		"name":           updatedSecurityTest.Name,
+		"image":          updatedSecurityTest.Image,
+		"imageTag":       updatedSecurityTest.ImageTag,
+		"cmd":            updatedSecurityTest.Cmd,
+		"type":           updatedSecurityTest.Type,
+		"language":       updatedSecurityTest.Language,
+		"default":        updatedSecurityTest.Default,
+		"timeOutSeconds": updatedSecurityTest.TimeOutInSeconds,
+	}
+	finalQuery, values := ConfigureUpsertQuery(
+		`INSERT into securityTest`, mapParams, updatedSecurityMap)
+	rowsAff, err := pR.DataRetriever.WriteInDB(finalQuery, values)
+	if err != nil {
+		return nil, err
+	}
+	if rowsAff == int64(0) {
+		return nil, errors.New("No data was updated")
+	}
+	return rowsAff, nil
+}
+
+// UpdateOneDBAnalysis checks if a given analysis is present into analysis table and update it.
+func (pR *PostgresRequests) UpdateOneDBAnalysis(
+	mapParams map[string]interface{}, updatedAnalysis map[string]interface{}) error {
+	if len(updatedAnalysis) == 0 {
+		return errors.New("Empty fields to be updated")
+	}
+	if len(mapParams) == 0 {
+		return errors.New("Empty fields to search")
+	}
+	finalQuery, values := ConfigureUpdateQuery(
+		`UPDATE analysis`, mapParams, updatedAnalysis)
+	rowsAff, err := pR.DataRetriever.WriteInDB(finalQuery, values)
+	if err != nil {
+		return err
+	}
+	if rowsAff == int64(0) {
+		return errors.New("No data was updated")
+	}
+	return nil
+}
+
+// UpdateOneDBUser checks if a given user is present into user table and update it.
+func (pR *PostgresRequests) UpdateOneDBUser(
+	mapParams map[string]interface{}, updatedUser types.User) error {
+	if (types.User{}) == updatedUser {
+		return errors.New("Empty fields to be updated")
+	}
+	if len(mapParams) == 0 {
+		return errors.New("Empty fields to search")
+	}
+	updatedUserMap := map[string]interface{}{
+		"username":     updatedUser.Username,
+		"password":     updatedUser.Password,
+		"salt":         updatedUser.Salt,
+		"iterations":   updatedUser.Iterations,
+		"keylen":       updatedUser.KeyLen,
+		"hashfunction": updatedUser.HashFunction,
+	}
+	finalQuery, values := ConfigureUpdateQuery(
+		`UPDATE user`, mapParams, updatedUserMap)
+	rowsAff, err := pR.DataRetriever.WriteInDB(finalQuery, values)
+	if err != nil {
+		return err
+	}
+	if rowsAff == int64(0) {
+		return errors.New("No data was updated")
+	}
+	return nil
+}
+
+// UpdateOneDBAnalysisContainer checks if a given analysis is present into analysis table
+// and update the container associated in it.
+func (pR *PostgresRequests) UpdateOneDBAnalysisContainer(
+	mapParams, updateQuery map[string]interface{}) error {
+	if len(updateQuery) == 0 {
+		return errors.New("Empty fields to be updated")
+	}
+	if len(mapParams) == 0 {
+		return errors.New("Empty fields to search")
+	}
+	finalQuery, values := ConfigureUpdateQuery(
+		`UPDATE analysis`, mapParams, updateQuery)
+	rowsAff, err := pR.DataRetriever.WriteInDB(finalQuery, values)
+	if err != nil {
+		return err
+	}
+	if rowsAff == int64(0) {
+		return errors.New("No data was updated")
+	}
+	return nil
+}
+
+// UpdateOneDBAccessToken checks if a given access token is present into accessToken and update it.
+func (pR *PostgresRequests) UpdateOneDBAccessToken(
+	mapParams map[string]interface{}, updatedAccessToken types.DBToken) error {
+	if (types.DBToken{}) == updatedAccessToken {
+		return errors.New("Empty fields to be updated")
+	}
+	if len(mapParams) == 0 {
+		return errors.New("Empty fields to search")
+	}
+	updatedAccessTokenMap := map[string]interface{}{
+		"huskytoken":    updatedAccessToken.HuskyToken,
+		"repositoryURL": updatedAccessToken.URL,
+		"isValid":       updatedAccessToken.IsValid,
+		"createdAt":     updatedAccessToken.CreatedAt,
+		"salt":          updatedAccessToken.Salt,
+		"uuid":          updatedAccessToken.UUID,
+	}
+	finalQuery, values := ConfigureUpdateQuery(
+		`UPDATE accessToken`, mapParams, updatedAccessTokenMap)
+	rowsAff, err := pR.DataRetriever.WriteInDB(finalQuery, values)
+	if err != nil {
+		return err
+	}
+	if rowsAff == int64(0) {
+		return errors.New("No data was updated")
+	}
+	return nil
+}
+
+// GetMetricByType returns data about the metric received
+func (pR *PostgresRequests) GetMetricByType(
+	metricType string, queryStringParams map[string][]string) (interface{}, error) {
+	return nil, errors.New("Function not supported yet in postgres")
+}
+
+// ConfigureUpdateQuery will receive a partial update query and mount the final query with
+// all data to be set and the search parameters related to the row to be changed.
+func ConfigureUpdateQuery(
+	query string, searchValues, newValues map[string]interface{}) (string, []interface{}) {
+	valuesQuery := ""
+	searchQuery := ""
+	values := make([]interface{}, 0)
+	i := 1
+	for k, v := range searchValues {
+		if !strings.Contains(searchQuery, "WHERE") {
+			searchQuery = `WHERE`
+		}
+		if strings.Contains(searchQuery, "=") {
+			searchQuery = fmt.Sprintf("%s AND", searchQuery)
+		}
+		searchQuery = fmt.Sprintf("%s %s = $%d", searchQuery, k, i)
+		i++
+		values = append(values, v)
+	}
+	for k, v := range newValues {
+		if !strings.Contains(valuesQuery, "SET") {
+			valuesQuery = `SET`
+		}
+		if strings.Contains(valuesQuery, "=") {
+			valuesQuery = fmt.Sprintf("%s,", valuesQuery)
+		}
+		valuesQuery = fmt.Sprintf("%s %s = $%d", valuesQuery, k, i)
+		i++
+		values = append(values, v)
+	}
+	if valuesQuery != "" {
+		query = fmt.Sprintf("%s %s", query, valuesQuery)
+	}
+	if searchQuery != "" {
+		query = fmt.Sprintf("%s %s", query, searchQuery)
+	}
+	return query, values
+}
+
+// ConfigureInsertQuery will receive a partial query and mount the final query with all data
+// to be inserted in the table with its related fields.
+func ConfigureInsertQuery(query string, params map[string]interface{}) (string, []interface{}) {
+	values := make([]interface{}, 0)
+	i := 1
+	argsQuery := `(`
+	valuesQuery := `VALUES (`
+	for k, v := range params {
+		if i == len(params) {
+			argsQuery = fmt.Sprintf("%s%s)", argsQuery, k)
+			valuesQuery = fmt.Sprintf("%s$%d)", valuesQuery, i)
+		} else {
+			argsQuery = fmt.Sprintf("%s%s, ", argsQuery, k)
+			valuesQuery = fmt.Sprintf("%s$%d, ", valuesQuery, i)
+		}
+		values = append(values, v)
+		i++
+	}
+	query = fmt.Sprintf("%s %s %s", query, argsQuery, valuesQuery)
+	return query, values
+}
+
+// ConfigureUpsertQuery will receive a partial query and mount the final query
+// CONFLICT statement so it will allow Postgres make an Upsert in the entry
+// based on the conflicted columns passed in this statement. An UPDATE query is build
+// with the related values to be updated in case of a conflict.
+func ConfigureUpsertQuery(
+	query string, searchValues, newValues map[string]interface{}) (string, []interface{}) {
+	insertQuery, values := ConfigureInsertQuery(query, newValues)
+	conflictQuery := ""
+	index := 1
+	for key := range searchValues {
+		if !strings.Contains(conflictQuery, "CONFLICT") {
+			conflictQuery = `ON CONFLICT (`
+		}
+		if index == len(searchValues) {
+			conflictQuery = fmt.Sprintf("%s%s)", conflictQuery, key)
+		} else {
+			conflictQuery = fmt.Sprintf("%s%s, ", conflictQuery, key)
+		}
+		index++
+	}
+	updateQuery := ""
+	for key := range newValues {
+		if !strings.Contains(updateQuery, "UPDATE") {
+			updateQuery = `DO UPDATE SET`
+		}
+		if strings.Contains(updateQuery, "=") {
+			updateQuery = fmt.Sprintf("%s,", updateQuery)
+		}
+		updateQuery = fmt.Sprintf("%s %s = EXCLUDED.%s", updateQuery, key, key)
+	}
+	if conflictQuery != "" {
+		insertQuery = fmt.Sprintf("%s %s", insertQuery, conflictQuery)
+	}
+	if updateQuery != "" {
+		insertQuery = fmt.Sprintf("%s %s", insertQuery, updateQuery)
+	}
+	return insertQuery, values
+}
+
+// ConfigureQuery will receive a partial search query and will mount the final query with the
+// search if it exists.
+func ConfigureQuery(query string, params map[string]interface{}) (string, []interface{}) {
+	if len(params) != 0 {
+		query = fmt.Sprintf("%s WHERE", query)
+	}
+	values := make([]interface{}, 0)
+	i := 1
+	for k, v := range params {
+		if strings.Contains(query, "=") {
+			query = fmt.Sprintf("%s AND", query)
+		}
+		query = fmt.Sprintf("%s %s = $%d", query, k, i)
+		values = append(values, v)
+		i++
+	}
+	return query, values
+}
diff --git a/api/db/postgres/postgres_handler.go b/api/db/postgres/postgres_handler.go
index 818ed5b..8b7aa3f 100644
--- a/api/db/postgres/postgres_handler.go
+++ b/api/db/postgres/postgres_handler.go
@@ -5,6 +5,7 @@ import (
 	"fmt"
 	"sync"
 	"time"
+
 	_ "github.com/lib/pq" // Defining postgres plugin
 )
 
@@ -27,7 +28,7 @@ func (pHandler *PostgresHandler) ConfigureDB(
 			password,
 			address,
 			dbName)
-		db, dbErr = sql.Open("posgres", connStr)
+		db, dbErr = sql.Open("postgres", connStr)
 	})
 	return dbErr
 }
@@ -46,3 +47,61 @@ func (pHandler *PostgresHandler) ConfigurePool(maxOpenConns, maxIdleConns int, c
 func (pHandler *PostgresHandler) CloseDB() error {
 	return db.Close()
 }
+
+// ConfigureQuery will call the function Query
+// to make a query to DB and it will return the
+// rows from DB. This will be stored in Rows pointer
+// and the error will be returned.
+func (pHandler *PostgresHandler) ConfigureQuery(query string, args ...interface{}) error {
+	var err error
+	pHandler.Rows, err = db.Query(query, args...)
+	return err
+}
+
+// CloseRows will call Close function from db.Rows struct.
+// It will destroy all rows returned from the query.
+func (pHandler *PostgresHandler) CloseRows() error {
+	return pHandler.Rows.Close()
+}
+
+// GetColumns will return all the columns stored in the
+// Rows. If it won't be possible, it will return an empty
+// slice and an error.
+func (pHandler *PostgresHandler) GetColumns() ([]string, error) {
+	return pHandler.Rows.Columns()
+}
+
+// HasNextRow will call Next from sql.Rows and will return
+// a boolean. True if has a next row to be read. Otherwise,
+// the boolean will be false.
+func (pHandler *PostgresHandler) HasNextRow() bool {
+	return pHandler.Rows.Next()
+}
+
+// ScanRow will call Scan from db.Rows and return an error
+// if the scan fails. The result of the scan will be returned
+// on dest slice interface.
+func (pHandler *PostgresHandler) ScanRow(dest ...interface{}) error {
+	return pHandler.Rows.Scan(dest...)
+}
+
+// GetRowsErr will call Err from db.Rows to verify if an
+// error ocurred during rows retrieval.
+func (pHandler *PostgresHandler) GetRowsErr() error {
+	return pHandler.Rows.Err()
+}
+
+// Exec will run Exec function with. the query passed in the argument.
+// It will store db.Result struct in PostgresHandler.
+func (pHandler *PostgresHandler) Exec(query string, args ...interface{}) error {
+	var err error
+	pHandler.Result, err = db.Exec(query, args...)
+	return err
+}
+
+// GetRowsAffected will call RowsAffected to return the number of
+// rows affected during query process in Exec. In case of any failures in query,
+// an error will be returned.
+func (pHandler *PostgresHandler) GetRowsAffected() (int64, error) {
+	return pHandler.Result.RowsAffected()
+}
diff --git a/api/db/postgres/sql.go b/api/db/postgres/sql.go
index 2d101e8..6b5f008 100644
--- a/api/db/postgres/sql.go
+++ b/api/db/postgres/sql.go
@@ -3,16 +3,27 @@ package db
 import (
 	"errors"
 	"log"
+	"time"
 )
 
 // Connect will call Postgres and establish
 // a new connection considering the pool of
 // connections configured in the enviroment.
-func (sqlConfig *SQLConfig) Connect() error {
-	if err := sqlConfig.Postgres.ConfigureDB(); err != nil {
+func (sqlConfig *SQLConfig) Connect(address string,
+	username string,
+	password string,
+	dbName string,
+	maxOpenConns int,
+	maxIdleConns int,
+	connLT time.Duration) error {
+	if err := sqlConfig.Postgres.ConfigureDB(
+		address,
+		username,
+		password,
+		dbName); err != nil {
 		return err
 	}
-	sqlConfig.Postgres.ConfigurePool()
+	sqlConfig.Postgres.ConfigurePool(maxOpenConns, maxIdleConns, connLT)
 	return nil
 }
 
diff --git a/api/db/postgres/types.go b/api/db/postgres/types.go
index 9a0a870..81cc6b7 100644
--- a/api/db/postgres/types.go
+++ b/api/db/postgres/types.go
@@ -2,6 +2,7 @@ package db
 
 import (
 	"database/sql"
+	"time"
 )
 
 // PostgresHandler implements
@@ -17,8 +18,8 @@ type PostgresHandler struct {
 // all the required interactions with Postgres
 // database directly.
 type PostgresOperations interface {
-	ConfigureDB() error
-	ConfigurePool()
+	ConfigureDB(address, username, password, dbName string) error
+	ConfigurePool(maxOpenConns, maxIdleConns int, connLT time.Duration)
 	CloseDB() error
 	ConfigureQuery(query string, args ...interface{}) error
 	CloseRows() error
@@ -30,11 +31,20 @@ type PostgresOperations interface {
 	GetRowsAffected() (int64, error)
 }
 
-// SQLConfig will implement the required logic
-// for data interaction with Postgres. It will
-// make the calls generic so any data could be
-// retrieved or any valid queries requested without
-// broken contract with DB.
+// SQLGen defines the functions that will
+// make generic calls to a SQL database.
+type SQLGen interface {
+	Connect(address string, username string, password string, dbName string, maxOpenConns int, maxIdleConns int, connLT time.Duration) error
+	GetValuesFromDB(query string, args ...interface{}) ([]map[string]interface{}, error)
+	WriteInDB(query string, args ...interface{}) (int64, error)
+}
+
+// SQLConfig will implement SQLGen. It is
+// the required logic for data interaction
+// with Postgres. It will make the calls generic
+// so any data could be retrieved or any valid
+// queries requested without broken contract
+// with DB.
 type SQLConfig struct {
 	Postgres PostgresOperations
 }
diff --git a/api/db/psqlretriever.go b/api/db/psqlretriever.go
new file mode 100644
index 0000000..419f5f2
--- /dev/null
+++ b/api/db/psqlretriever.go
@@ -0,0 +1,50 @@
+package db
+
+import (
+	"time"
+)
+
+// Connect will establish and a connection with Postgres DB based on the received arguments
+func (sR *SQLJSONRetrieve) Connect(
+	address string,
+	dbName string,
+	username string,
+	password string,
+	maxOpenConns int,
+	maxIdleConns int,
+	connMaxLifetime time.Duration) error {
+	return sR.Psql.Connect(
+		address,
+		username,
+		password,
+		dbName,
+		maxOpenConns,
+		maxIdleConns,
+		connMaxLifetime)
+}
+
+// RetrieveFromDB will get values from Postgres DB through a SELECT query. The response will
+// be returned in response interface. It needs to be a pointer to the struct that will map the
+// returned values. The params passed are the ones that will be listed in WHERE argument of the
+// query if it exists.
+func (sR *SQLJSONRetrieve) RetrieveFromDB(
+	query string, response interface{}, params ...interface{}) error {
+	values, err := sR.Psql.GetValuesFromDB(query, params)
+	if err != nil {
+		return err
+	}
+	jsonValues, err := sR.JSONHandler.Marshal(values)
+	if err != nil {
+		return err
+	}
+	if err := sR.JSONHandler.Unmarshal(jsonValues, response); err != nil {
+		return err
+	}
+	return nil
+}
+
+// WriteInDB will call Postgres with INSERT and UPDATE queries. The values to be inserted or
+// updated are passed in args variable.
+func (sR *SQLJSONRetrieve) WriteInDB(query string, args ...interface{}) (int64, error) {
+	return sR.Psql.WriteInDB(query, args)
+}
diff --git a/api/db/types.go b/api/db/types.go
index 0b344cc..549d683 100644
--- a/api/db/types.go
+++ b/api/db/types.go
@@ -1,8 +1,10 @@
 package db
 
 import (
-	"github.com/globocom/huskyCI/api/types"
 	"time"
+
+	postgres "github.com/globocom/huskyCI/api/db/postgres"
+	"github.com/globocom/huskyCI/api/types"
 )
 
 // Requests defines all functions
@@ -27,16 +29,46 @@ type Requests interface {
 	InsertDBAccessToken(accessToken types.DBToken) error
 	UpdateOneDBRepository(mapParams, updateQuery map[string]interface{}) error
 	UpsertOneDBSecurityTest(mapParams map[string]interface{}, updatedSecurityTest types.SecurityTest) (interface{}, error)
-	UpdateOneDBAnalysis(mapParams map[string]interface{}, updatedAnalysis types.Analysis) error
+	UpdateOneDBAnalysis(mapParams map[string]interface{}, updatedAnalysis map[string]interface{}) error
 	UpdateOneDBUser(mapParams map[string]interface{}, updatedUser types.User) error
 	UpdateOneDBAnalysisContainer(mapParams, updateQuery map[string]interface{}) error
 	UpdateOneDBAccessToken(mapParams map[string]interface{}, updatedAccessToken types.DBToken) error
 	GetMetricByType(metricType string, queryStringParams map[string][]string) (interface{}, error)
 }
+
 // MongoRequests implements Requests
 // for Mongo, a non-relational DB.
 type MongoRequests struct{}
 
+// JSON interface defines the functions that will threat data
+// to be transformed to JSON or a JSON that will be mapped in
+// a struct.
+type JSON interface {
+	Marshal(v interface{}) ([]byte, error)
+	Unmarshal(data []byte, v interface{}) error
+}
+
+// DataGenerator defines the functions that will interact directly
+// with DB functions. It abstracts the database functions
+type DataGenerator interface {
+	Connect(address string, username string, password string, dbName string, maxOpenConns int, maxIdleConns int, connLT time.Duration) error
+	RetrieveFromDB(query string, response interface{}, params ...interface{}) error
+	WriteInDB(query string, args ...interface{}) (int64, error)
+}
+
+// JSONCaller implements JSON interface calling functions
+// from encoding/json package.
+type JSONCaller struct{}
+
+// SQLJSONRetrieve implements DataGenerator that will interact with
+// the Postgres functions. This struct will DB data in JSON format.
+type SQLJSONRetrieve struct {
+	Psql        postgres.SQLGen
+	JSONHandler JSON
+}
+
 // PostgresRequests implements Requests
 // for Postgres, a relational DB.
-type PostgresRequests struct{}
+type PostgresRequests struct {
+	DataRetriever DataGenerator
+}
diff --git a/api/types/types.go b/api/types/types.go
index 01540c4..83ee7dd 100644
--- a/api/types/types.go
+++ b/api/types/types.go
@@ -160,10 +160,10 @@ type AccessToken struct {
 // for a repository URL
 type DBToken struct {
 	ID         bson.ObjectId `bson:"_id,omitempty"`
-	HuskyToken string        `bson:"huskytoken"`
-	URL        string        `bson:"repositoryURL"`
-	IsValid    bool          `bson:"isValid"`
-	CreatedAt  time.Time     `bson:"createdAt"`
-	Salt       string        `bson:"salt"`
-	UUID       string        `bson:"uuid"`
+	HuskyToken string        `bson:"huskytoken" json:"huskytoken"`
+	URL        string        `bson:"repositoryURL" json:"repositoryURL"`
+	IsValid    bool          `bson:"isValid" json:"isValid"`
+	CreatedAt  time.Time     `bson:"createdAt" json:"createdAt"`
+	Salt       string        `bson:"salt" json:"salt"`
+	UUID       string        `bson:"uuid" json:"uuid"`
 }
diff --git a/go.mod b/go.mod
index 05a1f6c..4304108 100644
--- a/go.mod
+++ b/go.mod
@@ -31,8 +31,8 @@ require (
 	github.com/mattn/goveralls v0.0.3 // indirect
 	github.com/mitchellh/go-homedir v1.1.0
 	github.com/nightlyone/lockfile v0.0.0-20180618180623-0ad87eef1443 // indirect
-	github.com/onsi/ginkgo v1.10.2
-	github.com/onsi/gomega v1.7.0
+	github.com/onsi/gomega v1.7.1
+	github.com/onsi/ginkgo v1.10.3
 	github.com/opencontainers/go-digest v1.0.0-rc1 // indirect
 	github.com/pelletier/go-toml v1.5.0 // indirect
 	github.com/sdboyer/constext v0.0.0-20170321163424-836a14457353 // indirect
@@ -40,7 +40,7 @@ require (
 	github.com/spf13/afero v1.2.2 // indirect
 	github.com/spf13/cobra v0.0.5
 	github.com/spf13/jwalterweatherman v1.1.0 // indirect
-	github.com/spf13/viper v1.4.0
+	github.com/spf13/viper v1.5.0
 	github.com/stretchr/testify v1.4.0
 	github.com/uudashr/gocognit v1.0.0 // indirect
 	github.com/valyala/fasttemplate v1.0.1 // indirect
diff --git a/go.sum b/go.sum
index 1e0ed1c..0b2d6a1 100644
--- a/go.sum
+++ b/go.sum
@@ -237,12 +237,16 @@ github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+W
 github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
 github.com/onsi/ginkgo v1.10.2 h1:uqH7bpe+ERSiDa34FDOF7RikN6RzXgduUF8yarlZp94=
 github.com/onsi/ginkgo v1.10.2/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
+github.com/onsi/ginkgo v1.10.3 h1:OoxbjfXVZyod1fmWYhI7SEyaD8B00ynP3T+D5GiyHOY=
+github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
 github.com/onsi/gomega v1.5.0 h1:izbySO9zDPmjJ8rDjLvkA2zJHIo+HkYXHnf7eN7SSyo=
 github.com/onsi/gomega v1.5.0 h1:izbySO9zDPmjJ8rDjLvkA2zJHIo+HkYXHnf7eN7SSyo=
 github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
 github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
 github.com/onsi/gomega v1.7.0 h1:XPnZz8VVBHjVsy1vzJmRwIcSwiUO+JFfrv/xGiigmME=
 github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
+github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ=
+github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
 github.com/opencontainers/go-digest v1.0.0-rc1 h1:WzifXhOVOEOuFYOJAW6aQqW0TooG2iki3E3Ii+WN7gQ=
 github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s=
 github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
@@ -305,6 +309,8 @@ github.com/spf13/viper v1.3.2 h1:VUFqw5KcqRf7i70GOzW7N+Q7+gxVBkSSqiXB12+JQ4M=
 github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s=
 github.com/spf13/viper v1.4.0 h1:yXHLWeravcrgGyFSyCgdYpXQ9dR9c/WED3pg1RhxqEU=
 github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE=
+github.com/spf13/viper v1.5.0 h1:GpsTwfsQ27oS/Aha/6d1oD7tpKIqWnOA6tgOX9HHkt4=
+github.com/spf13/viper v1.5.0/go.mod h1:AkYRkVJF8TkSG/xet6PzXX+l39KhhXa2pdqVSxnTcn4=
 github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
 github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
 github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48=
@@ -316,6 +322,8 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf
 github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
 github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
 github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
+github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
+github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
 github.com/timakin/bodyclose v0.0.0-20190930140734-f7f2e9bca95e h1:RumXZ56IrCj4CL+g1b9OL/oH0QnsF976bC8xQFYUD5Q=
 github.com/timakin/bodyclose v0.0.0-20190930140734-f7f2e9bca95e/go.mod h1:Qimiffbc6q9tBWlVV6x0P9sat/ao1xEkREYPPj9hphk=
 github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=


Test patch:
diff --git a/api/db/db_suite_test.go b/api/db/db_suite_test.go
new file mode 100644
index 0000000..d085f52
--- /dev/null
+++ b/api/db/db_suite_test.go
@@ -0,0 +1,13 @@
+package db_test
+
+import (
+	"testing"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+func TestDb(t *testing.T) {
+	RegisterFailHandler(Fail)
+	RunSpecs(t, "Db Suite")
+}
diff --git a/api/db/postgres/sql_test.go b/api/db/postgres/sql_test.go
index f7e6fb2..3e977bf 100644
--- a/api/db/postgres/sql_test.go
+++ b/api/db/postgres/sql_test.go
@@ -1,6 +1,8 @@
 package db_test
 
 import (
+	"time"
+
 	. "github.com/onsi/ginkgo"
 	. "github.com/onsi/gomega"
 
@@ -26,11 +28,11 @@ type FakeSql struct {
 	ExpectedResult          []map[string]interface{}
 }
 
-func (fakeDB *FakeSql) ConfigureDB() error {
+func (fakeDB *FakeSql) ConfigureDB(address, username, password, dbName string) error {
 	return fakeDB.ExpectedConfigDbError
 }
 
-func (fakeDB *FakeSql) ConfigurePool() {}
+func (fakeDB *FakeSql) ConfigurePool(maxOpenConns, maxIdleConns int, connLT time.Duration) {}
 
 func (fakeDB *FakeSql) CloseDB() error {
 	return fakeDB.ExpectedCloseDbError
@@ -86,7 +88,7 @@ var _ = Describe("Sql", func() {
 				sqlConfig := SQLConfig{
 					Postgres: &fakeDB,
 				}
-				Expect(sqlConfig.Connect()).To(Equal(fakeDB.ExpectedConfigDbError))
+				Expect(sqlConfig.Connect("test", "test", "test", "test", 1, 1, time.Hour)).To(Equal(fakeDB.ExpectedConfigDbError))
 			})
 		})
 		Context("When ConfigureDB returns a nil error", func() {
@@ -97,7 +99,7 @@ var _ = Describe("Sql", func() {
 				sqlConfig := SQLConfig{
 					Postgres: &fakeDB,
 				}
-				Expect(sqlConfig.Connect()).To(BeNil())
+				Expect(sqlConfig.Connect("test", "test", "test", "test", 1, 1, time.Hour)).To(BeNil())
 			})
 		})
 	})
diff --git a/api/db/postgres_test.go b/api/db/postgres_test.go
new file mode 100644
index 0000000..d979869
--- /dev/null
+++ b/api/db/postgres_test.go
@@ -0,0 +1,1190 @@
+package db_test
+
+import (
+	"errors"
+	"time"
+
+	. "github.com/globocom/huskyCI/api/db"
+	"github.com/globocom/huskyCI/api/types"
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+type FakeRetriever struct {
+	expectedRetrieveError error
+	expectedRepository    types.Repository
+	expectedSecurityTest  types.SecurityTest
+	expectedAnalysis      types.Analysis
+	expectedUser          types.User
+	expectedDBToken       types.DBToken
+	expectedWriteError    error
+	expectedNumberRows    int64
+	expectedConnectError  error
+}
+
+func (fR *FakeRetriever) Connect(
+	address string,
+	dbName string,
+	username string,
+	password string,
+	maxOpenConns int,
+	maxIdleConns int,
+	connMaxLifetime time.Duration) error {
+	return fR.expectedConnectError
+}
+
+func (fR *FakeRetriever) RetrieveFromDB(
+	query string, response interface{}, params ...interface{}) error {
+	if fR.expectedRetrieveError == nil {
+		switch r := response.(type) {
+		case *[]types.Repository:
+			// newV := response.(*[]types.Repository)
+			(*r) = append((*r), fR.expectedRepository)
+		case *[]types.SecurityTest:
+			// newV := response.(*[]types.SecurityTest)
+			(*r) = append((*r), fR.expectedSecurityTest)
+		case *[]types.Analysis:
+			// newV := response.(*[]types.Analysis)
+			(*r) = append((*r), fR.expectedAnalysis)
+		case *[]types.User:
+			// newV := response.(*[]types.User)
+			(*r) = append((*r), fR.expectedUser)
+		case *[]types.DBToken:
+			// newV := response.(*[]types.DBToken)
+			(*r) = append((*r), fR.expectedDBToken)
+		}
+	}
+	return fR.expectedRetrieveError
+}
+
+func (fR *FakeRetriever) WriteInDB(query string, args ...interface{}) (int64, error) {
+	return fR.expectedNumberRows, fR.expectedWriteError
+}
+
+var _ = Describe("Postgres", func() {
+
+	var (
+		securityTest types.SecurityTest
+		repository   types.Repository
+		analysis     types.Analysis
+		user         types.User
+		accessToken  types.DBToken
+		validParams  map[string]interface{}
+		validUpdate  map[string]interface{}
+	)
+
+	BeforeEach(func() {
+		securityTest = types.SecurityTest{
+			Name:  "teste",
+			Image: "teste",
+			Cmd:   "teste",
+		}
+		repository = types.Repository{
+			URL:       "teste",
+			CreatedAt: time.Now(),
+		}
+		analysis = types.Analysis{
+			RID:    "teste",
+			URL:    "teste",
+			Branch: "teste",
+			Status: "teste",
+		}
+		user = types.User{
+			Username: "teste",
+			Password: "teste",
+			Salt:     "teste",
+		}
+		accessToken = types.DBToken{
+			HuskyToken: "teste",
+			URL:        "teste",
+			IsValid:    true,
+		}
+		validParams = map[string]interface{}{"id": "teste"}
+		validUpdate = map[string]interface{}{"changeField": "changeValue"}
+	})
+
+	Describe("ConnectDB", func() {
+		Context("When Connect returns an error", func() {
+			It("Should return the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedConnectError: errors.New("Failed to connect to DB"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.ConnectDB("", "", "", "", time.Second, 0, 0, 0, 0, time.Second)).To(
+					Equal(fakeRetriever.expectedConnectError))
+			})
+		})
+	})
+
+	Describe("FindOneDBRepository", func() {
+		Context("When key map verification returns false", func() {
+			It("Should return an empty Repository with the expected error", func() {
+				postgres := PostgresRequests{}
+				repo, err := postgres.FindOneDBRepository(
+					map[string]interface{}{"Wrong Key": "Failed"})
+				Expect(repo).To(Equal(types.Repository{}))
+				Expect(err).To(Equal(errors.New("Could not find repository URL")))
+			})
+		})
+		Context("When RetrieveFromDB returns an error", func() {
+			It("Should return an empty Repository with the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: errors.New("Failed to retrieve data"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				repo, err := postgres.FindOneDBRepository(
+					map[string]interface{}{"repositoryURL": "teste"})
+				Expect(repo).To(Equal(types.Repository{}))
+				Expect(err).To(Equal(fakeRetriever.expectedRetrieveError))
+			})
+		})
+		Context("When RetrieveFromDB returns the valid Repository struct", func() {
+			It("Should return the expected Repository with a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: nil,
+					expectedRepository: types.Repository{
+						URL:       "teste",
+						Branch:    "teste",
+						CreatedAt: time.Now(),
+					},
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				repo, err := postgres.FindOneDBRepository(
+					map[string]interface{}{"repositoryURL": "teste"})
+				Expect(repo).To(Equal(fakeRetriever.expectedRepository))
+				Expect(err).To(BeNil())
+			})
+		})
+	})
+	Describe("FindOneDBSecurityTest", func() {
+		Context("When key map verification returns false", func() {
+			It("Should return an empty SecurityTest with the expected error", func() {
+				postgres := PostgresRequests{}
+				repo, err := postgres.FindOneDBSecurityTest(
+					map[string]interface{}{"Wrong Key": "Failed"})
+				Expect(repo).To(Equal(types.SecurityTest{}))
+				Expect(err).To(Equal(errors.New("Could not find securityTest name field")))
+			})
+		})
+		Context("When RetrieveFromDB returns an error", func() {
+			It("Should return an empty SecurityTest with the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: errors.New("Failed to retrieve data"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				repo, err := postgres.FindOneDBSecurityTest(
+					map[string]interface{}{"name": "teste"})
+				Expect(repo).To(Equal(types.SecurityTest{}))
+				Expect(err).To(Equal(fakeRetriever.expectedRetrieveError))
+			})
+		})
+		Context("When RetrieveFromDB returns the valid SecurityTest struct", func() {
+			It("Should return the expected SecurityTest with a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: nil,
+					expectedSecurityTest: types.SecurityTest{
+						Name:     "teste",
+						Image:    "teste",
+						ImageTag: "teste",
+					},
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				repo, err := postgres.FindOneDBSecurityTest(
+					map[string]interface{}{"name": "teste"})
+				Expect(repo).To(Equal(fakeRetriever.expectedSecurityTest))
+				Expect(err).To(BeNil())
+			})
+		})
+	})
+	Describe("FindOneDBAnalysis", func() {
+		Context("When key map verification returns false", func() {
+			It("Should return an empty Analysis with the expected error", func() {
+				postgres := PostgresRequests{}
+				repo, err := postgres.FindOneDBAnalysis(
+					map[string]interface{}{"Wrong Key": "Failed"})
+				Expect(repo).To(Equal(types.Analysis{}))
+				Expect(err).To(Equal(errors.New("Could not find RID field")))
+			})
+		})
+		Context("When RetrieveFromDB returns an error", func() {
+			It("Should return an empty Analysis with the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: errors.New("Failed to retrieve data"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				repo, err := postgres.FindOneDBAnalysis(
+					map[string]interface{}{"RID": "teste"})
+				Expect(repo).To(Equal(types.Analysis{}))
+				Expect(err).To(Equal(fakeRetriever.expectedRetrieveError))
+			})
+		})
+		Context("When RetrieveFromDB returns the valid Analysis struct", func() {
+			It("Should return the expected Analysis with a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: nil,
+					expectedAnalysis: types.Analysis{
+						RID:    "teste",
+						URL:    "teste",
+						Branch: "teste",
+					},
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				repo, err := postgres.FindOneDBAnalysis(
+					map[string]interface{}{"RID": "teste"})
+				Expect(repo).To(Equal(fakeRetriever.expectedAnalysis))
+				Expect(err).To(BeNil())
+			})
+		})
+	})
+	Describe("FindOneDBUser", func() {
+		Context("When key map verification returns false", func() {
+			It("Should return an empty User with the expected error", func() {
+				postgres := PostgresRequests{}
+				repo, err := postgres.FindOneDBUser(
+					map[string]interface{}{"Wrong Key": "Failed"})
+				Expect(repo).To(Equal(types.User{}))
+				Expect(err).To(Equal(errors.New("Could not find user in DB")))
+			})
+		})
+		Context("When RetrieveFromDB returns an error", func() {
+			It("Should return an empty User with the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: errors.New("Failed to retrieve data"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				repo, err := postgres.FindOneDBUser(
+					map[string]interface{}{"username": "teste"})
+				Expect(repo).To(Equal(types.User{}))
+				Expect(err).To(Equal(fakeRetriever.expectedRetrieveError))
+			})
+		})
+		Context("When RetrieveFromDB returns the valid User struct", func() {
+			It("Should return the expected User with a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: nil,
+					expectedUser: types.User{
+						Username:   "teste",
+						Password:   "teste",
+						Salt:       "teste",
+						Iterations: 1,
+					},
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				repo, err := postgres.FindOneDBUser(
+					map[string]interface{}{"username": "teste"})
+				Expect(repo).To(Equal(fakeRetriever.expectedUser))
+				Expect(err).To(BeNil())
+			})
+		})
+	})
+	Describe("FindOneDBAccessToken", func() {
+		Context("When key map verification returns false", func() {
+			It("Should return an empty DBToken with the expected error", func() {
+				postgres := PostgresRequests{}
+				repo, err := postgres.FindOneDBAccessToken(
+					map[string]interface{}{"Wrong Key": "Failed"})
+				Expect(repo).To(Equal(types.DBToken{}))
+				Expect(err).To(Equal(errors.New("Could not find uuid parameter")))
+			})
+		})
+		Context("When RetrieveFromDB returns an error", func() {
+			It("Should return an empty DBToken with the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: errors.New("Failed to retrieve data"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				repo, err := postgres.FindOneDBAccessToken(
+					map[string]interface{}{"uuid": "teste"})
+				Expect(repo).To(Equal(types.DBToken{}))
+				Expect(err).To(Equal(fakeRetriever.expectedRetrieveError))
+			})
+		})
+		Context("When RetrieveFromDB returns the valid DBToken struct", func() {
+			It("Should return the expected DBToken with a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: nil,
+					expectedDBToken: types.DBToken{
+						HuskyToken: "teste",
+						URL:        "teste",
+						IsValid:    true,
+					},
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				repo, err := postgres.FindOneDBAccessToken(
+					map[string]interface{}{"uuid": "teste"})
+				Expect(repo).To(Equal(fakeRetriever.expectedDBToken))
+				Expect(err).To(BeNil())
+			})
+		})
+	})
+	Describe("ConfigureQuery", func() {
+		Context("When a simple query is passed without parameters", func() {
+			It("Should return the same query passed and an empty arguments slice", func() {
+				expectedQuery := `SELECT * FROM test`
+				params := map[string]interface{}{}
+				expectedVals := make([]interface{}, 0)
+				query, vals := ConfigureQuery(expectedQuery, params)
+				Expect(query).To(Equal(expectedQuery))
+				Expect(vals).To(Equal(expectedVals))
+			})
+		})
+		Context("When a query is passed with parameters", func() {
+			It("Should return the expected final query with the listed arguments", func() {
+				params := map[string]interface{}{"teste1": "myTest", "teste2": 1}
+				query, vals := ConfigureQuery(`SELECT * FROM test`, params)
+				if _, ok := vals[0].(string); ok {
+					expectedQuery := `SELECT * FROM test WHERE teste1 = $1 AND teste2 = $2`
+					expectedVals := []interface{}{"myTest", 1}
+					Expect(query).To(Equal(expectedQuery))
+					Expect(vals).To(Equal(expectedVals))
+				} else {
+					expectedQuery := `SELECT * FROM test WHERE teste2 = $1 AND teste1 = $2`
+					expectedVals := []interface{}{1, "myTest"}
+					Expect(query).To(Equal(expectedQuery))
+					Expect(vals).To(Equal(expectedVals))
+				}
+			})
+		})
+		Context("When a query is passed with only one parameter", func() {
+			It("Should return the expected final query with just one argument", func() {
+				expectedQuery := `SELECT * FROM test WHERE teste1 = $1`
+				expectedVals := []interface{}{"myTest"}
+				params := map[string]interface{}{"teste1": "myTest"}
+				query, vals := ConfigureQuery(`SELECT * FROM test`, params)
+				Expect(query).To(Equal(expectedQuery))
+				Expect(vals).To(Equal(expectedVals))
+			})
+		})
+	})
+	Describe("FindAllDBRepository", func() {
+		Context("When RetrieveFromDB returns an error", func() {
+			It("Should return an empty array and the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: errors.New("Failed to retrieve data"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				repo, err := postgres.FindAllDBRepository(
+					map[string]interface{}{"teste": "teste"})
+				Expect(repo).To(Equal([]types.Repository{}))
+				Expect(err).To(Equal(fakeRetriever.expectedRetrieveError))
+			})
+		})
+		Context("When RetrieveFromDB returns a nil error", func() {
+			It("Should return the expected RepositoryResponse and a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: nil,
+					expectedRepository: types.Repository{
+						URL:       "teste",
+						Branch:    "teste",
+						CreatedAt: time.Now(),
+					},
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				expectedRepositoryArray := []types.Repository{}
+				expectedRepositoryArray = append(expectedRepositoryArray,
+					fakeRetriever.expectedRepository)
+				repos, err := postgres.FindAllDBRepository(
+					map[string]interface{}{"teste": "teste"})
+				Expect(repos).To(Equal(expectedRepositoryArray))
+				Expect(err).To(BeNil())
+			})
+		})
+	})
+	Describe("FindAllDBSecurityTest", func() {
+		Context("When RetrieveFromDB returns an error", func() {
+			It("Should return an empty array and the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: errors.New("Failed to retrieve data"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				repo, err := postgres.FindAllDBSecurityTest(
+					map[string]interface{}{"teste": "teste"})
+				Expect(repo).To(Equal([]types.SecurityTest{}))
+				Expect(err).To(Equal(fakeRetriever.expectedRetrieveError))
+			})
+		})
+		Context("When RetrieveFromDB returns a nil error", func() {
+			It("Should return the expected SecurityTestResponse and a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: nil,
+					expectedSecurityTest: types.SecurityTest{
+						Name:     "teste",
+						Image:    "teste",
+						ImageTag: "teste",
+					},
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				expectedSecurityTestArray := []types.SecurityTest{}
+				expectedSecurityTestArray = append(expectedSecurityTestArray,
+					fakeRetriever.expectedSecurityTest)
+				repos, err := postgres.FindAllDBSecurityTest(
+					map[string]interface{}{"teste": "teste"})
+				Expect(repos).To(Equal(expectedSecurityTestArray))
+				Expect(err).To(BeNil())
+			})
+		})
+	})
+	Describe("FindAllDBAnalysis", func() {
+		Context("When RetrieveFromDB returns an error", func() {
+			It("Should return an empty array and the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: errors.New("Failed to retrieve data"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				repo, err := postgres.FindAllDBAnalysis(
+					map[string]interface{}{"teste": "teste"})
+				Expect(repo).To(Equal([]types.Analysis{}))
+				Expect(err).To(Equal(fakeRetriever.expectedRetrieveError))
+			})
+		})
+		Context("When RetrieveFromDB returns a nil error", func() {
+			It("Should return the expected AnalysisResponse and a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedRetrieveError: nil,
+					expectedAnalysis: types.Analysis{
+						RID:    "teste",
+						URL:    "teste",
+						Branch: "teste",
+					},
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				expectedAnalysisArray := []types.Analysis{}
+				expectedAnalysisArray = append(expectedAnalysisArray,
+					fakeRetriever.expectedAnalysis)
+				repos, err := postgres.FindAllDBAnalysis(
+					map[string]interface{}{"teste": "teste"})
+				Expect(repos).To(Equal(expectedAnalysisArray))
+				Expect(err).To(BeNil())
+			})
+		})
+	})
+	Describe("InsertDBRepository", func() {
+		Context("When Repository is set with a nil URL", func() {
+			It("Should return the expected error", func() {
+				postgres := PostgresRequests{}
+				expectedError := errors.New("Empty repository data")
+				Expect(postgres.InsertDBRepository(types.Repository{})).To(Equal(expectedError))
+			})
+		})
+		Context("When WriteInDB returns an error", func() {
+			It("Should return the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: errors.New("Failed to write data in DB"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(
+					postgres.InsertDBRepository(repository)).To(
+					Equal(fakeRetriever.expectedWriteError))
+			})
+		})
+		Context("When WriteInDB returns zero rows affected", func() {
+			It("Should return the expected error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 0,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(
+					postgres.InsertDBRepository(repository)).To(
+					Equal(errors.New("No data was inserted")))
+			})
+		})
+		Context("When WriteInDB returns a number of rows affected", func() {
+			It("Should return a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 1,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(
+					postgres.InsertDBRepository(repository)).To(
+					BeNil())
+			})
+		})
+	})
+	Describe("InsertDBSecurityTest", func() {
+		Context("When an empty SecurityTest is passed as an argument", func() {
+			It("Should return the expected error", func() {
+				postgres := PostgresRequests{}
+				Expect(
+					postgres.InsertDBSecurityTest(types.SecurityTest{})).To(
+					Equal(errors.New("Empty SecurityTest data")))
+			})
+		})
+		Context("When WriteInDB returns an error", func() {
+			It("Should return the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: errors.New("Failed to write data in DB"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(
+					postgres.InsertDBSecurityTest(securityTest)).To(
+					Equal(fakeRetriever.expectedWriteError))
+			})
+		})
+		Context("When WriteInDB returns 0 rows affected", func() {
+			It("Should return the expected error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 0,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.InsertDBSecurityTest(securityTest)).To(
+					Equal(errors.New("No data was inserted")))
+			})
+		})
+		Context("When WriteInDB returns some rows affected", func() {
+			It("Should return a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 1,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.InsertDBSecurityTest(securityTest)).To(BeNil())
+			})
+		})
+	})
+	Describe("InsertDBAnalysis", func() {
+		Context("When an empty Analysis is passed as an argument", func() {
+			It("Should return the expected error", func() {
+				postgres := PostgresRequests{}
+				Expect(
+					postgres.InsertDBAnalysis(types.Analysis{})).To(
+					Equal(errors.New("Empty Analysis data")))
+			})
+		})
+		Context("When WriteInDB returns an error", func() {
+			It("Should return the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: errors.New("Failed to write data in DB"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(
+					postgres.InsertDBAnalysis(analysis)).To(
+					Equal(fakeRetriever.expectedWriteError))
+			})
+		})
+		Context("When WriteInDB returns 0 rows affected", func() {
+			It("Should return the expected error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 0,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.InsertDBAnalysis(analysis)).To(
+					Equal(errors.New("No data was inserted")))
+			})
+		})
+		Context("When WriteInDB returns some rows affected", func() {
+			It("Should return a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 1,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.InsertDBAnalysis(analysis)).To(BeNil())
+			})
+		})
+	})
+
+	Describe("InsertDBUser", func() {
+		Context("When an empty User is passed as an argument", func() {
+			It("Should return the expected error", func() {
+				postgres := PostgresRequests{}
+				Expect(
+					postgres.InsertDBUser(types.User{})).To(
+					Equal(errors.New("Empty User data")))
+			})
+		})
+		Context("When WriteInDB returns an error", func() {
+			It("Should return the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: errors.New("Failed to write data in DB"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(
+					postgres.InsertDBUser(user)).To(
+					Equal(fakeRetriever.expectedWriteError))
+			})
+		})
+		Context("When WriteInDB returns 0 rows affected", func() {
+			It("Should return the expected error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 0,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.InsertDBUser(user)).To(
+					Equal(errors.New("No data was inserted")))
+			})
+		})
+		Context("When WriteInDB returns some rows affected", func() {
+			It("Should return a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 1,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.InsertDBUser(user)).To(BeNil())
+			})
+		})
+	})
+
+	Describe("InsertDBAccessToken", func() {
+		Context("When an empty DBToken is passed as an argument", func() {
+			It("Should return the expected error", func() {
+				postgres := PostgresRequests{}
+				Expect(
+					postgres.InsertDBAccessToken(types.DBToken{})).To(
+					Equal(errors.New("Empty DBToken data")))
+			})
+		})
+		Context("When WriteInDB returns an error", func() {
+			It("Should return the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: errors.New("Failed to write data in DB"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(
+					postgres.InsertDBAccessToken(accessToken)).To(
+					Equal(fakeRetriever.expectedWriteError))
+			})
+		})
+		Context("When WriteInDB returns 0 rows affected", func() {
+			It("Should return the expected error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 0,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.InsertDBAccessToken(accessToken)).To(
+					Equal(errors.New("No data was inserted")))
+			})
+		})
+		Context("When WriteInDB returns some rows affected", func() {
+			It("Should return a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 1,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.InsertDBAccessToken(accessToken)).To(BeNil())
+			})
+		})
+	})
+
+	Describe("UpdateOneDBRepository", func() {
+		Context("When an empty updateQuery is passed as argument", func() {
+			It("Should return the expected error", func() {
+				postgres := PostgresRequests{}
+				mapParams := map[string]interface{}{}
+				updateQuery := map[string]interface{}{}
+				Expect(postgres.UpdateOneDBRepository(mapParams, updateQuery)).To(
+					Equal(errors.New("Empty fields to be updated")))
+			})
+		})
+		Context("When an empty mapParams is passed as argument", func() {
+			It("Should return the expected error for empty mapParams", func() {
+				postgres := PostgresRequests{}
+				mapParams := map[string]interface{}{}
+				updateQuery := map[string]interface{}{"teste": "update"}
+				Expect(postgres.UpdateOneDBRepository(mapParams, updateQuery)).To(
+					Equal(errors.New("Empty fields to search")))
+			})
+		})
+		Context("When WriteInDB returns an error", func() {
+			It("Should return the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: errors.New("Failed to write in DB"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.UpdateOneDBRepository(validParams, validUpdate)).To(
+					Equal(fakeRetriever.expectedWriteError))
+			})
+		})
+		Context("When WriteInDB returns 0 rows affected", func() {
+			It("Should return the expected error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 0,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.UpdateOneDBRepository(validParams, validUpdate)).To(
+					Equal(errors.New("No data was updated")))
+			})
+		})
+		Context("When WriteInDB returns a number of rows affected", func() {
+			It("Should return a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 1,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.UpdateOneDBRepository(validParams, validUpdate)).To(
+					BeNil())
+			})
+		})
+	})
+
+	Describe("UpdateOneDBAnalysis", func() {
+		Context("When an empty updateQuery is passed as argument", func() {
+			It("Should return the expected error", func() {
+				postgres := PostgresRequests{}
+				mapParams := map[string]interface{}{}
+				updateQuery := map[string]interface{}{}
+				Expect(postgres.UpdateOneDBAnalysis(mapParams, updateQuery)).To(
+					Equal(errors.New("Empty fields to be updated")))
+			})
+		})
+		Context("When an empty mapParams is passed as argument", func() {
+			It("Should return the expected error for empty mapParams", func() {
+				postgres := PostgresRequests{}
+				mapParams := map[string]interface{}{}
+				updateQuery := map[string]interface{}{"teste": "update"}
+				Expect(postgres.UpdateOneDBAnalysis(mapParams, updateQuery)).To(
+					Equal(errors.New("Empty fields to search")))
+			})
+		})
+		Context("When WriteInDB returns an error", func() {
+			It("Should return the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: errors.New("Failed to write in DB"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.UpdateOneDBAnalysis(validParams, validUpdate)).To(
+					Equal(fakeRetriever.expectedWriteError))
+			})
+		})
+		Context("When WriteInDB returns 0 rows affected", func() {
+			It("Should return the expected error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 0,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.UpdateOneDBAnalysis(validParams, validUpdate)).To(
+					Equal(errors.New("No data was updated")))
+			})
+		})
+		Context("When WriteInDB returns a number of rows affected", func() {
+			It("Should return a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 1,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.UpdateOneDBAnalysis(validParams, validUpdate)).To(
+					BeNil())
+			})
+		})
+	})
+
+	Describe("UpdateOneDBUser", func() {
+		Context("When an empty updateUser is passed as argument", func() {
+			It("Should return the expected error", func() {
+				postgres := PostgresRequests{}
+				mapParams := map[string]interface{}{}
+				updateUser := types.User{}
+				Expect(postgres.UpdateOneDBUser(mapParams, updateUser)).To(
+					Equal(errors.New("Empty fields to be updated")))
+			})
+		})
+		Context("When an empty mapParams is passed as argument", func() {
+			It("Should return the expected error for empty mapParams", func() {
+				postgres := PostgresRequests{}
+				mapParams := map[string]interface{}{}
+				Expect(postgres.UpdateOneDBUser(mapParams, user)).To(
+					Equal(errors.New("Empty fields to search")))
+			})
+		})
+		Context("When WriteInDB returns an error", func() {
+			It("Should return the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: errors.New("Failed to write in DB"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.UpdateOneDBUser(validParams, user)).To(
+					Equal(fakeRetriever.expectedWriteError))
+			})
+		})
+		Context("When WriteInDB returns 0 rows affected", func() {
+			It("Should return the expected error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 0,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.UpdateOneDBUser(validParams, user)).To(
+					Equal(errors.New("No data was updated")))
+			})
+		})
+		Context("When WriteInDB returns a number of rows affected", func() {
+			It("Should return a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 1,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.UpdateOneDBUser(validParams, user)).To(
+					BeNil())
+			})
+		})
+	})
+
+	Describe("UpdateOneDBAnalysisContainer", func() {
+		Context("When an empty updateQuery is passed as argument", func() {
+			It("Should return the expected error", func() {
+				postgres := PostgresRequests{}
+				mapParams := map[string]interface{}{}
+				updateQuery := map[string]interface{}{}
+				Expect(postgres.UpdateOneDBAnalysisContainer(mapParams, updateQuery)).To(
+					Equal(errors.New("Empty fields to be updated")))
+			})
+		})
+		Context("When an empty mapParams is passed as argument", func() {
+			It("Should return the expected error for empty mapParams", func() {
+				postgres := PostgresRequests{}
+				mapParams := map[string]interface{}{}
+				updateQuery := map[string]interface{}{"teste": "update"}
+				Expect(postgres.UpdateOneDBAnalysisContainer(mapParams, updateQuery)).To(
+					Equal(errors.New("Empty fields to search")))
+			})
+		})
+		Context("When WriteInDB returns an error", func() {
+			It("Should return the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: errors.New("Failed to write in DB"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.UpdateOneDBAnalysisContainer(validParams, validUpdate)).To(
+					Equal(fakeRetriever.expectedWriteError))
+			})
+		})
+		Context("When WriteInDB returns 0 rows affected", func() {
+			It("Should return the expected error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 0,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.UpdateOneDBAnalysisContainer(validParams, validUpdate)).To(
+					Equal(errors.New("No data was updated")))
+			})
+		})
+		Context("When WriteInDB returns a number of rows affected", func() {
+			It("Should return a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 1,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.UpdateOneDBAnalysisContainer(validParams, validUpdate)).To(
+					BeNil())
+			})
+		})
+	})
+
+	Describe("UpdateOneDBAccessToken", func() {
+		Context("When an empty updatedAccessToken is passed as argument", func() {
+			It("Should return the expected error", func() {
+				postgres := PostgresRequests{}
+				mapParams := map[string]interface{}{}
+				updatedAccessToken := types.DBToken{}
+				Expect(postgres.UpdateOneDBAccessToken(mapParams, updatedAccessToken)).To(
+					Equal(errors.New("Empty fields to be updated")))
+			})
+		})
+		Context("When an empty mapParams is passed as argument", func() {
+			It("Should return the expected error for empty mapParams", func() {
+				postgres := PostgresRequests{}
+				mapParams := map[string]interface{}{}
+				Expect(postgres.UpdateOneDBAccessToken(mapParams, accessToken)).To(
+					Equal(errors.New("Empty fields to search")))
+			})
+		})
+		Context("When WriteInDB returns an error", func() {
+			It("Should return the same error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: errors.New("Failed to write in DB"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.UpdateOneDBAccessToken(validParams, accessToken)).To(
+					Equal(fakeRetriever.expectedWriteError))
+			})
+		})
+		Context("When WriteInDB returns 0 rows affected", func() {
+			It("Should return the expected error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 0,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.UpdateOneDBAccessToken(validParams, accessToken)).To(
+					Equal(errors.New("No data was updated")))
+			})
+		})
+		Context("When WriteInDB returns a number of rows affected", func() {
+			It("Should return a nil error", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 1,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				Expect(postgres.UpdateOneDBAccessToken(validParams, accessToken)).To(
+					BeNil())
+			})
+		})
+	})
+	Describe("UpsertOneDBSecurityTest", func() {
+		Context("When an empty SecurityTest is passed", func() {
+			It("Should return the expected error and a nil interface", func() {
+				params := map[string]interface{}{}
+				postgres := PostgresRequests{}
+				status, err := postgres.UpsertOneDBSecurityTest(params, types.SecurityTest{})
+				Expect(err).To(Equal(errors.New("Empty fields to be updated")))
+				Expect(status).To(BeNil())
+			})
+		})
+		Context("When an empty mapParams is passed", func() {
+			It("Should return the expected error", func() {
+				params := map[string]interface{}{}
+				postgres := PostgresRequests{}
+				status, err := postgres.UpsertOneDBSecurityTest(params, securityTest)
+				Expect(err).To(Equal(errors.New("Empty fields to search")))
+				Expect(status).To(BeNil())
+			})
+		})
+		Context("When DataRetriever returns an error", func() {
+			It("Should return the same error with a nil interface", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: errors.New("Failed to write in DB"),
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				status, err := postgres.UpsertOneDBSecurityTest(validParams, securityTest)
+				Expect(err).To(Equal(fakeRetriever.expectedWriteError))
+				Expect(status).To(BeNil())
+			})
+		})
+		Context("When DataRetriever returns 0 rows affected", func() {
+			It("Should return the expected error with a nil interface", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 0,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				status, err := postgres.UpsertOneDBSecurityTest(validParams, securityTest)
+				Expect(err).To(Equal(errors.New("No data was updated")))
+				Expect(status).To(BeNil())
+			})
+		})
+		Context("When DataRetriever returns a valid number of rows affected", func() {
+			It("Should return a nil error and the number of rows affected", func() {
+				fakeRetriever := FakeRetriever{
+					expectedWriteError: nil,
+					expectedNumberRows: 1,
+				}
+				postgres := PostgresRequests{
+					DataRetriever: &fakeRetriever,
+				}
+				status, err := postgres.UpsertOneDBSecurityTest(validParams, securityTest)
+				Expect(err).To(BeNil())
+				Expect(status).To(Equal(int64(1)))
+			})
+		})
+	})
+	Describe("ConfigureInsertQuery", func() {
+		Context("When an Insert query is passed with some params", func() {
+			It("Should return the expected query with the params to be inserted", func() {
+				query := `INSERT into test`
+				params := map[string]interface{}{
+					"test1": "value1",
+					"test2": 3,
+				}
+				finalQuery, values := ConfigureInsertQuery(query, params)
+				if _, ok := values[0].(string); ok {
+					expectedQuery := `INSERT into test (test1, test2) VALUES ($1, $2)`
+					expectedValues := []interface{}{"value1", 3}
+					Expect(finalQuery).To(Equal(expectedQuery))
+					Expect(values).To(Equal(expectedValues))
+				} else {
+					expectedQuery := `INSERT into test (test2, test1) VALUES ($1, $2)`
+					expectedValues := []interface{}{3, "value1"}
+					Expect(finalQuery).To(Equal(expectedQuery))
+					Expect(values).To(Equal(expectedValues))
+				}
+			})
+		})
+		Context("When an Insert query is passed with one param", func() {
+			It("Should return the expected query with the one param to be inserted", func() {
+				query := `INSERT into test`
+				params := map[string]interface{}{
+					"test1": "value1",
+				}
+				expectedQuery := `INSERT into test (test1) VALUES ($1)`
+				expectedValues := []interface{}{"value1"}
+				finalQuery, values := ConfigureInsertQuery(query, params)
+				Expect(finalQuery).To(Equal(expectedQuery))
+				Expect(values).To(Equal(expectedValues))
+			})
+		})
+	})
+	Describe("ConfigureUpdateQuery", func() {
+		Context("When an update query is passed with a search value and a new value", func() {
+			It("Should return the expected query and with the params to be updated", func() {
+				query := `UPDATE test`
+				searchValues := map[string]interface{}{"id": 1}
+				newValues := map[string]interface{}{"teste1": "newVal"}
+				expectedQuery := `UPDATE test SET teste1 = $2 WHERE id = $1`
+				expectedValues := []interface{}{1, "newVal"}
+				finalQuery, values := ConfigureUpdateQuery(query, searchValues, newValues)
+				Expect(finalQuery).To(Equal(expectedQuery))
+				Expect(values).To(Equal(expectedValues))
+			})
+		})
+		Context("When an update query is passed with a search value and a new value", func() {
+			It("Should return the expected query and with the params to be updated", func() {
+				query := `UPDATE test`
+				searchValues := map[string]interface{}{"id": 1, "id2": 2}
+				newValues := map[string]interface{}{"teste1": "newVal", "teste2": 3}
+				finalQuery, values := ConfigureUpdateQuery(query, searchValues, newValues)
+				if _, ok := values[2].(string); ok {
+					if values[0].(int) == 1 {
+						expectedQuery := `UPDATE test SET teste1 = $3, teste2 = $4 WHERE id = $1 AND id2 = $2`
+						expectedValues := []interface{}{1, 2, "newVal", 3}
+						Expect(finalQuery).To(Equal(expectedQuery))
+						Expect(values).To(Equal(expectedValues))
+					} else {
+						expectedQuery := `UPDATE test SET teste1 = $3, teste2 = $4 WHERE id2 = $1 AND id = $2`
+						expectedValues := []interface{}{2, 1, "newVal", 3}
+						Expect(finalQuery).To(Equal(expectedQuery))
+						Expect(values).To(Equal(expectedValues))
+					}
+				} else {
+					if values[0].(int) == 1 {
+						expectedQuery := `UPDATE test SET teste2 = $3, teste1 = $4 WHERE id = $1 AND id2 = $2`
+						expectedValues := []interface{}{1, 2, 3, "newVal"}
+						Expect(finalQuery).To(Equal(expectedQuery))
+						Expect(values).To(Equal(expectedValues))
+					} else {
+						expectedQuery := `UPDATE test SET teste2 = $3, teste1 = $4 WHERE id2 = $1 AND id = $2`
+						expectedValues := []interface{}{2, 1, 3, "newVal"}
+						Expect(finalQuery).To(Equal(expectedQuery))
+						Expect(values).To(Equal(expectedValues))
+					}
+				}
+			})
+		})
+	})
+	Describe("ConfigureUpsertQuery", func() {
+		Context("When a Insert query is passed with one existed param and one new value", func() {
+			It("Should return the expected query with the expected values", func() {
+				query := `INSERT into test`
+				newValues := map[string]interface{}{"value1": "teste1"}
+				columnsConflict := map[string]interface{}{"unique": "existed"}
+				expectedQuery := `INSERT into test (value1) VALUES ($1) ON CONFLICT (unique) DO UPDATE SET value1 = EXCLUDED.value1`
+				expectedValues := []interface{}{"teste1"}
+				finalQuery, values := ConfigureUpsertQuery(query, columnsConflict, newValues)
+				Expect(finalQuery).To(Equal(expectedQuery))
+				Expect(values).To(Equal(expectedValues))
+			})
+		})
+	})
+})