示例#1
0
func TestMeta(t *testing.T) {
	var spec = "user=postgres host=" + CONF.Host + " port=" + CONF.Port + " dbname=" + CONF.Database + " sslmode=disable"
	fmt.Println(spec)
	conn, err := sql.Open("postgres", spec)
	if err != nil {
		t.Errorf("error: %v", err)
	}
	defer conn.Close()

	_, err = conn.Exec(CREATE)
	if err != nil {
		t.Errorf("error: %v", err)
	}

	stmt, err := conn.Prepare(main.SELECT_TABLE_META)
	if err != nil {
		t.Errorf("error: %v", err)
	}
	defer stmt.Close()

	row, err := stmt.Query("test01")
	if err != nil {
		t.Errorf("error: %v", err)
	}
	var m meta.ColumnMeta
	var n, tt, mm string
	for row.Next() {
		row.Scan(&n, &tt, &mm)
		m = meta.NewColumnMeta(n, tt, mm, "")
		if n == "col01" {
			break
		}

	}

	if m.Name != "col01" {
		t.Errorf("m.Name=%v, expected=%v", m.Name, "col01")
	} else if m.Type != "int8" {
		t.Errorf("m.Type=%v, expected=%v", m.Type, "int8")
	} else if m.GoType != "*int64" {
		t.Errorf("m.GoType=%v, expected=%v", m.GoType, "*int64")
	}

	row.Close()

}
示例#2
0
func doExport() {
	//	fmt.Printf("%v:%v, %v\n", c.Host, c.Port, c.Database)

	var spec = "user=postgres host=" + c.Host + " port=" + c.Port + " dbname=" + c.Database + " sslmode=disable"
	//	fmt.Println(spec)

	conn, err := sql.Open("postgres", spec)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	defer conn.Close()
	conn.SetMaxOpenConns(10)

	rows, err := conn.Query(SELECT_TABLE_NAMES)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	defer rows.Close()

	fmt.Println(HEADER)

	var tables []meta.TableMeta
	var table_name string
	for rows.Next() {
		rows.Scan(&table_name)
		//		fmt.Printf("table=%v\n", table_name)
		tbl := meta.NewTableMeta(table_name)
		tables = append(tables, tbl)
	}
	rows.Close()

	stmt, err := conn.Prepare(SELECT_PRIMARY_KEY)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	defer stmt.Close()

	st2, err := conn.Prepare(SELECT_TABLE_META)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	defer st2.Close()

	for _, tb := range tables {

		row, err := stmt.Query(tb.TableName)
		if err != nil {
			log.Fatalf("error: %v", err)
		}
		var pk string
		for row.Next() {
			row.Scan(&pk)
			break
		}
		row.Close()

		rw2, err := st2.Query(tb.TableName)
		if err != nil {
			log.Fatalf("error: %v", err)
		}

		var n string
		var t string
		var m string
		for rw2.Next() {
			rw2.Scan(&n, &t, &m)
			cm := meta.NewColumnMeta(n, t, m, pk)
			tb.Columns = append(tb.Columns, cm)
		}
		rw2.Close()

		var buf bytes.Buffer
		tb.Export(&buf)
		fmt.Println(buf.String())
	}
}