Class: Visor::Meta::Backends::MySQL

Inherits:
Base
  • Object
show all
Includes:
Common::Exception
Defined in:
lib/meta/backends/mysql_db.rb

Overview

The MySQL Backend for the VISoR Meta.

Constant Summary collapse

DEFAULT_DB =

Connection constants

Default MySQL database

'visor'
DEFAULT_HOST =

Default MySQL host address

'127.0.0.1'
DEFAULT_PORT =

Default MySQL host port

3306
DEFAULT_USER =

Default MySQL user

'visor'
DEFAULT_PASSWORD =

Default MySQL password

'passwd'

Constants inherited from Base

Base::ACCESS, Base::ALL, Base::ARCHITECTURE, Base::BRIEF, Base::DETAIL_EXC, Base::FILTERS, Base::FORMAT, Base::MANDATORY, Base::OPTIONAL, Base::READONLY, Base::STATUS, Base::STORE, Base::TYPE

Instance Attribute Summary

Attributes inherited from Base

#conn, #db, #host, #password, #port, #user

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#build_uri, #deserialize_others, #serialize_others, #set_protected_post, #set_protected_put, #string_time_or_hash?, #to_sql_insert, #to_sql_update, #to_sql_where, #validate_data_post, #validate_data_put, #validate_query_filters

Constructor Details

#initialize(opts) ⇒ MySQL

Returns a new instance of MySQL.



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/meta/backends/mysql_db.rb', line 55

def initialize(opts)
  super opts
  @conn = connection
  @conn.query %[
  CREATE TABLE IF NOT EXISTS `#{opts[:db]}`.`images` (
    `_id` VARCHAR(45) NOT NULL ,
    `uri` VARCHAR(255) NULL ,
    `name` VARCHAR(45) NOT NULL ,
    `architecture` VARCHAR(45) NOT NULL ,
    `access` VARCHAR(45) NOT NULL ,
    `type` VARCHAR(45) NULL ,
    `format` VARCHAR(45) NULL ,
    `store` VARCHAR(45) NULL ,
    `location` VARCHAR(255) NULL ,
    `kernel` VARCHAR(45) NULL ,
    `ramdisk` VARCHAR(45) NULL ,
    `owner` VARCHAR(45) NULL ,
    `status` VARCHAR(45) NULL ,
    `size` INT NULL ,
    `created_at` DATETIME NULL ,
    `uploaded_at` DATETIME NULL ,
    `updated_at` DATETIME NULL ,
    `accessed_at` DATETIME NULL ,
    `access_count` INT NULL DEFAULT 0 ,
    `checksum` VARCHAR(255) NULL ,
    `others` VARCHAR(255) NULL,
    PRIMARY KEY (`_id`) )
    ENGINE = InnoDB;
  ]
end

Class Method Details

.connect(opts = {}) ⇒ Object

Initializes a MongoDB Backend instance.

Parameters:

  • [Hash] (Hash)

    a customizable set of options

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :uri (String)

    The connection uri, if provided, no other option needs to be setted.

  • :db (String) — default: DEFAULT_DB

    The wanted database.

  • :host (String) — default: DEFAULT_HOST

    The host address.

  • :port (Integer) — default: DEFAULT_PORT

    The port to be used.

  • :user (String) — default: DEFAULT_USER

    The user to be used.

  • :password (String) — default: DEFAULT_PASSWORD

    The password to be used.

  • :conn (Object)

    The connection pool to access database.



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/meta/backends/mysql_db.rb', line 43

def self.connect(opts = {})
  opts[:uri]      ||= ''
  uri             = URI.parse(opts[:uri])
  opts[:db]       = uri.path ? uri.path.gsub('/', '') : DEFAULT_DB
  opts[:host]     = uri.host || DEFAULT_HOST
  opts[:port]     = uri.port || DEFAULT_PORT
  opts[:user]     = uri.user || DEFAULT_USER
  opts[:password] = uri.password || DEFAULT_PASSWORD

  self.new opts
end

Instance Method Details

#connectionMysql2::Client

Establishes and returns a MySQL database connection and creates Images table if it does not exists.

Returns:

  • (Mysql2::Client)

    It returns a database client object.



91
92
93
94
# File 'lib/meta/backends/mysql_db.rb', line 91

def connection
  Mysql2::Client.new(host:     @host, port: @port, database: @db,
                     username: @user, password: @password)
end

#delete_all!Object

Delete all images records.



