Ejemplo n.º 1
0
func newConveyor(t testing.TB) *Conveyor {
	db := sqlx.MustConnect("postgres", databaseURL)
	if err := core.Reset(db); err != nil {
		t.Fatal(err)
	}

	c := core.New(db)
	c.BuildQueue = core.NewBuildQueue(100)
	c.Logger = logs.Discard

	ch := make(chan core.BuildContext)
	c.BuildQueue.Subscribe(ch)

	w := worker.New(c, worker.Options{
		Builder: builder.BuilderFunc(func(ctx context.Context, w io.Writer, options builder.BuildOptions) (string, error) {
			io.WriteString(w, "Pulling base image\n")
			return "remind101/acme-inc:1234", nil
		}),
		BuildRequests: ch,
	})

	go w.Start()

	return &Conveyor{
		Conveyor: c,
		worker:   w,
	}
}
Ejemplo n.º 2
0
func main() {
	// Connect to the database
	db := db.NewDB(sqlx.MustConnect(os.Getenv("DATABASE_KIND"), os.Getenv("DATABASE_URL")))

	// URL of the program
	// TODO: move to an external file
	urls := map[string]string{
		"reCaptchaSecret": "secrets/googleReCaptcha",
		"reCaptchaCheck":  "https://www.google.com/recaptcha/api/siteverify",
		"jwtSecret":       "secrets/jwt",
	}

	// Create the GoBox Main Server
	server, err := web.NewServer(db, urls)

	if err != nil {
		fmt.Printf("Cannot initialize server (error: %v)\n", err)
		return
	}

	port := flag.Arg(0)

	if port == "" {
		port = "8083"
	}

	// And listen
	log.Println("Server running")
	log.Println(server.ListenAndServer(":" + port))

}
Ejemplo n.º 3
0
func main() {
	var dbname, user string
	flag.StringVar(&dbname, "db", "zaymyonline", "a string var")
	flag.StringVar(&user, "user", "radex", "a string var")
	flag.Parse()
	connectStr := fmt.Sprintf("host=/run/postgresql user=%s dbname=%s sslmode=disable", user, dbname)
	fmt.Println(connectStr)
	db := sqlx.MustConnect("postgres", connectStr)
	defer db.Close()

	posts_sql := `CREATE TABLE IF NOT EXISTS posts (
	    id serial PRIMARY KEY,
	    slug varchar(200),
	    title varchar(200),
	    shortmessage text,
	    body text,
	    created timestamp DEFAULT now(),
	    modified timestamp DEFAULT now(),
	    contenttype varchar(20),
	    tags varchar(30)[],
	    categories varchar(30)[],
	    status smallint DEFAULT 0,
	    allowcomments boolean DEFAULT TRUE
	);`

	res, err := db.Exec(posts_sql)
	if err != nil {
		panic(err)
	}

	fmt.Println(res)

}
Ejemplo n.º 4
0
func MustConnect(cfg *config.Config) *DB {
	db, err := New(sqlx.MustConnect("postgres", cfg.DatabaseURL), cfg)
	if err != nil {
		panic(err)
	}
	return db
}
Ejemplo n.º 5
0
// Returns a StockDB with all  tables, panics if can't connect to db or make tables
// <requires> "$ createdb -Olocaluser trendydb", for Local
// <requires> "$ createdb -Olocaluser trendytestdb", for TestLocal
// <side effect> sets the global DB to the returned db
func (db *StockDB) Setup(env Environment) *StockDB {
	// TODO(jhurwich) implement user/pass/address switch based on local or prod environment
	var dbname, password, host, user, suffix string
	switch env {
	case Local:
		dbname = "trendydb"
		password = "******"
		host = "localhost"
		user = "******"
		suffix = "?sslmode=disable"
	case Production:
		// TODO(jhurwich) define for production environment
	case TestLocal:
		dbname = "trendytestdb"
		password = "******"
		host = "localhost"
		user = "******"
		suffix = "?sslmode=disable"
	}
	dbSource := fmt.Sprintf("postgres://%s:%s@%s/%s%s", user, password, host, dbname, suffix)

	// initialize the db, note that it's a global object, it is never closed
	db = &StockDB{*(sqlx.MustConnect("postgres", dbSource))}
	db.CreateIfNotExists()
	DB = db // not entirely sure why we need this line with the address assignment two up, but whatever
	return db
}
Ejemplo n.º 6
0
func main() {
	db := sqlx.MustConnect("sqlite3", ":memory:")

	if err := createFooTable(db); err != nil {
		log.Fatal("couldn't create table: ", err)
	}

	for i := 0; i < 10; i++ {
		id, err := insertFoo(db, "hello world "+strconv.Itoa(i))
		if err != nil {
			log.Fatal("failed to insert value: ", err)
		}
		log.Print("inserted foo record ", id)
	}

	h := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fooListEndpoint(w, r, &FooStore{db: db})
	}))
	h = handlers.LoggingHandler(os.Stdout, h)
	h = handlers.ContentTypeHandler(h, "application/json")

	http.Handle("/foo/", h)

	flag.Parse()
	log.Print("starting http server on ", *addr)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Printf("http server failed: ", err)
	}
}
Ejemplo n.º 7
0
func main() {

	db := sqlx.MustConnect("mysql", "root:root@tcp(127.0.0.1:7701)/gotraining")
	rows, err := db.Queryx("SELECT id, name, description FROM items")

	if err != nil {
		panic(err)
	}

	for rows.Next() {
		var item Item
		err = rows.StructScan(&item)

		if err != nil {
			panic(err)
		}

		fmt.Printf(
			"%d - %s:  %s\n===================\n",
			item.Id,
			item.Nme.String,
			item.Dsc.String,
		)
	}
}
Ejemplo n.º 8
0
func NewConnection() *sqlx.DB {
	dbconfig, err := config()
	if err != nil {
		log.Panic(err)
	}
	return sqlx.MustConnect(dbconfig.Driver.Name, dbconfig.Driver.OpenStr)
}
Ejemplo n.º 9
0
func main() {
	db := sqlx.MustConnect("postgres", "postgres://localhost:15432/auth_sh?sslmode=disable")
	defer db.Close()

	s := oauth.New(db)

	m := martini.Classic()
	m.Use(handlers.NoCache())
	m.Use(sessions.Sessions("auth-sh", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(render.Renderer(render.Options{Layout: "layout"}))
	m.Use(dump_request)
	m.Map(db)
	m.Map(s)

	m.Get("/login", handlers.GET_login)
	m.Get("/link", handlers.GET_link)
	m.Any("/authorize", handlers.GET_authorize)
	m.Any("/token", handlers.GET_token)
	m.Any("/info", handlers.GET_info)
	m.Get("/continue/:provider", handlers.GET_continue)
	m.Get("/logout", handlers.GET_logout)
	m.Get("/callback", handlers.GET_callback)

	m.Get("/", handlers.MayAuthenticate(), handlers.GET_home)
	m.Get("/me", handlers.MustAuthenticate(), handlers.GET_me)
	m.Get("/profile", handlers.MustAuthenticate(), handlers.GET_profile)
	m.Post("/applications", handlers.MustAuthenticate(), handlers.POST_application)

	m.Run()
}
Ejemplo n.º 10
0
func newDB(c *cli.Context) *sqlx.DB {
	db := sqlx.MustConnect("postgres", c.String("db"))
	if err := conveyor.MigrateUp(db); err != nil {
		panic(err)
	}
	return db
}
Ejemplo n.º 11
0
func main() {
	db := sqlx.MustConnect("sqlite3", ":memory:")

	if err := createFooTable(db); err != nil {
		log.Fatal("couldn't create table: ", err)
	}

	id, err := insertFoo(db, "hello world")
	if err != nil {
		log.Fatal("failed to insert value: ", err)
	}
	log.Print("inserted foo record ", id)

	foos, err := queryAllFoo(db)
	if err != nil {
		log.Fatal("failed to query all foos: ", err)
	}
	log.Printf("foos: %+v", foos)

	foo, err := querySingleFoo(db, id)
	if err != nil {
		log.Fatal("failed to query single foo: ", err)
	}
	log.Printf("found single foo: %+v", foo)
}
Ejemplo n.º 12
0
Archivo: 3do.go Proyecto: 3onyc/3do
func initDB() *sqlx.DB {
	log.Printf("Initialising database at %s...\n", *DB_URI)
	db := sqlx.MustConnect("sqlite3", *DB_URI)
	appinit.CreateDBSchema(db)

	return db
}
Ejemplo n.º 13
0
func TestAccount(t *testing.T) {
	Convey("with a database", t, func() {
		Convey("create account", func() {
			db := sqlx.MustConnect("postgres", "postgres://*****:*****@gmail.com",
				Picture:    "",
				RawProfile: []byte("{}"),
				RawToken:   []byte("{}"),
			}
			err = CreateAccount(tx, account)
			So(err, ShouldBeNil)
			So(account.Id, ShouldBeGreaterThan, 0)
		})
	})
}
Ejemplo n.º 14
0
func init() {
	models.DB = model.NewDB(sqlx.MustConnect("postgres", DSN))
	err := models.DB.Ping()
	if err != nil {
		log.Fatal(err)
	}

	log.Println("Connected to test DB.")
}
Ejemplo n.º 15
0
func Connect(addr string) *Store {
	// db := sqlx.MustConnect("pgx", addr)
	db := sqlx.MustConnect("postgres", addr)
	db.SetMaxIdleConns(4)
	db.SetMaxOpenConns(16)
	db.MapperFunc(snaker.CamelToSnake)
	dat.EnableInterpolation = true

	return &Store{db: db, ru: runner.NewDB(db.DB, "postgres")}
}
Ejemplo n.º 16
0
func newConveyor(t testing.TB) *Conveyor {
	db := sqlx.MustConnect("postgres", databaseURL)
	if err := Reset(db); err != nil {
		t.Fatal(err)
	}

	c := New(db)
	c.BuildQueue = NewBuildQueue(100)

	return c
}
Ejemplo n.º 17
0
// This method collects all the errors and submits them to Rollbar
func Database(connString string) gin.HandlerFunc {
	db := sqlx.MustConnect("mysql", connString)
	if err := RunMigrations(db); err != nil {
		panic(err)
	}

	return func(c *gin.Context) {
		c.Set(DBKey, db)
		c.Next()
	}
}
Ejemplo n.º 18
0
func InitDatabase() {
	db = sqlx.MustConnect("mysql", dbConnString)
	db.Ping()
	var check TableCheck
	err := db.Get(&check, checkIfSchemaExists)
	if err != nil {
		log.Fatalf("error connecting to the database: %v", err)
	}
	if check.DoesExist < 1 {
		db.MustExec(schema)
	}
}
Ejemplo n.º 19
0
func main() {
	db := sqlx.MustConnect("postgres", "host=/run/postgresql user=radex dbname=vsmail sslmode=disable")
	defer db.Close()

	urls := []string{
		"http://speedyspin.ru/french-junior-cadet-open-2016",
		"http://speedyspin.ru/obzor-victas-v-15-extra",
		"http://speedyspin.ru/ttsport-vperedi-planety-vsei",
		"http://speedyspin.ru/raketki-dlia-nastol-nogo-tennisa",
		"http://speedyspin.ru/nastol-nyi-tennis-video",
		"http://speedyspin.ru/itogi-goda",
		"http://speedyspin.ru/baiki-chast-1",
		"http://speedyspin.ru/baiki-chast-2",
		"http://speedyspin.ru/komandnyi-kubok-sankt-peterburga-sredi-iunoshei-i-devushek-1997-goda-rozhdeniia-i-molozhe",
		"http://speedyspin.ru/pervenstvo-sankt-peterburga-sredi-par",
		"http://speedyspin.ru/pervyi-pro-tur-vziat",
		"http://speedyspin.ru/turnir-sil-neishikh-sportsmenov-rossii-top-24-2015",
		"http://speedyspin.ru/vii-letniaia-spartakiada-uchashchikhsia-rossii-2015",
		"http://speedyspin.ru/zakryli-ligu-v",
		"http://speedyspin.ru/vania-nikulin-smog",
		"http://speedyspin.ru/pobeda-na-rodine-il-icha",
		"http://speedyspin.ru/trenerskie-sekrety",
		"http://speedyspin.ru/krasotishcha-osnovanie-stiga-emerald-i-nakladki-stiga-airoc-m",
		"http://speedyspin.ru/nagrada-nashla-geroia",
		"http://speedyspin.ru/poedinok-robota-s-olimpiiskim-chempionom",
		"http://speedyspin.ru/patsanchik-k-uspekhu-prishel",
		"http://speedyspin.ru/xv-mezhdunarodnyi-turnir-po-nastol-nomu-tennisu-pamiati-nikolaia-nikitina",
		"http://speedyspin.ru/osennie-kanikuly-2014",
		"http://speedyspin.ru/pobeda-v-podmoskov-e",
		"http://speedyspin.ru/komandnoe-pervenstvo-sankt-peterburga-sredi-iuniorov-2014",
		"http://speedyspin.ru/vse-te-zhe-vse-tam-zhe-chast-2",
		"http://speedyspin.ru/euro-minichamp-2014",
		"http://speedyspin.ru/vse-te-zhe-vse-tam-zhe",
		"http://speedyspin.ru/euro-minichamp-s-2014",
		"http://speedyspin.ru/albena-2014",
		"http://speedyspin.ru/my-luchshie-na-pervenstve-rossii",
		"http://speedyspin.ru/my-opiat-sil-ny-v-smeshannykh-parakh",
		"http://speedyspin.ru/pervenstvo-sportivnykh-shkol-sankt-peterburga",
		"http://speedyspin.ru/shestaia-letniaia-spartakiada-uchashchikhsia-rossii-2013-goda",
		"http://speedyspin.ru/shkola-olimpiiskogo-rezerva-kometa",
		"http://speedyspin.ru/diussh-2-krasnogvardeiskogo-raiona",
		"http://speedyspin.ru/diussh-2-kalininskogo-raiona",
		"http://speedyspin.ru/klub-nastol-nogo-tennisa-belye-molnii",
	}

	for _, url := range urls {
		p := Post{}
		p.Fill(url)
		id := p.New(db)
		fmt.Println(id)
	}

}
Ejemplo n.º 20
0
func main() {
	// Must.... functions will panic on fail
	db := sqlx.MustConnect("mysql", "root:root@tcp(127.0.0.1:7701)/gotraining")
	var item Item

	// We'll get most recent item and map it into our struct
	err := db.Get(&item, "SELECT * FROM items ORDER BY id DESC LIMIT 1")
	if err != nil {
		panic(err)
	}

	fmt.Printf("id: %d, %s, %s", item.Id, item.Name.String, item.Description.String)
}
Ejemplo n.º 21
0
Archivo: db.go Proyecto: alxp/deadci
// Bootstrap database
func InitDB() {
	DB = sqlx.MustConnect("sqlite3", Config.DataDir+"/deadci.sqlite")
	DB.MustExec("CREATE TABLE IF NOT EXISTS deadci " + tableDef)
	DB.MustExec("CREATE INDEX IF NOT EXISTS status_index on deadci (status)")
	DB.MustExec("CREATE INDEX IF NOT EXISTS domain_index on deadci (domain)")
	DB.MustExec("CREATE INDEX IF NOT EXISTS owner_index on deadci (domain, owner)")
	DB.MustExec("CREATE INDEX IF NOT EXISTS repo_index on deadci (domain, owner, repo)")
	DB.MustExec("CREATE INDEX IF NOT EXISTS branch_index on deadci (domain, owner, repo, branch)")
	DB.MustExec("CREATE UNIQUE INDEX IF NOT EXISTS combined_index on deadci (domain, owner, repo, branch, `commit`)")

	// Upon start-up, anything that is set to "running" should be moved to "pending"
	DB.MustExec("UPDATE deadci SET status = 'pending' WHERE status = 'running'")
}
Ejemplo n.º 22
0
func main() {

	db := sqlx.MustConnect(
		"mysql",
		"root:dev@tcp(172.19.8.101:3306)/test?parseTime=true",
	)

	// testuuid := Insert(db)

	// Select(db, testuuid.String())
	tetuint := uint64(9223372036854775826)
	SelectuInt(db, tetuint)

}
Ejemplo n.º 23
0
func BenchmarkInsertIntAuto(b *testing.B) {
	b.StopTimer()
	dbx := sqlx.MustConnect(
		"mysql",
		"root:dev@tcp(172.19.8.101:3306)/test",
	)
	_, _ = dbx.Exec("DROP TABLE IF EXISTS test_table_int")
	_, _ = dbx.Exec("CREATE TABLE IF NOT EXISTS test_table_int (`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, `time_created` INT(11) DEFAULT UNIX_TIMESTAMP(), PRIMARY KEY (`id`)) ENGINE = InnoDB AUTO_INCREMENT=9223372036854775807")
	b.StartTimer()
	// run the Fib function b.N times
	for n := 0; n < b.N; n++ {
		InsertIntAuto(dbx)
	}
}
Ejemplo n.º 24
0
func BenchmarkInsert(b *testing.B) {
	b.StopTimer()
	dbx := sqlx.MustConnect(
		"mysql",
		"root:dev@tcp(172.19.8.101:3306)/test",
	)

	_, _ = dbx.Exec("DROP TABLE IF EXISTS test_table_bin")
	_, _ = dbx.Exec("CREATE TABLE IF NOT EXISTS test_table_bin (`id` BINARY(16) NOT NULL, `time_created` INT(11) DEFAULT UNIX_TIMESTAMP(NOW()), PRIMARY KEY (`id`)) ENGINE = InnoDB")
	b.StartTimer()
	// run the Fib function b.N times
	for n := 0; n < b.N; n++ {
		InsertBin(dbx)
	}
}
Ejemplo n.º 25
0
func NewDataplane(sqlUrl string) *Dataplane {
	client := &http.Client{}
	d := &Dataplane{
		client: client,
		db:     sqlx.MustConnect("sqlite3", sqlUrl),
	}
	d.db.Exec(`
CREATE TABLE endpoints (
	ip CHAR(50)     PRIMARY KEY NOT NULL,
	tenant CHAR(40) NOT NULL,
	epg CHAR(40)    NOT NULL
);
`)
	return d
}
Ejemplo n.º 26
0
func main() {
	var item Item

	// Must.... functions will panic on fail
	db := sqlx.MustConnect("mysql", "root:root@tcp(127.0.0.1:7701)/gotraining")

	row := db.QueryRowx("SELECT * FROM items WHERE id=?", 3)
	err := row.StructScan(&item)

	if err != nil {
		panic(err)
	}

	fmt.Println(item)
}
Ejemplo n.º 27
0
func TestIdentity(t *testing.T) {
	Convey("with a database", t, func() {
		Convey("create identity", func() {
			db := sqlx.MustConnect("postgres", "postgres://localhost:15432/auth_sh?sslmode=disable")
			tx := db.MustBegin()

			defer db.Close()
			defer tx.Rollback()

			identity := &Identity{}
			err := CreateIdentity(tx, identity)
			So(err, ShouldBeNil)
			So(identity.Id, ShouldBeGreaterThan, 0)
		})
	})
}
Ejemplo n.º 28
0
func NewEnv() *Env {
	logger := NewLogger()
	renderer := render.New(render.Options{
		Layout:        "layout",
		Funcs:         []template.FuncMap{funcMap},
		IsDevelopment: true,
	})
	db := sqlx.MustConnect("sqlite3", "./holzrepublic.db")
	cookieStore := sessions.NewCookieStore([]byte(securecookie.GenerateRandomKey(128)))
	env := &Env{
		Logger:      logger,
		Datastore:   models.NewDatastore(db),
		Renderer:    renderer,
		CookieStore: cookieStore,
	}
	return env
}
Ejemplo n.º 29
0
package db

import (
	"fmt"

	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
	"github.com/samertm/sample-goji-app/conf"
)

var DB *sqlx.DB = sqlx.MustConnect("postgres", conf.Config.PostgresDataSource)

type Binder struct {
	Len   int
	Items []interface{}
}

// Returns "$b.Len".
func (b *Binder) Bind(i interface{}) string {
	b.Items = append(b.Items, i)
	b.Len++
	return fmt.Sprintf("$%d", b.Len)
}
Ejemplo n.º 30
0
const (
	DBNAME   = "jason"
	USER     = "******"
	PASSWORD = "******"
	HOST     = "localhost"
	PORT     = "5432"
	SSLMODE  = "disable"
)

var dsn = fmt.Sprintf(
	"dbname=%s user=%s password=%s host=%s port=%s sslmode=%s",
	DBNAME, USER, PASSWORD, HOST, PORT, SSLMODE,
)

var db = model.NewDB(sqlx.MustConnect("postgres", dsn))

//
// Define a TestUser model.
//

type TestUser struct {
	ID     uint64
	Name   string
	Email  string
	Weight int
}

func (_ *TestUser) TableName() string {
	return "test_users"
}