• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang pgx.Connect函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/jackc/pgx.Connect函数的典型用法代码示例。如果您正苦于以下问题:Golang Connect函数的具体用法?Golang Connect怎么用?Golang Connect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Connect函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: tableExists

func tableExists(t *testing.T, tableName string) bool {
	connConfig, err := readConfig("testdata/tern.conf")
	if err != nil {
		t.Fatal(err)
	}

	connConfig.TLSConfig = &tls.Config{InsecureSkipVerify: true}

	conn, err := pgx.Connect(*connConfig)
	if err != nil {
		connConfig.TLSConfig = nil
		conn, err = pgx.Connect(*connConfig)
	}
	if err != nil {
		t.Fatal(err)
	}
	defer conn.Close()

	var exists bool
	err = conn.QueryRow(
		"select exists(select 1 from information_schema.tables where table_catalog=$1 and table_name=$2)",
		connConfig.Database,
		tableName,
	).Scan(&exists)
	if err != nil {
		t.Fatal(err)
	}

	return exists
}
开发者ID:jackc,项目名称:tern,代码行数:30,代码来源:tern_test.go


示例2: TestConnectWithTLSFallback

func TestConnectWithTLSFallback(t *testing.T) {
	t.Parallel()

	if tlsConnConfig == nil {
		t.Skip("Skipping due to undefined tlsConnConfig")
	}

	connConfig := *tlsConnConfig
	connConfig.TLSConfig = &tls.Config{ServerName: "bogus.local"} // bogus ServerName should ensure certificate validation failure

	conn, err := pgx.Connect(connConfig)
	if err == nil {
		t.Fatal("Expected failed connection, but succeeded")
	}

	connConfig.UseFallbackTLS = true
	connConfig.FallbackTLSConfig = &tls.Config{InsecureSkipVerify: true}

	conn, err = pgx.Connect(connConfig)
	if err != nil {
		t.Fatal("Unable to establish connection: " + err.Error())
	}

	err = conn.Close()
	if err != nil {
		t.Fatal("Unable to close connection")
	}
}
开发者ID:yunhor,项目名称:pgx,代码行数:28,代码来源:conn_test.go


示例3: totalrep

func totalrep(wg *sync.WaitGroup) {
	var snapshot int64
	conn1, err := pgx.Connect(cfg1)
	checkErr(err)
	defer conn1.Close()

	conn2, err := pgx.Connect(cfg2)
	checkErr(err)
	defer conn2.Close()

	var prevSum int64 = 0

	for running {
		exec(conn1, "begin transaction")
		exec(conn2, "begin transaction")

		snapshot = execQuery(conn1, "select dtm_extend()")
		snapshot = execQuery(conn2, "select dtm_access($1)", snapshot)

		sum1 := execQuery(conn1, "select sum(v) from t")
		sum2 := execQuery(conn2, "select sum(v) from t")

		exec(conn1, "commit")
		exec(conn2, "commit")

		sum := sum1 + sum2
		if sum != prevSum {
			fmt.Printf("Total=%d snapshot=%d\n", sum, snapshot)
			prevSum = sum
		}
	}
	wg.Done()
}
开发者ID:kelvich,项目名称:pg_tsdtm,代码行数:33,代码来源:transfers.go


示例4: prepare_db

