Midgard2 and database views
Posted on 2009-07-06 15:04:27 EEST.
Midgard2 provides flexible support for database views. The basic idea originates from well known MgdSchema technology introduced in Midgard 1.7. And to get better overview, you probably should read midgard_view mRFC, but I'll try to explain how you could start with views quickly.
First of all, you have to create view xml file which describes and defines real database view. As view can be complex, you can also define any database join type:
<?xml version="1.0" encoding="UTF-8"?>
<Schema xmlns="http://www.midgard-project.org/repligard/1.4">
<view name="mystyleview" table="style">
<property name="pagename" use="midgard_style:name" />
<property name="parentid" use="midgard_style:up" />
<property name="elementname" use="midgard_element:name" />
<property name="value" use="midgard_element:value" />
<join type="left" class="midgard_host" >
<condition left="midgard_host:style" right="midgard_style:id" />
</join>
<join type="inner" class="midgard_element" >
<condition left="midgard_element:style" right="midgard_style:id" />
</join>
<join type="inner" table="element_i" >
<condition left="midgard_element:sid" right="midgard_element:id" />
</join>
</view>
</Schema>
Once xml file for view is created, it should be copied to views directory under Midgard2 share dir.
This one depends on midgard core prefix, and in my case it's /usr/share/midgard-2.0/views/.
Then, you can start any Midgard2 application. View definition will be read on start up, and new GObject class will be created on the fly. If your application is written in PHP or Python, then proper language related class will be initialized as well.
Now, you can create new mystyleview instance (in Python):
mystyle = midgard.view.mystyleview()
or in C:
MidgardView mystyle = g_object_new(g_type_from_name("mystyleview"), NULL);
OK, but at this moment, you can do nothing with your view. Database view is considered read only, so you need to fetch some database records, which are represented as objects.
First of all, prepare database storage for newly created view. MidgardStorage (midgard_storage) should do the hard job for you:
midgard.storage.create_class_storage("mystyleview")
Of course, you can delete this storage, once you decide you do not need it any longer:
midgard.storage.delete_class_storage("mystyleview")
Both tasks can be done also in C or in PHP.
Now, when database view is created you can start query objects. The best helper, is MidgardQueryBuilder:
qb = midgard.query_builder("mystyleview")
qb.add_constraint("pagename", "<>", "")
list = qb.execute()
As midgard_view is nothing but database storage abstraction, you can also benefit from midgard_collector or midgard_reflection_property.
Also, any instance of registered midgard_view class has properties which has been defined in xml view file. So (for example) access to pagename property is done via list[0].pagename.