SlideShare a Scribd company logo
Использование специальных
 типов данных PostgreSQL в
    Александр Коротков, Интаро
        Doctrine 2 ORM
            Alexander Korotkov
          aekorotkov@gmail.com




                                 Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




    Произвольный набор свойств

   • Товар (e-commerce)

   • Документ (документооборот,
     каталоги и т.д.)



                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




                         Подходы

   • Entity-Attribute-Value
   • Каждое свойство – отдельная
     колонка
   • СУБД-специфичные методы


                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




     Entity-Attribute-Value (EAV)


                   1     *             *    1
       Entity                Value              Attribute




                                                      Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




     Entity-Attribute-Value (EAV)
   • Не нужно изменять модель

   • Сложные запросы
   • Медленно


                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




                               EAV




                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




              Добавление каждого
               свойства в модель
   • Запросы работают быстро

   • Необходимо динамически
     менять модель
   • Много столбцов

                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




              Добавление каждого
               свойства в модель




                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




                      PostgreSQL




                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




                             hstore


                               SQL
                           NoSQL
                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




            hstore в PostgreSQL
   • Не нужно изменять модель
   • Прозрачная работа со стороны
     PHP
   • Запросы работают быстро

   • СУБД-зависимое решение

                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




          Объявление в модели
   /**
    * @var array $properties
    *
    * @ORMColumn(name="properties",
     type="hstore", nullable=true)
    */
   private $properties;

                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




            Сохранение данных
   $product = new Product();
   $product->setName(‘box’);
   $product->setProperties(array(
     'w' => 80,
     'h' => 60
   ));
   $em->persist($product);
   $em->flush();

                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




             Прозрачная работа




                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




         Что происходит в базе
   crm=# select id, name, properties from
   product;

    id | name | properties
   ----+------+----------------------
     1 | box | "h"=>"60", "w"=>"80"
   (1 row)

                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM



            Извлечение из базы
   $product = $this->getDoctrine()
     ->getRepository(‘Product')
     ->find(1);
   print_r($product->getProperties());
   Array (
       [h] => 60
       [w] => 80
   )
                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




    Функция fetchval: фильтрация

   $query = $em->createQuery(“
     SELECT p
     FROM Product p
     WHERE
       fetchval(p.properties, 'w') =
     :value
   “)->setParameter('value', '80');

                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




                               SQL
   SELECT
     ...
   FROM
     product i0_
   WHERE
     fetchval(i0_.properties, 'w') = ?

                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




     Функция fetchval: сортировка

   $query = $em->createQuery(“
     SELECT
       p,
       fetchval(p.properties, 'w') AS w
     FROM Product p
     ORDER BY w
   “);

                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




                               SQL
   SELECT
     ...,
     fetchval(i0_.properties, 'w') AS sclr13,
     ...
   FROM
     product i0_
   ORDER BY
     sclr13 ASC

                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




              Операторы >= и <=
   $query = $em->createQuery(‘
     SELECT p
     FROM Product p
     WHERE p.properties >= :property
   ’)->setParameter('property',
     array('w' => 80), 'hstore');

                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




                           Удобно




                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




                             Хак (((
   CREATE OPERATOR <=
   (
     PROCEDURE = hs_contained,
     LEFTARG = hstore,
     RIGHTARG = hstore,
     COMMUTATOR = >=,
     RESTRICT = contsel,
     JOIN = contjoinsel);

                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




               Скорости нннада?
                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




                              Index
   CREATE INDEX
      i_crm_product_properties_w
   ON
      i_crm_product
      (
         fetchval(properties, 'w')
      );

                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




                              Index
   CREATE INDEX
      i_crm_product_properties
   ON
      i_crm_product
   USING
      gin
   (properties);

                                                    Alexadner Korotkov
Специальные типы данных PostgreSQL в Doctrine ORM




          Спасибо за внимание!




                                                    Alexadner Korotkov

More Related Content

PPTX
C#. От основ к эффективному коду
PPTX
2 лекция
PDF
Использование json/xml в БД PostgreSQL и Oracle для хранения произвольных ат...
PDF
Doctrine for NoSQL
PDF
Live migrating a container: pros, cons and gotchas
PPT
ФГОС начальная школа
PDF
ファイナンシャル・エクストラネット
DOCX
45 lessons life taught me
C#. От основ к эффективному коду
2 лекция
Использование json/xml в БД PostgreSQL и Oracle для хранения произвольных ат...
Doctrine for NoSQL
Live migrating a container: pros, cons and gotchas
ФГОС начальная школа
ファイナンシャル・エクストラネット
45 lessons life taught me

Viewers also liked (20)

PPT
Seven things to make your pup ONE in a million
DOCX
Tugas 3 Rangkuman Protocol DNS, FTP, HTTP, dan SMTP
PDF
Researchers - recommendations from AIGLIA2014
PPTX
Donor Relationship Management
PDF
File management 101
PPTX
Proses Start-Up Komputer
PPTX
Goose chasegroup
PDF
Steve Wiggins: Agricultural_policy - issues of consensus and debate
PDF
Business Innovation, CSR and Competitive Advantage: Strategic pathways to value
PDF
Learn OpenStack from trystack.cn ——Folsom in practice
PDF
How are drugs developed? - Lesson plans
PDF
長野市地域きらめき隊 2016.02.02
PDF
Notam 24-04-2015
PDF
01 05-14
DOCX
ร้านกาแฟวาวี
PPTX
Powerfull point ala Wenni
PDF
Business Presentation[1]
PPTX
Our Services increase your business as a Brand name.
PDF
Scalable javascript application - طراحی نرم افزارهای مقیاس پذیر با جاوا اسکریپت
PPTX
Assessing enablers and constrainers of graduation
Seven things to make your pup ONE in a million
Tugas 3 Rangkuman Protocol DNS, FTP, HTTP, dan SMTP
Researchers - recommendations from AIGLIA2014
Donor Relationship Management
File management 101
Proses Start-Up Komputer
Goose chasegroup
Steve Wiggins: Agricultural_policy - issues of consensus and debate
Business Innovation, CSR and Competitive Advantage: Strategic pathways to value
Learn OpenStack from trystack.cn ——Folsom in practice
How are drugs developed? - Lesson plans
長野市地域きらめき隊 2016.02.02
Notam 24-04-2015
01 05-14
ร้านกาแฟวาวี
Powerfull point ala Wenni
Business Presentation[1]
Our Services increase your business as a Brand name.
Scalable javascript application - طراحی نرم افزارهای مقیاس پذیر با جاوا اسکریپت
Assessing enablers and constrainers of graduation
Ad

More from Alexander Korotkov (7)

PDF
Solving PostgreSQL wicked problems
PDF
In-memory OLTP storage with persistence and transaction support
PDF
Oh, that ubiquitous JSON !
PDF
Jsquery - the jsonb query language with GIN indexing support
PDF
Our answer to Uber
PDF
The future is CSN
PDF
Open Source SQL databases enter millions queries per second era
Solving PostgreSQL wicked problems
In-memory OLTP storage with persistence and transaction support
Oh, that ubiquitous JSON !
Jsquery - the jsonb query language with GIN indexing support
Our answer to Uber
The future is CSN
Open Source SQL databases enter millions queries per second era
Ad

Использование специальных типов данных PostgreSQL в ORM Doctrine