This post has as goal to provide basics to help you understanding how work triggers in PostgreSQL.
A trigger is the possibility to associate an automatic operation to a table in case a write event happens on this given table.

Here is the synopsis of this query.
CREATE [ CONSTRAINT ] TRIGGER name { BEFORE | AFTER | INSTEAD OF } { event [ OR ... ] }
  ON table
  [ FROM referenced_table_name ]
  { NOT DEFERRABLE | [ DEFERRABLE ] { INITIALLY IMMEDIATE | INITIALLY DEFERRED } }
  [ FOR [ EACH ] { ROW | STATEMENT } ]
  [ WHEN ( condition ) ]
  EXECUTE PROCEDURE function_name ( arguments )

The parts that are essential to get the basics are written in strong characters.

  • event, this is the database operation that will cause the trigger to fire. In Postgres 9.2 and prior versions, this can occur for INSERT, UPDATE, DELETE and TRUNCATE
  • table, this is the database table where the event has to occur
  • EXECUTE PROCEDURE function_name ( arguments ), this is the operation that is launched by trigger after being fired. The procedure can be customized with data related to the table or other things depending on the circumstances trigger is fired. Have a look here for more details about trigger procedures.

Triggers have many usages. Defined on the given table of your database, you can set up a trigger to launch automatic operations on a table each time an event is done on it. Once fired, this trigger will execute an automatic procedure that will perform a list of operations predefined by user. So this limits the amount of code you need to write on the application side, limiting the possibility of bugs in your own code while using Postgres server robustness.

But let’s take a simple example: an address book.
Let’s imagine that you are managing your address book with Postgres. Really for simplicity’s sake, your system manages only the names and addresses of people you know.
The people you know have a unique name, but they can have multiple addresses, as you might register their main home address and work address for example. So, your system will have the following basic schema:
CREATE TABLE users (id int PRIMARY KEY, name varchar(256));
CREATE TABLE address (id_user int, address text);

Let’s suppose that you are a lucky guy and that you know where I live and where is my workplace (some of this data is perhaps wrong).
postgres=# INSERT INTO users VALUES (1, 'Michael P');
INSERT 0 1
postgres=# INSERT INTO address VALUES (1, 'Work in Tokyo, Japan');
INSERT 0 1
postgres=# INSERT INTO address VALUES (1, 'Live in San Francisco, California');
INSERT 0 1

Then you can recover my addresses easily.
postgres=# SELECT address FROM users JOIN address
postgres=# ON (users.id = address.id_user) WHERE name = 'Michael P';
address
-----------------------------------
Work in Tokyo, Japan
Live in San Francisco, California
(2 rows)

However it happens that you are not caring anymore about me and that you wish to delete my data from your address book. Intuitively, deleting an entry from an address book is simply removing the wanted name. But, if you do that the address data will remain. Of course you can let your application manage the deletion for both tables “users” and “address”, but you will need to send 2 SQL queries. This is a waste of resource as you need to go twice to your database to perform the complete deletion. In this case at least it is.

Triggers can allow you to simplify the deletion operation by automatizing the data deletion on table “addresses” if a user is deleted from your address book. You need to create the following objects in order to do that.
CREATE FUNCTION delete_address() RETURNS TRIGGER AS $_$
  BEGIN
    DELETE FROM address WHERE address.id_user = OLD.id;
    RETURN OLD;
  END $_$ LANGUAGE 'plpgsql';

This function is set to delete the addresses for a given user ID.
Then create the trigger event. What is necessary here is to launch the previous function each time an entry is removed from table “users”, explaining the clause “FOR EACH ROW”. The address clean up is also done before the actual DELETE happens on table “users”.
CREATE TRIGGER delete_user_address BEFORE DELETE ON users FOR EACH ROW EXECUTE PROCEDURE delete_address();

Let’s test the entry deletion.
postgres=# DELETE FROM users WHERE name = 'Michael P';
DELETE 1
postgres=# select * from address;
id_user | address
---------+---------
(0 rows)

And my address data has completely disappeared from your database thanks to the trigger.
Have fun with this feature.

This article is made using Eclipse 3.7 and its famous plug-in dedicated to GIT called Egit.

When working on a java project, eclipse is a nice way to implement, code and debug. It is even nicer when it can be used with a version controller like GIT. Since Eclipse 3.5, GIT has its own plug-in called EGit. Let’s be honest. It rocks. The interface is well-thought, and you can manage easily your GIT repository through friendly interface. In case you get crazy with some error messages, you can still easily fallback to the good-old command terminal, and everything made will still be visible in Eclipse. That is really a nice tool

