Wednesday, June 2, 2010

Difference between TRUNCATE & DELETE?

TRUNCATE:
1. Faster - does its work in single execution by
deallocating the data pages used by the table and reducing
the resource overhead of logging the deletions, as well as
the number of locks acquired.
2. Is DDL command
3. Removes all data
4. Does not make entries in a LOG file
3. Can't be rolled-back
4. Can't filter using WHERE clause
5. Can't call DML triggers
6. Can't ensure data consistency in case of foreign-key
references
7. Resets the IDENTITY back to the SEED

DELETE:
1. Slower - does its work by deleting rows one at a time,
logging each row in the transaction log, maintaining log
sequence number (LSN) information and consuming more
database resources and locks.
2. Is DML command
3. Removes data row-by-row
4. Makes entry per row in a LOG file
3. Can use COMMIT or ROLLBACK
4. Can filter using WHERE clause
5. Can call DML triggers
6. Ensures data consistency in case of foreign-key references
7. Does not reset the IDENTITY

Tuesday, June 1, 2010

MySQL to HSQL Migration Tips

Some of the important points that I had jotted down while working on MySQL to HSQL Migration:

1. HSQL does not support the BLOB. We can use LONGVARBINARY. That is, an HSQLDB Blob object does not contain a logical pointer to SQL BLOB data; rather it directly contains a representation of the data (a byte array). Similarly, for 'mediumblob' we can use VARBINARY.

2. HSQL does not support the TEXT / MEDIUMTEXT. We can use LONGVARCHAR.

3. We can not create a column which is equivalent to a keyword without putting it inside escape (double) quotes. HSQL Syntax: CREATE TABLE test_table ( key_id VARCHAR(500) NOT NULL, first_col VARCHAR(50) NOT NULL, "position" BIGINT NOT NULL, third_col VARCHAR(50) NOT NULL, PRIMARY KEY (key_id) );

4. TINYINT, INT, BIGINT does not have precision support. We can not use the precision for the columns and using the data types as is without precision.

5. HSQL does not support column level privileges. UNSIGNED keyword is not supported. We can neglect this keyword.

6. HSQL does not support column level privileges. HSQL does not support the AUTO_INCREMENT. We can use IDENTITY keyword instead. An IDENTITY column is always treated as the primary key for the table (as a result, multi-column primary keys are not possible with an IDENTITY column present).

7. HSQL does not support column level privileges. HSQL (1.8.1) does not support the UNIQUE keyword in a column definition. But it does support unique constraints defined separately. HSQL Syntax: ALTER TABLE <tablename> ADD CONSTRAINT <constraintname> UNIQUE (username);

8. HSQL does not support column level privileges. HSQL does not support the DEFAULT key word in a column definition. But it does support default values to be defined separately. HSQL Syntax: ALTER TABLE <tablename> ALTER COLUMN <columnname> SET DEFAULT <defaultvalue>;

9. HSQL does not support column level privileges. HSQL does not support creation of indices using create table statement. We can create them separately. HSQL Syntax: CREATE INDEX <indexname> ON <tablename> (<columnname>, ...);

10. HSQL does not support "..IF NOT EXISTS.." clause for create table statement and “...IF EXISTS...” clause for drop table statement. We can simply attempt to create the table and catch the exception if it doesn't succeed, then coninue.

11. HSQL does not support "ENGINE, DEFAULT_CHARSET and ROW_FORMAT" options for create table statement. We will provide a work-around to support the same functionality or if not supported at all then will add our comments to the JIRA issue.

12. HSQL does not support insert statment variation such as: "INSERT INTO ... ON DUPLICATE KEY UPDATE". We will provide a work-around to support the same functionality or if not supported at all then will add our comments to the JIRA issue.

13. HSQL (1.8.1.2) does not support TRUNCATE keyword. But it is supported in versions 1.9 onwards. We can use DELETE FROM <tablename> for HSQL (1.8.1.2).

14. HSQL does not support the keyword IGNORE for insert statments.

15. We can use RAWTOHEX(str) method to test insertion of BLOB, CLOB fields. HSQL Syntax: INSERT INTO <tablename> VALUES (RAWTOHEX('SomeStringDataToBeConvertedToBinary'))

16. HSQL does not support LIMIT clause separately. But it does support the LIMIT clause within the SELECT clause itself. HSQL Syntax: SELECT LIMIT <offset> <length> <<columnname>, ... > FROM <tablename>

17. HSQL does not support statement USE <schemaname>. But it does support SET SCHEMA <schemaname> statement.

18. HSQL does not support create/drop of database. We can use create/drop schema directly. HSQL Syntax: CREATE SCHEMA <schemaname> AUTHORIZATION DBA; and DROP SCHEMA <schemaname> CASCADE;

19. HSQL does not support GRANT with wild-cards.

20. HSQL does not support “ALGORITHM=UNDEFINED DEFINER=<username> SQL SECURITY DEFINER” part for the create procedure syntax.

