<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Intelligrape  Groovy &#38; Grails Blogs &#187; Database</title>
	<atom:link href="http://www.intelligrape.com/blog/category/database/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.intelligrape.com/blog</link>
	<description></description>
	<lastBuildDate>Thu, 02 Feb 2012 07:48:06 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<image>
			<title>Intelligrape  Groovy &amp; Grails Blogs</title>
			<url>http://www.intelligrape.com/blog/wp-content/uploads/2011/05/favicon2.ico</url>
			<link>http://www.intelligrape.com/blog</link>
			<width></width>
			<height></height>
			<description></description>
		</image>		<item>
		<title>Alphanumeric Sorting using Criteria Query (with MySQL database)</title>
		<link>http://www.intelligrape.com/blog/2012/02/02/alphanum_sort/</link>
		<comments>http://www.intelligrape.com/blog/2012/02/02/alphanum_sort/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 07:48:06 +0000</pubDate>
		<dc:creator>Gaurav Sharma</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[GORM]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Alphanumeric Sort]]></category>
		<category><![CDATA[criteria query]]></category>
		<category><![CDATA[formula]]></category>
		<category><![CDATA[Human Sort]]></category>
		<category><![CDATA[MySql]]></category>
		<category><![CDATA[Natural Sort]]></category>
		<category><![CDATA[sorting]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=5051</guid>
		<description><![CDATA[I am working on a Grails application with MySQL database. I had a use case in which I had to implement alphanumeric sorting using Criteria Query on Grails. By alphanumeric sorting I mean if there is a class Employee with field empId then on doing :

Employee e1 = new Employee(empId:'emp10').save()
Employee e2 = new Employee(empId:'emp2').save()
Employee e3 = [...]]]></description>
			<content:encoded><![CDATA[<p>I am working on a Grails application with MySQL database. I had a use case in which I had to implement alphanumeric sorting using Criteria Query on Grails. By alphanumeric sorting I mean if there is a class Employee with field empId then on doing :</p>
<pre class="brush: plain;">
Employee e1 = new Employee(empId:'emp10').save()
Employee e2 = new Employee(empId:'emp2').save()
Employee e3 = new Employee(empId:'emp1').save()
Employee e4 = new Employee(empId:'1emp').save()
Employee e5 = new Employee(empId:'10emp').save()
Employee e6 = new Employee(empId:'2emp').save()

Employee.createCriteria().list([sort:'empId'])
            /* OR */
Employee.createCriteria().list{
    order('empId')
}
</pre>
<p><strong>should give result like [e4,e6,e5,e3,e2,e1]</strong>. But according to sql sorting the <strong>result would be [e5,e4,e6,e3,e1,e2]</strong><br />
<br />
One thing to note was that criteria query implemented sorting at the database end.<br />
After googling around, I came <a href="http://drupal.org/project/natsort">across a script</a> that had a SQL function which converted the field value to string that can alphanumerically sorted easily at database end.</p>
<p>To migrate the functions in script to database you have to unzip the script and write following command on terminal:</p>
<pre class="brush: bash;">mysql -u username -p database_name &lt; /path/to/unzipped/directory/natsort.install.mysql</pre>
<p>Now only thing I had to do was to get a derived field from the Grails property that had to be sorted alphanumerically which was easily possible as the Grails had ability to create transient field using formula (thanks to wonderful <a href="http://www.intelligrape.com/blog/2010/12/31/create-transients-using-formula-in-grails/">Blog by Uday</a>). Thus I had to create a new transient field using SQL function in formula. So I did something like this :</p>
<pre class="brush: groovy;">
class Employee {
    String empId
    String empIdSortField           //transient field
    static mapping = {
        empIdSortField formula: 'natsort_canon(empId, &quot;natural&quot;)'
    }
}
</pre>
<p>Now if I had to get Employee objects are sorted by empId alphanumerically, what I would do is :  </p>
<pre class="brush: groovy;">
Employee.createCriteria().list {
    order('empIdSortField')
}
</pre>
<p>Hope this was helpful to you!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2012/02/02/alphanum_sort/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Dbconsole in Grails.</title>
		<link>http://www.intelligrape.com/blog/2011/12/25/dbconsole-in-grails/</link>
		<comments>http://www.intelligrape.com/blog/2011/12/25/dbconsole-in-grails/#comments</comments>
		<pubDate>Sun, 25 Dec 2011 08:56:38 +0000</pubDate>
		<dc:creator>Sachin</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[GUI console]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=4829</guid>
		<description><![CDATA[So, Grails 2.0 was released a few days back and I upgraded my application to it as soon as I came to know of its final release and it rocks.!!
Among the many things which are making a lot of noise on grails 2.0, there seems to be a lack of noise over the GUI Database [...]]]></description>
			<content:encoded><![CDATA[<p>So, Grails 2.0 was released a few days back and I upgraded my application to it as soon as I came to know of its final release and it rocks.!!</p>
<p>Among the many things which are making a lot of noise on grails 2.0, there seems to be a lack of noise over the GUI Database console which grails has provided. Developers can connect to the database from a GUI right inside there application, see the data in tables and execute simple queries. Probably its not polished yet so that could be a reason why there is not much noise over it but it still is a usable feature.</p>
<p>All you need to do is, run your grails 2.0 app navigate to<strong> http://localhost:8080/app-name/dbconsole/</strong> and configure your database connection. Just select what database you are using, Select the driver, a couple of entries for username and password and you are good to go.</p>
<p>The query builder isn&#8217;t too great, but that is no reason to miss this useful tool. No need to move to any other application or console to see whats in the database. The database is available right in your application, and its available only in development mode, so no worries of this slipping into production. Hope this saves some time for all of us.</p>
<p>Thanks.<br />
Sachin Anand<br />
mail : sachin[at]intelligrape[dot]com<br />
twitter : @sachin__anand</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/12/25/dbconsole-in-grails/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Batch update performance enhancements using SQL withBatch()</title>
		<link>http://www.intelligrape.com/blog/2011/07/05/batch-update-performance-enhancements-using-sql-withbatch/</link>
		<comments>http://www.intelligrape.com/blog/2011/07/05/batch-update-performance-enhancements-using-sql-withbatch/#comments</comments>
		<pubDate>Tue, 05 Jul 2011 08:42:37 +0000</pubDate>
		<dc:creator>roni</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[batch update and insert]]></category>
		<category><![CDATA[groovy sql]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[withBatch]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=3986</guid>
		<description><![CDATA[Hi guys,

Recently as part of a project, I had to populate a SQLite database with large amounts of data pertaining to a number of classes requiring more than 5000 inserts and updates per class. I created a new SQLite database using Groovy&#8217;s Sql class. The initial strategy involved creating prepared statements and executing individual insert/update [...]]]></description>
			<content:encoded><![CDATA[<p>Hi guys,<br />
<br />
Recently as part of a project, I had to populate a SQLite database with large amounts of data pertaining to a number of classes requiring more than 5000 inserts and updates per class. I created a new SQLite database using Groovy&#8217;s Sql class. The initial strategy involved creating prepared statements and executing individual insert/update statements for each record that needed to be inserted/updated in the new SQLite database.<br />
<br />
However the process was taking longer than expected, and the cumulative time taken for the whole application to sync less than 30 classes was coming to be more than 2 minutes. This time taken was extremely high regarding the context of the application and was a real performance bottleneck. What I did notice was that the insert statements were identical for a particular class, disregarding the values that needed to be inserted. The same was the case with the update statements.<br />
<br />
After looking through the Sql GDK, I found a method named <em>Sql.withBatch()</em> that performs batch manipulation of records in a database. See the following code for illustration:<br />
</p>
<pre class="brush: plain;">
Sql sql = Sql.newInstance(&quot;jdbc:sqlite:/home/ron/Desktop/test.db&quot;, &quot;org.sqlite.JDBC&quot;)
sql.execute(&quot;create table dummyTable(number)&quot;)
Long startTime = System.currentTimeMillis()
100.times {
     sql.execute(&quot;insert into dummyTable(number) values(${it})&quot;)
}
Long endTime = System.currentTimeMillis()

println &quot;Time taken: &quot; + ((endTime - startTime)/1000)
</pre>
<p>
The output of the above code comes out to be 14.313 seconds. That is to execute 100 insert statements with only a single attribute, it would take around 15 seconds. The time taken to insert records is dependent on the number of records being inserted and increases exponentially. Clearly a performance bottleneck in any application involving batch inserts and updates.<br />
<br />
Let us consider the same code and the performance with the <em>withBatch()</em> closure.</p>
<pre class="brush: plain;">
Sql sql = Sql.newInstance(&quot;jdbc:sqlite:/home/ron/Desktop/test.db&quot;, &quot;org.sqlite.JDBC&quot;)
sql.execute(&quot;create table dummyTable(number)&quot;)
Long startTime = System.currentTimeMillis()
sql.withBatch {stmt-&gt;
    100.times {
      stmt.addBatch(&quot;insert into dummyTable(number) values(${it})&quot;)
    }
    stmt.executeBatch()
}
Long endTime = System.currentTimeMillis()
println &quot;Time taken: &quot; + ((endTime - startTime)/1000)
</pre>
<p>
The time taken with the above code comes out to be 0.103 seconds! A remarkable performance improvement over the conventional method of inserting records using the execute() method.<br />
<br />
The only drawback with using the <em>withBatch()</em> closure is that it does not allow prepared statements to be added to the batch. This limits the use of batch statements as we have to manually create insert or update statements.<br />
<br />
Cheers<br />
Ron<br />
roni[at]intelligrape[at]com  </p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/07/05/batch-update-performance-enhancements-using-sql-withbatch/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to apply liquibase change set conditionally</title>
		<link>http://www.intelligrape.com/blog/2011/05/18/how-to-apply-liquibase-change-set-conditionally/</link>
		<comments>http://www.intelligrape.com/blog/2011/05/18/how-to-apply-liquibase-change-set-conditionally/#comments</comments>
		<pubDate>Wed, 18 May 2011 10:34:50 +0000</pubDate>
		<dc:creator>Uday Pratap Singh</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Plugin]]></category>
		<category><![CDATA[conditional changeset execution in liquibase]]></category>
		<category><![CDATA[grails liquibase integration]]></category>
		<category><![CDATA[how to add liquibase in middle of project]]></category>
		<category><![CDATA[liquibase]]></category>
		<category><![CDATA[Liquibase integration]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=3819</guid>
		<description><![CDATA[In our recent grails project, we were about to move to production so we decided to manage the database changes with liquibase. So we generated the changelog from development env by executing the command &#8220;grails generate-changelog /home/uday/projects/projectName/grails-app/migrations/changelog.xml&#8221; which contained all the table creation changesets. We updated the dbCreate=&#8217;none&#8217; in all env.  When we ran [...]]]></description>
			<content:encoded><![CDATA[<p>In our recent grails project, we were about to move to production so we decided to manage the database changes with liquibase. So we generated the changelog from development env by executing the command &#8220;grails generate-changelog /home/uday/projects/projectName/grails-app/migrations/changelog.xml&#8221; which contained all the table creation changesets. We updated the dbCreate=&#8217;none&#8217; in all env.  When we ran the application in test env, having the database in create-drop mode, it worked, but in other envs, which had database in &#8220;update&#8221; mode, it started failing.  Now we wanted some hook to execute the creation changeset only if the tables did not exist.<br />
We just went through the liquibase site and we got the answer to our problem. The solution was in liquibase <a href="http://www.liquibase.org/manual/preconditions">PRECONDITIONS</a>. We added the preconditions to the changesets to check whether the table existed or not.</p>
<pre class="brush: java;">
&lt;changeSet author=&quot;uday (generated)&quot; id=&quot;1305002274717-1&quot;&gt;
    &lt;preConditions onFail=&quot;MARK_RAN&quot;&gt;
      &lt;not&gt;
        &lt;tableExists tableName=&quot;account&quot;/&gt;
      &lt;/not&gt;
    &lt;/preConditions&gt;
    &lt;createTable tableName=&quot;account&quot;&gt;
      &lt;column autoIncrement=&quot;true&quot; name=&quot;id&quot; type=&quot;BIGINT&quot;&gt;
        &lt;constraints nullable=&quot;false&quot; primaryKey=&quot;true&quot;/&gt;
      &lt;/column&gt;
      &lt;column name=&quot;version&quot; type=&quot;BIGINT&quot;&gt;
        &lt;constraints nullable=&quot;false&quot;/&gt;
      &lt;/column&gt;
      &lt;column name=&quot;balance&quot; type=&quot;DECIMAL(19,2)&quot;&gt;
        &lt;constraints nullable=&quot;false&quot;/&gt;
      &lt;/column&gt;
      &lt;column name=&quot;date_created&quot; type=&quot;DATETIME&quot;&gt;
        &lt;constraints nullable=&quot;false&quot;/&gt;
      &lt;/column&gt;
      &lt;column name=&quot;last_updated&quot; type=&quot;DATETIME&quot;&gt;
        &lt;constraints nullable=&quot;false&quot;/&gt;
      &lt;/column&gt;
      &lt;column name=&quot;firstname&quot; type=&quot;VARCHAR(255)&quot;/&gt;
    &lt;/createTable&gt;
  &lt;/changeSet&gt;
</pre>
<p>In the above example the changeset will execute only if the precondition passes, if the condition fails you can specify what needs to be done. In our case we mark it as run so that liquibase marks it as being executed. You can do other things on fail event like HALT, CONTINUE, WARN,MARK_RAN.<br />
The documentation is quite good, you can find the examples of other changesets like constraints and indexes as well.</p>
<p><br/><br />
Hope it helps<br />
<br/><br />
## Uday Pratap Singh ##<br />
uday@intelligrape.com<br />
<a href="http://www.IntelliGrape.com/">http://www.IntelliGrape.com/</a><br />
<a href="http://in.linkedin.com/in/meudaypratap">http://in.linkedin.com/in/meudaypratap</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/05/18/how-to-apply-liquibase-change-set-conditionally/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mounting an EBS Volume to an Instance and Soft Linking a Growing Directory to it</title>
		<link>http://www.intelligrape.com/blog/2011/05/05/mounting-an-ebs-volume-to-an-instance-and-soft-linking-a-growing-directory-to-it/</link>
		<comments>http://www.intelligrape.com/blog/2011/05/05/mounting-an-ebs-volume-to-an-instance-and-soft-linking-a-growing-directory-to-it/#comments</comments>
		<pubDate>Thu, 05 May 2011 05:44:56 +0000</pubDate>
		<dc:creator>Vivek Krishna</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[System]]></category>
		<category><![CDATA[Amazon EC2]]></category>
		<category><![CDATA[EBS]]></category>
		<category><![CDATA[Mounting]]></category>
		<category><![CDATA[Ubuntu]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=3781</guid>
		<description><![CDATA[We were having a crisis on our project the other day. The VPS on which we were running our application had some issues with kernel and Tomcat, for that matter, any java process was running unpredictably. Tomcat would explode the WAR file once in a while and even if it did, it would just pause [...]]]></description>
			<content:encoded><![CDATA[<p>We were having a crisis on our project the other day. The VPS on which we were running our application had some issues with kernel and Tomcat, for that matter, any java process was running unpredictably. Tomcat would explode the WAR file once in a while and even if it did, it would just pause at &#8220;Deploying app.war&#8221; forever. After spending some time troubleshooting (we didn&#8217;t know that it was an issue with the kernel), we decided to move our infrastructure to Amazon EC2. We picked up an EBS based large instance, running Ubuntu and copied the setup from our production server to this new machine. The setup was a breeze, thanks to the scripts we already had in place for migrating our production setup to our QA machines for testing purposes.</p>
<p>However, we realized that Image Magick, which was being used from our application was not working as expected. In fact, it wasn&#8217;t working at all. We noticed that we were able to perform it as root, but not as any other user. The error which showed up was that there was lack of disk space. Static documents generated by our application were stored on the file system and it was meant to be an ever expanding directory. The EBS instance we had chosen had a capacity of just 8GB and about 6 GB of that was being occupied by the OS and the rest of our infrastructure. We decided to move this particular directory to a new EBS volume.</p>
<p>This could be accomplished smoothly, thanks to the ease of attaching a new EBS volume to an instance. We added a new volume and then, performed the following steps to move this particular expanding directory.</p>
<pre class="brush: java;">

mke2fs -F -j /dev/sdh #This is to create an ext3 file system for the device attached at /dev/sdh

mkdir /path_to_new_file_system

mount /dev/sdh /path_to_new_file_system #mount the new file system at this directory

cp -r static_documents_location /path_to_new_file_system #Copy the files from the existing directory to the new directory

mv static_documents_location static_documents_location_backup #Backup the existing documents, just in case anything goes wrong

ln -s /path_to_new_file_system/static_documents_location static_documents_location #Create a soft link to refer to the new file location with the same name as the previous one
</pre>
<p>With these steps, we were good to go on the Amazon machine without even requiring a Server restart. We were expecting a downtime of at least 10 minutes but this happened so flawlessly.</p>
<p>Hope this helps someone.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/05/05/mounting-an-ebs-volume-to-an-instance-and-soft-linking-a-growing-directory-to-it/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Grails domain class and DDL sql file using schema-export</title>
		<link>http://www.intelligrape.com/blog/2011/05/04/grails-domain-class-and-ddl-sql-file-using-schema-export/</link>
		<comments>http://www.intelligrape.com/blog/2011/05/04/grails-domain-class-and-ddl-sql-file-using-schema-export/#comments</comments>
		<pubDate>Tue, 03 May 2011 19:19:07 +0000</pubDate>
		<dc:creator>Bhagwat Kumar</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[datasource]]></category>
		<category><![CDATA[domain DDL]]></category>
		<category><![CDATA[environment]]></category>
		<category><![CDATA[GANT script]]></category>
		<category><![CDATA[schema-export]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=3734</guid>
		<description><![CDATA[Grails Schema-export GANT script to generate DDL sql file of the grails project domains.

eg.
   grails prod schema-export myProd.sql]]></description>
			<content:encoded><![CDATA[<p>While debugging a domain and its database schema I found an interesting <code>grails command line Gant script</code>: <a href="http://www.grails.org/doc/latest/ref/Command%20Line/schema-export.html" target="_blank"><strong>schema-expor</strong>t</a>.</p>
<p>One of the great <code>Grails command line Gant script</code> to generate<code> SQL scripts(DDL) </code> which is executed against your database to model your <code>grails domain</code>. You can control the environment and the output file to generate the SQL script. Without going into much details lets see an example. Here is the only domain in my <code>grails project</code> :</p>
<pre class="brush: groovy;">
Class Person{
	String name
	Integer age

static hasMany=[emails:String]
}
</pre>
<p>And here is the script I used</p>
<pre class="brush: bash;">
grails schema-export
</pre>
<p>Here is the content of generated DDL file which is created in project&#8217;s target folder with name ddl.sql by default(obviously data source settings of Development environment).</p>
<pre class="brush: sql;">
alter table person_emails drop foreign key FKADA31081669C99A9;
drop table if exists person;
drop table if exists person_emails;
create table person (id bigint not null auto_increment, version bigint not null, name varchar(255) not null, primary key (id)) ENGINE=InnoDB;
create table person_emails (person_id bigint, emails_string varchar(255)) ENGINE=InnoDB;
alter table person_emails add index FKADA31081669C99A9 (person_id), add constraint FKADA31081669C99A9 foreign key (person_id) references person (id);
</pre>
<p>You can also specify the environment (e.g. <code>prod</code>) whose <code>data source</code> settings will be used to generate DDL and output to a different file(e.g. <code>prodDDL.sql</code>) like :</p>
<pre class="brush: bash;">
grails prod schema-export prodDDL.sql
</pre>
<p>Full documentation ca be found here <a href="http://www.grails.org/doc/latest/ref/Command%20Line/schema-export.html" target="_blank"><strong>schema-expor</strong>t</a>.</p>
<p>Hope it encourage you to read the <strong><a href="http://www.grails.org/doc/latest/">Grails documentation</a></strong> in spare time to find and share <strong>hidden features of grails</strong>.</p>
<p>~~~~Cheers ~~~~</p>
<p>Bhagwat Kumar<br />
bhagwat(at)intelligrape(dot)com</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/05/04/grails-domain-class-and-ddl-sql-file-using-schema-export/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A use case of Bitwise AND</title>
		<link>http://www.intelligrape.com/blog/2011/04/15/a-use-case-of-bitwise-and/</link>
		<comments>http://www.intelligrape.com/blog/2011/04/15/a-use-case-of-bitwise-and/#comments</comments>
		<pubDate>Thu, 14 Apr 2011 19:20:12 +0000</pubDate>
		<dc:creator>Mohd Farid</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[GORM]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[MySql]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=3666</guid>
		<description><![CDATA[Recently, I used bitwise Anding in my grails project. I am sharing the approach that we followed by means of an example.

Suppose we have a domain class Person which can have multiple attributes like Smart, Intelligent, Talkative etc.
What sort of relationship comes to our mind when we see this?
I believe the obvious answer would be [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I used bitwise Anding in my grails project. I am sharing the approach that we followed by means of an example.<br />
</br><br />
Suppose we have a domain class Person which can have multiple attributes like Smart, Intelligent, Talkative etc.</p>
<p>What sort of relationship comes to our mind when we see this?<br />
I believe the obvious answer would be Person hasMany Attributes</p>
<p>Next, what if we want to optimize our design so that the searches on the Person becomes better.</p>
<p>Well, this was the question we were facing in our recent project where we finally used the bitwise AND.<br />
We decided to have one field of type Long in our Person class. We named this as attributes . Soon, I ll be explaining  why a long for Attribute&#8230;</p>
<p>We ensured that the Attributes are never going to be more than 20-30 . So, it became a nice candidate which could utilize the benefit of Bitwise ANDing.</p>
<p>We associated a binary weight to every instance of Attribute domain class.</p>
<p>The rows in the attribute table of our database looked somewhat like this</p>
<pre class="brush: java;">
id | attribute      | weight
1 | Smart          | 1
2 | Talkative      | 2
3 | Intelligent     | 4
4 | Cooperative  | 8
5 | Ignorant       | 16
</pre>
<p>So, in order to save a Person who is Smart and Cooperative , we would set his attributes field.<br />
weight of Smart + weight of Cooperative.<br />
ie 1+8 = 9.</p>
<p>Suppose our Person table has some entries as follows:</p>
<pre class="brush: java;">
id  | name  | attributes
1   | Tom   |  9
2   | Fred   |  12
3   | John   | 18
</pre>
<p>If we want to search a person who is Intelligent  we need to have a final query like this</p>
<pre class="brush: java;">
Select * from person where attributes&amp;4 = 4
(4 is the weight of Attribute - Intelligent)
</pre>
<p>Search a person who is Cooperative and Talkative</p>
<pre class="brush: java;">
Select * from person where attributes&amp;2=2 and attributes&amp;8=8
or more optimally,
Select * from person where attributes&amp;10=10
(2 is the weight of Talkative and 8 is the weight of Cooperative)
</pre>
<p><strong><br />
Some points to be kept in mind before taking this approach:</strong><br />
There is a maximum limit of 64 values for the field on which we plan to do BitwiseANDing.<br />
Bitwise AND is not directly supported by Hibernate, but we can add a custom function and dialect.</p>
<p></br><br />
Hope this helped.</p>
<p>Thanks &amp; Regards<br />
Mohd Farid</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/04/15/a-use-case-of-bitwise-and/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Groovy: Sort list of objects on the basis of more than one field</title>
		<link>http://www.intelligrape.com/blog/2011/01/25/groovy-sort-list-of-objects-on-the-basis-of-more-than-one-field/</link>
		<comments>http://www.intelligrape.com/blog/2011/01/25/groovy-sort-list-of-objects-on-the-basis-of-more-than-one-field/#comments</comments>
		<pubDate>Mon, 24 Jan 2011 19:29:03 +0000</pubDate>
		<dc:creator>Salil</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java tools]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[comparator]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[sorting]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=2699</guid>
		<description><![CDATA[Usually, when we deal with databases, we don&#8217;t face such kind of situation because we query database to get result-set in required order.
But let&#8217;s say you have a List of objects that you want to sort on the basis of two fields. Let&#8217;s discuss it with an example.

I have a list of Tasks (with date [...]]]></description>
			<content:encoded><![CDATA[<p>Usually, when we deal with databases, we don&#8217;t face such kind of situation because we query database to get result-set in required order.</p>
<p>But let&#8217;s say you have a List of objects that you want to sort on the basis of two fields. Let&#8217;s discuss it with an example.<br />
<br/><br />
I have a list of Tasks (with date and priority fields). I want to sort these tasks ordered by Date and priority-wise (as second level sorting).</p>
<p>Here, I gonna use Expando class, so I can directly run this in my groovyConsole. But definitely you can use some &#8216;Task&#8217; class.</p>
<pre class="brush: groovy;">
Expando a = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-01'), priority:1)
Expando b = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-01'), priority:2)
Expando c = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-02'), priority:1)
Expando d = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-01'), priority:3)

def list = [a,d,c,b]
</pre>
<p>If sorting was required on the basis of date only, it was very simple.</p>
<pre class="brush: groovy;">
list.sort(it.date)
</pre>
<p>But as per our requirements &#8211; order by date (first level sorting) and priority (second level sorting). We can do something like following.</p>
<pre class="brush: groovy;">
list.sort{x,y-&gt;
  if(x.date == y.date){
    x.priority &lt;=&gt; y.priority
  }else{
    x.date &lt;=&gt; y.date
  }
}
</pre>
<p>Well, there could be some better way. If you know please put your comments. But it worked well in my case.</p>
<p><br/><br />
Cheers!<br />
Salil Kalia<br />
Salil [at] IntelliGrape [dot] com<br />
<a href="http://twitter.com/salil_kalia" target='_blank'>Twitter</a> <a href="http://in.linkedin.com/in/salilkalia" target='_blank'>LinkedIn</a> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/01/25/groovy-sort-list-of-objects-on-the-basis-of-more-than-one-field/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Getting up and Running With Cassandra</title>
		<link>http://www.intelligrape.com/blog/2011/01/17/getting-up-and-running-with-cassandra/</link>
		<comments>http://www.intelligrape.com/blog/2011/01/17/getting-up-and-running-with-cassandra/#comments</comments>
		<pubDate>Sun, 16 Jan 2011 19:06:54 +0000</pubDate>
		<dc:creator>Sachin</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[cassandra]]></category>
		<category><![CDATA[starting cassandra]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=2648</guid>
		<description><![CDATA[Luckily, I got some time outside my usual obligations in the project, to learn something new and I devoted the time to getting up and running with cassandra . Getting starting up with it was a bit bumpy, as the case almost always is when you start with something entirely new.
Lets get Started..
1) First step [...]]]></description>
			<content:encoded><![CDATA[<p>Luckily, I got some time outside my usual obligations in the project, to learn something new and I devoted the time to getting up and running with <a href="http://wiki.apache.org/cassandra/" target="_blank">cassandra</a> . Getting starting up with it was a bit bumpy, as the case almost always is when you start with something entirely new.</p>
<p>Lets get Started..</p>
<p>1) First step of course is to get the binary files for the cassandra from <a href="http://cassandra.apache.org/" target="_blank">here</a></p>
<p>2) It is assumed that you have got jdk&gt;1.5 installed on your machine and JAVA_HOME variable is set. Now extract the tar file to the location you want (I extracted in the /opt folder and created a soft link to it with name cassandra).</p>
<p>3) Create the necessary directories for cassandra in /var/lib and /var/log folders and change their ownership</p>
<pre class="brush: java;">

sudo mkdir -p /var/lib/cassandra

sudo chown -R &quot;user&quot; /var/lib/cassandra

sudo mkdir -p /var/log/cassandra

sudo chown -R &quot;user&quot; /var/log/cassandra
</pre>
<p>Now move the extracted cassandra project move to the bin folder inside it (in my case /opt/cassandra/bin) and type the command</p>
<pre class="brush: java;">

./cassandra  -f
</pre>
<p>The -f switch will ensure that cassandra runs in the foreground and its logs will print to standard output.</p>
<p>Now a few lines similar to a java stack trace will appear. I expected to see some kind of &#8220;successful or server running message&#8221; but there was none. So if you are not seeing any FATAL or ERROR messages it means you have succeeded in running cassandra. <img src='http://www.intelligrape.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Now notice in that stack trace that your cassandra runs on port 9160 by default.</p>
<p>So to connect to cassandra open a new terminal and start the cassandra CLI available in the same bin folder.</p>
<pre class="brush: java;">

./cassandra-cli
</pre>
<p>You will see a message like</p>
<p>Welcome to cassandra CLI.</p>
<p>Type &#8216;help;&#8217; or &#8216;?&#8217; for help. Type &#8216;quit;&#8217; or &#8216;exit;&#8217; to quit.<br />
[default@unknown]</p>
<p>typing help here will show you a list of commands available.</p>
<p>Now, we will connect to the cassandra server instance we started earlier.</p>
<pre class="brush: java;">

connect localhost/9160;
</pre>
<p>Don&#8217;t miss that semicolon <img src='http://www.intelligrape.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . All statements here must end with semicolon.</p>
<p>You will now be connected to a &#8220;Test Cluster&#8221;. It is the default cluster which comes with cassandra. Cluster is a container which encapsulates many &#8216;keyspaces&#8217; and keyspaces are things similar to a database in relational DBMS. I better leave the data model topic here and concentrate on task at hand. I intend to take up data model topic in a separate blog.</p>
<p>So, Now we have a cluster to work in.</p>
<p>We will create a keyspace (database in relational DBMS world) and then enter and retrieve some data from it.</p>
<p>First of all lets see what all keyspaces are already available. Invoke</p>
<pre class="brush: java;">

show keyspaces;
</pre>
<p>The  keyspaces you see are used by cassandra and are not to be intended to be used by the us. So lets make our own keyspace.</p>
<pre class="brush: java;">

create keyspace CustomKeySpace with replication_factor=1;

use CustomKeySpace;
</pre>
<p>What we have just done is created a new keyspace and started using in. (Quite similar to create database &lt;database-name&gt;; and use &lt;database-name&gt;;) Lets leave replication_factor for now.</p>
<p>[default@unknown]<br />
[default@unknown] use CustomKeySpace;<br />
Authenticated to keyspace: CustomKeySpace<br />
[default@CustomKeySpace]</p>
<p>notice the change from [default@unknown] to [default@CustomKeySpace]. It shows you are a &#8220;default&#8221; user which earlier was not using a keyspace and is now using CustomKeySpace. Another way to look at it is default user is &#8220;logged&#8221; into CustomKeySpace.</p>
<p>Next step is to create a table, just that it is called a column-family here.</p>
<pre class="brush: java;">

create column_family user;
</pre>
<p>lets enter some data to this column family now.</p>
<pre class="brush: java;">

[default@CustomKeySpace] set user ['sachin'] ['lname']= 'Anand' ;
Value inserted.
[default@CustomKeySpace] set user ['sachin'] ['email']= 'sachin[at]intelligrape[dot]com' ;

Value inserted.
</pre>
<p>Now we created two columns for user &#8217;sachin&#8217; one is called ['lname'] and contains value &#8216;Anand&#8217;, other is called &#8216;email&#8217; and contains value sachin[at]intelligrape[dot]com.</p>
<p>To count the number of columns for a record</p>
<pre class="brush: java;">

count user ['sachin'];
</pre>
<p>To retrieve the values from the database &#8212; you guessed it we will use get.</p>
<pre class="brush: java;">

[default@CustomKeySpace] get user ['sachin'];
=&gt; (column=656d61696c, value=73616368696e40696e74656c6c6967726170652e636f6d, timestamp=1295199962515000)
=&gt; (column=[java]666e616d65, value=4562656e, timestamp=1295199873677000)
Returned 2 results.
</pre>
<p>problem here column names and values are coming in hex code here. So, we need to add some metadata to tell what kind of values we are expecting. here we go..</p>
<pre class="brush: java;">

[default@CustomKeySpace] update column family user with column_metadata=[{column_name:lname, validation_class:UTF8Type},{column_name:email, validation_class:UTF8Type}];
</pre>
<p>Again writing get user command</p>
<pre class="brush: java;">

[default@MyKeySpace] get user ['sachin'];
=&gt; (column=656d61696c, value=sachin@intelligrape.com, timestamp=1295199962515000)
=&gt; (column=666e616d65, value=Anand, timestamp=1295199873677000)
Returned 2 results.
</pre>
<p>So we have got the results we wanted. So in this small article we learnt how to start cassandra connect to it. create a new keyspace add a column_family and set and get data from it. I will be back with more on this for sure.</p>
<p>Thanks &amp; Regards.</p>
<p>Sachin Anand</p>
<p>Email  : sachin[at]intelligrape[dot]com</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/01/17/getting-up-and-running-with-cassandra/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Number Formating using regular expression and format method of String class</title>
		<link>http://www.intelligrape.com/blog/2010/12/14/number-formating-using-regular-expression-and-format-method-of-string-class/</link>
		<comments>http://www.intelligrape.com/blog/2010/12/14/number-formating-using-regular-expression-and-format-method-of-string-class/#comments</comments>
		<pubDate>Tue, 14 Dec 2010 06:24:21 +0000</pubDate>
		<dc:creator>Salil</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=2380</guid>
		<description><![CDATA[Hey guys, I found something very useful, so sharing it here.
In one of my project there was a requirement to create a fixed length user-id. Let&#8217;s say it was 5 characters ID.

So in other words we required to convert -
&#8216;123&#8242; to &#8216;00123&#8242; and &#8216;1000&#8242; to &#8216;01000&#8242; and &#8216;12345&#8242; will remain &#8216;12345&#8242;.
It appears very simple, but [...]]]></description>
			<content:encoded><![CDATA[<p>Hey guys, I found something very useful, so sharing it here.<br />
In one of my project there was a requirement to create a fixed length user-id. Let&#8217;s say it was 5 characters ID.<br />
<br/><br />
So in other words <strong>we required to convert </strong>-<br />
&#8216;123&#8242; to &#8216;00123&#8242; and &#8216;1000&#8242; to &#8216;01000&#8242; and &#8216;12345&#8242; will remain &#8216;12345&#8242;.<br />
It appears very simple, but the thing is <strong>how quick we do this</strong>.<br />
<br/><br />
Earlier I thought to do this by calculating the length of id and prefixing required number of zeros.<br />
<br/><br />
Alternate single-line and faster solution is -</p>
<pre class="brush: groovy;">
      // following will return a String with size of 5 characters and prefixes zeros (if id has digits lesser than 5).
         String.format('%05d', id)
      // Note down, id is a digit here.
</pre>
<p>That&#8217;s all. . isn&#8217;t it nice?. We can utilize it at many places like &#8211; converting date from &#8216;1-1-2010&#8242; to &#8216;01-01-2010&#8242;.<br />
Idea is to introduce such kind of utility. If you already knew this, please ignore <img src='http://www.intelligrape.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /><br />
please open the ideas &#8211; if you know something better than this.<br />
<br/><br />
cheers!<br />
salil at IntelliGrape dot com</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2010/12/14/number-formating-using-regular-expression-and-format-method-of-string-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