func prepare_db() {
	var snapshot int64
	var csn int64
	var gtid string = "init"

	conn1, err := pgx.Connect(cfg1)
	checkErr(err)
	defer conn1.Close()

	conn2, err := pgx.Connect(cfg2)
	checkErr(err)
	defer conn2.Close()

	exec(conn1, "drop extension if exists pg_dtm")
	exec(conn1, "create extension pg_dtm")
	exec(conn1, "drop table if exists t")
	exec(conn1, "create table t(u int primary key, v int)")

	exec(conn2, "drop extension if exists pg_dtm")
	exec(conn2, "create extension pg_dtm")
	exec(conn2, "drop table if exists t")
	exec(conn2, "create table t(u int primary key, v int)")

	exec(conn1, "begin transaction")
	exec(conn2, "begin transaction")

	snapshot = execQuery(conn1, "select dtm_extend($1)", gtid)
	snapshot = execQuery(conn2, "select dtm_access($1, $2)", snapshot, gtid)

	//for i := 0; i < N_ACCOUNTS; i++ {
	//    exec(conn1, "insert into t values($1, $2)", i, INIT_AMOUNT)
	//    exec(conn2, "insert into t values($1, $2)", i, INIT_AMOUNT)
	//}
	exec(conn1, "insert into t (select generate_series(0,$1-1), $2)", N_ACCOUNTS, 0)
	exec(conn2, "insert into t (select generate_series(0,$1-1), $2)", N_ACCOUNTS, 0)

	exec(conn1, "prepare transaction '"+gtid+"'")
	exec(conn2, "prepare transaction '"+gtid+"'")

	exec(conn1, "select dtm_begin_prepare($1)", gtid)
	exec(conn2, "select dtm_begin_prepare($1)", gtid)

	csn = execQuery(conn1, "select dtm_prepare($1, 0)", gtid)
	csn = execQuery(conn2, "select dtm_prepare($1, $2)", gtid, csn)

	exec(conn1, "select dtm_end_prepare($1, $2)", gtid, csn)
	exec(conn2, "select dtm_end_prepare($1, $2)", gtid, csn)

	exec(conn1, "commit prepared '"+gtid+"'")
	exec(conn2, "commit prepared '"+gtid+"'")
}
开发者ID:kelvich,项目名称:pg_tsdtm,代码行数:51,代码来源:transfers.go


示例5: transfer

func transfer(id int, wg *sync.WaitGroup) {
	var err error
	var snapshot int64
	var csn int64

	nGlobalTrans := 0

	conn1, err := pgx.Connect(cfg1)
	checkErr(err)
	defer conn1.Close()

	conn2, err := pgx.Connect(cfg2)
	checkErr(err)
	defer conn2.Close()

	for i := 0; i < N_ITERATIONS; i++ {

		gtid := strconv.Itoa(id) + "." + strconv.Itoa(i)
		amount := 2*rand.Intn(2) - 1
		account1 := 2*id + 1
		account2 := 2*id + 2

		exec(conn1, "begin transaction")
		exec(conn2, "begin transaction")
		snapshot = execQuery(conn1, "select dtm_extend($1)", gtid)
		snapshot = execQuery(conn2, "select dtm_access($1, $2)", snapshot, gtid)

		exec(conn1, "update t set v = v - $1 where u=$2", amount, account1)
		exec(conn2, "update t set v = v + $1 where u=$2", amount, account2)

		exec(conn1, "prepare transaction '"+gtid+"'")
		exec(conn2, "prepare transaction '"+gtid+"'")

		exec(conn1, "select dtm_begin_prepare($1)", gtid)
		exec(conn2, "select dtm_begin_prepare($1)", gtid)

		csn = execQuery(conn1, "select dtm_prepare($1, 0)", gtid)
		csn = execQuery(conn2, "select dtm_prepare($1, $2)", gtid, csn)

		exec(conn1, "select dtm_end_prepare($1, $2)", gtid, csn)
		exec(conn2, "select dtm_end_prepare($1, $2)", gtid, csn)

		exec(conn1, "commit prepared '"+gtid+"'")
		exec(conn2, "commit prepared '"+gtid+"'")
		nGlobalTrans++

	}

	fmt.Printf("Test completed, performed %d global transactions\n", nGlobalTrans)
	wg.Done()
}
开发者ID:kelvich,项目名称:pg_tsdtm,代码行数:51,代码来源:transfers.go


示例6: main

func main() {
	// get the database name as the first command-line argument
	if len(os.Args) <= 1 {
		fmt.Fprintf(os.Stderr, "Expected the name of a database as a command-line argument, but got nothing\n")
		os.Exit(1)
	}
	database_name := os.Args[1]

	pgxConfig := extractConfig()
	pgxConfig.Database = database_name

	var err error
	conn, err = pgx.Connect(pgxConfig)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to connect to the database: %v\n", err)
		os.Exit(1)
	}

	db := AnalyzeDatabase(conn)
	initiateDeepAnalysis(db.name)
	// print a bunch of stats about the database
	fmt.Printf("database name: %s\n", db.name)
	fmt.Printf("database size: %s\n", db.size)
	publicTables := selectTablesBySchema("public")
	fmt.Printf("the 'public' schema contains %d tables\n", len(publicTables))
	printTables(publicTables)
	fmt.Printf("\n-----\n")
	printTableColumns("public", publicTables)
}
开发者ID:jbranchaud,项目名称:dat,代码行数:29,代码来源:main.go