21. NOTE: Since HSQLDB is written in Java, it uses Java classes for its stored procs. Thus, potentially any "public static" java method can be configured as a stored procedure.
 public class HSQLAllStoredProcs {
      public static void proc_Int(Integer i1) {
      }
      public static void proc_IntInt(Integer i1, Integer i2) {
      }
      public static void proc_IntDate(Integer i1, Date d1) {
      }
      public static void proc_LongDate(Long l1, Date d1) {
      }
 }
These static java functions are called directly from the SQL language or using an alias.
CREATE ALIAS load_proc_IntDate FOR "com.mycompany.dao.sp.HSQLAllStoredProcs.proc_IntDate";
22. Datatype Mappings:

MySQL Datatype HSQL (1.8.1.2) Datatype Oracle (10 g) Datatype MS SQL 2005 Datatype
INT INT INT INT
INT(PRECISION) INT NUMBER(PRECISION) INT
VARCHAR VARCHAR VARCHAR VARCHAR
VARCHAR(PRECISION) VARCHAR(PRECISION) VARCHAR(PRECISION) VARCHAR(PRECISION)
CHAR CHAR CHAR CHAR
MEDIUMTEXT LONGVARCHAR CLOB NVARCHAR(MAX)
TEXT LONGVARCHAR CLOB TEXT
DATETIME DATETIME TIMESTAMP DATETIME
TIMESTAMP TIMESTAMP TIMESTAMP TIMESTAMP
TINYINT TINYINT TINYINT TINYINT
TINYINT(PRECISION) TINYINT NUMBER(PRECISION) TINYINT(PRECISION)
BIGINT BIGINT BIGINT BIGINT
BIGINT(PRECISION) BIGINT NUMBER(PRECISION) BIGINT(PRECISION)
MEDIUMBLOB VARBINARY BLOB VARBINARY(MAX)
BLOB LONGVARBINARY BLOB VARBINARY(MAX)
BOOLEAN BOOLEAN NUMBER(1) TINYINT
BOOLEAN DEFAULT TRUE BOOLEAN NUMBER(1) DEFAULT 1 TINYINT DEFAULT 1
VARCHAR(4096) - Precision more than 4000 VARCHAR(4096) CLOB VARCHAR(4096)
UNSIGNED -- NA --
There is no discrimination between SIGNED and UNSIGNED numbers.
-- NA --
There is no discrimination between SIGNED and UNSIGNED numbers.
-- NA --
There is no discrimination between SIGNED and UNSIGNED numbers.
DEFAULT now() CURRENT_TIMESTAMP DEFAULT SYSTIMESTAMP -- NA --
We cannot set to default value for TIMESTAMP fields.
SQL Error: Defaults cannot be created on columns of data type timestamp
ON DELETE RESTRICT (while defining foreign contraint) ON DELETE RESTRICT -- NA --
Default behavior provided by Oracle
-- NA --
Default behavior provided by MS SQL
NOT NULL DEFAULT '' NOT NULL DEFAULT '' DEFAULT '' NOT NULL DEFAULT ''
TIMESTAMP DEFAULT '0000-00-00 00:00:00' CURRENT_TIMESTAMP TIMESTAMP DEFAULT SYSTIMESTAMP -- NA --
We cannot set to default value for TIMESTAMP fields.
SQL Error: Defaults cannot be created on columns of data type timestamp
BEGIN TRANSACTION -- NA --
Stored procedures are not supported using SQL syntax in HSQL.
-- NA --
Transactions are inbuilt in Oracle
BEGIN TRANSACTION

Friday, May 14, 2010

Varargs methods

Varargs methods have been introduced in Java 5, but they currently don’t have a wide diffusion and most part of the Java developers are not aware of their existence.

The vararg notation allows methods to accept a variable number of arguments and packs them into an array. This notation is not as convenient as you might like, because the arrays it creates suffer from the same issues involving reification as other arrays.

A Varargs methods is a standard Java method that can be invoked using a different number of objects as parameters. Example:
 // Method declaration  
 public void print(String... strs) {  
      for (int i = 0; i < strs.length; i++) {  
           System.out.println(strs[i]);  
      }  
 }  
 // Method call  
 print(null, "Hello", "World", "!");  
The syntax "String…" stands for "any number of objects of type string". You can manage this “strange” object as a normal array inside the method body. From the method writer point of view, a Varargs method is just a method with an array as its last argument. The real difference between this method and a standard one becomes evident when it is invoked. Note that the first argument is ignored in the declaration of the print method and if you desire you can write a method using just a Varargs parameter and nothing else.
The compiler translates
 return arithmetic.add(x, x, x);  
to
 return arithmetic.add(x, new Object[] {x, x});  
when the type is given in the method call. It is, as if it was doing the translation before making the decision of the T type.
 int testMethod (int x, int y, int z, int ... n) {}  
