장 성훈

장 성훈

1611721980

제품판매웹앱 구현 - 07.DB 테이블 설계하기

제품판매웹앱 구현 - 07.DB 테이블 설계하기

#database

What is GEEK

Buddha Community

제품판매웹앱 구현 - 07.DB 테이블 설계하기
장 성훈

장 성훈

1611721980

제품판매웹앱 구현 - 07.DB 테이블 설계하기

제품판매웹앱 구현 - 07.DB 테이블 설계하기

#database

Anissa  Barrows

Anissa Barrows

1659741540

ActiveMocker: Creates Stub Classes From any ActiveRecord Model - Ruby

ActiveMocker  

Description

Creates stub classes from any ActiveRecord model.

By using stubs in your tests you don't need to load Rails or the database, sometimes resulting in a 10x speed improvement.

ActiveMocker analyzes the methods and database columns to generate a Ruby class file.

The stub file can be run standalone and comes included with many useful parts of ActiveRecord.

Stubbed out methods contain their original argument signatures or ActiveMocker's friendly code can be brought over in its entirety.

Mocks are regenerated when the schema is modified so your mocks won't go stale, preventing the case where your unit tests pass but production code fails.

Examples from a real app

    Finished in 1 seconds
    374 examples, 0 failures

Around the web

"Mocking ActiveRecord with ActiveMocker" by Envy


Documentation

rdoc


Contact

Ask a question in the chat room.


Installation

Add this line to your application's Gemfile:

group :development, :test do
  gem 'active_mocker'
end

It needs to be in development as well as test groups, as the development environment is where mocks will be generated. Then execute:

$ bundle

Or install it yourself as:

$ gem install active_mocker

Dependencies

  • Tested with Rails 4.x, 5.x, 6.x
  • Requires Ruby MRI >= 2.4.x

Setup

See example_rails_app for complete setup.

Generate Mocks

Running this rake task builds/rebuilds the mocks. It will be ran automatically after every schema modification. If the model changes, this rake task needs to be called manually. You could add a file watcher for when your models change and have it run the rake task.

rake active_mocker:build

Usage

#db/schema.rb

ActiveRecord::Schema.define(version: 20140327205359) do

  create_table "people", force: true do |t|
    t.integer  "account_id"
    t.string   "first_name",        limit: 128
    t.string   "last_name",         limit: 128
    t.string   "address",           limit: 200
    t.string   "city",              limit: 100
  end

end

#app/models/person.rb

class Person < ActiveRecord::Base
  belongs_to :account

  def self.bar(name, type=nil)
    puts name
  end

end

Using With Rspec, --tag active_mocker:true

require 'rspec'
require 'active_mocker/rspec_helper'
require 'spec/mocks/person_mock'
require 'spec/mocks/account_mock'

describe 'Example', active_mocker:true do

  before do
    Person.create # stubbed for PersonMock.create
  end

end

  • Assigning the tag active_mocker:true will stub any ActiveRecord model Constants for Mock classes in an it or a before/after(:each). This removes any need for dependency injection. Write tests and code like you would normally.
  • To stub any Constants in before(:all), after(:all) use active_mocker.find('ClassName').
  • Mock state will be cleaned up for you in an after(:all). To clean state by yourself, use active_mocker.delete_all.

Person.column_names
  => ["id", "account_id", "first_name", "last_name", "address", "city"]

person = Person.new( first_name:  "Dustin", 
                     last_name:   "Zeisler", 
                     account:      Account.new )
  => "#<PersonMock id: nil, account_id: nil, first_name: "Dustin", last_name: "Zeisler", address: nil, city: nil>"

person.first_name
  => "Dustin"

When schema.rb changes, the mock fails

(After rake db:migrate is called the mocks will be regenerated.)

#db/schema.rb

