powering rails application with postgresql

28
Powering Rails Application with PostgreSQL Nidhi Sarvaiya

Upload: icicletech

Post on 17-Nov-2014

631 views

Category:

Technology


4 download

DESCRIPTION

Overview of advanced features provided by PostgreSQL for Rails applications.

TRANSCRIPT

  • 1. Powering RailsApplication withPostgreSQLNidhi Sarvaiya

2. Who am I? Developer at Icicle technologies from last 7years. Ruby/Ruby on Rails developer since 2009 Official Handle @ice_on_rails Personal Handle @sarvaiya_nidhi 3. What Are We Covering Today? Why PostgreSQL Advance Inbuilt Data Types UUID Full Text Search Indexes Third Party Gems 4. Why PostgreSQL? First stable version was 6.0released in 1996 Latest stable version 9.3.5 Fast and reliable Free, community support 5. Rails 4 Handshakes with PostgreSQL As of Rails 4, manyPostgreSQL featuresare supported out of boxby Active Record 6. Built In Data Types JSON Arrays hstore Range Types PostGis Network Types 7. JSONScenarioStoring different social media information in your RailsApplication.Traditional ApproachEach social media sites returns different type of informationso we usually go for NoSQL databaseAlternativeStore data in JSON format in PostgreSQL 8. JSON ImplementationMigrationcreate_table :socials do |t|t.json 'profile'endQueryingSocial.first.profile['name'] => nidhiSocial.select(profile)Sample Twitter JSON{username :sarvaiya_nidhi,name:nidhi,followers:80} 9. ArrayScenarioNeed to add multiple tags and ratings for BookTraditional ApproachAdd Separate table and map it with BookAlternativeAdd array field in Book table to map multiple tags andratings 10. Array ImplementationMigrationcreate_table :books do |t|t.string :titlet.string :tags, array: trueendQueryingGet Books with specific tagBook.where("fiction = ANY (tags)")Get Books with all tags or multiple tagsBook.where("fiction = ALL (tags)")Book.where("tags @> ARRAY[?]::varchar[]",["fantasy", "fiction"])Sampe Book DataBook 1Book 2 11. HstoreHStore is a key value store within Postgres.ScenarioNeed to apply different configuration for different clientsTraditional ApproachMaintain multiple entries in settings table by addingKey/Value details for each clientAlternativeUse Hstore to maintain all setting for client in single record 12. HStore ImplementationMigrationdef self.upexecute "CREATE EXTENSION hstore"endcreate_table :clients do |t|t.hstore 'settings'endQueryingclient = Client.firstclient.settings # => { "background-color" => "blue",font-size:14px" }Get Specific value - client.settings["-background-color"]= "blue"Sample Hstore Datasettings: { "background-color" =>"blue",font-size:14px" } 13. Range Types daterange int4range int8rangenumrange tsrange tstzrangeLets look at some of the them with example -> 14. Range Type - daterangeScenarioImplement functionality of booking hotels room for specificdurationTraditional ApproachNeed to maintain two different fields capturing start dateand end date for booking durationAlternativeUse daterange data type to store duration details 15. daterange ImplementationMigrationcreate_table :rooms do |t|t.daterange 'duration'endQueryingAll Events on a given date:Room.where("duration @> ?::date",Date.new(2014, 8, 14))Sample DataRoom110/08/2014 - 14/08/2014Room116/08/2014 - 21/08/2014 16. Range Type - int4rangeScenarioImplement functionality of capturing weather forecastTraditional ApproachNeed to maintain two different fields capturing high and lowtemperature detailsAlternativeUse int4range data type to store temperature details 17. int4range ImplementationMigrationcreate_table :forecasts do |t|t.string :cityt.int4range :hi_loendQueryingForecast.create!(city: mumbai, hi_lo:29..32)Forecast.first.hi..lo => 29..32Sample DataMumbai: 29..32Delhi: 31..24 18. PostGis Geospatial extension to PostgresSupport for Geographic objectsNew data typesFunctions to work with those data types Spatial Index Support 19. Setup & Configuration Installing Postgis Add gems to support postgis with Active Record activerecord-postgis-adaptor rgeo Add postgis adaptor in database.ymlReferencehttp://daniel-azuma.com/articles/georails 20. Postgis Data Types geometry - Any geometric type point - Point data line_string - LineString data polygon - Polygon data geometry_collection - Any collection type multi_point - A collection of Points multi_line_string - A collection of LineStrings multi_polygon - A collection of Polygons 21. Network DataType PostgreSQL comes with column types exclusively for IPv4, IPv6,and MAC addresses. Active Record datatypes - inet, cidr and macaddreMigrationcreate_table :network_addresses do |t|t.inet :inet_addresst.cidr :cidr_addresst.macaddr :mac_addressend 22. UUID (Universally Unique Identifier) Most of the applications now have API, so use UUID rather thaninteger for the ids The uuid column type represents a universally unique identifier(UUID), a 128-bit value that is generated by an algorithm thatmakes it highly unlikely that the same value can be generatedtwice. Sharding would be easier. Even re-merging all the data into asingle database, if that's something you need at some point. 23. UUID ImplementaTionEnabling UUID Supportdef changeenable_extension 'uuid-ossp'endMigrationcreate_table :users, id: false do |t|t.primary_key :id, :uuidendorcreate_table :revisions do |t|t.column :identifier, :uuidend 24. Full Text Search Since PostgreSQL 8.3 TSVECTOR to represent text data TSQUERY to represent search predicates Use pg_search gem for Rails application 25. Indexes Support in PostgreSQLB-Tree Indexes Unique Index Sorted Index Partial Indexes Functional Indexes Multi Column Indexes GIST & GIN indexes 26. Gems Full Text Search Gem pg_search - https://github.com/Casecommons/pg_searchDatabase Insight pghero - https://github.com/ankane/pghero Postgres Extensions postgres_ext - https://github.com/dockyard/postgres_ext 27. Referenceshttp://edgeguides.rubyonrails.org/active_record_postgresql.htmlhttp://www.informit.com/articles/article.aspx?p=2220311&seqNum=13 28. THANKYOU