However, when starting a new Java project from an existing GIT repository, you can easily import your project by doing Files -> Import. Then in the import window, select Git -> Projects from GIT.
And in a couple of clicks, you are able to clone existing repositories, and add new projects. The problem is that you generally need to import the code as a general project, and under Eclipse it will be recognized as a Java project.

There is a workaround for this problem after importing a GIT code as a general project. You first need to modify the .project file in the project repository and modify it as below to make it a Java project.
<projectDescription>
 <name>my_project</name>
 <comment></comment>
 <projects>
 </projects>
 <buildSpec>
  <buildCommand>
   <name>org.eclipse.jdt.core.javabuilder</name>
   <arguments>
   </arguments>
  </buildCommand>
   </buildSpec>
   <natures>
    <nature>org.eclipse.jdt.core.javanature</nature>
   </natures>
</projectDescription>

Then, restart eclipse. So now the project became a Java project, but there are still no JRE libraries.
In order to do that, modify .classpath as follows:
<classpath>
  <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
</classpath>

What remains to do, depending on the project is to add at least a source folder. This can be done by right-clicking on the project, then New -> Source Folder.
And you are done.

Java is a proprietary software language owned by Sun Microsystems and very popular among applications. As an example, Minecraft is written in Java.

Java has its syntax deriving from C and C++. Java is based on a class/method/object architecture. Let’s think about classes as objects containing methods can can be used to modify the contents of this objects or make it interact with other classes or objects. So, when you want to create a java program, you need first to create a class that will run as your main program. Files have the extension .java. Its code is compiled into bytecode (.class files) that can be run on java virtual machines, resolving a lot of cross-platform compatibility problems. In few words, by creating a java application, you can be sure it will run on Windows, Linux and Mac.

At the moment of this post, even I have only few hours of practice of java, but it is quite amazing how you can understand its structure quickly if you have done a bit of C++, C, or C# in your life.
What to do when studying java for the first time of your life and you know nothing about it? First you are going to need a java development environment. By working Ubuntu 10.04 LTS, just pick up the package openjdk-6-jdk in Synaptic package manager.

Once this is installed, let’s get started with a simple example.
By being a programmer, what you *need* to feel when learning a new software language is:

  1. How to code it with a simple example like “Hello World”
  2. How to make objects interact
  3. How to compile it
  4. How to run it

The example below takes everything in this list into account. Let’s take 3 class A, B and C containing each different methods.
Class A is defined in file A.java.
public class A {
  public void Hello() {
    System.out.println("Hello World, class A");
  }
  public static void static_hello() {
    System.out.println("Hello World, static class A");
  }
}

This class contains two methods, a static and a normal one. A static method can be called even if the class is not compiled (A.class file not present). A non-static method can be called only if class is compiled.
In another class, if you want to call a method inside class A, you first need to create a new object based on class A and then you can call the method:
A a = new A();
a.Hello();

This will print out the message “Hello World, class A”.

Compilation of this file is made by the command javac:
javac A.java

If you want to call the static method of class A from another object, you need to use:
A.static_hello();
This will print the message “Hello World, static class A”. You don’t need to create a new object related to this class when calling a static method. You do not even need to compile the class to use a static method. This has to be called inside another object. By trying to call a method which is not static on a class that is not compiled or not a new object, compilation returns an error tellings that non-static methods have to be used on new objects.

When trying to launch class A independently with a method (done by command java $CLASS_NAME):
~/bin/jar $ java A
Exception in thread "main" java.lang.NoClassDefFoundError: A

Java throws an exception (error message) because class A does not contain a method “main”.

Now let’s imagine two other classes B (saved) in and C.
/* Saved in B.java */
public class B {
  public void Hello() {
    System.out.println("Hello World, class B");
  }
}

/* Saved in C.java */
File Edit Options Buffers Tools Java Help
public class C {
  /* Main method that can be called independently */
  public static void main(String[] args) {
    A.static_hello();
    /* A.Hello(); */ /* Error if A not compiled with C */
    A a = new A();
    B b = new B();
    a.Hello();
    b.Hello();
  }
}

If all the java files are in same repository, compilation is done with command javac:
javac *.java

In case you want to a new class that depends on objects of an external class, you need:

  • To set up the environment variable $CLASSPATH with the full directory data to a jar file (java library). Ex: CLASSPATH=.:$FOLDER/A.jar
  • Import needed java libraries in the head of the java file of your new class. Ex: import java.A.* if this library is included in $CLASSPATH

About classes B and C, class C contains a main method, so it can be called independently.
$ java C
Hello World, static class A
Hello World, class A
Hello World, class B

©2010-2013 Michael Paquier All content is ©Copyright of Otacoo.com 2010-2013. Privacy Policy - Terms of Use