示例7: Example_OnStartMigrationProgressLogging

func Example_OnStartMigrationProgressLogging() {
	conn, err := pgx.Connect(*defaultConnectionParameters)
	if err != nil {
		fmt.Printf("Unable to establish connection: %v", err)
		return
	}

	// Clear any previous runs
	if _, err = conn.Exec("drop table if exists schema_version"); err != nil {
		fmt.Printf("Unable to drop schema_version table: %v", err)
		return
	}

	var m *migrate.Migrator
	m, err = migrate.NewMigrator(conn, "schema_version")
	if err != nil {
		fmt.Printf("Unable to create migrator: %v", err)
		return
	}

	m.OnStart = func(_ int32, name, direction, _ string) {
		fmt.Printf("Migrating %s: %s", direction, name)
	}

	m.AppendMigration("create a table", "create temporary table foo(id serial primary key)", "")

	if err = m.Migrate(); err != nil {
		fmt.Printf("Unexpected failure migrating: %v", err)
		return
	}
	// Output:
	// Migrating up: create a table
}
开发者ID:jackc,项目名称:tern,代码行数:33,代码来源:migrate_test.go


示例8: SetUpTest

func (s *MigrateSuite) SetUpTest(c *C) {
	var err error
	s.conn, err = pgx.Connect(*defaultConnectionParameters)
	c.Assert(err, IsNil)

	s.cleanupSampleMigrator(c)
}
开发者ID:jackc,项目名称:tern,代码行数:7,代码来源:migrate_test.go


示例9: prepare_master

func (t TransfersFDW) prepare_master() {
	dbconf, err := pgx.ParseDSN(cfg.ConnStrs[0])
	checkErr(err)
	conn, err := pgx.Connect(dbconf)
	checkErr(err)
	defer conn.Close()

	exec(conn, "CREATE EXTENSION postgres_fdw")

	for i, connstr := range cfg.ConnStrs[1:] {
		conf, _ := pgx.ParseDSN(connstr)
		server_sql := fmt.Sprintf(
			"CREATE SERVER dtm%d FOREIGN DATA WRAPPER postgres_fdw options(dbname '%s', host '%s', port '%d')",
			i, conf.Database, conf.Host, conf.Port)
		foreign_sql := fmt.Sprintf(
			"CREATE FOREIGN TABLE t_fdw%d() inherits (t) server dtm%d options(table_name 't')",
			i, i)
		mapping_sql := fmt.Sprintf(
			"CREATE USER MAPPING for %s SERVER dtm%d options (user '%s')",
			conf.User, i, conf.User)

		exec(conn, server_sql)
		exec(conn, foreign_sql)
		exec(conn, mapping_sql)
	}

	if dbconf.User != "" {

	}

}
开发者ID:gavioto,项目名称:postgres_cluster,代码行数:31,代码来源:transfers-fdw.go


示例10: Example_CustomType

func Example_CustomType() {
	conn, err := pgx.Connect(*defaultConnConfig)
	if err != nil {
		fmt.Printf("Unable to establish connection: %v", err)
		return
	}

	var p NullPoint
	err = conn.QueryRow("select null::point").Scan(&p)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(p)

	err = conn.QueryRow("select point(1.5,2.5)").Scan(&p)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(p)
	// Output:
	// null point
	// 1.5, 2.5
}
开发者ID:jgrossophoff,项目名称:pgx,代码行数:25,代码来源:example_custom_type_test.go


示例11: TestFatalTxError

func TestFatalTxError(t *testing.T) {
	t.Parallel()

	// Run timing sensitive test many times
	for i := 0; i < 50; i++ {
		func() {
			conn := mustConnect(t, *defaultConnConfig)
			defer closeConn(t, conn)

			otherConn, err := pgx.Connect(*defaultConnConfig)
			if err != nil {
				t.Fatalf("Unable to establish connection: %v", err)
			}
			defer otherConn.Close()

			_, err = otherConn.Exec("select pg_terminate_backend($1)", conn.Pid)
			if err != nil {
				t.Fatalf("Unable to kill backend PostgreSQL process: %v", err)
			}

			_, err = conn.Query("select 1")
			if err == nil {
				t.Fatal("Expected error but none occurred")
			}

			if conn.IsAlive() {
				t.Fatalf("Connection should not be live but was. Previous Query err: %v", err)
			}
		}()
	}
}
开发者ID:yunhor,项目名称:pgx,代码行数:31,代码来源:conn_test.go