ActiveRecord::Schema.define(version: 20140327205359) do

  create_table "people", force: true do |t|
    t.integer  "account_id"
    t.string   "f_name",        limit: 128
    t.string   "l_name",        limit: 128
    t.string   "address",       limit: 200
    t.string   "city",          limit: 100
  end

end

Person.new(first_name: "Dustin", last_name: "Zeisler")
  =>#<UnknownAttributeError unknown attribute: first_name >

Creating Custom collections

If you want to create a custom set of records that is not part of the global collection for model. (ie. for stubbing in a test)

User::ScopeRelation.new([User.new, User.new])

This gives the full query API (ie. find_by, where, etc).

This is not a feature available in ActiveRecord, so do not include this where you intend to swap for ActiveRecord.

Optional Features

Use theses defaults if you are starting fresh

ActiveMocker::LoadedMocks.features.enable(:timestamps)
ActiveMocker::LoadedMocks.features.enable(:delete_all_before_example)
ActiveMocker::LoadedMocks.features.enable(:stub_active_record_exceptions)

timestamps

Enables created_at and updated_at to be updated on save and create

delete_all_before_example

When using "active_mocker/rspec_helper", it deletes all records from all mocks before each example.

stub_active_record_exceptions

When requiring "active_mocker/rspec_helper", and adding active_mocker: true to the describe metadata, these errors will be auto stubbed:

  • ActiveRecord::RecordNotFound
  • ActiveRecord::RecordNotUnique
  • ActiveRecord::UnknownAttributeError

Copy over Mock safe methods into the generated mock

Adding the comment ActiveMocker.safe_methods at the top of a class marks it as safe to copy to the mock. Be careful. It should not contain anything that ActiveMocker cannot run.

# ActiveMocker.safe_methods(scopes: [], instance_methods: [:full_name], class_methods: [])
class User
  def full_name
    "#{first_name} + #{last_name}"
  end
end

Mocking Methods

Rspec 3 Mocks - verify double

Verifying doubles is a stricter alternative to normal doubles that provides guarantees about what is being verified. When using verifying doubles, RSpec will check if the methods being stubbed are actually present on the underlying object if it is available. rspec-mocks/docs/verifying-doubles

RSpec.configure do |config|
  config.mock_framework = :rspec
  config.mock_with :rspec do |mocks|
    mocks.verify_doubled_constant_names = true
    mocks.verify_partial_doubles = true
  end
end
Person.bar('baz')
  => NotImplementedError: ::bar is not Implemented for Class :PersonMock. To continue stub the method.

allow(Person).to receive(:bar) do |name, type=nil|
  "Now implemented with #{name} and #{type}"
end

Person.bar('foo', 'type')
=> "Now implemented with foo and type"

When the model changes, the mock fails

(Requires a regeneration of the mocks files.)

#app/models/person.rb

class Person < ActiveRecord::Base
  belongs_to :account

  def self.bar(name)
    puts name
  end

end

Person.bar('foo', 'type')
  => ArgumentError: wrong number of arguments (2 for 1)

#app/models/person.rb

class Person < ActiveRecord::Base
  belongs_to :account

  def self.foo(name, type=nil)
    puts name
  end

end

allow(Person).to receive(:bar) do |name, type=nil|
  "Now implemented with #{name} and #{type}"
end
=> RSpec::Mocks::MockExpectationError: PersonMock does not implement: bar

Constants and Modules

  • Any locally defined modules will not be included or extended. It can be disabled by ActiveMocker::Config.disable_modules_and_constants = true

class Person < ActiveRecord::Base
  CONSTANT_VALUE = 13
end

PersonMock::CONSTANT_VALUE
  => 13

Scoped Methods

  • Any chained scoped methods will be available when the mock file that defines it is required. When called, it raises a NotImplementedError. Stub the method with a value to continue.

Managing Mocks

require "active_mocker/rspec_helper"

active_mocker.delete_all # Delete all records from loaded mocks

active_mocker.find("User") # Find a mock by model name. Useful in before(:all)/after(:all) where automatic constant stubbing is unavailable.