162
163
164
# File 'lib/meta/backends/mysql_db.rb', line 162

def delete_all!
  @conn.query "DELETE FROM images"
end

#delete_image(id) ⇒ Hash

Delete an image record.

Parameters:

  • id (String)

    The image’s _id to remove.

Returns:

  • (Hash)

    The deleted image metadata.

Raises:

  • (NotFound)

    If image not found.



152
153
154
155
156
157
158
# File 'lib/meta/backends/mysql_db.rb', line 152

def delete_image(id)
  meta = @conn.query("SELECT * FROM images WHERE _id='#{id}'", symbolize_keys: true).first
  raise NotFound, "No image found with id '#{id}'." if meta.nil?

  @conn.query "DELETE FROM images WHERE _id='#{id}'"
  meta
end

#get_image(id, pass_timestamps = false) ⇒ Hash

Returns the requested image metadata.

Parameters:

  • id (String)

    The requested image’s _id.

Returns:

  • (Hash)

    The requested image metadata.

Raises:

  • (NotFound)

    If image not found.



104
105
106
107
108
109
110
111
112
# File 'lib/meta/backends/mysql_db.rb', line 104

def get_image(id, pass_timestamps = false)
  meta = @conn.query("SELECT * FROM images WHERE _id='#{id}'", symbolize_keys: true).first
  raise NotFound, "No image found with id '#{id}'." if meta.nil?

  set_protected_get(id) unless pass_timestamps

  exclude(meta)
  meta
end

#get_public_images(brief = false, filters = {}) ⇒ Array

Returns an array with the public images metadata.

Parameters:

  • brief (true, false) (defaults to: false)

    (false) If true, the returned images will only contain BRIEF attributes.

  • [Hash] (Hash)

    a customizable set of options

  • opts (Hash)

    a customizable set of options

Returns:

  • (Array)

    The public images metadata.

Raises:

  • (NotFound)

    If there is no public images.



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/meta/backends/mysql_db.rb', line 128

def get_public_images(brief = false, filters = {})
  validate_query_filters filters unless filters.empty?

  sort   = [(filters.delete(:sort) || '_id'), (filters.delete(:dir) || 'asc')]
  filters.merge!({access: 'public'}) unless filters[:owner]
  fields = brief ? BRIEF.join(', ') : '*'

  pub = @conn.query("SELECT #{fields} FROM images WHERE #{to_sql_where(filters)}
                          ORDER BY #{sort[0]} #{sort[1]}", symbolize_keys: true).to_a

  raise NotFound, "No public images found." if pub.empty? && filters.empty?
  raise NotFound, "No public images found with given parameters." if pub.empty?
  pub.each { |meta| exclude(meta) } if fields == '*'
  pub
end

#post_image(meta, opts = {}) ⇒ Hash

Create a new image record for the given metadata.

Parameters:

  • meta (Hash)

    The metadata.

  • [Hash] (Hash)

    a customizable set of options

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :owner (String) — default: Nil

    The owner of the image.

  • :size (Integer) — default: Nil

    The image file size.

Returns:

  • (Hash)

    The already inserted image metadata.

Raises:

  • (Invalid)

    If image meta validation fails.



177
178
179
180
181
182
183
184
185
186
# File 'lib/meta/backends/mysql_db.rb', line 177

def post_image(meta, opts = {})
  validate_data_post meta

  set_protected_post meta, opts
  serialize_others(meta)

  keys_values = to_sql_insert(meta)
  @conn.query "INSERT INTO images #{keys_values[0]} VALUES #{keys_values[1]}"
  self.get_image(meta[:_id], true)
end

#put_image(id, update) ⇒ Hash

Update an image’s metadata.

Parameters:

  • id (String)

    The image _id to update.

  • update (Hash)

    The image metadata to update.

Returns:

  • (Hash)

    The updated image metadata.

Raises:

  • (Invalid)

    If update metadata validation fails.

  • (NotFound)

    If image not found.



197
198
199
200
201
202
203
204
205
206
207
# File 'lib/meta/backends/mysql_db.rb', line 197

def put_image(id, update)
  validate_data_put update
  img  = @conn.query("SELECT * FROM images WHERE _id='#{id}'", symbolize_keys: true).first
  raise NotFound, "No image found with id '#{id}'." if img.nil?

  set_protected_put update
  serialize_others(update)

  @conn.query "UPDATE images SET #{to_sql_update(update)} WHERE _id='#{id}'"
  self.get_image(id, true)
end