Exemple #1
0
func (t *Table) definePks(db *DB, m driver.Model) (string, error) {
	pks := t.PrimaryKeys()
	if len(pks) < 2 {
		return "", nil
	}
	pkFields := generic.Map(pks, db.QuoteIdentifier).([]string)
	return fmt.Sprintf("PRIMARY KEY(%s)", strings.Join(pkFields, ", ")), nil
}
Exemple #2
0
func (w *fsWatcher) AddPackages(pkgs []*build.Package) error {
	paths := generic.Map(pkgs, func(pkg *build.Package) string { return pkg.Dir }).([]string)
	for _, p := range paths {
		if err := w.Add(p); err != nil {
			return err
		}
	}
	return nil
}
Exemple #3
0
func (b *Backend) AddFields(db *sql.DB, m driver.Model, prevTable *sql.Table, newTable *sql.Table, fields []*sql.Field) error {
	rewrite := false
	for _, v := range fields {
		if !b.canAddField(v) {
			rewrite = true
			break
		}
	}
	if rewrite {
		name := db.QuoteIdentifier(m.Table())
		tmpName := fmt.Sprintf("%s_%s", m.Table(), stringutil.Random(8))
		quotedTmpName := db.QuoteIdentifier(tmpName)
		createSql, err := newTable.SQL(db, b, m, tmpName)
		if err != nil {
			return err
		}
		if _, err := db.Exec(createSql); err != nil {
			return err
		}
		fieldNames := generic.Map(prevTable.Fields, func(f *sql.Field) string { return f.Name }).([]string)
		// The previous table might have fields that we're not part
		// of the new table.
		fieldSet := make(map[string]bool)
		for _, v := range newTable.Fields {
			fieldSet[v.Name] = true
		}
		fieldNames = generic.Filter(fieldNames, func(n string) bool { return fieldSet[n] }).([]string)
		sqlFields := strings.Join(generic.Map(fieldNames, db.QuoteIdentifier).([]string), ", ")
		copySql := fmt.Sprintf("INSERT INTO %s (%s) SELECT %s FROM %s", quotedTmpName, sqlFields, sqlFields, name)
		if _, err := db.Exec(copySql); err != nil {
			return err
		}
		if _, err := db.Exec(fmt.Sprintf("DROP TABLE %s", name)); err != nil {
			return err
		}
		if _, err := db.Exec(fmt.Sprintf("ALTER TABLE %s RENAME TO %s", quotedTmpName, name)); err != nil {
			return err
		}
		return nil
	}
	return b.SqlBackend.AddFields(db, m, prevTable, newTable, fields)
}
Exemple #4
0
// ParseAddressList splits a comma separated list of addresses
// into multiple email addresses. The returned addresses can be
// used to call Send().
func ParseAddressList(s string) ([]string, error) {
	addrs, err := mail.ParseAddressList(s)
	if err != nil {
		return nil, err
	}
	return generic.Map(addrs, func(addr *mail.Address) string {
		if addr.Name != "" {
			return fmt.Sprintf("%s <%s>", addr.Name, addr.Address)
		}
		return addr.Address
	}).([]string), nil
}
Exemple #5
0
func newCommand(args *command.Args, opts *newOptions) error {
	var projectTmplDir string
	if envDir := os.Getenv("GONDOLA_PROJECT_TEMPLATES"); envDir != "" {
		projectTmplDir = envDir
	} else {
		// Check for updated templates
		usr, err := user.Current()
		if err != nil {
			return err
		}
		cache := filepath.Join(usr.HomeDir, ".gondola", "project-templates")
		projectTmplDir = filepath.Join(cache, "templates")
		etagFile := filepath.Join(cache, "etag")
		if err := updateTemplates(projectTmplDir, etagFile); err != nil {
			// Check if the directory exists
			if st, _ := os.Stat(projectTmplDir); st == nil || !st.IsDir() {
				return err
			}
		}
	}
	tmpls, err := LoadTemplates(projectTmplDir)
	if err != nil {
		return err
	}
	if opts.List {
		w := tabwriter.NewWriter(os.Stdout, 8, 4, 2, ' ', 0)
		for _, v := range tmpls {
			fmt.Fprintf(w, "%s:\t%s\n", v.Name, v.Description)
		}
		return w.Flush()
	}
	if len(args.Args()) == 0 {
		return errors.New("missing directory name")
	}
	var projectTmpl *Template
	for _, v := range tmpls {
		if v.Name == opts.Template {
			projectTmpl = v
			break
		}
	}
	dir := args.Args()[0]
	if projectTmpl != nil {
		return projectTmpl.ExpandInto(dir, opts.Gae)
	}
	available := generic.Map(tmpls, func(t *Template) string { return t.Name }).([]string)
	return fmt.Errorf("template %s not found, availble ones are: %s", opts.Template, strings.Join(available, ", "))
}
Exemple #6
0
func (b *SqlBackend) Inspect(db *DB, m driver.Model, schema string) (*Table, error) {
	var val int
	name := db.QuoteString(m.Table())
	s := db.QuoteString(schema)
	eq := fmt.Sprintf("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE "+
		"TABLE_NAME = %s AND TABLE_SCHEMA = %s", name, s)
	err := db.QueryRow(eq).Scan(&val)
	if err != nil {
		if err == ErrNoRows {
			return nil, nil
		}
		return nil, err
	}
	// Select fields with their types
	iq := fmt.Sprintf("SELECT COLUMN_NAME, IS_NULLABLE, DATA_TYPE, "+
		"CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS "+
		"WHERE TABLE_NAME = %s AND TABLE_SCHEMA = %s", name, s)
	rows, err := db.Query(iq)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var fields []*Field
	fieldsByName := make(map[string]*Field)
	for rows.Next() {
		var f Field
		var nullable string
		var maxLength *int
		if err := rows.Scan(&f.Name, &nullable, &f.Type, &maxLength); err != nil {
			return nil, err
		}
		if maxLength != nil {
			f.Type = fmt.Sprintf("%s (%d)", f.Type, *maxLength)
		}
		f.Type = strings.ToUpper(f.Type)
		if nullable != "YES" {
			f.AddConstraint(ConstraintNotNull)
		}
		fields = append(fields, &f)
		fieldsByName[f.Name] = &f
	}
	// Field constraints
	cq := fmt.Sprintf("SELECT C.CONSTRAINT_NAME, CONSTRAINT_TYPE, COLUMN_NAME "+
		"FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS C JOIN "+
		"INFORMATION_SCHEMA.KEY_COLUMN_USAGE K ON C.CONSTRAINT_NAME = "+
		"K.CONSTRAINT_NAME WHERE C.TABLE_NAME = %s AND K.TABLE_NAME = %s "+
		"AND C.TABLE_SCHEMA = %s", name, name, s)
	rows, err = db.Query(cq)
	if err != nil {
		return nil, err
	}
	foreignKeys := make(map[string]string)
	defer rows.Close()
	for rows.Next() {
		var constraintName string
		var constraintType string
		var name string
		if err := rows.Scan(&constraintName, &constraintType, &name); err != nil {
			return nil, err
		}
		field := fieldsByName[name]
		if field == nil {
			return nil, fmt.Errorf("table %s has constraint on non-existing field %s", m.Table(), name)
		}
		switch strings.ToLower(constraintType) {
		case "primary key":
			field.AddConstraint(ConstraintPrimaryKey)
		case "foreign key":
			foreignKeys[constraintName] = name
		case "unique":
			field.AddConstraint(ConstraintUnique)
		default:
			return nil, fmt.Errorf("unknown constraint type %s on field %s in table %s", constraintType, name, m.Table())
		}
	}
	if len(foreignKeys) > 0 {
		// Resolve FKs
		fks := strings.Join(generic.Map(generic.Keys(foreignKeys).([]string), db.QuoteString).([]string), ", ")
		fq := fmt.Sprintf("SELECT CONSTRAINT_NAME, TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE CONSTRAINT_NAME IN (%s)", fks)
		rows, err := db.Query(fq)
		if err != nil {
			return nil, err
		}
		defer rows.Close()
		for rows.Next() {
			var constraintName string
			var tableName string
			var columnName string
			if err := rows.Scan(&constraintName, &tableName, &columnName); err != nil {
				return nil, err
			}
			fieldName := foreignKeys[constraintName]
			// Field was validated previously, won't be nil
			field := fieldsByName[fieldName]
			field.Constraints = append(field.Constraints, &Constraint{Type: ConstraintForeignKey, References: MakeReference(tableName, columnName)})
		}
	}
	return &Table{Fields: fields}, nil
}
Exemple #7
0
func ExampleMap_extract_type() {
	in := []interface{}{1, 2, 3, 4}
	out := generic.Map(in, func(a interface{}) int { return a.(int) }).([]int)
	fmt.Println(out)
	// Output: [1 2 3 4]
}
Exemple #8
0
func ExampleMap_add_float() {
	in := []int{1, 2, 3, 4}
	out := generic.Map(in, func(a int) float64 { return float64(a) + 0.1 }).([]float64)
	fmt.Println(out)
	// Output: [1.1 2.1 3.1 4.1]
}
Exemple #9
0
func ExampleMap_square() {
	in := []int{1, 2, 3, 4}
	out := generic.Map(in, func(a int) int { return a * a }).([]int)
	fmt.Println(out)
	// Output: [1 4 9 16]
}