Tables not getting created in Postgresql using Gorm











up vote
0
down vote

favorite












I am trying to create a table from a struct using the following code. It had initially worked by hard coding the credentials to test. Once changing to env vars, I wanted to test that the tables and schemas would get created as expected.



So far I have tried:





  1. Removing the tables from the db, running "go run main.go".




    • Result: Established connection successfully to the db, but tables do not get created.




  2. Deleting the database, recreating the database using psql "CREATE DATABASE" command, and running "go run main.go"




    • Result: Established connection successfully to the db, but tables do not get created.



  3. Use AutoMigrate, but was not able to successfully create the tables.


  4. Debug: When I run it in debug mode, the debug console displays that its connected, i see no indication of any errors. I have not been coding for many years, still in the learning process.



Below are 2 files, main.go and api.go (opens db)



MAIN.GO



import (
"fmt"
"log"
"net/http"
"time"

"github.com/gorilla/handlers"
"gitlab......"
_ "gitlab....."
)

var err error

func main() {

api := controllers.API{}

// Using env vars from a config file
api.Initialize("user=%s password=%s dbname=%s port=%s sslmode=disable")

// BIND TO A PORT AND PASS OUR ROUTER IN
log.Fatal(http.ListenAndServe(":8000", handlers.CORS()(api.Router)))

if err != nil {
panic(err.Error())
}

// Models
type Application struct {
ID string `json:"id" gorm:"primary_key"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
Name string `json:"name"`
Ci string `json:"ci"`

// CREATE TABLES AND SCHEMA IF TABLES DO NOT EXIST
if !api.Database.HasTable(&Application{}) {
api.Database.CreateTable(&Application{})
}


API.GO



func (api *API) Initialize(opts string) {

// Initialize DB
dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s port=%s sslmode=disable",
config.DB_USER, config.DB_PASSWORD, config.DB_NAME, config.PORT)
api.Database, err = gorm.Open("postgres", dbinfo)

if err != nil {
log.Print("failed to connect to the database")
log.Fatal(err)

}

fmt.Println("Connection established")
log.Printf("Postgres started at %s PORT", config.PORT)
}


I have already created the database, and am able to establish a connection to the database. Just can not get the tables created.



Ideas?










share|improve this question
























  • SO is a terrible debugger. Have you tested your code to make sure the statements you think are being run are being run? Are you even reaching the CreateTable statement? What is the typical manner you would handle the case where a function would fail?
    – jdv
    Nov 8 at 16:57










  • @ jdv, lol -> SO is a terrible debugger, i aggree.I would usually use breakpoints to make sure that portion of the code is hit. The
    – Khaled Aman
    Nov 8 at 17:46












  • Accidently hit enter too soon. I would usually use breakpoints to make sure that portion of the code is reached. When i run it in debug mode, the debug console displays that its connected, i see no indication of any errors. I have not been doing this for so long, this I am learning.
    – Khaled Aman
    Nov 8 at 17:54










  • (You should put details like this in the text of the question.)
    – jdv
    Nov 8 at 18:48










  • Thanks for the advice, ill remember that next time.
    – Khaled Aman
    Nov 8 at 19:31















up vote
0
down vote

favorite












I am trying to create a table from a struct using the following code. It had initially worked by hard coding the credentials to test. Once changing to env vars, I wanted to test that the tables and schemas would get created as expected.



So far I have tried:





  1. Removing the tables from the db, running "go run main.go".




    • Result: Established connection successfully to the db, but tables do not get created.




  2. Deleting the database, recreating the database using psql "CREATE DATABASE" command, and running "go run main.go"




    • Result: Established connection successfully to the db, but tables do not get created.



  3. Use AutoMigrate, but was not able to successfully create the tables.


  4. Debug: When I run it in debug mode, the debug console displays that its connected, i see no indication of any errors. I have not been coding for many years, still in the learning process.



Below are 2 files, main.go and api.go (opens db)



MAIN.GO



import (
"fmt"
"log"
"net/http"
"time"

"github.com/gorilla/handlers"
"gitlab......"
_ "gitlab....."
)

var err error

func main() {

api := controllers.API{}

// Using env vars from a config file
api.Initialize("user=%s password=%s dbname=%s port=%s sslmode=disable")

// BIND TO A PORT AND PASS OUR ROUTER IN
log.Fatal(http.ListenAndServe(":8000", handlers.CORS()(api.Router)))

if err != nil {
panic(err.Error())
}

// Models
type Application struct {
ID string `json:"id" gorm:"primary_key"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
Name string `json:"name"`
Ci string `json:"ci"`

// CREATE TABLES AND SCHEMA IF TABLES DO NOT EXIST
if !api.Database.HasTable(&Application{}) {
api.Database.CreateTable(&Application{})
}


API.GO



func (api *API) Initialize(opts string) {

// Initialize DB
dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s port=%s sslmode=disable",
config.DB_USER, config.DB_PASSWORD, config.DB_NAME, config.PORT)
api.Database, err = gorm.Open("postgres", dbinfo)

if err != nil {
log.Print("failed to connect to the database")
log.Fatal(err)

}

fmt.Println("Connection established")
log.Printf("Postgres started at %s PORT", config.PORT)
}


I have already created the database, and am able to establish a connection to the database. Just can not get the tables created.



Ideas?










share|improve this question
























  • SO is a terrible debugger. Have you tested your code to make sure the statements you think are being run are being run? Are you even reaching the CreateTable statement? What is the typical manner you would handle the case where a function would fail?
    – jdv
    Nov 8 at 16:57










  • @ jdv, lol -> SO is a terrible debugger, i aggree.I would usually use breakpoints to make sure that portion of the code is hit. The
    – Khaled Aman
    Nov 8 at 17:46












  • Accidently hit enter too soon. I would usually use breakpoints to make sure that portion of the code is reached. When i run it in debug mode, the debug console displays that its connected, i see no indication of any errors. I have not been doing this for so long, this I am learning.
    – Khaled Aman
    Nov 8 at 17:54










  • (You should put details like this in the text of the question.)
    – jdv
    Nov 8 at 18:48










  • Thanks for the advice, ill remember that next time.
    – Khaled Aman
    Nov 8 at 19:31













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I am trying to create a table from a struct using the following code. It had initially worked by hard coding the credentials to test. Once changing to env vars, I wanted to test that the tables and schemas would get created as expected.



So far I have tried:





  1. Removing the tables from the db, running "go run main.go".




    • Result: Established connection successfully to the db, but tables do not get created.




  2. Deleting the database, recreating the database using psql "CREATE DATABASE" command, and running "go run main.go"




    • Result: Established connection successfully to the db, but tables do not get created.



  3. Use AutoMigrate, but was not able to successfully create the tables.


  4. Debug: When I run it in debug mode, the debug console displays that its connected, i see no indication of any errors. I have not been coding for many years, still in the learning process.



Below are 2 files, main.go and api.go (opens db)



MAIN.GO



import (
"fmt"
"log"
"net/http"
"time"

"github.com/gorilla/handlers"
"gitlab......"
_ "gitlab....."
)

var err error

func main() {

api := controllers.API{}

// Using env vars from a config file
api.Initialize("user=%s password=%s dbname=%s port=%s sslmode=disable")

// BIND TO A PORT AND PASS OUR ROUTER IN
log.Fatal(http.ListenAndServe(":8000", handlers.CORS()(api.Router)))

if err != nil {
panic(err.Error())
}

// Models
type Application struct {
ID string `json:"id" gorm:"primary_key"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
Name string `json:"name"`
Ci string `json:"ci"`

// CREATE TABLES AND SCHEMA IF TABLES DO NOT EXIST
if !api.Database.HasTable(&Application{}) {
api.Database.CreateTable(&Application{})
}


API.GO



func (api *API) Initialize(opts string) {

// Initialize DB
dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s port=%s sslmode=disable",
config.DB_USER, config.DB_PASSWORD, config.DB_NAME, config.PORT)
api.Database, err = gorm.Open("postgres", dbinfo)

if err != nil {
log.Print("failed to connect to the database")
log.Fatal(err)

}

fmt.Println("Connection established")
log.Printf("Postgres started at %s PORT", config.PORT)
}


I have already created the database, and am able to establish a connection to the database. Just can not get the tables created.



Ideas?










share|improve this question















I am trying to create a table from a struct using the following code. It had initially worked by hard coding the credentials to test. Once changing to env vars, I wanted to test that the tables and schemas would get created as expected.



So far I have tried:





  1. Removing the tables from the db, running "go run main.go".




    • Result: Established connection successfully to the db, but tables do not get created.




  2. Deleting the database, recreating the database using psql "CREATE DATABASE" command, and running "go run main.go"




    • Result: Established connection successfully to the db, but tables do not get created.



  3. Use AutoMigrate, but was not able to successfully create the tables.


  4. Debug: When I run it in debug mode, the debug console displays that its connected, i see no indication of any errors. I have not been coding for many years, still in the learning process.



Below are 2 files, main.go and api.go (opens db)



MAIN.GO



import (
"fmt"
"log"
"net/http"
"time"

"github.com/gorilla/handlers"
"gitlab......"
_ "gitlab....."
)

var err error

func main() {

api := controllers.API{}

// Using env vars from a config file
api.Initialize("user=%s password=%s dbname=%s port=%s sslmode=disable")

// BIND TO A PORT AND PASS OUR ROUTER IN
log.Fatal(http.ListenAndServe(":8000", handlers.CORS()(api.Router)))

if err != nil {
panic(err.Error())
}

// Models
type Application struct {
ID string `json:"id" gorm:"primary_key"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
Name string `json:"name"`
Ci string `json:"ci"`

// CREATE TABLES AND SCHEMA IF TABLES DO NOT EXIST
if !api.Database.HasTable(&Application{}) {
api.Database.CreateTable(&Application{})
}


API.GO



func (api *API) Initialize(opts string) {

// Initialize DB
dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s port=%s sslmode=disable",
config.DB_USER, config.DB_PASSWORD, config.DB_NAME, config.PORT)
api.Database, err = gorm.Open("postgres", dbinfo)

if err != nil {
log.Print("failed to connect to the database")
log.Fatal(err)

}

fmt.Println("Connection established")
log.Printf("Postgres started at %s PORT", config.PORT)
}


I have already created the database, and am able to establish a connection to the database. Just can not get the tables created.



Ideas?







go-gorm






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 8 at 21:30

























asked Nov 8 at 16:46









Khaled Aman

11




11












  • SO is a terrible debugger. Have you tested your code to make sure the statements you think are being run are being run? Are you even reaching the CreateTable statement? What is the typical manner you would handle the case where a function would fail?
    – jdv
    Nov 8 at 16:57










  • @ jdv, lol -> SO is a terrible debugger, i aggree.I would usually use breakpoints to make sure that portion of the code is hit. The
    – Khaled Aman
    Nov 8 at 17:46












  • Accidently hit enter too soon. I would usually use breakpoints to make sure that portion of the code is reached. When i run it in debug mode, the debug console displays that its connected, i see no indication of any errors. I have not been doing this for so long, this I am learning.
    – Khaled Aman
    Nov 8 at 17:54










  • (You should put details like this in the text of the question.)
    – jdv
    Nov 8 at 18:48










  • Thanks for the advice, ill remember that next time.
    – Khaled Aman
    Nov 8 at 19:31


















  • SO is a terrible debugger. Have you tested your code to make sure the statements you think are being run are being run? Are you even reaching the CreateTable statement? What is the typical manner you would handle the case where a function would fail?
    – jdv
    Nov 8 at 16:57










  • @ jdv, lol -> SO is a terrible debugger, i aggree.I would usually use breakpoints to make sure that portion of the code is hit. The
    – Khaled Aman
    Nov 8 at 17:46












  • Accidently hit enter too soon. I would usually use breakpoints to make sure that portion of the code is reached. When i run it in debug mode, the debug console displays that its connected, i see no indication of any errors. I have not been doing this for so long, this I am learning.
    – Khaled Aman
    Nov 8 at 17:54










  • (You should put details like this in the text of the question.)
    – jdv
    Nov 8 at 18:48










  • Thanks for the advice, ill remember that next time.
    – Khaled Aman
    Nov 8 at 19:31
















SO is a terrible debugger. Have you tested your code to make sure the statements you think are being run are being run? Are you even reaching the CreateTable statement? What is the typical manner you would handle the case where a function would fail?
– jdv
Nov 8 at 16:57




SO is a terrible debugger. Have you tested your code to make sure the statements you think are being run are being run? Are you even reaching the CreateTable statement? What is the typical manner you would handle the case where a function would fail?
– jdv
Nov 8 at 16:57












@ jdv, lol -> SO is a terrible debugger, i aggree.I would usually use breakpoints to make sure that portion of the code is hit. The
– Khaled Aman
Nov 8 at 17:46






@ jdv, lol -> SO is a terrible debugger, i aggree.I would usually use breakpoints to make sure that portion of the code is hit. The
– Khaled Aman
Nov 8 at 17:46














Accidently hit enter too soon. I would usually use breakpoints to make sure that portion of the code is reached. When i run it in debug mode, the debug console displays that its connected, i see no indication of any errors. I have not been doing this for so long, this I am learning.
– Khaled Aman
Nov 8 at 17:54




Accidently hit enter too soon. I would usually use breakpoints to make sure that portion of the code is reached. When i run it in debug mode, the debug console displays that its connected, i see no indication of any errors. I have not been doing this for so long, this I am learning.
– Khaled Aman
Nov 8 at 17:54












(You should put details like this in the text of the question.)
– jdv
Nov 8 at 18:48




(You should put details like this in the text of the question.)
– jdv
Nov 8 at 18:48












Thanks for the advice, ill remember that next time.
– Khaled Aman
Nov 8 at 19:31




Thanks for the advice, ill remember that next time.
– Khaled Aman
Nov 8 at 19:31

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53212394%2ftables-not-getting-created-in-postgresql-using-gorm%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53212394%2ftables-not-getting-created-in-postgresql-using-gorm%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Schultheiß

Liste der Kulturdenkmale in Wilsdruff

Android Play Services Check