active_mocker.mocks.except("User").delete_all # Delete all loaded mock expect the User mock.

ActiveRecord supported methods

See Documentation for a complete list of methods and usage.

Class Methods - docs

  • new
  • create/create!
  • column_names/attribute_names
  • delete_all/destroy_all
  • table_name
  • slice
  • alias_attributes

Query Methods - docs

  • all
  • find
  • find_by/find_by!
  • find_or_create_by
  • find_or_initialize_by
  • where(conditions_hash)
  • where(key: array_of_values)
  • where.not(conditions_hash)
  • delete_all/destroy_all
  • delete_all(conditions_hash)
  • destroy(id)/delete(id)
  • update_all
  • update(id, attributes)
  • count
  • uniq
  • first/last
  • average(:field_name)
  • minimum(:field_name)
  • maximum(:field_name)
  • sum(:field_name)
  • order(:field_name)
  • reverse_order
  • limit
  • none

Relation Methods - docs

  • concat
  • include
  • push
  • clear
  • take
  • empty?
  • replace
  • any?
  • many?

instance methods - docs

  • attributes
  • update
  • save/save!
  • write_attribute/read_attribute
  • delete
  • new_record?
  • persisted?
  • reload
  • attribute_names
  • attribute_present?
  • has_attribute?
  • slice
  • attribute_alias?
  • alias_attributes
  • touch

has_one/belongs_to/has_many

  • build_< association >
  • create_< association >
  • create_< association >!
  • < association >.create
  • < association >.build

Schema/Migration Option Support

  • A db/schema.rb is not required.
  • All schema types are supported and coerced by Virtus. If coercion fails, the passed value will be retained.
  • Default value is supported.
  • Scale and Precision are not supported.

Known Limitations

  • Namespaced modules are not currently supported.
  • When an association is set in one object it may not always be reflective in other objects, especially when it is a non standard/custom association. See test_rails_4_app/spec/active_record_compatible_api.rb for a complete list of supported associations.
  • Validation/Callbacks are not supported.
  • Sql queries, joins, etc will never be supported.
  • A record that has been created and then is modified will persist changes without calling #save. Beware of this difference.
  • This is not a full replacement for ActiveRecord.
  • Primary key will always default to id. If this is causing a problem, feel free to open an issue (or even better, a PR =)).

Inspiration

Thanks to Jeff Olfert for being my original inspiration for this project.

Contributing

