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:
Removing the tables from the db, running "go run main.go".
Result: Established connection successfully to the db, but tables do not get created.
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.
Use AutoMigrate, but was not able to successfully create the tables.
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?
Related
I am trying to retrieve Stripe datas and parse them into a CSV file.
Here is my code:
package main
import (
"github.com/stripe/stripe-go"
"github.com/stripe/stripe-go/invoice"
"fmt"
"os"
"encoding/csv"
)
func main() {
stripe.Key = "" // I can't share the API key
params := &stripe.InvoiceListParams{}
params.Filters.AddFilter("limit", "", "3")
params.Filters.AddFilter("status", "", "paid")
i := invoice.List(params)
// Create a CSV file
csvdatafile, err := os.Create("./mycsvfile.csv")
if err != nil {
fmt.Println(err)
}
defer csvdatafile.Close()
// Write Unmarshaled json data to CSV file
w := csv.NewWriter(csvdatafile)
//Column title
var header []string
header = append(header, "ID")
w.Write(header)
for i.Next() {
in := i.Invoice()
fmt.Printf(in.ID) // It is working
w.Write(in) // It is not working
}
w.Flush()
fmt.Println("Appending succed")
}
When I am running my program with go run *.go I obtain the following error:
./main.go:35:10: cannot use in (type *stripe.Invoice) as type []string in argument to w.Write
I think I am not far from the solution.
I just need to understand how to write correctly in the CSV file thank's to w.Write() command.
According to the doc, the Write function is:
func (w *Writer) Write(record []string) error
That is, it is expecting you to pass a slice of strings representing a line of CSV data with each string being a slice. So, if you have only one field, you have to pass a string slice of 1:
w.Write([]string{in.ID})
here my main.go
package cmd
import (
"context"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
)
func main() {
cli, err := client.NewClientWithOpts(client.WithVersion("1.38"))
if err != nil {
panic(err)
}
networks, err := cli.NetworkList(context.Background(), types.NetworkListOptions{})
if err != nil {
panic(err)
}
fmt.Println(networks)
}
i tried to run dep init but vendor folder ended up with an older version of docker/docker because the newest tag is 17.05 tried to pin the actual commit but that did not work either
i give a shot to go mod vendor but that also rely on git tags
Strangely enough docker/docker is an alias to moby/moby and docker/engine.
Anyone could explain me and give example how can i successfully use vendoring with docker API?
[[constraint]]
name = "github.com/docker/docker"
branch = "master"
[[override]]
name = "github.com/docker/distribution"
branch = "master"
Actually this two entries helped solve the dependency issue in Gopkg.toml, then running dep ensure
When I try to use database/sql in this way it compiles and works:
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
But if I try to use postgres specific connectors it doesn't even compile:
import(
"database/sql"
_ "github.com/lib/pq"
)
import(
"database/sql"
_ "github.com/jbarham/gopgsqldriver"
)
both fail with the error
sql: unknown driver "mysql" (forgotten import?)
I have done go get for both of these packages, and am really not sure why it is not compiling
Are you doing
db, err := sql.Open("mysql",
later on? When you import "github.com/lib/pq" for example, it registers itself by calling sql.Register, and then in the source of sql.Open you have:
func Open(driverName, dataSourceName string) (*DB, error) {
driversMu.RLock()
driveri, ok := drivers[driverName]
driversMu.RUnlock()
if !ok {
return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName)
}
}
So, since you are no longer importing mysql, you need to change sql.Open to use the pq driver (or whichever one you end up picking).
package main
import (
"flag"
"fmt"
)
func main() {
passArguments()
}
func passArguments() string {
username := flag.String("user", "root", "Username for this server")
flag.Parse()
fmt.Printf("Your username is %q.", *username)
usernameToString := *username
return usernameToString
}
Passing an argument to the compiled code:
./args -user=bla
results in:
Your username is "bla"
the username that has been passed is displayed.
Aim: in order to prevent that the code needs to be build and run manually every time to test the code the aim is to write a test that is able to test the passing of arguments.
Attempt
Running the following test:
package main
import (
"os"
"testing"
)
func TestArgs(t *testing.T) {
expected := "bla"
os.Args = []string{"-user=bla"}
actual := passArguments()
if actual != expected {
t.Errorf("Test failed, expected: '%s', got: '%s'", expected, actual)
}
}
results in:
Your username is "root".Your username is "root".--- FAIL: TestArgs (0.00s)
args_test.go:15: Test failed, expected: 'bla', got: 'root'
FAIL
coverage: 87.5% of statements
FAIL tool 0.008s
Problem
It looks like that the os.Args = []string{"-user=bla is not able to pass this argument to the function as the outcome is root instead of bla
Per my comment, the very first value in os.Args is a (path to) executable itself, so os.Args = []string{"cmd", "-user=bla"} should fix your issue. You can take a look at flag test from the standard package where they're doing something similar.
Also, as os.Args is a "global variable", it might be a good idea to keep the state from before the test and restore it after. Similarly to the linked test:
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
This might be useful where other tests are, for example, examining the real arguments passed when evoking go test.
This is old enough but still searched out, while it seems out dated.
Because Go 1.13 changed sth.
I find this change helpful, putting flag.*() in init() and flag.Parse() in Test*()
-args cannot take -<test-args>=<val> after it, but only <test-args>, otherwise the test-args will be taken as go test's command line parameter, instead of your Test*'s
I've been attempting for the last couple of days to update unidata using sample code as a basis using .NET without success. I can read the database successfully and view the raw data within visual studio. The error reported back is a out of range error. The program is attempting to update the unit price of a purchase order.
Error:
{" Error on Socket Receive. Index was outside the bounds of the array.POD"}
[IBMU2.UODOTNET.UniFileException]: {" Error on Socket Receive. Index was outside the bounds of the array.POD"}
Data: {System.Collections.ListDictionaryInternal}
HelpLink: null
HResult: -2146232832
InnerException: null
Message: " Error on Socket Receive. Index was outside the bounds of the array.POD"
Source: "UniFile Class"
StackTrace: " at IBMU2.UODOTNET.UniFile.Write()\r\n at IBMU2.UODOTNET.UniFile.Write(String aRecordID, UniDynArray aRecordData)\r\n at ReadXlsToUnix.Form1.TestUpdate(String PO_LINE_SHIP, String price) in c:\Users\xxx\Documents\Visual Studio 2013\Projects\ReadXlsToUnix\ReadXlsToUnix\Form1.cs:line 330"
TargetSite: {Void Write()}
failing Test Code is:
private void TestUpdate(string PO_LINE_SHIP,string price)
{
UniFile pod =null;
UniSession uniSession =null;
//connection string
uniSession = UniObjects.OpenSession("unixMachine", "userid", Properties.Settings.Default.PWD, "TRAIN", "udcs");
//open file
pod = uniSession.CreateUniFile("POD");
//read data
pod.Read(PO_LINE_SHIP);
//locking strategy
pod.UniFileLockStrategy = 1;
pod.UniFileReleaseStrategy = 1;
if (pod.RecordID == ""){
pod.UnlockRecord();
}
//replace existing value with one entered by user
pod.Record.Replace(4, (string)uniSession.Iconv(price, "MD4"));
try
{
pod.Write(pod.RecordID,pod.Record); //RecordId and Record both show correctly hover/immediate window
//pod.Write() fails with same message
}
catch (Exception err)
{
MessageBox.Show("Error" + err);
}
pod.Close();
UniObjects.CloseSession(uniSession);
}
}
Running on HP UX 11.31 unidata 7.2 and using UODOTNET.dll 2.2.3.7377
Any help greatly appreciated.
This is the write record version and have also tried writefield functionality with same error.
Rajan - thanks for the update and link. I have tried unsuccessfully to read/update my unidata tables using the U2 Toolkit. I can however read/update a file I have created within the same account. Does this mean there is a missing entry somewhere VOC, DICT for example.