A method can accept "normal" parameters along with variable length parameter lists. To do this you must ensure that the variable length parameter list is declared last. Also, a method can't declare more than one varargs parameter.
SYNTAX:
 methodName (type t1, type t2, type t ... arguments) {}  
NOTE: Statements/Snippets taken from multiple posts purely for my understanding as well as jotting different experiences at a single place.

Thursday, May 13, 2010

Spring Transaction Management Facts

Spring Transaction Management Facts: (we may call it as business transactions as opposed to db transactions):

1. One of the most compelling reasons to use the Spring Framework is the comprehensive transaction support. Without a transaction, Spring can use a different connections between the two queries back-to-back.

2. Transactions are declared on the method level, but are actually bound to the running thread. It means that once you declare a method as transactional that transaction can span a called method tree of unlimited depth. That's why DAO layer is, normally, not declared as transactional.

3. Transaction is bound to the thread once you start a method declared as transactional. It stays bound to the thread until the method is finished or transaction is suspended. Non-transactional methods do not suspend transactions. Any method in the call tree that knows how to lookup the transaction bound to the thread can do it, no matter if method is marked as transactional or not.

4. Spring does not change autocommit mode or execute commits or rollbacks or do anything to your connection unless explicitly told.

5. Transactional behavior cannot work when autocommit is on.

6. Spring has capability of rollback the transaction in case of checked exceptions also but for that we need to configure the spring beans.xml accordingly.

7. For more details, please refer the link:
http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html

NOTE: Sincere thanks to all the posts that I referred to when I implemented, experienced the above important points.

Monday, May 10, 2010

Database Basics

Something everyone wants to have quick access to ....

1. Catalog: A relational database contains a catalog that describes the various elements in the system. The catalog divides the database into sub-databases known as schemas. Within each schema are database objects -- tables, views and privileges.
The catalog itself is a set of tables with its own schema name - definition_schema. Tables in the catalog cannot be modified directly. They are modified indirectly with SQL-schema statements.
2. Schema: It is a collection of named objects used to provide a logical classification of database objects. It may contain objects such as tables,
views, aliases, indexes, triggers, and structured types.
3. Table: It is a logical structure maintained by database manager which is made up of columns and rows.
4. View: It is a parsed SQL statement which fetches record at the time of execution. It may be thought of as a virtual table that doesn't really exist in its own right but is instead derived from one or more underlying base tables.
5. Alias: The alias names are local synonyms given to certain database object.
6. Index: It is a type of data structure that allows for (potentially) faster access by providing the database with quick jump points on where to find the full reference (or to find the database row).
7. Function: It is a subprogram written to perform certain computations and return a single value.
8. Stored Procedure: It is collection of SQL statments compiled as a program which reside in the database.
9. Trigger: It is procedural code that is automatically executed in response to certain events on a particular table or view in a database.
10. Synonym: It is an object in Oracle that basically allows you to create a pointer to an object that exists somewhere else.
11. Sequence: It is an object in Oracle that is used to generate a number sequence.
12. JOIN: Return rows when there is at least one match in both tables.
13. LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table.
14. RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table.
15. FULL JOIN: Return rows when there is a match in one of the tables.
16. SELF JOIN: Querying for the result set of join with the same table.

Thursday, April 29, 2010

Power of Log4j

Recently, while working on a client project I came across following factual power of log4j:

1. Log4j has its own class loaders for loading its Appenders.

2. To avoid the log statements mix-in for scenarios when a servlet is serving more than one clients at the same time [NOTE: This would be especially tedious to trace and debug if any processing error occurred in servlet life cycle]; log4j provides an excellent way called as MDC or Mapped Diagnostic Context.

So, how do we make MDC to differentiate logging statements from multiple clients? Simple: Before starting any business process in your code, get the user name (for our Servlet, we can get it from request object) and put that into MDC. Now the user name will be available to the further processing. In your log4j.properties while defining the ‘conversionPattern’, add a pattern %X{key} to retrieve the values that are present in the MDC. The key will be ‘userName’ in our example. It's like getting a value from a Session object.

3. Each log statement throws-up an event called as LoggingEvent which is listened by the registered listeners and/or appenders.

4. NDC vs MDC - Which one should I use?
=> a. NDC has been part of the log4j framework longer than MDC.
b. NDC implements a "stack" onto which context information can be pushed and popped (ie "nested") while MDC implements a "map" into which key/value pair information can be stored.
c. NDC would work even with JDK1.1 but MDC requires JDK 1.2 or later. Under JDK 1.1 the MDC will always return empty values but otherwise will not affect or harm your application.
d. NDC use can lead to memory leaks if you do not periodically call the NDC.remove() method.
e. The MDC is managed on a per thread basis. A child thread automatically inherits a copy of the mapped diagnostic context of its parent.

... there are few more which I will add to this post shortly - So!! Keep Watching!!