示例12: mustConnect

func mustConnect(t testing.TB, config pgx.ConnConfig) *pgx.Conn {
	conn, err := pgx.Connect(config)
	if err != nil {
		t.Fatalf("Unable to establish connection: %v", err)
	}
	return conn
}
开发者ID:segmentio,项目名称:pgx,代码行数:7,代码来源:helper_test.go


示例13: reader

func (t TransfersFDW) reader(wg *sync.WaitGroup, cFetches chan int, inconsistency *bool) {
	var sum int64
	var prevSum int64 = 0

	dbconf, err := pgx.ParseDSN(cfg.ConnStrs[0])
	checkErr(err)
	conn, err := pgx.Connect(dbconf)
	checkErr(err)
	defer conn.Close()

	for running {
		exec(conn, "select dtm_begin_transaction()")
		exec(conn, "begin transaction isolation level "+cfg.Isolation)
		sum = execQuery64(conn, "select sum(v) from t")
		if sum != prevSum {
			fmt.Printf("Total=%d\n", sum)
			fmt.Printf("inconsistency!\n")
			*inconsistency = true
			prevSum = sum
		}
		exec(conn, "commit")
	}
	conn.Close()
	wg.Done()
}
开发者ID:gavioto,项目名称:postgres_cluster,代码行数:25,代码来源:transfers-fdw.go


示例14: Connect

func (c *Config) Connect() (*pgx.Conn, error) {
	if c.SSHConnConfig.Host != "" {
		client, err := NewSSHClient(&c.SSHConnConfig)
		if err != nil {
			return nil, err
		}

		c.ConnConfig.Dial = client.Dial
	}

	// If sslmode was set in config file or cli argument, set it in the
	// environment so we can use pgx.ParseEnvLibpq to use pgx's built-in
	// functionality.
	switch c.SslMode {
	case "disable", "allow", "prefer", "require", "verify-ca", "verify-full":
		if err := os.Setenv("PGHOST", c.ConnConfig.Host); err != nil {
			return nil, err
		}
		if err := os.Setenv("PGSSLMODE", c.SslMode); err != nil {
			return nil, err
		}

		if cc, err := pgx.ParseEnvLibpq(); err == nil {
			c.ConnConfig.TLSConfig = cc.TLSConfig
			c.ConnConfig.UseFallbackTLS = cc.UseFallbackTLS
			c.ConnConfig.FallbackTLSConfig = cc.FallbackTLSConfig
		} else {
			return nil, err
		}
	}

	return pgx.Connect(c.ConnConfig)
}
开发者ID:jackc,项目名称:tern,代码行数:33,代码来源:main.go


示例15: TestConnectCustomDialer

func TestConnectCustomDialer(t *testing.T) {
	t.Parallel()

	if customDialerConnConfig == nil {
		t.Skip("Skipping due to undefined customDialerConnConfig")
	}

	dialled := false
	conf := *customDialerConnConfig
	conf.Dial = func(network, address string) (net.Conn, error) {
		dialled = true
		return net.Dial(network, address)
	}

	conn, err := pgx.Connect(conf)
	if err != nil {
		t.Fatalf("Unable to establish connection: %s", err)
	}
	if !dialled {
		t.Fatal("Connect did not use custom dialer")
	}

	err = conn.Close()
	if err != nil {
		t.Fatal("Unable to close connection")
	}
}
开发者ID:yunhor,项目名称:pgx,代码行数:27,代码来源:conn_test.go


示例16: InitDB

func (api *Api) InitDB() {
	var err error
	api.DB, err = pgx.Connect(extractConfig())
	if err != nil {
		log.Fatalf("Got error when connect database, the error is '%v'", err)
	}
}
开发者ID:david-wilson,项目名称:go-json-rest-postgresql-example,代码行数:7,代码来源:server.go


示例17: TestStressTLSConnection

