<commit_before>// Copyright 2016 Mender Software AS
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

package mongo

import (
	"time"

	"github.com/asaskevich/govalidator"
	"github.com/mendersoftware/deployments/resources/images"
	"github.com/mendersoftware/deployments/resources/images/model"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

// Database KEYS
const (
	// Keys are corelated to field names in SoftwareImageMeta
	// and SoftwareImageMetaArtifact structures
	// Need to be kept in sync with that structure filed names
	StorageKeySoftwareImageDeviceType = "meta_yocto.device_type"
	StorageKeySoftwareImageName       = "meta.name"
	StorageKeySoftwareImageId         = "_id"
)

// Indexes
const (
	IndexUniqeNameAndDeviceTypeStr = "uniqueNameAndDeviceTypeIndex"
)

// Database
const (
	DatabaseName     = "deployment_service"
	CollectionImages = "images"
)

// SoftwareImagesStorage is a data layer for SoftwareImages based on MongoDB
// Implements model.SoftwareImagesStorage
type SoftwareImagesStorage struct {
	session *mgo.Session
}

// NewSoftwareImagesStorage new data layer object
func NewSoftwareImagesStorage(session *mgo.Session) *SoftwareImagesStorage {

	return &SoftwareImagesStorage{
		session: session,
	}
}

// IndexStorage set required indexes.
// * Set unique index on name-model image keys.
func (i *SoftwareImagesStorage) IndexStorage() error {

	session := i.session.Copy()
	defer session.Close()

	uniqueNameVersionIndex := mgo.Index{
		Key:    []string{StorageKeySoftwareImageName, StorageKeySoftwareImageDeviceType},
		Unique: true,
		Name:   IndexUniqeNameAndDeviceTypeStr,
		// Build index upfront - make sure this index is allways on.
		Background: false,
	}

	return session.DB(DatabaseName).C(CollectionImages).EnsureIndex(uniqueNameVersionIndex)
}

// Exists checks if object with ID exists
func (i *SoftwareImagesStorage) Exists(id string) (bool, error) {

	if govalidator.IsNull(id) {
		return false, model.ErrSoftwareImagesStorageInvalidID
	}

	session := i.session.Copy()
	defer session.Close()

	var image *images.SoftwareImage
	if err := session.DB(DatabaseName).C(CollectionImages).FindId(id).One(&image); err != nil {
		if err.Error() == mgo.ErrNotFound.Error() {
			return false, nil
		}
		return false, err
	}

	return true, nil
}

// Update proviced SoftwareImage
// Return false if not found
func (i *SoftwareImagesStorage) Update(image *images.SoftwareImage) (bool, error) {

	if err := image.Validate(); err != nil {
		return false, err
	}

	session := i.session.Copy()
	defer session.Close()

	image.SetModified(time.Now())
	if err := session.DB(DatabaseName).C(CollectionImages).UpdateId(image.Id, image); err != nil {
		if err.Error() == mgo.ErrNotFound.Error() {
			return false, nil
		}
		return false, err
	}

	return true, nil
}

// ImageByNameAndDeviceType find image with speficied application name and targed device type
func (i *SoftwareImagesStorage) ImageByNameAndDeviceType(name, deviceType string) (*images.SoftwareImage, error) {

	if govalidator.IsNull(name) {
		return nil, model.ErrSoftwareImagesStorageInvalidName

	}

	if govalidator.IsNull(deviceType) {
		return nil, model.ErrSoftwareImagesStorageInvalidDeviceType
	}

	// equal to device type & software version (application name + version)
	query := bson.M{
		StorageKeySoftwareImageDeviceType: deviceType,
		StorageKeySoftwareImageName:       name,
	}

	session := i.session.Copy()<commit_msg>images/mongo: handle the artifact's 'device_types_compatible' fields<commit_after>// Copyright 2016 Mender Software AS
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

package mongo

import (
	"time"

	"github.com/asaskevich/govalidator"
	"github.com/mendersoftware/deployments/resources/images"
	"github.com/mendersoftware/deployments/resources/images/model"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

// Database KEYS
const (
	// Keys are corelated to field names in SoftwareImageMeta
	// and SoftwareImageMetaArtifact structures
	// Need to be kept in sync with that structure filed names
	StorageKeySoftwareImageDeviceTypes = "meta_yocto.device_types_compatible"
	StorageKeySoftwareImageName        = "meta.name"
	StorageKeySoftwareImageId          = "_id"
)

// Indexes
const (
	IndexUniqeNameAndDeviceTypeStr = "uniqueNameAndDeviceTypeIndex"
)

// Database
const (
	DatabaseName     = "deployment_service"
	CollectionImages = "images"
)

// SoftwareImagesStorage is a data layer for SoftwareImages based on MongoDB
// Implements model.SoftwareImagesStorage
type SoftwareImagesStorage struct {
	session *mgo.Session
}

// NewSoftwareImagesStorage new data layer object
func NewSoftwareImagesStorage(session *mgo.Session) *SoftwareImagesStorage {

	return &SoftwareImagesStorage{
		session: session,
	}
}

// IndexStorage set required indexes.
// * Set unique index on name-model image keys.
func (i *SoftwareImagesStorage) IndexStorage() error {

	session := i.session.Copy()
	defer session.Close()

	uniqueNameVersionIndex := mgo.Index{
		Key:    []string{StorageKeySoftwareImageName, StorageKeySoftwareImageDeviceTypes},
		Unique: true,
		Name:   IndexUniqeNameAndDeviceTypeStr,
		// Build index upfront - make sure this index is allways on.
		Background: false,
	}

	return session.DB(DatabaseName).C(CollectionImages).EnsureIndex(uniqueNameVersionIndex)
}

// Exists checks if object with ID exists
func (i *SoftwareImagesStorage) Exists(id string) (bool, error) {

	if govalidator.IsNull(id) {
		return false, model.ErrSoftwareImagesStorageInvalidID
	}

	session := i.session.Copy()
	defer session.Close()

	var image *images.SoftwareImage
	if err := session.DB(DatabaseName).C(CollectionImages).FindId(id).One(&image); err != nil {
		if err.Error() == mgo.ErrNotFound.Error() {
			return false, nil
		}
		return false, err
	}

	return true, nil
}

// Update proviced SoftwareImage
// Return false if not found
func (i *SoftwareImagesStorage) Update(image *images.SoftwareImage) (bool, error) {

	if err := image.Validate(); err != nil {
		return false, err
	}

	session := i.session.Copy()
	defer session.Close()

	image.SetModified(time.Now())
	if err := session.DB(DatabaseName).C(CollectionImages).UpdateId(image.Id, image); err != nil {
		if err.Error() == mgo.ErrNotFound.Error() {
			return false, nil
		}
		return false, err
	}

	return true, nil
}

// ImageByNameAndDeviceType find image with speficied application name and targed device type
func (i *SoftwareImagesStorage) ImageByNameAndDeviceType(name, deviceType string) (*images.SoftwareImage, error) {

	if govalidator.IsNull(name) {
		return nil, model.ErrSoftwareImagesStorageInvalidName

	}

	if govalidator.IsNull(deviceType) {
		return nil, model.ErrSoftwareImagesStorageInvalidDeviceType
	}

	// equal to device type & software version (application name + version)
	query := bson.M{
		StorageKeySoftwareImageDeviceTypes: deviceType,
		StorageKeySoftwareImageName:        name,
	}

	session := i.session.Copy()
{'fraction_non_alphanumeric': 0.09853511956930011, 'fraction_numerical': 0.0025040691123074995, 'mean_word_length': 4.255263157894737, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2992731', 'n_tokens_mistral': 2477, 'n_tokens_neox': 2356, 'n_words': 688}