Your contributions are welcome!

  1. Fork it ( http://github.com/zeisler/active_mocker/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Author: zeisler
Source code: https://github.com/zeisler/active_mocker
License: MIT license

#ruby 

Ikram Mihan

Ikram Mihan

1582683309

An Overview of Azure Cosmos DB

In this article, we will discuss Azure Cosmos DB. We will answer questions such as: What is a Cosmos DB? Why do we need to use the Cosmos DB? We will also learn how to create a new Azure Cosmos DB account using Azure subscriptions, how to create a new database and collection using Azure, and how to add data to the collection.

In this article, we will see the following,

  • What is Azure Cosmos DB?
  • Why do we need to use the Cosmos DB?
  • How to create a new Azure Cosmos DB account using Azure
  • How to create a new database and collection using Azure
  • How to add data to the collection using Data Explorer
  • How to use SQL Query to the collection using Data Explorer
  • How to get Cosmos DB connection string from Azure

Prerequisite

  • Azure Subscriptions

What is Azure Cosmos DB?

Azure Cosmos DB is a globally distributed database service. It supports multi-model approaches such as the document, Key/Value, wide columns and graph databases using APIs.

The list of APIs such as the following:

  • SQL API
  • MongoDB API
  • Graph API
  • Table API
  • Cassandra API

Why do we need to use the Cosmos DB?

Azure Cosmos DB is offering the following items:

  • Global distributions
  • Elastic scale out
  • Guaranteed low latency
  • Five consistency models
  • Comprehensive SLAs

How to create a new Azure Cosmos DB account using Azure

You can learn in this section, how to create a new Azure cosmos database account using the Azure portal with the following guidelines.

Go to open the new browser, you can copy and paste the following URL

https://portal.azure.com/

Then, sign in to the Azure portal using Microsoft Account credentials:

This is image title

After successfully logging into the Azure portal, you can see the dashboard looks like the following screenshot.

This is image title

You can go to create a resource-Databases - click the Azure Cosmos DB.

This is image title

The Azure Cosmos DB new account window will be opened and you can enter the following details, which are required. Then, click the Create button.

ID
API
Subscription Name
Resource Group Name
Location

The list of API options is available in the following screenshot:

This is image title

This is image title

Now, you can see the notification window displaying the deployment in progress notification. Once it is completed you will get the deployment succeeded notification in the notification window. Then, click the go to resource button.

This is image title

This is image title

After successfully creating the Azure Cosmos DB account, the Congratulations! Your Azure Cosmos DB account was created window will be opened, as in the following screenshot.

This is image title

How to create a new database and collection using Azure

You will learn in this section, how to create a new database and collection in Data Explorer using Azure portal.

You can go to Data Explorer - click the New Collections

This is image title

The Add Collection window will be opened and you can enter the following details, which are required. Then, click the OK button.

  • Database Id
  • Collection Id
  • Storage Capacity
  • Throughput

This is image title

You can see the new database and collection looks at the following screenshot.

This is image title

How to add data to the collection using Data Explorer

You can learn in this section, how to add sample data to the collection in Data Explorer using Azure portal at the following guidelines.

You can go to Data Explorer - Expand the Table collection in the Collection window, click the Documents - click the New Document.

This is image title

The new document window will be opened and add the data to the collection with the following format.

This is image title

{  
   “Id”: “1”,  
   “TableName”: “Table A”,  
   “Location”: “Front Row”,  
   “Status”: “Available”,  
   “Date”: “28-02-2018”  
}  

Once you have added json data to the document, click the Save button.

This is image title

After successfully added records to the collection it looks like the following screenshot:

This is image title

How to add SQL Query to the collection using Data Explorer

You can learn in this section, how to use SQL query to the collection in Data Explorer using Azure portal at the following guidelines.

You can go to Data Explorer - Expand the Table collection in the Collection window, click the New SQL Query

This is image title

The Query window will be opened as in the below screenshot

This is image title

Once you have executed query by clicking Execute Query button:

This is image title

You can use the Where condition and Order By for the select statement on SQL Query window in the Azure Cosmos DB as in the below screenshots:

This is image title

This is image title

How to get Cosmos DB connection string from Azure

You will learn in this section, how to get the Cosmos DB connection string in Keys using the Azure portal.

You can go to Settings - click the Keys

This is image title

Now you can copy the URI and Primary Key into your web.config file in your project

Conclusion

I hope you understand now about Azure Cosmos DB, how to create a new Azure Cosmos DB account using Azure, how to create a new database and collection using Azure, how to add data to the collection using Data Explorer, how to use SQL Query to the collection using Data Explorer and how to get Cosmos DB connection string from Azure. I have covered all the required things. If you find anything missing, please let me know. Thank you!

#Azure #Azure Cosmos DB #Cosmos DB

Cody  Osinski

Cody Osinski

1624469280

Understanding how to query arrays in Azure Cosmos DB

This blog is the final part of a series of blogs where we’ll demystify commonly confused concepts for developers learning how to query data using the SQL (core) API in Azure Cosmos DB. Today, we’ll walk through tips and tricks for querying arrays.

Using an example, we’ll show how to use these concepts when querying arrays:

  • Accessing a specific array element
  • Iterating over arrays
  • JOINs
  • Subqueries

Example Scenario:

Nick is a developer that created an app that stores shopping lists. His app is incredibly popular around the holidays and has soared to 1 million active users!

He has a Cosmos container that has the shopping lists modeled as JSON documents. Here’s an example document:

{
  "id": "Tim",
  "city": "Seattle",
  "gifts": [
     {
        "recipient": "Andrew",
        "gift": "blanket"
     },
     {
        "recipient": "Deborah",
        "gift": "board game"
     },
     {
        "recipient": "Chris",
        "gift": "coffee maker"
     }
  ]
}

The remainder of the blog will focus on ways to query arrays, starting with the simplest (and least expressive) and concluding with the more advanced concepts.

#core (sql) api #query #azure cosmos db #azure #cosmos db

Eric  Bukenya

Eric Bukenya

1624713540

Learn NoSQL in Azure: Diving Deeper into Azure Cosmos DB

This article is a part of the series – Learn NoSQL in Azure where we explore Azure Cosmos DB as a part of the non-relational database system used widely for a variety of applications. Azure Cosmos DB is a part of Microsoft’s serverless databases on Azure which is highly scalable and distributed across all locations that run on Azure. It is offered as a platform as a service (PAAS) from Azure and you can develop databases that have a very high throughput and very low latency. Using Azure Cosmos DB, customers can replicate their data across multiple locations across the globe and also across multiple locations within the same region. This makes Cosmos DB a highly available database service with almost 99.999% availability for reads and writes for multi-region modes and almost 99.99% availability for single-region modes.

In this article, we will focus more on how Azure Cosmos DB works behind the scenes and how can you get started with it using the Azure Portal. We will also explore how Cosmos DB is priced and understand the pricing model in detail.

How Azure Cosmos DB works

As already mentioned, Azure Cosmos DB is a multi-modal NoSQL database service that is geographically distributed across multiple Azure locations. This helps customers to deploy the databases across multiple locations around the globe. This is beneficial as it helps to reduce the read latency when the users use the application.

As you can see in the figure above, Azure Cosmos DB is distributed across the globe. Let’s suppose you have a web application that is hosted in India. In that case, the NoSQL database in India will be considered as the master database for writes and all the other databases can be considered as a read replicas. Whenever new data is generated, it is written to the database in India first and then it is synchronized with the other databases.

Consistency Levels

While maintaining data over multiple regions, the most common challenge is the latency as when the data is made available to the other databases. For example, when data is written to the database in India, users from India will be able to see that data sooner than users from the US. This is due to the latency in synchronization between the two regions. In order to overcome this, there are a few modes that customers can choose from and define how often or how soon they want their data to be made available in the other regions. Azure Cosmos DB offers five levels of consistency which are as follows:

  • Strong
  • Bounded staleness
  • Session
  • Consistent prefix
  • Eventual

In most common NoSQL databases, there are only two levels – Strong and EventualStrong being the most consistent level while Eventual is the least. However, as we move from Strong to Eventual, consistency decreases but availability and throughput increase. This is a trade-off that customers need to decide based on the criticality of their applications. If you want to read in more detail about the consistency levels, the official guide from Microsoft is the easiest to understand. You can refer to it here.

Azure Cosmos DB Pricing Model

Now that we have some idea about working with the NoSQL database – Azure Cosmos DB on Azure, let us try to understand how the database is priced. In order to work with any cloud-based services, it is essential that you have a sound knowledge of how the services are charged, otherwise, you might end up paying something much higher than your expectations.

If you browse to the pricing page of Azure Cosmos DB, you can see that there are two modes in which the database services are billed.

  • Database Operations – Whenever you execute or run queries against your NoSQL database, there are some resources being used. Azure terms these usages in terms of Request Units or RU. The amount of RU consumed per second is aggregated and billed
  • Consumed Storage – As you start storing data in your database, it will take up some space in order to store that data. This storage is billed per the standard SSD-based storage across any Azure locations globally

Let’s learn about this in more detail.

#azure #azure cosmos db #nosql #azure #nosql in azure #azure cosmos db