func TestStressTLSConnection(t *testing.T) {
	t.Parallel()

	if tlsConnConfig == nil {
		t.Skip("Skipping due to undefined tlsConnConfig")
	}

	if testing.Short() {
		t.Skip("Skipping due to testing -short")
	}

	conn, err := pgx.Connect(*tlsConnConfig)
	if err != nil {
		t.Fatalf("Unable to establish connection: %v", err)
	}
	defer conn.Close()

	for i := 0; i < 50; i++ {
		sql := `select * from generate_series(1, $1)`

		rows, err := conn.Query(sql, 2000000)
		if err != nil {
			t.Fatal(err)
		}

		var n int32
		for rows.Next() {
			rows.Scan(&n)
		}

		if rows.Err() != nil {
			t.Fatalf("queryCount: %d, Row number: %d. %v", i, n, rows.Err())
		}
	}
}
开发者ID:archsaber,项目名称:pgx,代码行数:35,代码来源:stress_test.go


示例18: TestConnectWithRuntimeParams

func TestConnectWithRuntimeParams(t *testing.T) {
	t.Parallel()

	connConfig := *defaultConnConfig
	connConfig.RuntimeParams = map[string]string{
		"application_name": "pgxtest",
		"search_path":      "myschema",
	}

	conn, err := pgx.Connect(connConfig)
	if err != nil {
		t.Fatalf("Unable to establish connection: %v", err)
	}
	defer conn.Close()

	var s string
	err = conn.QueryRow("show application_name").Scan(&s)
	if err != nil {
		t.Fatalf("QueryRow Scan unexpectedly failed: %v", err)
	}
	if s != "pgxtest" {
		t.Errorf("Expected application_name to be %s, but it was %s", "pgxtest", s)
	}

	err = conn.QueryRow("show search_path").Scan(&s)
	if err != nil {
		t.Fatalf("QueryRow Scan unexpectedly failed: %v", err)
	}
	if s != "myschema" {
		t.Errorf("Expected search_path to be %s, but it was %s", "myschema", s)
	}
}
开发者ID:yunhor,项目名称:pgx,代码行数:32,代码来源:conn_test.go


示例19: writer

func (t Readers) writer(id int, cCommits chan int, cAborts chan int, wg *sync.WaitGroup) {
	var updates = 0
	var conns []*pgx.Conn

	for _, connstr := range cfg.ConnStrs {
		dbconf, err := pgx.ParseDSN(connstr)
		checkErr(err)
		conn, err := pgx.Connect(dbconf)
		checkErr(err)
		defer conn.Close()
		conns = append(conns, conn)
	}
	for updates < cfg.IterNum {
		acc := rand.Intn(cfg.AccountsNum)

		if cfg.UseDtm {
			xid := execQuery(conns[0], "select dtm_begin_transaction()")
			for i := 1; i < len(conns); i++ {
				exec(conns[i], "select dtm_join_transaction($1)", xid)
			}
		}
		for _, conn := range conns {
			exec(conn, "begin transaction isolation level "+cfg.Isolation)
			exec(conn, "update t set v = v + 1 where u=$1", acc)
		}
		commit(conns...)
		updates++
	}
	// cCommits <- updates
	wg.Done()
}
开发者ID:gavioto,项目名称:postgres_cluster,代码行数:31,代码来源:readers.go


示例20: TestFatalRxError

func TestFatalRxError(t *testing.T) {
	t.Parallel()

	conn := mustConnect(t, *defaultConnConfig)
	defer closeConn(t, conn)

	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		var n int32
		var s string
		err := conn.QueryRow("select 1::int4, pg_sleep(10)::varchar").Scan(&n, &s)
		if err, ok := err.(pgx.PgError); !ok || err.Severity != "FATAL" {
			t.Fatalf("Expected QueryRow Scan to return fatal PgError, but instead received %v", err)
		}
	}()

	otherConn, err := pgx.Connect(*defaultConnConfig)
	if err != nil {
		t.Fatalf("Unable to establish connection: %v", err)
	}
	defer otherConn.Close()

	if _, err := otherConn.Exec("select pg_terminate_backend($1)", conn.Pid); err != nil {
		t.Fatalf("Unable to kill backend PostgreSQL process: %v", err)
	}

	wg.Wait()

	if conn.IsAlive() {
		t.Fatal("Connection should not be live but was")
	}
}
开发者ID:alaska,项目名称:pgx,代码行数:34,代码来源:conn_test.go



注:本文中的github.com/jackc/pgx.Connect函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang pgx.NewConnPool函数代码示例发布时间:2022-05-23
下一篇:
Golang box.Time类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap