// Model version of a name. ie. "user" => "User"
557507
func (n Name) Model() string {
	x := strings.Split(string(n), "/")
	for i, s := range x {
		x[i] = Camelize(Singularize(s))
	}

	return strings.Join(x, "")
}
215123
func registerModel(prefix string, model interface{}) {
	val := reflect.ValueOf(model)
	ind := reflect.Indirect(val)
	typ := ind.Type()

	if val.Kind() != reflect.Ptr {
		panic(fmt.Errorf("<orm.RegisterModel> cannot use non-ptr model struct `%s`", getFullName(typ)))
	}

	table := getTableName(val)

	if prefix != "" {
		table = prefix + table
	}

	name := getFullName(typ)
	if _, ok := modelCache.getByFN(name); ok {
		fmt.Printf("<orm.RegisterModel> model `%s` repeat register, must be unique\n", name)
		os.Exit(2)
	}

	if _, ok := modelCache.get(table); ok {
		fmt.Printf("<orm.RegisterModel> table name `%s` repeat register, must be unique\n", table)
		os.Exit(2)
	}

	info := newModelInfo(val)
	if info.fields.pk == nil {
	outFor:
		for _, fi := range info.fields.fieldsDB {
			if strings.ToLower(fi.name) == "id" {
				switch fi.addrValue.Elem().Kind() {
				case reflect.Int, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint32, reflect.Uint64:
					fi.auto = true
					fi.pk = true
					info.fields.pk = fi
					break outFor
				}
			}
		}

		if info.fields.pk == nil {
			fmt.Printf("<orm.RegisterModel> `%s` need a primary key field\n", name)
			os.Exit(2)
		}

	}

	info.table = table
	info.pkg = typ.PkgPath()
	info.model = model
	info.manual = true

	modelCache.set(table, info)
}
680968
func (c *modelsCommand) getModelInfo(
	client ModelManagerAPI,
	now time.Time,
	userModels []base.UserModel,
) ([]common.ModelInfo, map[string]jujuclient.ModelDetails, error) {
	tags := make([]names.ModelTag, len(userModels))
	for i, m := range userModels {
		tags[i] = names.NewModelTag(m.UUID)
	}
	results, err := client.ModelInfo(tags)
	if err != nil {
		return nil, nil, errors.Trace(err)
	}

	info := []common.ModelInfo{}
	modelsToStore := map[string]jujuclient.ModelDetails{}
	for i, result := range results {
		if result.Error != nil {
			if params.IsCodeUnauthorized(result.Error) {
				// If we get this, then the model was removed
				// between the initial listing and the call
				// to query its details.
				continue
			}
			return nil, nil, errors.Annotatef(
				result.Error, "getting model %s (%q) info",
				userModels[i].UUID, userModels[i].Name,
			)
		}

		model, err := common.ModelInfoFromParams(*result.Result, now)
		if err != nil {
			return nil, nil, errors.Trace(err)
		}
		model.ControllerName = c.runVars.controllerName
		info = append(info, model)
		modelsToStore[model.Name] = jujuclient.ModelDetails{ModelUUID: model.UUID, ModelType: model.Type}

		if len(model.Machines) != 0 {
			c.runVars.hasMachinesCount = true
			for _, m := range model.Machines {
				if m.Cores != 0 {
					c.runVars.hasCoresCount = true
					break
				}
			}
		}
	}
	return info, modelsToStore, nil
}
1167526
func (c *Client) GrantModel(user, access string, modelUUIDs ...string) error {
	return c.modifyModelUser(params.GrantModelAccess, user, access, modelUUIDs)
}
955119
func OwnerQualifiedModelName(modelName string, owner, user names.UserTag) string {
	if owner.Id() == user.Id() {
		return modelName
	}
	return jujuclient.JoinOwnerModelName(owner, modelName)
}
924542
func SplitModelName(name string) (controller, model string) {
	if i := strings.IndexRune(name, ':'); i >= 0 {
		return name[:i], name[i+1:]
	}
	return "", name
}
71878
func (m *Model) TableName() string {
	if s, ok := m.Value.(string); ok {
		return s
	}
	if n, ok := m.Value.(TableNameAble); ok {
		return n.TableName()
	}

	if m.tableName != "" {
		return m.tableName
	}

	t := reflect.TypeOf(m.Value)
	name := m.typeName(t)

	defer tableMapMu.Unlock()
	tableMapMu.Lock()

	if tableMap[name] == "" {
		m.tableName = nflect.Tableize(name)
		tableMap[name] = m.tableName
	}
	return tableMap[name]
}
371902
func (c *ControllerAPI) AllModels() (params.UserModelList, error) {
	result := params.UserModelList{}
	if err := c.checkHasAdmin(); err != nil {
		return result, errors.Trace(err)
	}

	modelUUIDs, err := c.state.AllModelUUIDs()
	if err != nil {
		return result, errors.Trace(err)
	}
	for _, modelUUID := range modelUUIDs {
		st, err := c.statePool.Get(modelUUID)
		if err != nil {
			// This model could have been removed.
			if errors.IsNotFound(err) {
				continue
			}
			return result, errors.Trace(err)
		}
		defer st.Release()

		model, err := st.Model()
		if err != nil {
			return result, errors.Trace(err)
		}

		userModel := params.UserModel{
			Model: params.Model{
				Name:     model.Name(),
				UUID:     model.UUID(),
				Type:     string(model.Type()),
				OwnerTag: model.Owner().String(),
			},
		}

		lastConn, err := model.LastModelConnection(c.apiUser)
		if err != nil {
			if !state.IsNeverConnectedError(err) {
				return result, errors.Trace(err)
			}
		} else {
			userModel.LastConnection = &lastConn
		}

		result.UserModels = append(result.UserModels, userModel)
	}

	return result, nil
}
127459
func (conn *Conn) User(ident, name string) {
	conn.Raw(USER + " " + ident + " 12 * :" + name)
}
173031
func (c *ModelCommandBase) SetModelName(modelName string, allowDefault bool) error {
	c._modelName = modelName
	c.allowDefaultModel = allowDefault

	// After setting the model name, we may need to ensure we have access to the
	// other model details if not already done.
	if err := c.maybeInitModel(); err != nil {
		return errors.Trace(err)
	}
	return nil
}
221507
func UserName() string {
	gender := randGender()
	switch r.Intn(3) {
	case 0:
		return lookup("en", gender+"_first_names", false) + lookup(lang, gender+"_last_names", false)
	case 1:
		return Character() + lookup(lang, gender+"_last_names", false)
	default:
		return strings.Replace(WordsN(r.Intn(3)+1), " ", "_", -1)
	}
}
655398
func (s *Session) Name() string {
	if s.sessionType == apitypes.MachineSession {
		return s.identity.(*envelope.Machine).Body.Name
	}

	return s.identity.(envelope.UserInf).Name()
}
512745
func (s *LookupService) Name(ctx context.Context, resource platform.ResourceType, id platform.ID) (string, error) {
	return s.NameFn(ctx, resource, id)
}
180544
func ConvertUsernameToIdentifier(username string, usrMgr *user.Manager, valMgr *validation.Manager) (string, error) {
	userIdentifier := username
	usr, err := usrMgr.GetByName(username)
	if err != nil {
		return userIdentifier, err
	}
	// check for a validated email address
	for _, email := range usr.EmailAddresses {
		validated, err := valMgr.IsEmailAddressValidated(username, email.EmailAddress)
		if err != nil {
			return userIdentifier, err
		}
		if validated {
			return email.EmailAddress, err
		}
	}
	// try the phone numbers
	for _, phone := range usr.Phonenumbers {
		validated, err := valMgr.IsPhonenumberValidated(username, phone.Phonenumber)
		if err != nil {
			return userIdentifier, err
		}
		if validated {
			return phone.Phonenumber, err
		}
	}
	// No verified email or phone number. Fallback to username
	return userIdentifier, err
}
1085890
func (st *State) ModelUUIDsForUser(user names.UserTag) ([]string, error) {
	// Consider the controller permissions overriding Model permission, for
	// this case the only relevant one is superuser.
	// The mgo query below wont work for superuser case because it needs at
	// least one model user per model.
	access, err := st.UserAccess(user, st.controllerTag)
	if err != nil && !errors.IsNotFound(err) {
		return nil, errors.Trace(err)
	}

	var modelUUIDs []string
	if access.Access == permission.SuperuserAccess {
		var err error
		modelUUIDs, err = st.AllModelUUIDs()
		if err != nil {
			return nil, errors.Trace(err)
		}
	} else {
		// Since there are no groups at this stage, the simplest way to get all
		// the models that a particular user can see is to look through the
		// model user collection. A raw collection is required to support
		// queries across multiple models.
		modelUsers, userCloser := st.db().GetRawCollection(modelUsersC)
		defer userCloser()

		var userSlice []userAccessDoc
		err := modelUsers.Find(bson.D{{"user", user.Id()}}).Select(bson.D{{"object-uuid", 1}, {"_id", 1}}).All(&userSlice)
		if err != nil {
			return nil, err
		}
		for _, doc := range userSlice {
			modelUUIDs = append(modelUUIDs, doc.ObjectUUID)
		}
	}

	modelsColl, close := st.db().GetCollection(modelsC)
	defer close()
	query := modelsColl.Find(bson.M{
		"_id":            bson.M{"$in": modelUUIDs},
		"migration-mode": bson.M{"$ne": MigrationModeImporting},
	}).Sort("name", "owner").Select(bson.M{"_id": 1})

	var docs []bson.M
	err = query.All(&docs)
	if err != nil {
		return nil, errors.Trace(err)
	}
	out := make([]string, len(docs))
	for i, doc := range docs {
		out[i] = doc["_id"].(string)
	}
	return out, nil
}
255430
func (u *UndertakerAPI) ModelInfo() (params.UndertakerModelInfoResult, error) {
	result := params.UndertakerModelInfoResult{}
	model, err := u.st.Model()

	if err != nil {
		return result, errors.Trace(err)
	}

	result.Result = params.UndertakerModelInfo{
		UUID:       model.UUID(),
		GlobalName: model.Owner().String() + "/" + model.Name(),
		Name:       model.Name(),
		IsSystem:   u.st.IsController(),
		Life:       params.Life(model.Life().String()),
	}

	return result, nil
}
1285898
func Model() string {
	seps := []string{"", " ", "-"}
	return CharactersN(r.Intn(3)+1) + seps[r.Intn(len(seps))] + Digits()
}