1
0
mirror of https://github.com/postgres/postgres.git synced 2025-11-24 00:23:06 +03:00

pgjindent jdbc files. First time jdbc files were formatted.

This commit is contained in:
Bruce Momjian
2001-10-25 06:00:05 +00:00
parent b81844b173
commit d2e27b0674
85 changed files with 23804 additions and 22165 deletions

View File

@@ -88,7 +88,8 @@ public class ImageViewer implements ItemListener
{ {
Dimension s = getSize(); Dimension s = getSize();
if(size==null || bkg==null || !s.equals(size)) { if (size == null || bkg == null || !s.equals(size))
{
size = s; size = s;
bkg = createImage(size.width, size.height); bkg = createImage(size.width, size.height);
} }
@@ -123,15 +124,20 @@ public class ImageViewer implements ItemListener
f.setMenuBar(mb); f.setMenuBar(mb);
mb.add(m = new Menu("PostgreSQL")); mb.add(m = new Menu("PostgreSQL"));
m.add(i = new MenuItem("Initialise")); m.add(i = new MenuItem("Initialise"));
i.addActionListener(new ActionListener() { i.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e) { {
public void actionPerformed(ActionEvent e)
{
ImageViewer.this.init(); ImageViewer.this.init();
} }
}); }
);
m.add(i = new MenuItem("Exit")); m.add(i = new MenuItem("Exit"));
ActionListener exitListener = new ActionListener() { ActionListener exitListener = new ActionListener()
public void actionPerformed(ActionEvent e) { {
public void actionPerformed(ActionEvent e)
{
ImageViewer.this.close(); ImageViewer.this.close();
} }
}; };
@@ -139,16 +145,20 @@ public class ImageViewer implements ItemListener
mb.add(m = new Menu("Image")); mb.add(m = new Menu("Image"));
m.add(i = new MenuItem("Import")); m.add(i = new MenuItem("Import"));
ActionListener importListener = new ActionListener() { ActionListener importListener = new ActionListener()
public void actionPerformed(ActionEvent e) { {
public void actionPerformed(ActionEvent e)
{
ImageViewer.this.importImage(); ImageViewer.this.importImage();
} }
}; };
i.addActionListener(importListener); i.addActionListener(importListener);
m.add(i = new MenuItem("Remove")); m.add(i = new MenuItem("Remove"));
ActionListener removeListener = new ActionListener() { ActionListener removeListener = new ActionListener()
public void actionPerformed(ActionEvent e) { {
public void actionPerformed(ActionEvent e)
{
ImageViewer.this.removeImage(); ImageViewer.this.removeImage();
} }
}; };
@@ -162,11 +172,14 @@ public class ImageViewer implements ItemListener
p.setLayout(new FlowLayout()); p.setLayout(new FlowLayout());
Button b; Button b;
p.add(b = new Button("Refresh List")); p.add(b = new Button("Refresh List"));
b.addActionListener(new ActionListener() { b.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e) { {
public void actionPerformed(ActionEvent e)
{
ImageViewer.this.refreshList(); ImageViewer.this.refreshList();
} }
}); }
);
p.add(b = new Button("Import new image")); p.add(b = new Button("Import new image"));
b.addActionListener(importListener); b.addActionListener(importListener);
p.add(b = new Button("Remove image")); p.add(b = new Button("Remove image"));
@@ -205,12 +218,15 @@ public class ImageViewer implements ItemListener
*/ */
public void init() public void init()
{ {
try { try
{
//db.setAutoCommit(true); //db.setAutoCommit(true);
stat.executeUpdate("create table images (imgname name,imgoid oid)"); stat.executeUpdate("create table images (imgname name,imgoid oid)");
label.setText("Initialised database"); label.setText("Initialised database");
db.commit(); db.commit();
} catch(SQLException ex) { }
catch (SQLException ex)
{
label.setText(ex.toString()); label.setText(ex.toString());
} }
@@ -227,9 +243,12 @@ public class ImageViewer implements ItemListener
*/ */
public void close() public void close()
{ {
try { try
{
db.close(); db.close();
} catch(SQLException ex) { }
catch (SQLException ex)
{
System.err.println(ex.toString()); System.err.println(ex.toString());
} }
System.exit(0); System.exit(0);
@@ -263,19 +282,23 @@ public class ImageViewer implements ItemListener
String name, dir; String name, dir;
Connection db; Connection db;
public importer(Connection db,String name,String dir) { public importer(Connection db, String name, String dir)
{
this.db = db; this.db = db;
this.name = name; this.name = name;
this.dir = dir; this.dir = dir;
} }
public void run() { public void run()
{
// Now the real import stuff // Now the real import stuff
if(name!=null && dir!=null) { if (name != null && dir != null)
{
Statement stat = null; Statement stat = null;
try { try
{
// fetch the large object manager // fetch the large object manager
LargeObjectManager lom = ((org.postgresql.Connection)db).getLargeObjectAPI(); LargeObjectManager lom = ((org.postgresql.Connection)db).getLargeObjectAPI();
@@ -296,7 +319,8 @@ public class ImageViewer implements ItemListener
// Note: we dont use write(buf), as the last block is rarely the same // Note: we dont use write(buf), as the last block is rarely the same
// size as our buffer, so we have to use the amount read. // size as our buffer, so we have to use the amount read.
int s, t = 0; int s, t = 0;
while((s=fis.read(buf,0,buf.length))>0) { while ((s = fis.read(buf, 0, buf.length)) > 0)
{
t += s; t += s;
blob.write(buf, 0, s); blob.write(buf, 0, s);
} }
@@ -316,14 +340,21 @@ public class ImageViewer implements ItemListener
// Finally refresh the names list, and display the current image // Finally refresh the names list, and display the current image
ImageViewer.this.refreshList(); ImageViewer.this.refreshList();
ImageViewer.this.displayImage(name); ImageViewer.this.displayImage(name);
} catch(Exception ex) { }
catch (Exception ex)
{
label.setText(ex.toString()); label.setText(ex.toString());
} finally { }
finally
{
// ensure the statement is closed after us // ensure the statement is closed after us
try { try
{
if (stat != null) if (stat != null)
stat.close(); stat.close();
} catch(SQLException se) { }
catch (SQLException se)
{
System.err.println("closing of Statement failed"); System.err.println("closing of Statement failed");
} }
} }
@@ -336,16 +367,20 @@ public class ImageViewer implements ItemListener
*/ */
public void refreshList() public void refreshList()
{ {
try { try
{
// First, we'll run a query, retrieving all of the image names // First, we'll run a query, retrieving all of the image names
ResultSet rs = stat.executeQuery("select imgname from images order by imgname"); ResultSet rs = stat.executeQuery("select imgname from images order by imgname");
if(rs!=null) { if (rs != null)
{
list.removeAll(); list.removeAll();
while (rs.next()) while (rs.next())
list.addItem(rs.getString(1)); list.addItem(rs.getString(1));
rs.close(); rs.close();
} }
} catch(SQLException ex) { }
catch (SQLException ex)
{
label.setText(ex.toString() + " Have you initialised the database?"); label.setText(ex.toString() + " Have you initialised the database?");
} }
} }
@@ -358,7 +393,8 @@ public class ImageViewer implements ItemListener
*/ */
public void removeImage() public void removeImage()
{ {
try { try
{
// //
// Delete any large objects for the current name // Delete any large objects for the current name
// //
@@ -367,10 +403,12 @@ public class ImageViewer implements ItemListener
// them // them
// //
ResultSet rs = stat.executeQuery("select imgoid from images where imgname='" + currentImage + "'"); ResultSet rs = stat.executeQuery("select imgoid from images where imgname='" + currentImage + "'");
if(rs!=null) { if (rs != null)
{
// Even though there should only be one image, we still have to // Even though there should only be one image, we still have to
// cycle through the ResultSet // cycle through the ResultSet
while(rs.next()) { while (rs.next())
{
lom.delete(rs.getInt(1)); lom.delete(rs.getInt(1));
} }
} }
@@ -382,7 +420,9 @@ public class ImageViewer implements ItemListener
label.setText(currentImage + " deleted"); label.setText(currentImage + " deleted");
currentImage = null; currentImage = null;
refreshList(); refreshList();
} catch(SQLException ex) { }
catch (SQLException ex)
{
label.setText(ex.toString()); label.setText(ex.toString());
} }
} }
@@ -394,7 +434,8 @@ public class ImageViewer implements ItemListener
*/ */
public void displayImage(String name) public void displayImage(String name)
{ {
try { try
{
// //
// Now as we are opening and reading a large object we must // Now as we are opening and reading a large object we must
// turn on Transactions. This includes the ResultSet.getBytes() // turn on Transactions. This includes the ResultSet.getBytes()
@@ -403,26 +444,35 @@ public class ImageViewer implements ItemListener
db.setAutoCommit(false); db.setAutoCommit(false);
ResultSet rs = stat.executeQuery("select imgoid from images where imgname='" + name + "'"); ResultSet rs = stat.executeQuery("select imgoid from images where imgname='" + name + "'");
if(rs!=null) { if (rs != null)
{
// Even though there should only be one image, we still have to // Even though there should only be one image, we still have to
// cycle through the ResultSet // cycle through the ResultSet
while(rs.next()) { while (rs.next())
{
canvas.setImage(canvas.getToolkit().createImage(rs.getBytes(1))); canvas.setImage(canvas.getToolkit().createImage(rs.getBytes(1)));
label.setText(currentImage = name); label.setText(currentImage = name);
} }
} }
rs.close(); rs.close();
} catch(SQLException ex) {
label.setText(ex.toString());
} finally {
try {
db.setAutoCommit(true);
} catch(SQLException ex2) {
} }
catch (SQLException ex)
{
label.setText(ex.toString());
}
finally
{
try
{
db.setAutoCommit(true);
}
catch (SQLException ex2)
{}
} }
} }
public void itemStateChanged(ItemEvent e) { public void itemStateChanged(ItemEvent e)
{
displayImage(list.getItem(((Integer)e.getItem()).intValue())); displayImage(list.getItem(((Integer)e.getItem()).intValue()));
} }
@@ -444,19 +494,23 @@ public class ImageViewer implements ItemListener
*/ */
public static void main(String args[]) public static void main(String args[])
{ {
if(args.length!=3) { if (args.length != 3)
{
instructions(); instructions();
System.exit(1); System.exit(1);
} }
try { try
{
Frame frame = new Frame("PostgreSQL ImageViewer v7.0 rev 1"); Frame frame = new Frame("PostgreSQL ImageViewer v7.0 rev 1");
frame.setLayout(new BorderLayout()); frame.setLayout(new BorderLayout());
ImageViewer viewer = new ImageViewer(frame, args[0], args[1], args[2]); ImageViewer viewer = new ImageViewer(frame, args[0], args[1], args[2]);
frame.pack(); frame.pack();
frame.setLocation(0, 50); frame.setLocation(0, 50);
frame.setVisible(true); frame.setVisible(true);
} catch(Exception ex) { }
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex); System.err.println("Exception caught.\n" + ex);
ex.printStackTrace(); ex.printStackTrace();
} }

View File

@@ -19,7 +19,8 @@ import java.util.*;
* *
* @author William Webber <william@live.com.au> * @author William Webber <william@live.com.au>
*/ */
public class Unicode { public class Unicode
{
/** /**
* The url for the database to connect to. * The url for the database to connect to.
@@ -36,21 +37,25 @@ public class Unicode {
*/ */
private String password; private String password;
private static void usage() { private static void usage()
{
log("usage: example.Unicode <url> <user> <password>"); log("usage: example.Unicode <url> <user> <password>");
} }
private static void log(String message) { private static void log(String message)
{
System.err.println(message); System.err.println(message);
} }
private static void log(String message, Exception e) { private static void log(String message, Exception e)
{
System.err.println(message); System.err.println(message);
e.printStackTrace(); e.printStackTrace();
} }
public Unicode(String url, String user, String password) { public Unicode(String url, String user, String password)
{
this.url = url; this.url = url;
this.user = user; this.user = user;
this.password = password; this.password = password;
@@ -60,7 +65,8 @@ public class Unicode {
* Establish and return a connection to the database. * Establish and return a connection to the database.
*/ */
private Connection getConnection() throws SQLException, private Connection getConnection() throws SQLException,
ClassNotFoundException { ClassNotFoundException
{
Class.forName("org.postgresql.Driver"); Class.forName("org.postgresql.Driver");
Properties info = new Properties(); Properties info = new Properties();
info.put("user", user); info.put("user", user);
@@ -73,14 +79,16 @@ public class Unicode {
* Get string representing a block of 256 consecutive unicode characters. * Get string representing a block of 256 consecutive unicode characters.
* We exclude the null character, "'", and "\". * We exclude the null character, "'", and "\".
*/ */
private String getSqlSafeUnicodeBlock(int blockNum) { private String getSqlSafeUnicodeBlock(int blockNum)
{
if (blockNum < 0 || blockNum > 255) if (blockNum < 0 || blockNum > 255)
throw new IllegalArgumentException("blockNum must be from 0 to " throw new IllegalArgumentException("blockNum must be from 0 to "
+ "255: " + blockNum); + "255: " + blockNum);
StringBuffer sb = new StringBuffer(256); StringBuffer sb = new StringBuffer(256);
int blockFirst = blockNum * 256; int blockFirst = blockNum * 256;
int blockLast = blockFirst + 256; int blockLast = blockFirst + 256;
for (int i = blockFirst; i < blockLast; i++) { for (int i = blockFirst; i < blockLast; i++)
{
char c = (char) i; char c = (char) i;
if (c == '\0' || c == '\'' || c == '\\') if (c == '\0' || c == '\'' || c == '\\')
continue; continue;
@@ -96,7 +104,8 @@ public class Unicode {
* These should not be used in actual Unicode strings; * These should not be used in actual Unicode strings;
* at least, jdk1.2 will not convert them to utf-8. * at least, jdk1.2 will not convert them to utf-8.
*/ */
private boolean isValidUnicodeBlock(int blockNum) { private boolean isValidUnicodeBlock(int blockNum)
{
if (blockNum >= 0xd8 && blockNum <= 0xdb) if (blockNum >= 0xd8 && blockNum <= 0xdb)
return false; return false;
else else
@@ -107,14 +116,19 @@ public class Unicode {
* Report incorrect block retrieval. * Report incorrect block retrieval.
*/ */
private void reportRetrievalError(int blockNum, String block, private void reportRetrievalError(int blockNum, String block,
String retrieved) { String retrieved)
{
String message = "Block " + blockNum + " returned incorrectly: "; String message = "Block " + blockNum + " returned incorrectly: ";
int i = 0; int i = 0;
for (i = 0; i < block.length(); i++) { for (i = 0; i < block.length(); i++)
if (i >= retrieved.length()) { {
if (i >= retrieved.length())
{
message += "too short"; message += "too short";
break; break;
} else if (retrieved.charAt(i) != block.charAt(i)) { }
else if (retrieved.charAt(i) != block.charAt(i))
{
message += message +=
"first changed character at position " + i + ", sent as 0x" "first changed character at position " + i + ", sent as 0x"
+ Integer.toHexString((int) block.charAt(i)) + Integer.toHexString((int) block.charAt(i))
@@ -131,7 +145,8 @@ public class Unicode {
/** /**
* Do the testing. * Do the testing.
*/ */
public void runTest() { public void runTest()
{
Connection connection = null; Connection connection = null;
Statement statement = null; Statement statement = null;
int blockNum = 0; int blockNum = 0;
@@ -140,15 +155,18 @@ public class Unicode {
final int SELECT = 2; final int SELECT = 2;
final int LIKE = 3; final int LIKE = 3;
int mode = CREATE; int mode = CREATE;
try { try
{
connection = getConnection(); connection = getConnection();
statement = connection.createStatement(); statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE test_unicode " statement.executeUpdate("CREATE TABLE test_unicode "
+ "( blockNum INT PRIMARY KEY, " + "( blockNum INT PRIMARY KEY, "
+ "block TEXT );"); + "block TEXT );");
mode = INSERT; mode = INSERT;
for (blockNum = 0; blockNum < 256; blockNum++) { for (blockNum = 0; blockNum < 256; blockNum++)
if (isValidUnicodeBlock(blockNum)) { {
if (isValidUnicodeBlock(blockNum))
{
String block = getSqlSafeUnicodeBlock(blockNum); String block = getSqlSafeUnicodeBlock(blockNum);
statement.executeUpdate statement.executeUpdate
("INSERT INTO test_unicode VALUES ( " + blockNum ("INSERT INTO test_unicode VALUES ( " + blockNum
@@ -156,25 +174,31 @@ public class Unicode {
} }
} }
mode = SELECT; mode = SELECT;
for (blockNum = 0; blockNum < 256; blockNum++) { for (blockNum = 0; blockNum < 256; blockNum++)
if (isValidUnicodeBlock(blockNum)) { {
if (isValidUnicodeBlock(blockNum))
{
String block = getSqlSafeUnicodeBlock(blockNum); String block = getSqlSafeUnicodeBlock(blockNum);
ResultSet rs = statement.executeQuery ResultSet rs = statement.executeQuery
("SELECT block FROM test_unicode WHERE blockNum = " ("SELECT block FROM test_unicode WHERE blockNum = "
+ blockNum + ";"); + blockNum + ";");
if (!rs.next()) if (!rs.next())
log("Could not retrieve block " + blockNum); log("Could not retrieve block " + blockNum);
else { else
{
String retrieved = rs.getString(1); String retrieved = rs.getString(1);
if (!retrieved.equals(block)) { if (!retrieved.equals(block))
{
reportRetrievalError(blockNum, block, retrieved); reportRetrievalError(blockNum, block, retrieved);
} }
} }
} }
} }
mode = LIKE; mode = LIKE;
for (blockNum = 0; blockNum < 256; blockNum++) { for (blockNum = 0; blockNum < 256; blockNum++)
if (isValidUnicodeBlock(blockNum)) { {
if (isValidUnicodeBlock(blockNum))
{
String block = getSqlSafeUnicodeBlock(blockNum); String block = getSqlSafeUnicodeBlock(blockNum);
String likeString = "%" + String likeString = "%" +
block.substring(2, block.length() - 3) + "%" ; block.substring(2, block.length() - 3) + "%" ;
@@ -185,8 +209,11 @@ public class Unicode {
log("Could get block " + blockNum + " using LIKE"); log("Could get block " + blockNum + " using LIKE");
} }
} }
} catch (SQLException sqle) { }
switch (mode) { catch (SQLException sqle)
{
switch (mode)
{
case CREATE: case CREATE:
log("Exception creating database", sqle); log("Exception creating database", sqle);
break; break;
@@ -203,35 +230,46 @@ public class Unicode {
log("Exception", sqle); log("Exception", sqle);
break; break;
} }
} catch (ClassNotFoundException cnfe) { }
catch (ClassNotFoundException cnfe)
{
log("Unable to load driver", cnfe); log("Unable to load driver", cnfe);
return ; return ;
} }
try { try
{
if (statement != null) if (statement != null)
statement.close(); statement.close();
if (connection != null) if (connection != null)
connection.close(); connection.close();
} catch (SQLException sqle) { }
catch (SQLException sqle)
{
log("Exception closing connections", sqle); log("Exception closing connections", sqle);
} }
if (mode > CREATE) { if (mode > CREATE)
{
// If the backend gets what it regards as garbage on a connection, // If the backend gets what it regards as garbage on a connection,
// that connection may become unusable. To be safe, we create // that connection may become unusable. To be safe, we create
// a fresh connection to delete the table. // a fresh connection to delete the table.
try { try
{
connection = getConnection(); connection = getConnection();
statement = connection.createStatement(); statement = connection.createStatement();
statement.executeUpdate("DROP TABLE test_unicode;"); statement.executeUpdate("DROP TABLE test_unicode;");
} catch (Exception sqle) { }
catch (Exception sqle)
{
log("*** ERROR: unable to delete test table " log("*** ERROR: unable to delete test table "
+ "test_unicode; must be deleted manually", sqle); + "test_unicode; must be deleted manually", sqle);
} }
} }
} }
public static void main(String [] args) { public static void main(String [] args)
if (args.length != 3) { {
if (args.length != 3)
{
usage(); usage();
System.exit(1); System.exit(1);
} }

View File

@@ -6,7 +6,7 @@ import java.text.*;
/** /**
* *
* $Id: basic.java,v 1.7 2001/01/31 09:23:45 peter Exp $ * $Id: basic.java,v 1.8 2001/10/25 05:59:58 momjian Exp $
* *
* This example tests the basic components of the JDBC driver, and shows * This example tests the basic components of the JDBC driver, and shows
* how even the simplest of queries can be implemented. * how even the simplest of queries can be implemented.
@@ -61,9 +61,12 @@ public class basic
*/ */
public void cleanup() public void cleanup()
{ {
try { try
{
st.executeUpdate("drop table basic"); st.executeUpdate("drop table basic");
} catch(Exception ex) { }
catch (Exception ex)
{
// We ignore any errors here // We ignore any errors here
} }
} }
@@ -107,7 +110,8 @@ public class basic
// manner. (DateStyles are PostgreSQL's way of handling different methods // manner. (DateStyles are PostgreSQL's way of handling different methods
// of representing dates in the Date data type.) // of representing dates in the Date data type.)
PreparedStatement ps = db.prepareStatement("insert into basic values (?,?)"); PreparedStatement ps = db.prepareStatement("insert into basic values (?,?)");
for(int i=2;i<5;i++) { for (int i = 2;i < 5;i++)
{
ps.setInt(1, 4); // "column a" = 5 ps.setInt(1, 4); // "column a" = 5
ps.setInt(2, i); // "column b" = i ps.setInt(2, i); // "column b" = i
ps.executeUpdate(); // executeUpdate because insert returns no data ps.executeUpdate(); // executeUpdate because insert returns no data
@@ -117,10 +121,12 @@ public class basic
// Finally perform a query on the table // Finally perform a query on the table
System.out.println("performing a query"); System.out.println("performing a query");
ResultSet rs = st.executeQuery("select a, b from basic"); ResultSet rs = st.executeQuery("select a, b from basic");
if(rs!=null) { if (rs != null)
{
// Now we run through the result set, printing out the result. // Now we run through the result set, printing out the result.
// Note, we must call .next() before attempting to read any results // Note, we must call .next() before attempting to read any results
while(rs.next()) { while (rs.next())
{
int a = rs.getInt("a"); // This shows how to get the value by name int a = rs.getInt("a"); // This shows how to get the value by name
int b = rs.getInt(2); // This shows how to get the value by column int b = rs.getInt(2); // This shows how to get the value by column
System.out.println(" a=" + a + " b=" + b); System.out.println(" a=" + a + " b=" + b);
@@ -130,9 +136,11 @@ public class basic
// Now run the query again, showing a more efficient way of getting the // Now run the query again, showing a more efficient way of getting the
// result if you don't know what column number a value is in // result if you don't know what column number a value is in
System.out.println("performing another query"); System.out.println("performing another query");
rs = st.executeQuery("select * from basic where b>1"); rs = st.executeQuery("select * from basic where b>1");
if(rs!=null) { if (rs != null)
{
// First find out the column numbers. // First find out the column numbers.
// //
// It's best to do this here, as calling the methods with the column // It's best to do this here, as calling the methods with the column
@@ -144,7 +152,8 @@ public class basic
// Now we run through the result set, printing out the result. // Now we run through the result set, printing out the result.
// Again, we must call .next() before attempting to read any results // Again, we must call .next() before attempting to read any results
while(rs.next()) { while (rs.next())
{
int a = rs.getInt(col_a); // This shows how to get the value by name int a = rs.getInt(col_a); // This shows how to get the value by name
int b = rs.getInt(col_b); // This shows how to get the value by column int b = rs.getInt(col_b); // This shows how to get the value by column
System.out.println(" a=" + a + " b=" + b); System.out.println(" a=" + a + " b=" + b);
@@ -153,10 +162,12 @@ public class basic
} }
// Now test maxrows by setting it to 3 rows // Now test maxrows by setting it to 3 rows
st.setMaxRows(3); st.setMaxRows(3);
System.out.println("performing a query limited to " + st.getMaxRows()); System.out.println("performing a query limited to " + st.getMaxRows());
rs = st.executeQuery("select a, b from basic"); rs = st.executeQuery("select a, b from basic");
while(rs.next()) { while (rs.next())
{
int a = rs.getInt("a"); // This shows how to get the value by name int a = rs.getInt("a"); // This shows how to get the value by name
int b = rs.getInt(2); // This shows how to get the value by column int b = rs.getInt(2); // This shows how to get the value by column
System.out.println(" a=" + a + " b=" + b); System.out.println(" a=" + a + " b=" + b);
@@ -193,9 +204,12 @@ public class basic
DriverManager.setLogStream(System.err); DriverManager.setLogStream(System.err);
// Now run the tests // Now run the tests
try { try
{
basic test = new basic(args); basic test = new basic(args);
} catch(Exception ex) { }
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex); System.err.println("Exception caught.\n" + ex);
ex.printStackTrace(); ex.printStackTrace();
} }

View File

@@ -111,7 +111,8 @@ public class blobtest
System.out.println("Copying file to large object"); System.out.println("Copying file to large object");
byte buf[] = new byte[2048]; byte buf[] = new byte[2048];
int s, tl = 0; int s, tl = 0;
while((s=fis.read(buf,0,2048))>0) { while ((s = fis.read(buf, 0, 2048)) > 0)
{
System.out.println("Block size=" + s + " offset=" + tl); System.out.println("Block size=" + s + " offset=" + tl);
//System.out.write(buf); //System.out.write(buf);
obj.write(buf, 0, s); obj.write(buf, 0, s);
@@ -144,9 +145,11 @@ public class blobtest
byte buf[] = new byte[512]; byte buf[] = new byte[512];
int s = obj.size(); int s = obj.size();
int tl = 0; int tl = 0;
while(s>0) { while (s > 0)
{
int rs = buf.length; int rs = buf.length;
if(s<rs) rs=s; if (s < rs)
rs = s;
obj.read(buf, 0, rs); obj.read(buf, 0, rs);
fos.write(buf, 0, rs); fos.write(buf, 0, rs);
tl += rs; tl += rs;
@@ -183,8 +186,10 @@ public class blobtest
System.out.println("Selecting row"); System.out.println("Selecting row");
ResultSet rs = s.executeQuery("select a from basic"); ResultSet rs = s.executeQuery("select a from basic");
if(rs!=null) { if (rs != null)
while(rs.next()) { {
while (rs.next())
{
System.out.println("Fetching Blob"); System.out.println("Fetching Blob");
Blob b = rs.getBlob("a"); Blob b = rs.getBlob("a");
System.out.println("Blob.length() = " + b.length()); System.out.println("Blob.length() = " + b.length());
@@ -202,9 +207,12 @@ public class blobtest
private void jdbc2api_cleanup() throws SQLException private void jdbc2api_cleanup() throws SQLException
{ {
db.setAutoCommit(true); db.setAutoCommit(true);
try { try
{
s.executeUpdate("drop table basic"); s.executeUpdate("drop table basic");
} catch(Exception ex) { }
catch (Exception ex)
{
// We ignore any errors here // We ignore any errors here
} }
db.setAutoCommit(false); db.setAutoCommit(false);
@@ -226,7 +234,8 @@ public class blobtest
{ {
System.out.println("PostgreSQL blobtest v7.0 rev 1\n"); System.out.println("PostgreSQL blobtest v7.0 rev 1\n");
if(args.length<3) { if (args.length < 3)
{
instructions(); instructions();
System.exit(1); System.exit(1);
} }
@@ -237,9 +246,12 @@ public class blobtest
DriverManager.setLogStream(System.err); DriverManager.setLogStream(System.err);
// Now run the tests // Now run the tests
try { try
{
blobtest test = new blobtest(args); blobtest test = new blobtest(args);
} catch(Exception ex) { }
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex); System.err.println("Exception caught.\n" + ex);
ex.printStackTrace(); ex.printStackTrace();
} }

View File

@@ -9,7 +9,7 @@ import org.omg.CosNaming.*;
* *
* It has no GUI, just a text frontend to keep it simple. * It has no GUI, just a text frontend to keep it simple.
* *
* $Id: StockClient.java,v 1.1 1999/01/25 21:22:03 scrappy Exp $ * $Id: StockClient.java,v 1.2 2001/10/25 05:59:58 momjian Exp $
*/ */
public class StockClient public class StockClient
{ {
@@ -20,8 +20,10 @@ public class StockClient
BufferedReader in; BufferedReader in;
public StockClient(String[] args) { public StockClient(String[] args)
try { {
try
{
// We need this for our IO // We need this for our IO
in = new BufferedReader(new InputStreamReader(System.in)); in = new BufferedReader(new InputStreamReader(System.in));
@@ -30,13 +32,15 @@ public class StockClient
// Get a reference to the Naming Service // Get a reference to the Naming Service
org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService"); org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService");
if(nameServiceObj==null) { if (nameServiceObj == null)
{
System.err.println("nameServiceObj == null"); System.err.println("nameServiceObj == null");
return ; return ;
} }
nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj); nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj);
if(nameService==null) { if (nameService == null)
{
System.err.println("nameService == null"); System.err.println("nameService == null");
return ; return ;
} }
@@ -46,29 +50,37 @@ public class StockClient
new NameComponent("StockDispenser", "Stock") new NameComponent("StockDispenser", "Stock")
}; };
dispenser = stock.StockDispenserHelper.narrow(nameService.resolve(dispName)); dispenser = stock.StockDispenserHelper.narrow(nameService.resolve(dispName));
if(dispenser==null) { if (dispenser == null)
{
System.err.println("dispenser == null"); System.err.println("dispenser == null");
return ; return ;
} }
// Now run the front end. // Now run the front end.
run(); run();
} catch(Exception e) { }
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
System.exit(1); System.exit(1);
} }
} }
public static void main(String[] args) { public static void main(String[] args)
{
new StockClient(args); new StockClient(args);
} }
public void run() { public void run()
{
// First reserve a StockItem // First reserve a StockItem
try { try
{
item = dispenser.reserveItem(); item = dispenser.reserveItem();
} catch(Exception e) { }
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
System.exit(1); System.exit(1);
@@ -77,18 +89,23 @@ public class StockClient
mainMenu(); mainMenu();
// finally free the StockItem // finally free the StockItem
try { try
{
dispenser.releaseItem(item); dispenser.releaseItem(item);
} catch(Exception e) { }
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
System.exit(1); System.exit(1);
} }
} }
private void mainMenu() { private void mainMenu()
{
boolean run = true; boolean run = true;
while(run) { while (run)
{
System.out.println("\nCORBA Stock System\n"); System.out.println("\nCORBA Stock System\n");
System.out.println(" 1 Display stock item"); System.out.println(" 1 Display stock item");
System.out.println(" 2 Remove item from stock"); System.out.println(" 2 Remove item from stock");
@@ -126,10 +143,13 @@ public class StockClient
} }
} }
private void displayItem() { private void displayItem()
try { {
try
{
int id = getMenu("\nStockID to display", item.getLastID()); int id = getMenu("\nStockID to display", item.getLastID());
if(id>0) { if (id > 0)
{
item.fetchItem(id); item.fetchItem(id);
System.out.println("========================================"); System.out.println("========================================");
@@ -146,7 +166,8 @@ public class StockClient
System.out.println("========================================"); System.out.println("========================================");
if (av > 0) if (av > 0)
if(yn("Take this item out of stock?")) { if (yn("Take this item out of stock?"))
{
int rem = 1; int rem = 1;
if (av > 1) if (av > 1)
rem = getMenu("How many?", av); rem = getMenu("How many?", av);
@@ -155,70 +176,91 @@ public class StockClient
} }
} }
} catch(Exception e) { }
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
} }
} }
private void bookOut() { private void bookOut()
try { {
try
{
int id = getMenu("\nStockID to take out", item.getLastID()); int id = getMenu("\nStockID to take out", item.getLastID());
if(id>0) { if (id > 0)
{
item.fetchItem(id); item.fetchItem(id);
int av = item.getAvailable(); int av = item.getAvailable();
if (av > 0) if (av > 0)
if(yn("Take this item out of stock?")) { if (yn("Take this item out of stock?"))
{
int rem = 1; int rem = 1;
if (av > 1) if (av > 1)
rem = getMenu("How many?", av); rem = getMenu("How many?", av);
if (rem > 0) if (rem > 0)
item.removeStock(rem); item.removeStock(rem);
} }
else { else
{
System.out.println("This item is not in stock."); System.out.println("This item is not in stock.");
int order = item.getOrdered(); int order = item.getOrdered();
if (order > 0) if (order > 0)
System.out.println("There are " + item.getOrdered() + " items on order."); System.out.println("There are " + item.getOrdered() + " items on order.");
else { else
if(item.isItemValid()) { {
if (item.isItemValid())
{
System.out.println("You will need to order some more " + item.getDescription()); System.out.println("You will need to order some more " + item.getDescription());
order(id); order(id);
} else }
else
System.out.println("This item is now obsolete"); System.out.println("This item is now obsolete");
} }
} }
} else }
else
System.out.println(item.getDescription() + "\nThis item is out of stock"); System.out.println(item.getDescription() + "\nThis item is out of stock");
} catch(Exception e) { }
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
} }
} }
// book an item into stock // book an item into stock
private void bookIn() { private void bookIn()
try { {
try
{
int id = getMenu("\nStockID to book in", item.getLastID()); int id = getMenu("\nStockID to book in", item.getLastID());
item.fetchItem(id); item.fetchItem(id);
System.out.println(item.getDescription()); System.out.println(item.getDescription());
if(item.getOrdered()>0) { if (item.getOrdered() > 0)
{
int am = getMenu("How many do you want to book in", item.getOrdered()); int am = getMenu("How many do you want to book in", item.getOrdered());
if (am > 0) if (am > 0)
item.addNewStock(am); item.addNewStock(am);
} else }
else
System.out.println("You don't have any of this item on ordered"); System.out.println("You don't have any of this item on ordered");
} catch(Exception e) { }
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
} }
} }
// Order an item // Order an item
private void order(int id) { private void order(int id)
try { {
try
{
if (id == 0) if (id == 0)
id = getMenu("\nStockID to order", item.getLastID()); id = getMenu("\nStockID to order", item.getLastID());
item.fetchItem(id); item.fetchItem(id);
@@ -226,50 +268,66 @@ public class StockClient
int am = getMenu("How many do you want to order", 999); int am = getMenu("How many do you want to order", 999);
if (am > 0) if (am > 0)
item.orderStock(am); item.orderStock(am);
} catch(Exception e) { }
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
} }
} }
private void displayAll() { private void displayAll()
try { {
try
{
boolean cont = true; boolean cont = true;
int nr = item.getLastID(); int nr = item.getLastID();
String header = "\nId\tAvail\tOrdered\tDescription"; String header = "\nId\tAvail\tOrdered\tDescription";
System.out.println(header); System.out.println(header);
for(int i=1;i<=nr && cont;i++) { for (int i = 1;i <= nr && cont;i++)
{
item.fetchItem(i); item.fetchItem(i);
System.out.println("" + i + "\t" + item.getAvailable() + "\t" + item.getOrdered() + "\t" + item.getDescription()); System.out.println("" + i + "\t" + item.getAvailable() + "\t" + item.getOrdered() + "\t" + item.getDescription());
if((i%20)==0) { if ((i % 20) == 0)
{
if ((cont = yn("Continue?"))) if ((cont = yn("Continue?")))
System.out.println(header); System.out.println(header);
} }
} }
} catch(Exception e) { }
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
} }
} }
private int getMenu(String title,int max) { private int getMenu(String title, int max)
{
int v = -1; int v = -1;
while(v<0 || v>max) { while (v < 0 || v > max)
{
System.out.print(title); System.out.print(title);
System.out.print(" [0-" + max + "]: "); System.out.print(" [0-" + max + "]: ");
System.out.flush(); System.out.flush();
try { try
{
v = Integer.parseInt(in.readLine()); v = Integer.parseInt(in.readLine());
} catch(Exception nfe) { }
catch (Exception nfe)
{
v = -1; v = -1;
} }
} }
return v; return v;
} }
private boolean yn(String title) { private boolean yn(String title)
try { {
while(true) { try
{
while (true)
{
System.out.print(title); System.out.print(title);
System.out.flush(); System.out.flush();
String s = in.readLine(); String s = in.readLine();
@@ -278,7 +336,9 @@ public class StockClient
if (s.startsWith("n") || s.startsWith("N")) if (s.startsWith("n") || s.startsWith("N"))
return false; return false;
} }
} catch(Exception nfe) { }
catch (Exception nfe)
{
System.out.println(nfe.toString()); System.out.println(nfe.toString());
nfe.printStackTrace(); nfe.printStackTrace();
System.exit(1); System.exit(1);

View File

@@ -13,7 +13,7 @@ import java.sql.*;
* that an object could be changed by another client, and we need to ensure that * that an object could be changed by another client, and we need to ensure that
* the returned data is live and accurate. * the returned data is live and accurate.
* *
* $Id: StockDB.java,v 1.2 2000/04/26 05:32:01 peter Exp $ * $Id: StockDB.java,v 1.3 2001/10/25 05:59:58 momjian Exp $
*/ */
public class StockDB public class StockDB
{ {
@@ -23,29 +23,35 @@ public class StockDB
// the current stock number // the current stock number
int id = -1; int id = -1;
public void connect(String url,String usr,String pwd) throws Exception { public void connect(String url, String usr, String pwd) throws Exception
{
Class.forName("org.postgresql.Driver"); Class.forName("org.postgresql.Driver");
System.out.println("Connecting to " + url); System.out.println("Connecting to " + url);
con = DriverManager.getConnection(url, usr, pwd); con = DriverManager.getConnection(url, usr, pwd);
st = con.createStatement(); st = con.createStatement();
} }
public void closeConnection() throws Exception { public void closeConnection() throws Exception
{
con.close(); con.close();
} }
public void fetchItem(int id) throws Exception { public void fetchItem(int id) throws Exception
{
this.id = id; this.id = id;
} }
public int newItem() throws Exception { public int newItem() throws Exception
{
// tba // tba
return -1; return -1;
} }
public String getDescription() throws SQLException { public String getDescription() throws SQLException
{
ResultSet rs = st.executeQuery("select description from stock where id=" + id); ResultSet rs = st.executeQuery("select description from stock where id=" + id);
if(rs!=null) { if (rs != null)
{
rs.next(); rs.next();
String s = rs.getString(1); String s = rs.getString(1);
rs.close(); rs.close();
@@ -54,9 +60,11 @@ public class StockDB
throw new SQLException("No ResultSet"); throw new SQLException("No ResultSet");
} }
public int getAvailable() throws SQLException { public int getAvailable() throws SQLException
{
ResultSet rs = st.executeQuery("select avail from stock where id=" + id); ResultSet rs = st.executeQuery("select avail from stock where id=" + id);
if(rs!=null) { if (rs != null)
{
rs.next(); rs.next();
int v = rs.getInt(1); int v = rs.getInt(1);
rs.close(); rs.close();
@@ -65,9 +73,11 @@ public class StockDB
throw new SQLException("No ResultSet"); throw new SQLException("No ResultSet");
} }
public int getOrdered() throws SQLException { public int getOrdered() throws SQLException
{
ResultSet rs = st.executeQuery("select ordered from stock where id=" + id); ResultSet rs = st.executeQuery("select ordered from stock where id=" + id);
if(rs!=null) { if (rs != null)
{
rs.next(); rs.next();
int v = rs.getInt(1); int v = rs.getInt(1);
rs.close(); rs.close();
@@ -76,9 +86,11 @@ public class StockDB
throw new SQLException("No ResultSet"); throw new SQLException("No ResultSet");
} }
public boolean isItemValid() throws SQLException { public boolean isItemValid() throws SQLException
{
ResultSet rs = st.executeQuery("select valid from stock where id=" + id); ResultSet rs = st.executeQuery("select valid from stock where id=" + id);
if(rs!=null) { if (rs != null)
{
rs.next(); rs.next();
boolean b = rs.getBoolean(1); boolean b = rs.getBoolean(1);
rs.close(); rs.close();
@@ -87,25 +99,30 @@ public class StockDB
throw new SQLException("No ResultSet"); throw new SQLException("No ResultSet");
} }
public void addNewStock(int amount) throws SQLException { public void addNewStock(int amount) throws SQLException
{
st.executeUpdate("update stock set avail=avail+" + amount + st.executeUpdate("update stock set avail=avail+" + amount +
", ordered=ordered-" + amount + ", ordered=ordered-" + amount +
" where id=" + id + " and ordered>=" + amount); " where id=" + id + " and ordered>=" + amount);
} }
public void removeStock(int amount) throws SQLException { public void removeStock(int amount) throws SQLException
{
st.executeUpdate("update stock set avail=avail-" + amount + st.executeUpdate("update stock set avail=avail-" + amount +
" where id=" + id); " where id=" + id);
} }
public void orderStock(int amount) throws SQLException { public void orderStock(int amount) throws SQLException
{
st.executeUpdate("update stock set ordered=ordered+" + amount + st.executeUpdate("update stock set ordered=ordered+" + amount +
" where id=" + id); " where id=" + id);
} }
public int getLastID() throws SQLException { public int getLastID() throws SQLException
{
ResultSet rs = st.executeQuery("select max(id) from stock"); ResultSet rs = st.executeQuery("select max(id) from stock");
if(rs!=null) { if (rs != null)
{
rs.next(); rs.next();
int v = rs.getInt(1); int v = rs.getInt(1);
rs.close(); rs.close();

View File

@@ -5,7 +5,7 @@ import org.omg.CosNaming.*;
/** /**
* This class implements the server side of the example. * This class implements the server side of the example.
* *
* $Id: StockDispenserImpl.java,v 1.1 1999/01/25 21:22:03 scrappy Exp $ * $Id: StockDispenserImpl.java,v 1.2 2001/10/25 05:59:58 momjian Exp $
*/ */
public class StockDispenserImpl extends stock._StockDispenserImplBase public class StockDispenserImpl extends stock._StockDispenserImplBase
{ {
@@ -17,7 +17,8 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
{ {
super(); super();
try { try
{
// get reference to orb // get reference to orb
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null); org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
@@ -25,12 +26,15 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
if (num >= maxObjects) if (num >= maxObjects)
num = maxObjects; num = maxObjects;
numObjects = num; numObjects = num;
for(int i=0;i<numObjects;i++) { for (int i = 0;i < numObjects;i++)
{
stock[i] = new StockItemStatus(); stock[i] = new StockItemStatus();
stock[i].ref = new StockItemImpl(args, "StockItem" + (i + 1)); stock[i].ref = new StockItemImpl(args, "StockItem" + (i + 1));
orb.connect(stock[i].ref); orb.connect(stock[i].ref);
} }
} catch(org.omg.CORBA.SystemException e) { }
catch (org.omg.CORBA.SystemException e)
{
e.printStackTrace(); e.printStackTrace();
} }
} }
@@ -40,8 +44,10 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
*/ */
public stock.StockItem reserveItem() throws stock.StockException public stock.StockItem reserveItem() throws stock.StockException
{ {
for(int i=0;i<numObjects;i++) { for (int i = 0;i < numObjects;i++)
if(!stock[i].inUse) { {
if (!stock[i].inUse)
{
stock[i].inUse = true; stock[i].inUse = true;
System.out.println("Reserving slot " + i); System.out.println("Reserving slot " + i);
return stock[i].ref; return stock[i].ref;
@@ -55,8 +61,10 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
*/ */
public void releaseItem(stock.StockItem item) throws stock.StockException public void releaseItem(stock.StockItem item) throws stock.StockException
{ {
for(int i=0;i<numObjects;i++) { for (int i = 0;i < numObjects;i++)
if(stock[i].ref.getInstanceName().equals(item.getInstanceName())) { {
if (stock[i].ref.getInstanceName().equals(item.getInstanceName()))
{
stock[i].inUse = false; stock[i].inUse = false;
System.out.println("Releasing slot " + i); System.out.println("Releasing slot " + i);
return ; return ;
@@ -74,7 +82,8 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
StockItemImpl ref; StockItemImpl ref;
boolean inUse; boolean inUse;
StockItemStatus() { StockItemStatus()
{
ref = null; ref = null;
inUse = false; inUse = false;
} }

View File

@@ -5,21 +5,25 @@ import org.omg.CosNaming.*;
/** /**
* This class implements the server side of the example. * This class implements the server side of the example.
* *
* $Id: StockItemImpl.java,v 1.1 1999/01/25 21:22:04 scrappy Exp $ * $Id: StockItemImpl.java,v 1.2 2001/10/25 05:59:58 momjian Exp $
*/ */
public class StockItemImpl extends stock._StockItemImplBase public class StockItemImpl extends stock._StockItemImplBase
{ {
private StockDB db; private StockDB db;
private String instanceName; private String instanceName;
public StockItemImpl(String[] args,String iname) { public StockItemImpl(String[] args, String iname)
{
super(); super();
try { try
{
db = new StockDB(); db = new StockDB();
db.connect(args[1], args[2], args[3]); db.connect(args[1], args[2], args[3]);
System.out.println("StockDB object " + iname + " created"); System.out.println("StockDB object " + iname + " created");
instanceName = iname; instanceName = iname;
} catch(Exception e) { }
catch (Exception e)
{
e.printStackTrace(); e.printStackTrace();
} }
} }
@@ -29,10 +33,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It sets the item to view * It sets the item to view
*/ */
public void fetchItem(int id) throws stock.StockException { public void fetchItem(int id) throws stock.StockException
try { {
try
{
db.fetchItem(id); db.fetchItem(id);
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
@@ -43,10 +51,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It sets the item to view * It sets the item to view
*/ */
public int newItem() throws stock.StockException { public int newItem() throws stock.StockException
try { {
try
{
return db.newItem(); return db.newItem();
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
@@ -56,10 +68,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It returns the description of a Stock item * It returns the description of a Stock item
*/ */
public String getDescription() throws stock.StockException { public String getDescription() throws stock.StockException
try { {
try
{
return db.getDescription(); return db.getDescription();
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
@@ -69,10 +85,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It returns the description of a Stock item * It returns the description of a Stock item
*/ */
public int getAvailable() throws stock.StockException { public int getAvailable() throws stock.StockException
try { {
try
{
return db.getAvailable(); return db.getAvailable();
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
@@ -82,10 +102,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It returns the description of a Stock item * It returns the description of a Stock item
*/ */
public int getOrdered() throws stock.StockException { public int getOrdered() throws stock.StockException
try { {
try
{
return db.getOrdered(); return db.getOrdered();
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
@@ -95,10 +119,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It returns the description of a Stock item * It returns the description of a Stock item
*/ */
public boolean isItemValid() throws stock.StockException { public boolean isItemValid() throws stock.StockException
try { {
try
{
return db.isItemValid(); return db.isItemValid();
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
@@ -108,10 +136,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It returns the description of a Stock item * It returns the description of a Stock item
*/ */
public void addNewStock(int id) throws stock.StockException { public void addNewStock(int id) throws stock.StockException
try { {
try
{
db.addNewStock(id); db.addNewStock(id);
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
@@ -121,10 +153,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It returns the description of a Stock item * It returns the description of a Stock item
*/ */
public void removeStock(int id) throws stock.StockException { public void removeStock(int id) throws stock.StockException
try { {
try
{
db.removeStock(id); db.removeStock(id);
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
@@ -134,10 +170,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It returns the description of a Stock item * It returns the description of a Stock item
*/ */
public void orderStock(int id) throws stock.StockException { public void orderStock(int id) throws stock.StockException
try { {
try
{
db.orderStock(id); db.orderStock(id);
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
@@ -145,10 +185,14 @@ public class StockItemImpl extends stock._StockItemImplBase
/** /**
* This returns the highest id used, hence the number of items available * This returns the highest id used, hence the number of items available
*/ */
public int getLastID() throws stock.StockException { public int getLastID() throws stock.StockException
try { {
try
{
return db.getLastID(); return db.getLastID();
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
@@ -156,7 +200,8 @@ public class StockItemImpl extends stock._StockItemImplBase
/** /**
* This is used by our Dispenser * This is used by our Dispenser
*/ */
public String getInstanceName() { public String getInstanceName()
{
return instanceName; return instanceName;
} }
} }

View File

@@ -5,7 +5,7 @@ import org.omg.CosNaming.*;
/** /**
* This class implements the server side of the example. * This class implements the server side of the example.
* *
* $Id: StockServer.java,v 1.1 1999/01/25 21:22:04 scrappy Exp $ * $Id: StockServer.java,v 1.2 2001/10/25 05:59:58 momjian Exp $
*/ */
public class StockServer public class StockServer
{ {
@@ -13,7 +13,8 @@ public class StockServer
{ {
int numInstances = 3; int numInstances = 3;
try { try
{
// Initialise the ORB // Initialise the ORB
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null); org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
@@ -25,13 +26,15 @@ public class StockServer
// Get the naming service // Get the naming service
org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService"); org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService");
if(nameServiceObj == null) { if (nameServiceObj == null)
{
System.err.println("nameServiceObj = null"); System.err.println("nameServiceObj = null");
return ; return ;
} }
org.omg.CosNaming.NamingContext nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj); org.omg.CosNaming.NamingContext nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj);
if(nameService == null) { if (nameService == null)
{
System.err.println("nameService = null"); System.err.println("nameService = null");
return ; return ;
} }
@@ -44,7 +47,9 @@ public class StockServer
// Now wait forever for the current thread to die // Now wait forever for the current thread to die
Thread.currentThread().join(); Thread.currentThread().join();
} catch(Exception e) { }
catch (Exception e)
{
e.printStackTrace(); e.printStackTrace();
} }
} }

View File

@@ -69,9 +69,12 @@ public class datestyle
*/ */
public void cleanup() public void cleanup()
{ {
try { try
{
st.executeUpdate("drop table datestyle"); st.executeUpdate("drop table datestyle");
} catch(Exception ex) { }
catch (Exception ex)
{
// We ignore any errors here // We ignore any errors here
} }
} }
@@ -112,7 +115,8 @@ public class datestyle
{ {
System.out.println("\nRunning tests:"); System.out.println("\nRunning tests:");
for(int i=0;i<styles.length;i++) { for (int i = 0;i < styles.length;i++)
{
System.out.print("Test " + i + " - " + styles[i]); System.out.print("Test " + i + " - " + styles[i]);
System.out.flush(); System.out.flush();
@@ -132,7 +136,8 @@ public class datestyle
if (rs == null) if (rs == null)
throw new SQLException("The test query returned no data"); throw new SQLException("The test query returned no data");
while(rs.next()) { while (rs.next())
{
// The JDBC spec states we should only read each column once. // The JDBC spec states we should only read each column once.
// In the current implementation of the driver, this is not necessary. // In the current implementation of the driver, this is not necessary.
// Here we use this fact to see what the query really returned. // Here we use this fact to see what the query really returned.
@@ -171,9 +176,12 @@ public class datestyle
DriverManager.setLogStream(System.err); DriverManager.setLogStream(System.err);
// Now run the tests // Now run the tests
try { try
{
datestyle test = new datestyle(args); datestyle test = new datestyle(args);
} catch(Exception ex) { }
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex); System.err.println("Exception caught.\n" + ex);
ex.printStackTrace(); ex.printStackTrace();
} }

View File

@@ -22,7 +22,8 @@ public class metadata
/** /**
* These are the available tests on DatabaseMetaData * These are the available tests on DatabaseMetaData
*/ */
public void doDatabaseMetaData() throws SQLException { public void doDatabaseMetaData() throws SQLException
{
if (doTest("getProcedures() - should show all available procedures")) if (doTest("getProcedures() - should show all available procedures"))
displayResult(dbmd.getProcedures(null, null, null)); displayResult(dbmd.getProcedures(null, null, null));
@@ -55,7 +56,8 @@ public class metadata
/** /**
* These are the available tests on ResultSetMetaData * These are the available tests on ResultSetMetaData
*/ */
public void doResultSetMetaData() throws SQLException { public void doResultSetMetaData() throws SQLException
{
String sql = "select imagename,descr,source,cost from test_a,test_b,test_c where test_a.id=test_b.imageid and test_a.id=test_c.imageid"; String sql = "select imagename,descr,source,cost from test_a,test_b,test_c where test_a.id=test_b.imageid and test_a.id=test_c.imageid";
@@ -70,17 +72,20 @@ public class metadata
// ResultSet. // ResultSet.
// //
// NB: displayResult() actually closes the ResultSet. // NB: displayResult() actually closes the ResultSet.
if(doTest("Display query result")) { if (doTest("Display query result"))
{
System.out.println("Query: " + sql); System.out.println("Query: " + sql);
displayResult(rs); displayResult(rs);
} else }
else
rs.close(); rs.close();
} }
/** /**
* This creates some test data * This creates some test data
*/ */
public void init() throws SQLException { public void init() throws SQLException
{
System.out.println("Creating some tables"); System.out.println("Creating some tables");
cleanup(); cleanup();
st.executeUpdate("create table test_a (imagename name,image oid,id int4)"); st.executeUpdate("create table test_a (imagename name,image oid,id int4)");
@@ -96,12 +101,16 @@ public class metadata
/** /**
* This removes the test data * This removes the test data
*/ */
public void cleanup() throws SQLException { public void cleanup() throws SQLException
try { {
try
{
st.executeUpdate("drop table test_a"); st.executeUpdate("drop table test_a");
st.executeUpdate("drop table test_b"); st.executeUpdate("drop table test_b");
st.executeUpdate("drop table test_c"); st.executeUpdate("drop table test_c");
} catch(Exception ex) { }
catch (Exception ex)
{
// We ignore any errors here // We ignore any errors here
} }
} }
@@ -146,17 +155,22 @@ public class metadata
/** /**
* This asks if the user requires to run a test. * This asks if the user requires to run a test.
*/ */
public boolean doTest(String s) { public boolean doTest(String s)
{
System.out.println(); System.out.println();
System.out.print(s); System.out.print(s);
System.out.print(" Perform test? Y or N:"); System.out.print(" Perform test? Y or N:");
System.out.flush(); System.out.flush();
char c = ' '; char c = ' ';
try { try
while(!(c=='n' || c=='y' || c=='N' || c=='Y')) { {
while (!(c == 'n' || c == 'y' || c == 'N' || c == 'Y'))
{
c = (char)System.in.read(); c = (char)System.in.read();
} }
} catch(IOException ioe) { }
catch (IOException ioe)
{
return false; return false;
} }
@@ -178,9 +192,11 @@ public class metadata
System.out.print(rsmd.getColumnLabel(i) + (i < cols ? "\t" : "\n")); System.out.print(rsmd.getColumnLabel(i) + (i < cols ? "\t" : "\n"));
// now the results // now the results
while(rs.next()) { while (rs.next())
{
count++; count++;
for(int i=1;i<=cols;i++) { for (int i = 1;i <= cols;i++)
{
Object o = rs.getObject(i); Object o = rs.getObject(i);
if (rs.wasNull()) if (rs.wasNull())
System.out.print("{null}" + (i < cols ? "\t" : "\n")); System.out.print("{null}" + (i < cols ? "\t" : "\n"));
@@ -200,13 +216,17 @@ public class metadata
*/ */
public void processSlashCommand(String line) throws SQLException public void processSlashCommand(String line) throws SQLException
{ {
if(line.startsWith("\\d")) { if (line.startsWith("\\d"))
{
if(line.startsWith("\\d ")) { if (line.startsWith("\\d "))
{
// Display details about a table // Display details about a table
String table = line.substring(3); String table = line.substring(3);
displayResult(dbmd.getColumns(null, null, table, "%")); displayResult(dbmd.getColumns(null, null, table, "%"));
} else { }
else
{
String types[] = null; String types[] = null;
if (line.equals("\\d")) if (line.equals("\\d"))
types = allUserTables; types = allUserTables;
@@ -228,7 +248,8 @@ public class metadata
// //
displayResult(dbmd.getTables(null, null, "%", types)); displayResult(dbmd.getTables(null, null, "%", types));
} }
} else }
else
throw new SQLException("Unsupported \\ command: " + line); throw new SQLException("Unsupported \\ command: " + line);
} }
@@ -264,9 +285,12 @@ public class metadata
DriverManager.setLogStream(System.err); DriverManager.setLogStream(System.err);
// Now run the tests // Now run the tests
try { try
{
metadata test = new metadata(args); metadata test = new metadata(args);
} catch(Exception ex) { }
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex); System.err.println("Exception caught.\n" + ex);
ex.printStackTrace(); ex.printStackTrace();
} }

View File

@@ -49,17 +49,22 @@ public class psql
// Now the main loop. // Now the main loop.
int tt = 0, lineno = 1; int tt = 0, lineno = 1;
while(tt!=StreamTokenizer.TT_EOF && ! done) { // done added by CWJ to permit \q command while (tt != StreamTokenizer.TT_EOF && ! done)
{ // done added by CWJ to permit \q command
System.out.print("[" + lineno + "] "); System.out.print("[" + lineno + "] ");
System.out.flush(); System.out.flush();
// Here, we trap SQLException so they don't terminate the application // Here, we trap SQLException so they don't terminate the application
try { try
if((tt=input.nextToken())==StreamTokenizer.TT_WORD) { {
if ((tt = input.nextToken()) == StreamTokenizer.TT_WORD)
{
processLine(input.sval); processLine(input.sval);
lineno++; lineno++;
} }
} catch(SQLException ex) { }
catch (SQLException ex)
{
System.out.println(ex.getMessage()); System.out.println(ex.getMessage());
} }
} }
@@ -75,25 +80,33 @@ public class psql
*/ */
public void processLine(String line) throws SQLException public void processLine(String line) throws SQLException
{ {
if(line.startsWith("\\")) { if (line.startsWith("\\"))
{
processSlashCommand(line); processSlashCommand(line);
return ; return ;
} }
boolean type = st.execute(line); boolean type = st.execute(line);
boolean loop = true; boolean loop = true;
while(loop) { while (loop)
if(type) { {
if (type)
{
// A ResultSet was returned // A ResultSet was returned
ResultSet rs = st.getResultSet(); ResultSet rs = st.getResultSet();
displayResult(rs); displayResult(rs);
} else { }
else
{
int count = st.getUpdateCount(); int count = st.getUpdateCount();
if(count==-1) { if (count == -1)
{
// This indicates nothing left // This indicates nothing left
loop = false; loop = false;
} else { }
else
{
// An update count was returned // An update count was returned
System.out.println("Updated " + st.getUpdateCount() + " rows"); System.out.println("Updated " + st.getUpdateCount() + " rows");
} }
@@ -118,8 +131,10 @@ public class psql
System.out.print(rsmd.getColumnLabel(i) + (i < cols ? "\t" : "\n")); System.out.print(rsmd.getColumnLabel(i) + (i < cols ? "\t" : "\n"));
// now the results // now the results
while(rs.next()) { while (rs.next())
for(int i=1;i<=cols;i++) { {
for (int i = 1;i <= cols;i++)
{
Object o = rs.getObject(i); Object o = rs.getObject(i);
if (rs.wasNull()) if (rs.wasNull())
System.out.print("{null}" + (i < cols ? "\t" : "\n")); System.out.print("{null}" + (i < cols ? "\t" : "\n"));
@@ -137,13 +152,17 @@ public class psql
*/ */
public void processSlashCommand(String line) throws SQLException public void processSlashCommand(String line) throws SQLException
{ {
if(line.startsWith("\\d")) { if (line.startsWith("\\d"))
{
if(line.startsWith("\\d ")) { if (line.startsWith("\\d "))
{
// Display details about a table // Display details about a table
String table = line.substring(3); String table = line.substring(3);
displayResult(dbmd.getColumns(null, null, table, "%")); displayResult(dbmd.getColumns(null, null, table, "%"));
} else { }
else
{
String types[] = null; String types[] = null;
if (line.equals("\\d")) if (line.equals("\\d"))
types = allUserTables; types = allUserTables;
@@ -165,7 +184,8 @@ public class psql
// //
displayResult(dbmd.getTables(null, null, "%", types)); displayResult(dbmd.getTables(null, null, "%", types));
} }
} else if(line.equals("\\q")) // Added by CWJ to permit \q command }
else if (line.equals("\\q")) // Added by CWJ to permit \q command
done = true; done = true;
else else
throw new SQLException("Unsupported \\ command: " + line); throw new SQLException("Unsupported \\ command: " + line);
@@ -203,9 +223,12 @@ public class psql
DriverManager.setLogStream(System.err); DriverManager.setLogStream(System.err);
// Now run the tests // Now run the tests
try { try
{
psql test = new psql(args); psql test = new psql(args);
} catch(Exception ex) { }
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex); System.err.println("Exception caught.\n" + ex);
ex.printStackTrace(); ex.printStackTrace();
} }

View File

@@ -61,15 +61,21 @@ public class threadsafe
*/ */
public void cleanup() public void cleanup()
{ {
try { try
{
st.executeUpdate("drop table basic1"); st.executeUpdate("drop table basic1");
} catch(Exception ex) { }
catch (Exception ex)
{
// We ignore any errors here // We ignore any errors here
} }
try { try
{
st.executeUpdate("drop table basic2"); st.executeUpdate("drop table basic2");
} catch(Exception ex) { }
catch (Exception ex)
{
// We ignore any errors here // We ignore any errors here
} }
} }
@@ -83,7 +89,8 @@ public class threadsafe
thread3 thread3 = null; thread3 thread3 = null;
try { try
{
// create the two threads // create the two threads
Thread thread0 = Thread.currentThread(); Thread thread0 = Thread.currentThread();
@@ -102,7 +109,9 @@ public class threadsafe
while (thread1.isAlive() || thread2.isAlive() || thread3.isAlive()) while (thread1.isAlive() || thread2.isAlive() || thread3.isAlive())
thread0.yield(); thread0.yield();
} finally { }
finally
{
// clean up after thread3 (the finally ensures this is run even // clean up after thread3 (the finally ensures this is run even
// if an exception is thrown inside the try { } construct) // if an exception is thrown inside the try { } construct)
if (thread3 != null) if (thread3 != null)
@@ -118,13 +127,16 @@ public class threadsafe
Connection c; Connection c;
Statement st; Statement st;
public thread1(Connection c) throws SQLException { public thread1(Connection c) throws SQLException
{
this.c = c; this.c = c;
st = c.createStatement(); st = c.createStatement();
} }
public void run() { public void run()
try { {
try
{
System.out.println("Thread 1 running..."); System.out.println("Thread 1 running...");
// First we need a table to store data in // First we need a table to store data in
@@ -145,7 +157,8 @@ public class threadsafe
// manner. (DateStyles are PostgreSQL's way of handling different methods // manner. (DateStyles are PostgreSQL's way of handling different methods
// of representing dates in the Date data type.) // of representing dates in the Date data type.)
PreparedStatement ps = db.prepareStatement("insert into basic1 values (?,?)"); PreparedStatement ps = db.prepareStatement("insert into basic1 values (?,?)");
for(int i=2;i<2000;i++) { for (int i = 2;i < 2000;i++)
{
ps.setInt(1, 4); // "column a" = 5 ps.setInt(1, 4); // "column a" = 5
ps.setInt(2, i); // "column b" = i ps.setInt(2, i); // "column b" = i
ps.executeUpdate(); // executeUpdate because insert returns no data ps.executeUpdate(); // executeUpdate because insert returns no data
@@ -159,10 +172,12 @@ public class threadsafe
DriverManager.println("Thread 1 performing a query"); DriverManager.println("Thread 1 performing a query");
ResultSet rs = st.executeQuery("select a, b from basic1"); ResultSet rs = st.executeQuery("select a, b from basic1");
int cnt = 0; int cnt = 0;
if(rs!=null) { if (rs != null)
{
// Now we run through the result set, printing out the result. // Now we run through the result set, printing out the result.
// Note, we must call .next() before attempting to read any results // Note, we must call .next() before attempting to read any results
while(rs.next()) { while (rs.next())
{
int a = rs.getInt("a"); // This shows how to get the value by name int a = rs.getInt("a"); // This shows how to get the value by name
int b = rs.getInt(2); // This shows how to get the value by column int b = rs.getInt(2); // This shows how to get the value by column
//System.out.println(" a="+a+" b="+b); //System.out.println(" a="+a+" b="+b);
@@ -175,7 +190,9 @@ public class threadsafe
// The last thing to do is to drop the table. This is done in the // The last thing to do is to drop the table. This is done in the
// cleanup() method. // cleanup() method.
System.out.println("Thread 1 finished"); System.out.println("Thread 1 finished");
} catch(SQLException se) { }
catch (SQLException se)
{
System.err.println("Thread 1: " + se.toString()); System.err.println("Thread 1: " + se.toString());
se.printStackTrace(); se.printStackTrace();
System.exit(1); System.exit(1);
@@ -190,13 +207,16 @@ public class threadsafe
Connection c; Connection c;
Statement st; Statement st;
public thread2(Connection c) throws SQLException { public thread2(Connection c) throws SQLException
{
this.c = c; this.c = c;
st = c.createStatement(); st = c.createStatement();
} }
public void run() { public void run()
try { {
try
{
System.out.println("Thread 2 running..."); System.out.println("Thread 2 running...");
// First we need a table to store data in // First we need a table to store data in
@@ -212,7 +232,8 @@ public class threadsafe
// manner. (DateStyles are PostgreSQL's way of handling different methods // manner. (DateStyles are PostgreSQL's way of handling different methods
// of representing dates in the Date data type.) // of representing dates in the Date data type.)
PreparedStatement ps = db.prepareStatement("insert into basic2 values (?,?)"); PreparedStatement ps = db.prepareStatement("insert into basic2 values (?,?)");
for(int i=2;i<2000;i++) { for (int i = 2;i < 2000;i++)
{
ps.setInt(1, 4); // "column a" = 5 ps.setInt(1, 4); // "column a" = 5
ps.setInt(2, i); // "column b" = i ps.setInt(2, i); // "column b" = i
ps.executeUpdate(); // executeUpdate because insert returns no data ps.executeUpdate(); // executeUpdate because insert returns no data
@@ -226,7 +247,8 @@ public class threadsafe
DriverManager.println("Thread 2 performing a query"); DriverManager.println("Thread 2 performing a query");
ResultSet rs = st.executeQuery("select * from basic2 where b>1"); ResultSet rs = st.executeQuery("select * from basic2 where b>1");
int cnt = 0; int cnt = 0;
if(rs!=null) { if (rs != null)
{
// First find out the column numbers. // First find out the column numbers.
// //
// It's best to do this here, as calling the methods with the column // It's best to do this here, as calling the methods with the column
@@ -238,7 +260,8 @@ public class threadsafe
// Now we run through the result set, printing out the result. // Now we run through the result set, printing out the result.
// Again, we must call .next() before attempting to read any results // Again, we must call .next() before attempting to read any results
while(rs.next()) { while (rs.next())
{
int a = rs.getInt(col_a); // This shows how to get the value by name int a = rs.getInt(col_a); // This shows how to get the value by name
int b = rs.getInt(col_b); // This shows how to get the value by column int b = rs.getInt(col_b); // This shows how to get the value by column
//System.out.println(" a="+a+" b="+b); //System.out.println(" a="+a+" b="+b);
@@ -251,7 +274,9 @@ public class threadsafe
// The last thing to do is to drop the table. This is done in the // The last thing to do is to drop the table. This is done in the
// cleanup() method. // cleanup() method.
System.out.println("Thread 2 finished"); System.out.println("Thread 2 finished");
} catch(SQLException se) { }
catch (SQLException se)
{
System.err.println("Thread 2: " + se.toString()); System.err.println("Thread 2: " + se.toString());
se.printStackTrace(); se.printStackTrace();
System.exit(1); System.exit(1);
@@ -272,7 +297,8 @@ public class threadsafe
LargeObject lo; LargeObject lo;
int oid; int oid;
public thread3(Connection c) throws SQLException { public thread3(Connection c) throws SQLException
{
this.c = c; this.c = c;
//st = c.createStatement(); //st = c.createStatement();
@@ -282,8 +308,10 @@ public class threadsafe
System.out.println("Thread 3 has created a blob of oid " + oid); System.out.println("Thread 3 has created a blob of oid " + oid);
} }
public void run() { public void run()
try { {
try
{
System.out.println("Thread 3 running..."); System.out.println("Thread 3 running...");
DriverManager.println("Thread 3: Loading data into blob " + oid); DriverManager.println("Thread 3: Loading data into blob " + oid);
@@ -292,7 +320,8 @@ public class threadsafe
// keep the buffer size small, to allow the other thread a chance // keep the buffer size small, to allow the other thread a chance
byte buf[] = new byte[128]; byte buf[] = new byte[128];
int rc, bc = 1, bs = 0; int rc, bc = 1, bs = 0;
while((rc=fis.read(buf))>0) { while ((rc = fis.read(buf)) > 0)
{
DriverManager.println("Thread 3 read block " + bc + " " + bs + " bytes"); DriverManager.println("Thread 3 read block " + bc + " " + bs + " bytes");
lo.write(buf, 0, rc); lo.write(buf, 0, rc);
bc++; bc++;
@@ -304,9 +333,11 @@ public class threadsafe
DriverManager.println("Thread 3: Reading blob " + oid); DriverManager.println("Thread 3: Reading blob " + oid);
lo = lom.open(oid); lo = lom.open(oid);
bc = 0; bc = 0;
while(buf.length>0) { while (buf.length > 0)
{
buf = lo.read(buf.length); buf = lo.read(buf.length);
if(buf.length>0) { if (buf.length > 0)
{
String s = new String(buf); String s = new String(buf);
bc++; bc++;
DriverManager.println("Thread 3 block " + bc); DriverManager.println("Thread 3 block " + bc);
@@ -316,15 +347,19 @@ public class threadsafe
lo.close(); lo.close();
System.out.println("Thread 3 finished"); System.out.println("Thread 3 finished");
} catch(Exception se) { }
catch (Exception se)
{
System.err.println("Thread 3: " + se.toString()); System.err.println("Thread 3: " + se.toString());
se.printStackTrace(); se.printStackTrace();
System.exit(1); System.exit(1);
} }
} }
public void cleanup() throws SQLException { public void cleanup() throws SQLException
if(lom!=null && oid!=0) { {
if (lom != null && oid != 0)
{
System.out.println("Thread 3: Removing blob oid=" + oid); System.out.println("Thread 3: Removing blob oid=" + oid);
lom.delete(oid); lom.delete(oid);
} }
@@ -357,9 +392,12 @@ public class threadsafe
DriverManager.setLogStream(System.err); DriverManager.setLogStream(System.err);
// Now run the tests // Now run the tests
try { try
{
threadsafe test = new threadsafe(args); threadsafe test = new threadsafe(args);
} catch(Exception ex) { }
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex); System.err.println("Exception caught.\n" + ex);
ex.printStackTrace(); ex.printStackTrace();
} }

View File

@@ -11,7 +11,7 @@ import org.postgresql.util.*;
import org.postgresql.core.*; import org.postgresql.core.*;
/** /**
* $Id: Connection.java,v 1.31 2001/10/16 20:05:22 barry Exp $ * $Id: Connection.java,v 1.32 2001/10/25 05:59:59 momjian Exp $
* *
* This abstract class is used by org.postgresql.Driver to open either the JDBC1 or * This abstract class is used by org.postgresql.Driver to open either the JDBC1 or
* JDBC2 versions of the Connection class. * JDBC2 versions of the Connection class.
@@ -88,8 +88,7 @@ public abstract class Connection
* This is called by Class.forName() from within org.postgresql.Driver * This is called by Class.forName() from within org.postgresql.Driver
*/ */
public Connection() public Connection()
{ {}
}
/** /**
* This method actually opens the connection. It is called by Driver. * This method actually opens the connection. It is called by Driver.
@@ -121,9 +120,12 @@ public abstract class Connection
PG_PORT = port; PG_PORT = port;
PG_HOST = host; PG_HOST = host;
PG_STATUS = CONNECTION_BAD; PG_STATUS = CONNECTION_BAD;
if(info.getProperty("compatible")==null) { if (info.getProperty("compatible") == null)
{
compatible = d.getMajorVersion() + "." + d.getMinorVersion(); compatible = d.getMajorVersion() + "." + d.getMinorVersion();
} else { }
else
{
compatible = info.getProperty("compatible"); compatible = info.getProperty("compatible");
} }
@@ -131,12 +133,16 @@ public abstract class Connection
try try
{ {
pg_stream = new PG_Stream(host, port); pg_stream = new PG_Stream(host, port);
} catch (ConnectException cex) { }
catch (ConnectException cex)
{
// Added by Peter Mount <peter@retep.org.uk> // Added by Peter Mount <peter@retep.org.uk>
// ConnectException is thrown when the connection cannot be made. // ConnectException is thrown when the connection cannot be made.
// we trap this an return a more meaningful message for the end user // we trap this an return a more meaningful message for the end user
throw new PSQLException ("postgresql.con.refused"); throw new PSQLException ("postgresql.con.refused");
} catch (IOException e) { }
catch (IOException e)
{
throw new PSQLException ("postgresql.con.failed", e); throw new PSQLException ("postgresql.con.failed", e);
} }
@@ -158,7 +164,8 @@ public abstract class Connection
// Now get the response from the backend, either an error message // Now get the response from the backend, either an error message
// or an authentication request // or an authentication request
int areq = -1; // must have a value here int areq = -1; // must have a value here
do { do
{
int beresp = pg_stream.ReceiveChar(); int beresp = pg_stream.ReceiveChar();
switch (beresp) switch (beresp)
{ {
@@ -176,7 +183,8 @@ public abstract class Connection
areq = pg_stream.ReceiveIntegerR(4); areq = pg_stream.ReceiveIntegerR(4);
// Get the password salt if there is one // Get the password salt if there is one
if(areq == AUTH_REQ_CRYPT) { if (areq == AUTH_REQ_CRYPT)
{
byte[] rst = new byte[2]; byte[] rst = new byte[2];
rst[0] = (byte)pg_stream.ReceiveChar(); rst[0] = (byte)pg_stream.ReceiveChar();
rst[1] = (byte)pg_stream.ReceiveChar(); rst[1] = (byte)pg_stream.ReceiveChar();
@@ -223,16 +231,20 @@ public abstract class Connection
default: default:
throw new PSQLException("postgresql.con.authfail"); throw new PSQLException("postgresql.con.authfail");
} }
} while(areq != AUTH_REQ_OK); }
while (areq != AUTH_REQ_OK);
} catch (IOException e) { }
catch (IOException e)
{
throw new PSQLException("postgresql.con.failed", e); throw new PSQLException("postgresql.con.failed", e);
} }
// As of protocol version 2.0, we should now receive the cancellation key and the pid // As of protocol version 2.0, we should now receive the cancellation key and the pid
int beresp = pg_stream.ReceiveChar(); int beresp = pg_stream.ReceiveChar();
switch(beresp) { switch (beresp)
{
case 'K': case 'K':
pid = pg_stream.ReceiveInteger(4); pid = pg_stream.ReceiveInteger(4);
ckey = pg_stream.ReceiveInteger(4); ckey = pg_stream.ReceiveInteger(4);
@@ -246,7 +258,8 @@ public abstract class Connection
// Expect ReadyForQuery packet // Expect ReadyForQuery packet
beresp = pg_stream.ReceiveChar(); beresp = pg_stream.ReceiveChar();
switch(beresp) { switch (beresp)
{
case 'Z': case 'Z':
break; break;
case 'E': case 'E':
@@ -280,7 +293,8 @@ public abstract class Connection
java.sql.ResultSet resultSet = java.sql.ResultSet resultSet =
ExecSQL("set datestyle to 'ISO'; select version(), " + encodingQuery + ";"); ExecSQL("set datestyle to 'ISO'; select version(), " + encodingQuery + ";");
if (! resultSet.next()) { if (! resultSet.next())
{
throw new PSQLException("postgresql.con.failed", "failed getting backend encoding"); throw new PSQLException("postgresql.con.failed", "failed getting backend encoding");
} }
String version = resultSet.getString(1); String version = resultSet.getString(1);
@@ -422,7 +436,8 @@ public abstract class Connection
/** /**
* Get the character encoding to use for this connection. * Get the character encoding to use for this connection.
*/ */
public Encoding getEncoding() throws SQLException { public Encoding getEncoding() throws SQLException
{
return encoding; return encoding;
} }
@@ -508,13 +523,15 @@ public abstract class Connection
*/ */
public Object getObject(String type, String value) throws SQLException public Object getObject(String type, String value) throws SQLException
{ {
try { try
{
Object o = objectTypes.get(type); Object o = objectTypes.get(type);
// If o is null, then the type is unknown, so check to see if type // If o is null, then the type is unknown, so check to see if type
// is an actual table name. If it does, see if a Class is known that // is an actual table name. If it does, see if a Class is known that
// can handle it // can handle it
if(o == null) { if (o == null)
{
Serialize ser = new Serialize(this, type); Serialize ser = new Serialize(this, type);
objectTypes.put(type, ser); objectTypes.put(type, ser);
return ser.fetch(Integer.parseInt(value)); return ser.fetch(Integer.parseInt(value));
@@ -525,24 +542,31 @@ public abstract class Connection
// //
// This is used to implement the org.postgresql unique types (like lseg, // This is used to implement the org.postgresql unique types (like lseg,
// point, etc). // point, etc).
if(o instanceof String) { if (o instanceof String)
{
// 6.3 style extending PG_Object // 6.3 style extending PG_Object
PGobject obj = null; PGobject obj = null;
obj = (PGobject)(Class.forName((String)o).newInstance()); obj = (PGobject)(Class.forName((String)o).newInstance());
obj.setType(type); obj.setType(type);
obj.setValue(value); obj.setValue(value);
return (Object)obj; return (Object)obj;
} else { }
else
{
// If it's an object, it should be an instance of our Serialize class // If it's an object, it should be an instance of our Serialize class
// If so, then call it's fetch method. // If so, then call it's fetch method.
if (o instanceof Serialize) if (o instanceof Serialize)
return ((Serialize)o).fetch(Integer.parseInt(value)); return ((Serialize)o).fetch(Integer.parseInt(value));
} }
} catch(SQLException sx) { }
catch (SQLException sx)
{
// rethrow the exception. Done because we capture any others next // rethrow the exception. Done because we capture any others next
sx.fillInStackTrace(); sx.fillInStackTrace();
throw sx; throw sx;
} catch(Exception ex) { }
catch (Exception ex)
{
throw new PSQLException("postgresql.con.creobj", type, ex); throw new PSQLException("postgresql.con.creobj", type, ex);
} }
@@ -559,14 +583,16 @@ public abstract class Connection
*/ */
public int putObject(Object o) throws SQLException public int putObject(Object o) throws SQLException
{ {
try { try
{
String type = o.getClass().getName(); String type = o.getClass().getName();
Object x = objectTypes.get(type); Object x = objectTypes.get(type);
// If x is null, then the type is unknown, so check to see if type // If x is null, then the type is unknown, so check to see if type
// is an actual table name. If it does, see if a Class is known that // is an actual table name. If it does, see if a Class is known that
// can handle it // can handle it
if(x == null) { if (x == null)
{
Serialize ser = new Serialize(this, type); Serialize ser = new Serialize(this, type);
objectTypes.put(type, ser); objectTypes.put(type, ser);
return ser.store(o); return ser.store(o);
@@ -580,11 +606,15 @@ public abstract class Connection
// Thow an exception because the type is unknown // Thow an exception because the type is unknown
throw new PSQLException("postgresql.con.strobj"); throw new PSQLException("postgresql.con.strobj");
} catch(SQLException sx) { }
catch (SQLException sx)
{
// rethrow the exception. Done because we capture any others next // rethrow the exception. Done because we capture any others next
sx.fillInStackTrace(); sx.fillInStackTrace();
throw sx; throw sx;
} catch(Exception ex) { }
catch (Exception ex)
{
throw new PSQLException("postgresql.con.strobjex", ex); throw new PSQLException("postgresql.con.strobjex", ex);
} }
} }
@@ -660,13 +690,18 @@ public abstract class Connection
* *
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public void close() throws SQLException { public void close() throws SQLException
if (pg_stream != null) { {
try { if (pg_stream != null)
{
try
{
pg_stream.SendChar('X'); pg_stream.SendChar('X');
pg_stream.flush(); pg_stream.flush();
pg_stream.close(); pg_stream.close();
} catch (IOException e) {} }
catch (IOException e)
{}
pg_stream = null; pg_stream = null;
} }
} }
@@ -681,7 +716,8 @@ public abstract class Connection
* @return the native form of this statement * @return the native form of this statement
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public String nativeSQL(String sql) throws SQLException { public String nativeSQL(String sql) throws SQLException
{
return sql; return sql;
} }
@@ -695,7 +731,8 @@ public abstract class Connection
* @return the first SQLWarning or null * @return the first SQLWarning or null
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public SQLWarning getWarnings() throws SQLException { public SQLWarning getWarnings() throws SQLException
{
return firstWarning; return firstWarning;
} }
@@ -705,7 +742,8 @@ public abstract class Connection
* *
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public void clearWarnings() throws SQLException { public void clearWarnings() throws SQLException
{
firstWarning = null; firstWarning = null;
} }
@@ -720,7 +758,8 @@ public abstract class Connection
* @param readOnly - true enables read-only mode; false disables it * @param readOnly - true enables read-only mode; false disables it
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public void setReadOnly(boolean readOnly) throws SQLException { public void setReadOnly(boolean readOnly) throws SQLException
{
this.readOnly = readOnly; this.readOnly = readOnly;
} }
@@ -732,7 +771,8 @@ public abstract class Connection
* @return true if the connection is read only * @return true if the connection is read only
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public boolean isReadOnly() throws SQLException { public boolean isReadOnly() throws SQLException
{
return readOnly; return readOnly;
} }
@@ -754,15 +794,20 @@ public abstract class Connection
* @param autoCommit - true enables auto-commit; false disables it * @param autoCommit - true enables auto-commit; false disables it
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public void setAutoCommit(boolean autoCommit) throws SQLException { public void setAutoCommit(boolean autoCommit) throws SQLException
{
if (this.autoCommit == autoCommit) if (this.autoCommit == autoCommit)
return ; return ;
if (autoCommit) if (autoCommit)
ExecSQL("end"); ExecSQL("end");
else { else
if (haveMinimumServerVersion("7.1")){ {
if (haveMinimumServerVersion("7.1"))
{
ExecSQL("begin;" + getIsolationLevelSQL()); ExecSQL("begin;" + getIsolationLevelSQL());
}else{ }
else
{
ExecSQL("begin"); ExecSQL("begin");
ExecSQL(getIsolationLevelSQL()); ExecSQL(getIsolationLevelSQL());
} }
@@ -777,7 +822,8 @@ public abstract class Connection
* @exception SQLException (why?) * @exception SQLException (why?)
* @see setAutoCommit * @see setAutoCommit
*/ */
public boolean getAutoCommit() throws SQLException { public boolean getAutoCommit() throws SQLException
{
return this.autoCommit; return this.autoCommit;
} }
@@ -791,12 +837,16 @@ public abstract class Connection
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
* @see setAutoCommit * @see setAutoCommit
*/ */
public void commit() throws SQLException { public void commit() throws SQLException
{
if (autoCommit) if (autoCommit)
return ; return ;
if (haveMinimumServerVersion("7.1")){ if (haveMinimumServerVersion("7.1"))
{
ExecSQL("commit;begin;" + getIsolationLevelSQL()); ExecSQL("commit;begin;" + getIsolationLevelSQL());
}else{ }
else
{
ExecSQL("commit"); ExecSQL("commit");
ExecSQL("begin"); ExecSQL("begin");
ExecSQL(getIsolationLevelSQL()); ExecSQL(getIsolationLevelSQL());
@@ -811,12 +861,16 @@ public abstract class Connection
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
* @see commit * @see commit
*/ */
public void rollback() throws SQLException { public void rollback() throws SQLException
{
if (autoCommit) if (autoCommit)
return ; return ;
if (haveMinimumServerVersion("7.1")){ if (haveMinimumServerVersion("7.1"))
{
ExecSQL("rollback; begin;" + getIsolationLevelSQL()); ExecSQL("rollback; begin;" + getIsolationLevelSQL());
}else{ }
else
{
ExecSQL("rollback"); ExecSQL("rollback");
ExecSQL("begin"); ExecSQL("begin");
ExecSQL(getIsolationLevelSQL()); ExecSQL(getIsolationLevelSQL());
@@ -829,12 +883,14 @@ public abstract class Connection
* @return the current TRANSACTION_* mode value * @return the current TRANSACTION_* mode value
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public int getTransactionIsolation() throws SQLException { public int getTransactionIsolation() throws SQLException
{
clearWarnings(); clearWarnings();
ExecSQL("show xactisolevel"); ExecSQL("show xactisolevel");
SQLWarning warning = getWarnings(); SQLWarning warning = getWarnings();
if (warning != null) { if (warning != null)
{
String message = warning.getMessage(); String message = warning.getMessage();
clearWarnings(); clearWarnings();
if (message.indexOf("READ COMMITTED") != -1) if (message.indexOf("READ COMMITTED") != -1)
@@ -862,7 +918,8 @@ public abstract class Connection
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
* @see java.sql.DatabaseMetaData#supportsTransactionIsolationLevel * @see java.sql.DatabaseMetaData#supportsTransactionIsolationLevel
*/ */
public void setTransactionIsolation(int level) throws SQLException { public void setTransactionIsolation(int level) throws SQLException
{
//In 7.1 and later versions of the server it is possible using //In 7.1 and later versions of the server it is possible using
//the "set session" command to set this once for all future txns //the "set session" command to set this once for all future txns
//however in 7.0 and prior versions it is necessary to set it in //however in 7.0 and prior versions it is necessary to set it in
@@ -872,11 +929,15 @@ public abstract class Connection
isolationLevel = level; isolationLevel = level;
String isolationLevelSQL; String isolationLevelSQL;
if (!haveMinimumServerVersion("7.1")) { if (!haveMinimumServerVersion("7.1"))
{
isolationLevelSQL = getIsolationLevelSQL(); isolationLevelSQL = getIsolationLevelSQL();
} else { }
else
{
isolationLevelSQL = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL "; isolationLevelSQL = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL ";
switch(isolationLevel) { switch (isolationLevel)
{
case java.sql.Connection.TRANSACTION_READ_COMMITTED: case java.sql.Connection.TRANSACTION_READ_COMMITTED:
isolationLevelSQL += "READ COMMITTED"; isolationLevelSQL += "READ COMMITTED";
break; break;
@@ -900,15 +961,18 @@ public abstract class Connection
* servers, and should be removed when support for these older * servers, and should be removed when support for these older
* servers are dropped * servers are dropped
*/ */
protected String getIsolationLevelSQL() throws SQLException { protected String getIsolationLevelSQL() throws SQLException
{
//7.1 and higher servers have a default specified so //7.1 and higher servers have a default specified so
//no additional SQL is required to set the isolation level //no additional SQL is required to set the isolation level
if (haveMinimumServerVersion("7.1")) { if (haveMinimumServerVersion("7.1"))
{
return ""; return "";
} }
StringBuffer sb = new StringBuffer("SET TRANSACTION ISOLATION LEVEL"); StringBuffer sb = new StringBuffer("SET TRANSACTION ISOLATION LEVEL");
switch(isolationLevel) { switch (isolationLevel)
{
case java.sql.Connection.TRANSACTION_READ_COMMITTED: case java.sql.Connection.TRANSACTION_READ_COMMITTED:
sb.append(" READ COMMITTED"); sb.append(" READ COMMITTED");
break; break;
@@ -970,7 +1034,8 @@ public abstract class Connection
/** /**
* Get server version number * Get server version number
*/ */
public String getDBVersionNumber() { public String getDBVersionNumber()
{
return dbVersionNumber; return dbVersionNumber;
} }
@@ -1009,7 +1074,8 @@ public abstract class Connection
Integer sqlType = (Integer)typeOidCache.get(new Integer(oid)); Integer sqlType = (Integer)typeOidCache.get(new Integer(oid));
// it's not in the cache, so perform a query, and add the result to the cache // it's not in the cache, so perform a query, and add the result to the cache
if(sqlType==null) { if (sqlType == null)
{
ResultSet result = (org.postgresql.ResultSet)ExecSQL("select typname from pg_type where oid = " + oid); ResultSet result = (org.postgresql.ResultSet)ExecSQL("select typname from pg_type where oid = " + oid);
if (result.getColumnCount() != 1 || result.getTupleCount() != 1) if (result.getColumnCount() != 1 || result.getTupleCount() != 1)
throw new PSQLException("postgresql.unexpected"); throw new PSQLException("postgresql.unexpected");
@@ -1041,11 +1107,15 @@ public abstract class Connection
public int getOID(String typeName) throws SQLException public int getOID(String typeName) throws SQLException
{ {
int oid = -1; int oid = -1;
if(typeName != null) { if (typeName != null)
{
Integer oidValue = (Integer) typeOidCache.get(typeName); Integer oidValue = (Integer) typeOidCache.get(typeName);
if(oidValue != null) { if (oidValue != null)
{
oid = oidValue.intValue(); oid = oidValue.intValue();
} else { }
else
{
// it's not in the cache, so perform a query, and add the result to the cache // it's not in the cache, so perform a query, and add the result to the cache
ResultSet result = (org.postgresql.ResultSet)ExecSQL("select oid from pg_type where typname='" ResultSet result = (org.postgresql.ResultSet)ExecSQL("select oid from pg_type where typname='"
+ typeName + "'"); + typeName + "'");
@@ -1069,7 +1139,8 @@ public abstract class Connection
public String getPGType(int oid) throws SQLException public String getPGType(int oid) throws SQLException
{ {
String pgType = (String) pgTypeCache.get(new Integer(oid)); String pgType = (String) pgTypeCache.get(new Integer(oid));
if(pgType == null) { if (pgType == null)
{
getSQLType(oid); getSQLType(oid);
pgType = (String) pgTypeCache.get(new Integer(oid)); pgType = (String) pgTypeCache.get(new Integer(oid));
} }

View File

@@ -10,7 +10,7 @@ import org.postgresql.core.*;
import org.postgresql.util.*; import org.postgresql.util.*;
/** /**
* $Id: PG_Stream.java,v 1.13 2001/08/26 17:08:48 momjian Exp $ * $Id: PG_Stream.java,v 1.14 2001/10/25 05:59:59 momjian Exp $
* *
* This class is used by Connection & PGlobj for communicating with the * This class is used by Connection & PGlobj for communicating with the
* backend. * backend.
@@ -139,8 +139,11 @@ public class PG_Stream
try try
{ {
c = pg_input.read(); c = pg_input.read();
if (c < 0) throw new PSQLException("postgresql.stream.eof"); if (c < 0)
} catch (IOException e) { throw new PSQLException("postgresql.stream.eof");
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e); throw new PSQLException("postgresql.stream.ioerror", e);
} }
return c; return c;
@@ -167,7 +170,9 @@ public class PG_Stream
throw new PSQLException("postgresql.stream.eof"); throw new PSQLException("postgresql.stream.eof");
n = n | (b << (8 * i)) ; n = n | (b << (8 * i)) ;
} }
} catch (IOException e) { }
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e); throw new PSQLException("postgresql.stream.ioerror", e);
} }
return n; return n;
@@ -194,7 +199,9 @@ public class PG_Stream
throw new PSQLException("postgresql.stream.eof"); throw new PSQLException("postgresql.stream.eof");
n = b | (n << 8); n = b | (n << 8);
} }
} catch (IOException e) { }
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e); throw new PSQLException("postgresql.stream.ioerror", e);
} }
return n; return n;
@@ -213,22 +220,29 @@ public class PG_Stream
{ {
int s = 0; int s = 0;
byte[] rst = byte_buf; byte[] rst = byte_buf;
try { try
{
int buflen = rst.length; int buflen = rst.length;
boolean done = false; boolean done = false;
while (!done) { while (!done)
while (s < buflen) { {
while (s < buflen)
{
int c = pg_input.read(); int c = pg_input.read();
if (c < 0) if (c < 0)
throw new PSQLException("postgresql.stream.eof"); throw new PSQLException("postgresql.stream.eof");
else if (c == 0) { else if (c == 0)
{
rst[s] = 0; rst[s] = 0;
done = true; done = true;
break; break;
} else { }
else
{
rst[s++] = (byte)c; rst[s++] = (byte)c;
} }
if (s >= buflen) { // Grow the buffer if (s >= buflen)
{ // Grow the buffer
buflen = (int)(buflen * 2); // 100% bigger buflen = (int)(buflen * 2); // 100% bigger
byte[] newrst = new byte[buflen]; byte[] newrst = new byte[buflen];
System.arraycopy(rst, 0, newrst, 0, s); System.arraycopy(rst, 0, newrst, 0, s);
@@ -236,7 +250,9 @@ public class PG_Stream
} }
} }
} }
} catch (IOException e) { }
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e); throw new PSQLException("postgresql.stream.ioerror", e);
} }
return encoding.decode(rst, 0, s); return encoding.decode(rst, 0, s);
@@ -320,7 +336,9 @@ public class PG_Stream
throw new PSQLException("postgresql.stream.eof"); throw new PSQLException("postgresql.stream.eof");
s += w; s += w;
} }
} catch (IOException e) { }
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e); throw new PSQLException("postgresql.stream.ioerror", e);
} }
} }
@@ -332,9 +350,12 @@ public class PG_Stream
*/ */
public void flush() throws SQLException public void flush() throws SQLException
{ {
try { try
{
pg_output.flush(); pg_output.flush();
} catch (IOException e) { }
catch (IOException e)
{
throw new PSQLException("postgresql.stream.flush", e); throw new PSQLException("postgresql.stream.flush", e);
} }
} }

View File

@@ -40,7 +40,7 @@
* *
* Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved. * Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved.
* *
* $Id: PostgresqlDataSource.java,v 1.2 2000/11/10 22:06:26 momjian Exp $ * $Id: PostgresqlDataSource.java,v 1.3 2001/10/25 05:59:59 momjian Exp $
*/ */
@@ -223,8 +223,10 @@ private transient org.postgresql.Driver _driver;
Properties info; Properties info;
String url; String url;
if ( _driver == null ) { if ( _driver == null )
try { {
try
{
// Constructs a driver for use just by this data source // Constructs a driver for use just by this data source
// which will produce TwoPhaseConnection-s. This driver // which will produce TwoPhaseConnection-s. This driver
// is not registered with the driver manager. // is not registered with the driver manager.
@@ -237,7 +239,9 @@ _driver = new org.postgresql.Driver();
// _driver.setLogWriter( _logWriter ); // _driver.setLogWriter( _logWriter );
// Method seems to be unavailable. Just commented it out. // Method seems to be unavailable. Just commented it out.
//---------- //----------
} catch ( SQLException except ) { }
catch ( SQLException except )
{
if ( _logWriter != null ) if ( _logWriter != null )
_logWriter.println( "DataSource: Failed to initialize JDBC driver: " + except ); _logWriter.println( "DataSource: Failed to initialize JDBC driver: " + except );
throw except; throw except;
@@ -249,7 +253,8 @@ _driver = new org.postgresql.Driver();
info.put( "loginTimeout", Integer.toString( _loginTimeout ) ); info.put( "loginTimeout", Integer.toString( _loginTimeout ) );
// DriverManager will do that and not rely on the URL alone. // DriverManager will do that and not rely on the URL alone.
if ( user == null ) { if ( user == null )
{
user = _user; user = _user;
password = _password; password = _password;
} }
@@ -270,17 +275,21 @@ _driver = new org.postgresql.Driver();
// Attempt to establish a connection. Report a successful // Attempt to establish a connection. Report a successful
// attempt or a failure. // attempt or a failure.
try { try
{
conn = _driver.connect( url, info ); conn = _driver.connect( url, info );
// FIXME // FIXME
// if ( ! ( conn instanceof postgresql.jdbc2.Connection ) ) { // if ( ! ( conn instanceof postgresql.jdbc2.Connection ) ) {
if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) ) { if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) )
{
//-------- //--------
if ( _logWriter != null ) if ( _logWriter != null )
_logWriter.println( "DataSource: JDBC 1 connections not supported" ); _logWriter.println( "DataSource: JDBC 1 connections not supported" );
throw new PSQLException( "postgresql.ds.onlyjdbc2" ); throw new PSQLException( "postgresql.ds.onlyjdbc2" );
} }
} catch ( SQLException except ) { }
catch ( SQLException except )
{
if ( _logWriter != null ) if ( _logWriter != null )
_logWriter.println( "DataSource: getConnection failed " + except ); _logWriter.println( "DataSource: getConnection failed " + except );
throw except; throw except;
@@ -302,7 +311,8 @@ if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) ) {
// Once a log writer has been set, we cannot set it since some // Once a log writer has been set, we cannot set it since some
// thread might be conditionally accessing it right now without // thread might be conditionally accessing it right now without
// synchronizing. // synchronizing.
if ( writer != null ) { if ( writer != null )
{
if ( _driver != null ) if ( _driver != null )
// FIXME // FIXME
// _driver.setLogWriter( writer ); // _driver.setLogWriter( writer );
@@ -507,16 +517,19 @@ if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) ) {
{ {
if ( _description != null ) if ( _description != null )
return _description; return _description;
else { else
{
String url; String url;
url = "jdbc:postgresql:"; url = "jdbc:postgresql:";
if ( _serverName != null ) { if ( _serverName != null )
{
if ( _portNumber == DEFAULT_PORT ) if ( _portNumber == DEFAULT_PORT )
url = url + "//" + _serverName + "/"; url = url + "//" + _serverName + "/";
else else
url = url + "//" + _serverName + ":" + _portNumber + "/"; url = url + "//" + _serverName + ":" + _portNumber + "/";
} else if ( _portNumber != DEFAULT_PORT ) }
else if ( _portNumber != DEFAULT_PORT )
url = url + "//localhost:" + _portNumber + "/"; url = url + "//localhost:" + _portNumber + "/";
if ( _databaseName != null ) if ( _databaseName != null )
url = url + _databaseName; url = url + _databaseName;
@@ -555,17 +568,22 @@ if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) ) {
Reference ref; Reference ref;
// Can only reconstruct from a reference. // Can only reconstruct from a reference.
if ( refObj instanceof Reference ) { if ( refObj instanceof Reference )
{
ref = (Reference) refObj; ref = (Reference) refObj;
// Make sure reference is of datasource class. // Make sure reference is of datasource class.
if ( ref.getClassName().equals( getClass().getName() ) ) { if ( ref.getClassName().equals( getClass().getName() ) )
{
PostgresqlDataSource ds; PostgresqlDataSource ds;
RefAddr addr; RefAddr addr;
try { try
{
ds = (PostgresqlDataSource) Class.forName( ref.getClassName() ).newInstance(); ds = (PostgresqlDataSource) Class.forName( ref.getClassName() ).newInstance();
} catch ( Exception except ) { }
catch ( Exception except )
{
throw new NamingException( except.toString() ); throw new NamingException( except.toString() );
} }
// Mandatory properties // Mandatory properties
@@ -590,9 +608,11 @@ if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) ) {
setTransactionTimeout( Integer.parseInt( (String) addr.getContent() ) ); setTransactionTimeout( Integer.parseInt( (String) addr.getContent() ) );
return ds; return ds;
} else }
else
throw new NamingException( "DataSource: Reference not constructed from class " + getClass().getName() ); throw new NamingException( "DataSource: Reference not constructed from class " + getClass().getName() );
} else if ( refObj instanceof Remote ) }
else if ( refObj instanceof Remote )
return refObj; return refObj;
else else
return null; return null;

View File

@@ -190,7 +190,8 @@ public abstract class ResultSet
* *
* It converts ($##.##) to -##.## and $##.## to ##.## * It converts ($##.##) to -##.## and $##.## to ##.##
*/ */
public String getFixedString(int col) throws SQLException { public String getFixedString(int col) throws SQLException
{
String s = getString(col); String s = getString(col);
// Handle SQL Null // Handle SQL Null
@@ -199,10 +200,12 @@ public abstract class ResultSet
return null; return null;
// Handle Money // Handle Money
if(s.charAt(0)=='(') { if (s.charAt(0) == '(')
{
s = "-" + org.postgresql.util.PGtokenizer.removePara(s).substring(1); s = "-" + org.postgresql.util.PGtokenizer.removePara(s).substring(1);
} }
if(s.charAt(0)=='$') { if (s.charAt(0) == '$')
{
s = s.substring(1); s = s.substring(1);
} }

View File

@@ -23,7 +23,8 @@ import org.postgresql.util.PSQLException;
* JDBC3. * JDBC3.
*/ */
public abstract class Statement { public abstract class Statement
{
/** The warnings chain. */ /** The warnings chain. */
protected SQLWarning warnings = null; protected SQLWarning warnings = null;
@@ -45,8 +46,8 @@ public abstract class Statement {
private static final short BACKSLASH = 2; private static final short BACKSLASH = 2;
private static final short ESC_TIMEDATE = 3; private static final short ESC_TIMEDATE = 3;
public Statement() { public Statement()
} {}
/** /**
* Returns the status message from the current Result.<p> * Returns the status message from the current Result.<p>
@@ -54,7 +55,8 @@ public abstract class Statement {
* *
* @return status message from backend * @return status message from backend
*/ */
public String getResultStatusString() { public String getResultStatusString()
{
if (result == null) if (result == null)
return null; return null;
return ((org.postgresql.ResultSet) result).getStatusString(); return ((org.postgresql.ResultSet) result).getStatusString();
@@ -68,7 +70,8 @@ public abstract class Statement {
* @return the current maximum row limit; zero means unlimited * @return the current maximum row limit; zero means unlimited
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public int getMaxRows() throws SQLException { public int getMaxRows() throws SQLException
{
return maxrows; return maxrows;
} }
@@ -79,7 +82,8 @@ public abstract class Statement {
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
* @see getMaxRows * @see getMaxRows
*/ */
public void setMaxRows(int max) throws SQLException { public void setMaxRows(int max) throws SQLException
{
maxrows = max; maxrows = max;
} }
@@ -90,7 +94,8 @@ public abstract class Statement {
* @param enable true to enable; false to disable * @param enable true to enable; false to disable
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public void setEscapeProcessing(boolean enable) throws SQLException { public void setEscapeProcessing(boolean enable) throws SQLException
{
escapeProcessing = enable; escapeProcessing = enable;
} }
@@ -102,7 +107,8 @@ public abstract class Statement {
* @return the current query timeout limit in seconds; 0 = unlimited * @return the current query timeout limit in seconds; 0 = unlimited
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public int getQueryTimeout() throws SQLException { public int getQueryTimeout() throws SQLException
{
return timeout; return timeout;
} }
@@ -112,7 +118,8 @@ public abstract class Statement {
* @param seconds - the new query timeout limit in seconds * @param seconds - the new query timeout limit in seconds
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public void setQueryTimeout(int seconds) throws SQLException { public void setQueryTimeout(int seconds) throws SQLException
{
timeout = seconds; timeout = seconds;
} }
@@ -132,7 +139,8 @@ public abstract class Statement {
* @return the first SQLWarning on null * @return the first SQLWarning on null
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public SQLWarning getWarnings() throws SQLException { public SQLWarning getWarnings() throws SQLException
{
return warnings; return warnings;
} }
@@ -146,7 +154,8 @@ public abstract class Statement {
* @return the current max column size limit; zero means unlimited * @return the current max column size limit; zero means unlimited
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public int getMaxFieldSize() throws SQLException { public int getMaxFieldSize() throws SQLException
{
return 8192; // We cannot change this return 8192; // We cannot change this
} }
@@ -157,7 +166,8 @@ public abstract class Statement {
* @param max the new max column size limit; zero means unlimited * @param max the new max column size limit; zero means unlimited
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public void setMaxFieldSize(int max) throws SQLException { public void setMaxFieldSize(int max) throws SQLException
{
throw new PSQLException("postgresql.stat.maxfieldsize"); throw new PSQLException("postgresql.stat.maxfieldsize");
} }
@@ -167,7 +177,8 @@ public abstract class Statement {
* *
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public void clearWarnings() throws SQLException { public void clearWarnings() throws SQLException
{
warnings = null; warnings = null;
} }
@@ -179,7 +190,8 @@ public abstract class Statement {
* *
* @exception SQLException only because thats the spec. * @exception SQLException only because thats the spec.
*/ */
public void cancel() throws SQLException { public void cancel() throws SQLException
{
// FIXME: Cancel feature has been available since 6.4. Implement it here! // FIXME: Cancel feature has been available since 6.4. Implement it here!
} }
@@ -189,7 +201,8 @@ public abstract class Statement {
* null. * null.
* @return OID of last insert * @return OID of last insert
*/ */
public int getInsertedOID() throws SQLException { public int getInsertedOID() throws SQLException
{
if (result == null) if (result == null)
return 0; return 0;
return ((org.postgresql.ResultSet) result).getInsertedOID(); return ((org.postgresql.ResultSet) result).getInsertedOID();
@@ -202,7 +215,8 @@ public abstract class Statement {
* @return the current result set; null if there are no more * @return the current result set; null if there are no more
* @exception SQLException if a database access error occurs (why?) * @exception SQLException if a database access error occurs (why?)
*/ */
public java.sql.ResultSet getResultSet() throws SQLException { public java.sql.ResultSet getResultSet() throws SQLException
{
if (result != null && ((org.postgresql.ResultSet) result).reallyResultSet()) if (result != null && ((org.postgresql.ResultSet) result).reallyResultSet())
return result; return result;
return null; return null;
@@ -220,7 +234,8 @@ public abstract class Statement {
* *
* @exception SQLException if a database access error occurs (why?) * @exception SQLException if a database access error occurs (why?)
*/ */
public void close() throws SQLException { public void close() throws SQLException
{
// Force the ResultSet to close // Force the ResultSet to close
java.sql.ResultSet rs = getResultSet(); java.sql.ResultSet rs = getResultSet();
if (rs != null) if (rs != null)

View File

@@ -4,7 +4,8 @@ package org.postgresql.core;
* A simple and efficient class to pool one dimensional byte arrays * A simple and efficient class to pool one dimensional byte arrays
* of different sizes. * of different sizes.
*/ */
public class BytePoolDim1 { public class BytePoolDim1
{
/** /**
* The maximum size of the array we manage. * The maximum size of the array we manage.
@@ -26,8 +27,10 @@ public class BytePoolDim1 {
/** /**
* Construct a new pool * Construct a new pool
*/ */
public BytePoolDim1(){ public BytePoolDim1()
for(int i = 0; i <= maxsize; i++){ {
for (int i = 0; i <= maxsize; i++)
{
binit[i] = new byte[i]; binit[i] = new byte[i];
inusemap[i] = new SimpleObjectPool(); inusemap[i] = new SimpleObjectPool();
notusemap[i] = new SimpleObjectPool(); notusemap[i] = new SimpleObjectPool();
@@ -39,7 +42,8 @@ public class BytePoolDim1 {
* larger than maxsize then it is not pooled. * larger than maxsize then it is not pooled.
* @return the byte[] allocated * @return the byte[] allocated
*/ */
public byte[] allocByte(int size) { public byte[] allocByte(int size)
{
// for now until the bug can be removed // for now until the bug can be removed
return new byte[size]; return new byte[size];
/* /*
@@ -69,7 +73,8 @@ public class BytePoolDim1 {
* Release an array * Release an array
* @param b byte[] to release * @param b byte[] to release
*/ */
public void release(byte[] b) { public void release(byte[] b)
{
// If it's larger than maxsize then we don't touch it // If it's larger than maxsize then we don't touch it
if (b.length > maxsize) if (b.length > maxsize)
return ; return ;
@@ -85,7 +90,8 @@ public class BytePoolDim1 {
* Deallocate all * Deallocate all
* @deprecated Real bad things happen if this is called! * @deprecated Real bad things happen if this is called!
*/ */
public void deallocate() { public void deallocate()
{
//for(int i = 0; i <= maxsize; i++){ //for(int i = 0; i <= maxsize; i++){
// notusemap[i].addAll(inusemap[i]); // notusemap[i].addAll(inusemap[i]);
// inusemap[i].clear(); // inusemap[i].clear();

View File

@@ -1,18 +1,22 @@
package org.postgresql.core; package org.postgresql.core;
public class BytePoolDim2 { public class BytePoolDim2
{
int maxsize = 32; int maxsize = 32;
ObjectPool notusemap[] = new ObjectPool[maxsize + 1]; ObjectPool notusemap[] = new ObjectPool[maxsize + 1];
ObjectPool inusemap[] = new ObjectPool[maxsize + 1]; ObjectPool inusemap[] = new ObjectPool[maxsize + 1];
public BytePoolDim2(){ public BytePoolDim2()
for(int i = 0; i <= maxsize; i++){ {
for (int i = 0; i <= maxsize; i++)
{
inusemap[i] = new SimpleObjectPool(); inusemap[i] = new SimpleObjectPool();
notusemap[i] = new SimpleObjectPool(); notusemap[i] = new SimpleObjectPool();
} }
} }
public byte[][] allocByte(int size){ public byte[][] allocByte(int size)
{
// For now until the bug can be removed // For now until the bug can be removed
return new byte[size][0]; return new byte[size][0];
/* /*
@@ -34,8 +38,10 @@ public class BytePoolDim2 {
*/ */
} }
public void release(byte[][] b){ public void release(byte[][] b)
if(b.length > maxsize){ {
if (b.length > maxsize)
{
return ; return ;
} }
ObjectPool not_usel = notusemap[b.length]; ObjectPool not_usel = notusemap[b.length];
@@ -52,7 +58,8 @@ public class BytePoolDim2 {
* code to use some form of Statement context, so the buffers are per * code to use some form of Statement context, so the buffers are per
* Statement and not per Connection/PG_Stream as it is now. * Statement and not per Connection/PG_Stream as it is now.
*/ */
public void deallocate(){ public void deallocate()
{
//for(int i = 0; i <= maxsize; i++){ //for(int i = 0; i <= maxsize; i++){
// notusemap[i].addAll(inusemap[i]); // notusemap[i].addAll(inusemap[i]);
// inusemap[i].clear(); // inusemap[i].clear();

View File

@@ -8,10 +8,11 @@ import org.postgresql.util.*;
/** /**
* Converts to and from the character encoding used by the backend. * Converts to and from the character encoding used by the backend.
* *
* $Id: Encoding.java,v 1.2 2001/10/16 20:07:17 barry Exp $ * $Id: Encoding.java,v 1.3 2001/10/25 05:59:59 momjian Exp $
*/ */
public class Encoding { public class Encoding
{
private static final Encoding DEFAULT_ENCODING = new Encoding(null); private static final Encoding DEFAULT_ENCODING = new Encoding(null);
@@ -59,7 +60,8 @@ public class Encoding {
private final String encoding; private final String encoding;
private Encoding(String encoding) { private Encoding(String encoding)
{
this.encoding = encoding; this.encoding = encoding;
} }
@@ -70,13 +72,19 @@ public class Encoding {
public static Encoding getEncoding(String databaseEncoding, public static Encoding getEncoding(String databaseEncoding,
String passedEncoding) String passedEncoding)
{ {
if (passedEncoding != null) { if (passedEncoding != null)
if (isAvailable(passedEncoding)) { {
if (isAvailable(passedEncoding))
{
return new Encoding(passedEncoding); return new Encoding(passedEncoding);
} else { }
else
{
return defaultEncoding(); return defaultEncoding();
} }
} else { }
else
{
return encodingForDatabaseEncoding(databaseEncoding); return encodingForDatabaseEncoding(databaseEncoding);
} }
} }
@@ -84,15 +92,19 @@ public class Encoding {
/** /**
* Get an Encoding matching the given database encoding. * Get an Encoding matching the given database encoding.
*/ */
private static Encoding encodingForDatabaseEncoding(String databaseEncoding) { private static Encoding encodingForDatabaseEncoding(String databaseEncoding)
{
// If the backend encoding is known and there is a suitable // If the backend encoding is known and there is a suitable
// encoding in the JVM we use that. Otherwise we fall back // encoding in the JVM we use that. Otherwise we fall back
// to the default encoding of the JVM. // to the default encoding of the JVM.
if (encodings.containsKey(databaseEncoding)) { if (encodings.containsKey(databaseEncoding))
{
String[] candidates = (String[]) encodings.get(databaseEncoding); String[] candidates = (String[]) encodings.get(databaseEncoding);
for (int i = 0; i < candidates.length; i++) { for (int i = 0; i < candidates.length; i++)
if (isAvailable(candidates[i])) { {
if (isAvailable(candidates[i]))
{
return new Encoding(candidates[i]); return new Encoding(candidates[i]);
} }
} }
@@ -103,21 +115,29 @@ public class Encoding {
/** /**
* Name of the (JVM) encoding used. * Name of the (JVM) encoding used.
*/ */
public String name() { public String name()
{
return encoding; return encoding;
} }
/** /**
* Encode a string to an array of bytes. * Encode a string to an array of bytes.
*/ */
public byte[] encode(String s) throws SQLException { public byte[] encode(String s) throws SQLException
try { {
if (encoding == null) { try
{
if (encoding == null)
{
return s.getBytes(); return s.getBytes();
} else { }
else
{
return s.getBytes(encoding); return s.getBytes(encoding);
} }
} catch (UnsupportedEncodingException e) { }
catch (UnsupportedEncodingException e)
{
throw new PSQLException("postgresql.stream.encoding", e); throw new PSQLException("postgresql.stream.encoding", e);
} }
} }
@@ -125,14 +145,21 @@ public class Encoding {
/** /**
* Decode an array of bytes into a string. * Decode an array of bytes into a string.
*/ */
public String decode(byte[] encodedString, int offset, int length) throws SQLException { public String decode(byte[] encodedString, int offset, int length) throws SQLException
try { {
if (encoding == null) { try
{
if (encoding == null)
{
return new String(encodedString, offset, length); return new String(encodedString, offset, length);
} else { }
else
{
return new String(encodedString, offset, length, encoding); return new String(encodedString, offset, length, encoding);
} }
} catch (UnsupportedEncodingException e) { }
catch (UnsupportedEncodingException e)
{
throw new PSQLException("postgresql.stream.encoding", e); throw new PSQLException("postgresql.stream.encoding", e);
} }
} }
@@ -140,21 +167,29 @@ public class Encoding {
/** /**
* Decode an array of bytes into a string. * Decode an array of bytes into a string.
*/ */
public String decode(byte[] encodedString) throws SQLException { public String decode(byte[] encodedString) throws SQLException
{
return decode(encodedString, 0, encodedString.length); return decode(encodedString, 0, encodedString.length);
} }
/** /**
* Get a Reader that decodes the given InputStream. * Get a Reader that decodes the given InputStream.
*/ */
public Reader getDecodingReader(InputStream in) throws SQLException { public Reader getDecodingReader(InputStream in) throws SQLException
try { {
if (encoding == null) { try
{
if (encoding == null)
{
return new InputStreamReader(in); return new InputStreamReader(in);
} else { }
else
{
return new InputStreamReader(in, encoding); return new InputStreamReader(in, encoding);
} }
} catch (UnsupportedEncodingException e) { }
catch (UnsupportedEncodingException e)
{
throw new PSQLException("postgresql.res.encoding", e); throw new PSQLException("postgresql.res.encoding", e);
} }
} }
@@ -162,18 +197,23 @@ public class Encoding {
/** /**
* Get an Encoding using the default encoding for the JVM. * Get an Encoding using the default encoding for the JVM.
*/ */
public static Encoding defaultEncoding() { public static Encoding defaultEncoding()
{
return DEFAULT_ENCODING; return DEFAULT_ENCODING;
} }
/** /**
* Test if an encoding is available in the JVM. * Test if an encoding is available in the JVM.
*/ */
private static boolean isAvailable(String encodingName) { private static boolean isAvailable(String encodingName)
try { {
try
{
"DUMMY".getBytes(encodingName); "DUMMY".getBytes(encodingName);
return true; return true;
} catch (UnsupportedEncodingException e) { }
catch (UnsupportedEncodingException e)
{
return false; return false;
} }
} }

View File

@@ -3,7 +3,8 @@ package org.postgresql.core;
/** /**
* This interface defines the methods to access the memory pool classes. * This interface defines the methods to access the memory pool classes.
*/ */
public interface MemoryPool { public interface MemoryPool
{
/** /**
* Allocate an array from the pool * Allocate an array from the pool
* @return byte[] allocated * @return byte[] allocated

View File

@@ -6,7 +6,8 @@ package org.postgresql.core;
* other for jdk1.2+ * other for jdk1.2+
*/ */
public interface ObjectPool { public interface ObjectPool
{
/** /**
* Adds an object to the pool * Adds an object to the pool
* @param o Object to add * @param o Object to add

View File

@@ -13,10 +13,11 @@ import org.postgresql.util.PSQLException;
* <p>The lifetime of a QueryExecutor object is from sending the query * <p>The lifetime of a QueryExecutor object is from sending the query
* until the response has been received from the backend. * until the response has been received from the backend.
* *
* $Id: QueryExecutor.java,v 1.2 2001/10/09 20:47:35 barry Exp $ * $Id: QueryExecutor.java,v 1.3 2001/10/25 05:59:59 momjian Exp $
*/ */
public class QueryExecutor { public class QueryExecutor
{
private final String sql; private final String sql;
private final java.sql.Statement statement; private final java.sql.Statement statement;
@@ -51,16 +52,19 @@ public class QueryExecutor {
/** /**
* Execute a query on the backend. * Execute a query on the backend.
*/ */
public java.sql.ResultSet execute() throws SQLException { public java.sql.ResultSet execute() throws SQLException
{
int fqp = 0; int fqp = 0;
boolean hfr = false; boolean hfr = false;
synchronized(pg_stream) { synchronized (pg_stream)
{
sendQuery(sql); sendQuery(sql);
while (!hfr || fqp > 0) { while (!hfr || fqp > 0)
{
int c = pg_stream.ReceiveChar(); int c = pg_stream.ReceiveChar();
switch (c) switch (c)
@@ -77,7 +81,8 @@ public class QueryExecutor {
if (fields != null) if (fields != null)
hfr = true; hfr = true;
else { else
{
sendQuery(" "); sendQuery(" ");
fqp++; fqp++;
} }
@@ -120,14 +125,18 @@ public class QueryExecutor {
/** /**
* Send a query to the backend. * Send a query to the backend.
*/ */
private void sendQuery(String query) throws SQLException { private void sendQuery(String query) throws SQLException
try { {
try
{
pg_stream.SendChar('Q'); pg_stream.SendChar('Q');
pg_stream.Send(connection.getEncoding().encode(query)); pg_stream.Send(connection.getEncoding().encode(query));
pg_stream.SendChar(0); pg_stream.SendChar(0);
pg_stream.flush(); pg_stream.flush();
} catch (IOException e) { }
catch (IOException e)
{
throw new PSQLException("postgresql.con.ioerror", e); throw new PSQLException("postgresql.con.ioerror", e);
} }
} }
@@ -137,11 +146,13 @@ public class QueryExecutor {
* *
* @param isBinary set if the tuple should be treated as binary data * @param isBinary set if the tuple should be treated as binary data
*/ */
private void receiveTuple(boolean isBinary) throws SQLException { private void receiveTuple(boolean isBinary) throws SQLException
{
if (fields == null) if (fields == null)
throw new PSQLException("postgresql.con.tuple"); throw new PSQLException("postgresql.con.tuple");
Object tuple = pg_stream.ReceiveTuple(fields.length, isBinary); Object tuple = pg_stream.ReceiveTuple(fields.length, isBinary);
if (isBinary) binaryCursor = true; if (isBinary)
binaryCursor = true;
if (maxRows == 0 || tuples.size() < maxRows) if (maxRows == 0 || tuples.size() < maxRows)
tuples.addElement(tuple); tuples.addElement(tuple);
} }
@@ -149,20 +160,26 @@ public class QueryExecutor {
/** /**
* Receive command status from the backend. * Receive command status from the backend.
*/ */
private void receiveCommandStatus() throws SQLException { private void receiveCommandStatus() throws SQLException
{
status = pg_stream.ReceiveString(connection.getEncoding()); status = pg_stream.ReceiveString(connection.getEncoding());
try { try
{
// Now handle the update count correctly. // Now handle the update count correctly.
if (status.startsWith("INSERT") || status.startsWith("UPDATE") || status.startsWith("DELETE") || status.startsWith("MOVE")) { if (status.startsWith("INSERT") || status.startsWith("UPDATE") || status.startsWith("DELETE") || status.startsWith("MOVE"))
{
update_count = Integer.parseInt(status.substring(1 + status.lastIndexOf(' '))); update_count = Integer.parseInt(status.substring(1 + status.lastIndexOf(' ')));
} }
if (status.startsWith("INSERT")) { if (status.startsWith("INSERT"))
{
insert_oid = Integer.parseInt(status.substring(1 + status.indexOf(' '), insert_oid = Integer.parseInt(status.substring(1 + status.indexOf(' '),
status.lastIndexOf(' '))); status.lastIndexOf(' ')));
} }
} catch (NumberFormatException nfe) { }
catch (NumberFormatException nfe)
{
throw new PSQLException("postgresql.con.fathom", status); throw new PSQLException("postgresql.con.fathom", status);
} }
} }
@@ -170,14 +187,16 @@ public class QueryExecutor {
/** /**
* Receive the field descriptions from the back end. * Receive the field descriptions from the back end.
*/ */
private void receiveFields() throws SQLException { private void receiveFields() throws SQLException
{
if (fields != null) if (fields != null)
throw new PSQLException("postgresql.con.multres"); throw new PSQLException("postgresql.con.multres");
int size = pg_stream.ReceiveIntegerR(2); int size = pg_stream.ReceiveIntegerR(2);
fields = new Field[size]; fields = new Field[size];
for (int i = 0; i < fields.length; i++) { for (int i = 0; i < fields.length; i++)
{
String typeName = pg_stream.ReceiveString(connection.getEncoding()); String typeName = pg_stream.ReceiveString(connection.getEncoding());
int typeOid = pg_stream.ReceiveIntegerR(4); int typeOid = pg_stream.ReceiveIntegerR(4);
int typeLength = pg_stream.ReceiveIntegerR(2); int typeLength = pg_stream.ReceiveIntegerR(2);

View File

@@ -21,7 +21,8 @@ public class SimpleObjectPool implements ObjectPool
*/ */
public void add(Object o) public void add(Object o)
{ {
if(cursize >= maxsize){ if (cursize >= maxsize)
{
Object newarr[] = new Object[maxsize * 2]; Object newarr[] = new Object[maxsize * 2];
System.arraycopy(arr, 0, newarr, 0, maxsize); System.arraycopy(arr, 0, newarr, 0, maxsize);
maxsize = maxsize * 2; maxsize = maxsize * 2;
@@ -34,7 +35,8 @@ public class SimpleObjectPool implements ObjectPool
* Removes the top object from the pool * Removes the top object from the pool
* @return Object from the top. * @return Object from the top.
*/ */
public Object remove(){ public Object remove()
{
return arr[--cursize]; return arr[--cursize];
} }
@@ -42,11 +44,13 @@ public class SimpleObjectPool implements ObjectPool
* Removes the given object from the pool * Removes the given object from the pool
* @param o Object to remove * @param o Object to remove
*/ */
public void remove(Object o) { public void remove(Object o)
{
int p = 0; int p = 0;
while (p < cursize && !arr[p].equals(o)) while (p < cursize && !arr[p].equals(o))
p++; p++;
if(arr[p].equals(o)) { if (arr[p].equals(o))
{
// This should be ok as there should be no overlap conflict // This should be ok as there should be no overlap conflict
System.arraycopy(arr, p + 1, arr, p, cursize - p); System.arraycopy(arr, p + 1, arr, p, cursize - p);
cursize--; cursize--;
@@ -56,14 +60,16 @@ public class SimpleObjectPool implements ObjectPool
/** /**
* @return true if the pool is empty * @return true if the pool is empty
*/ */
public boolean isEmpty(){ public boolean isEmpty()
{
return cursize == 0; return cursize == 0;
} }
/** /**
* @return the number of objects in the pool * @return the number of objects in the pool
*/ */
public int size(){ public int size()
{
return cursize; return cursize;
} }
@@ -71,14 +77,16 @@ public class SimpleObjectPool implements ObjectPool
* Adds all objects in one pool to this one * Adds all objects in one pool to this one
* @param pool The pool to take the objects from * @param pool The pool to take the objects from
*/ */
public void addAll(ObjectPool p){ public void addAll(ObjectPool p)
{
SimpleObjectPool pool = (SimpleObjectPool)p; SimpleObjectPool pool = (SimpleObjectPool)p;
int srcsize = pool.size(); int srcsize = pool.size();
if (srcsize == 0) if (srcsize == 0)
return ; return ;
int totalsize = srcsize + cursize; int totalsize = srcsize + cursize;
if(totalsize > maxsize){ if (totalsize > maxsize)
{
Object newarr[] = new Object[totalsize * 2]; Object newarr[] = new Object[totalsize * 2];
System.arraycopy(arr, 0, newarr, 0, cursize); System.arraycopy(arr, 0, newarr, 0, cursize);
maxsize = maxsize = totalsize * 2; maxsize = maxsize = totalsize * 2;
@@ -91,7 +99,8 @@ public class SimpleObjectPool implements ObjectPool
/** /**
* Clears the pool of all objects * Clears the pool of all objects
*/ */
public void clear(){ public void clear()
{
cursize = 0; cursize = 0;
} }
} }

View File

@@ -59,10 +59,12 @@ public class Fastpath
public Object fastpath(int fnid, boolean resulttype, FastpathArg[] args) throws SQLException public Object fastpath(int fnid, boolean resulttype, FastpathArg[] args) throws SQLException
{ {
// added Oct 7 1998 to give us thread safety // added Oct 7 1998 to give us thread safety
synchronized(stream) { synchronized (stream)
{
// send the function call // send the function call
try { try
{
// 70 is 'F' in ASCII. Note: don't use SendChar() here as it adds padding // 70 is 'F' in ASCII. Note: don't use SendChar() here as it adds padding
// that confuses the backend. The 0 terminates the command line. // that confuses the backend. The 0 terminates the command line.
stream.SendInteger(70, 1); stream.SendInteger(70, 1);
@@ -77,7 +79,9 @@ public class Fastpath
// This is needed, otherwise data can be lost // This is needed, otherwise data can be lost
stream.flush(); stream.flush();
} catch(IOException ioe) { }
catch (IOException ioe)
{
throw new PSQLException("postgresql.fp.send", new Integer(fnid), ioe); throw new PSQLException("postgresql.fp.send", new Integer(fnid), ioe);
} }
@@ -95,7 +99,8 @@ public class Fastpath
// Now loop, reading the results // Now loop, reading the results
Object result = null; // our result Object result = null; // our result
while(true) { while (true)
{
int in = stream.ReceiveChar(); int in = stream.ReceiveChar();
//DriverManager.println("ReceiveChar() = "+in+" '"+((char)in)+"'"); //DriverManager.println("ReceiveChar() = "+in+" '"+((char)in)+"'");
switch (in) switch (in)
@@ -113,7 +118,8 @@ public class Fastpath
// Return an Integer if // Return an Integer if
if (resulttype) if (resulttype)
result = new Integer(stream.ReceiveIntegerR(sz)); result = new Integer(stream.ReceiveIntegerR(sz));
else { else
{
byte buf[] = new byte[sz]; byte buf[] = new byte[sz];
stream.Receive(buf, 0, sz); stream.Receive(buf, 0, sz);
result = buf; result = buf;
@@ -253,7 +259,8 @@ public class Fastpath
*/ */
public void addFunctions(ResultSet rs) throws SQLException public void addFunctions(ResultSet rs) throws SQLException
{ {
while(rs.next()) { while (rs.next())
{
func.put(rs.getString(1), new Integer(rs.getInt(2))); func.put(rs.getString(1), new Integer(rs.getInt(2)));
} }
} }

View File

@@ -92,11 +92,14 @@ public class FastpathArg
*/ */
protected void send(org.postgresql.PG_Stream s) throws IOException protected void send(org.postgresql.PG_Stream s) throws IOException
{ {
if(type) { if (type)
{
// argument is an integer // argument is an integer
s.SendInteger(4, 4); // size of an integer s.SendInteger(4, 4); // size of an integer
s.SendInteger(value, 4); // integer value of argument s.SendInteger(value, 4); // integer value of argument
} else { }
else
{
// argument is a byte array // argument is a byte array
s.SendInteger(bytes.length, 4); // size of array s.SendInteger(bytes.length, 4); // size of array
s.Send(bytes); s.Send(bytes);

View File

@@ -79,7 +79,8 @@ public class PGbox extends PGobject implements Serializable,Cloneable
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(obj instanceof PGbox) { if (obj instanceof PGbox)
{
PGbox p = (PGbox)obj; PGbox p = (PGbox)obj;
return (p.point[0].equals(point[0]) && p.point[1].equals(point[1])) || return (p.point[0].equals(point[0]) && p.point[1].equals(point[1])) ||
(p.point[0].equals(point[1]) && p.point[1].equals(point[0])); (p.point[0].equals(point[1]) && p.point[1].equals(point[0]));

View File

@@ -69,10 +69,13 @@ public class PGcircle extends PGobject implements Serializable,Cloneable
if (t.getSize() != 2) if (t.getSize() != 2)
throw new PSQLException("postgresql.geo.circle", s); throw new PSQLException("postgresql.geo.circle", s);
try { try
{
center = new PGpoint(t.getToken(0)); center = new PGpoint(t.getToken(0));
radius = Double.valueOf(t.getToken(1)).doubleValue(); radius = Double.valueOf(t.getToken(1)).doubleValue();
} catch(NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException("postgresql.geo.circle", e); throw new PSQLException("postgresql.geo.circle", e);
} }
} }
@@ -83,7 +86,8 @@ public class PGcircle extends PGobject implements Serializable,Cloneable
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(obj instanceof PGcircle) { if (obj instanceof PGcircle)
{
PGcircle p = (PGcircle)obj; PGcircle p = (PGcircle)obj;
return p.center.equals(center) && p.radius == radius; return p.center.equals(center) && p.radius == radius;
} }

View File

@@ -77,7 +77,8 @@ public class PGline extends PGobject implements Serializable,Cloneable
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(obj instanceof PGline) { if (obj instanceof PGline)
{
PGline p = (PGline)obj; PGline p = (PGline)obj;
return (p.point[0].equals(point[0]) && p.point[1].equals(point[1])) || return (p.point[0].equals(point[0]) && p.point[1].equals(point[1])) ||
(p.point[0].equals(point[1]) && p.point[1].equals(point[0])); (p.point[0].equals(point[1]) && p.point[1].equals(point[0]));

View File

@@ -74,7 +74,8 @@ public class PGlseg extends PGobject implements Serializable,Cloneable
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(obj instanceof PGlseg) { if (obj instanceof PGlseg)
{
PGlseg p = (PGlseg)obj; PGlseg p = (PGlseg)obj;
return (p.point[0].equals(point[0]) && p.point[1].equals(point[1])) || return (p.point[0].equals(point[0]) && p.point[1].equals(point[1])) ||
(p.point[0].equals(point[1]) && p.point[1].equals(point[0])); (p.point[0].equals(point[1]) && p.point[1].equals(point[0]));

View File

@@ -55,13 +55,17 @@ public class PGpath extends PGobject implements Serializable,Cloneable
public void setValue(String s) throws SQLException public void setValue(String s) throws SQLException
{ {
// First test to see if were open // First test to see if were open
if(s.startsWith("[") && s.endsWith("]")) { if (s.startsWith("[") && s.endsWith("]"))
{
open = true; open = true;
s = PGtokenizer.removeBox(s); s = PGtokenizer.removeBox(s);
} else if(s.startsWith("(") && s.endsWith(")")) { }
else if (s.startsWith("(") && s.endsWith(")"))
{
open = false; open = false;
s = PGtokenizer.removePara(s); s = PGtokenizer.removePara(s);
} else }
else
throw new PSQLException("postgresql.geo.path"); throw new PSQLException("postgresql.geo.path");
PGtokenizer t = new PGtokenizer(s, ','); PGtokenizer t = new PGtokenizer(s, ',');
@@ -77,7 +81,8 @@ public class PGpath extends PGobject implements Serializable,Cloneable
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(obj instanceof PGpath) { if (obj instanceof PGpath)
{
PGpath p = (PGpath)obj; PGpath p = (PGpath)obj;
if (p.points.length != points.length) if (p.points.length != points.length)
@@ -113,8 +118,10 @@ public class PGpath extends PGobject implements Serializable,Cloneable
{ {
StringBuffer b = new StringBuffer(open ? "[" : "("); StringBuffer b = new StringBuffer(open ? "[" : "(");
for(int p=0;p<points.length;p++) { for (int p = 0;p < points.length;p++)
if(p>0) b.append(","); {
if (p > 0)
b.append(",");
b.append(points[p].toString()); b.append(points[p].toString());
} }
b.append(open ? "]" : ")"); b.append(open ? "]" : ")");

View File

@@ -62,10 +62,13 @@ public class PGpoint extends PGobject implements Serializable,Cloneable
public void setValue(String s) throws SQLException public void setValue(String s) throws SQLException
{ {
PGtokenizer t = new PGtokenizer(PGtokenizer.removePara(s), ','); PGtokenizer t = new PGtokenizer(PGtokenizer.removePara(s), ',');
try { try
{
x = Double.valueOf(t.getToken(0)).doubleValue(); x = Double.valueOf(t.getToken(0)).doubleValue();
y = Double.valueOf(t.getToken(1)).doubleValue(); y = Double.valueOf(t.getToken(1)).doubleValue();
} catch(NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException("postgresql.geo.point", e.toString()); throw new PSQLException("postgresql.geo.point", e.toString());
} }
} }
@@ -76,7 +79,8 @@ public class PGpoint extends PGobject implements Serializable,Cloneable
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(obj instanceof PGpoint) { if (obj instanceof PGpoint)
{
PGpoint p = (PGpoint)obj; PGpoint p = (PGpoint)obj;
return x == p.x && y == p.y; return x == p.x && y == p.y;
} }

View File

@@ -62,7 +62,8 @@ public class PGpolygon extends PGobject implements Serializable,Cloneable
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(obj instanceof PGpolygon) { if (obj instanceof PGpolygon)
{
PGpolygon p = (PGpolygon)obj; PGpolygon p = (PGpolygon)obj;
if (p.points.length != points.length) if (p.points.length != points.length)
@@ -95,8 +96,10 @@ public class PGpolygon extends PGobject implements Serializable,Cloneable
{ {
StringBuffer b = new StringBuffer(); StringBuffer b = new StringBuffer();
b.append("("); b.append("(");
for(int p=0;p<points.length;p++) { for (int p = 0;p < points.length;p++)
if(p>0) b.append(","); {
if (p > 0)
b.append(",");
b.append(points[p].toString()); b.append(points[p].toString());
} }
b.append(")"); b.append(")");

View File

@@ -64,8 +64,8 @@ public class CallableStatement extends PreparedStatement implements java.sql.Cal
* registerOutParameter that accepts a scale value * registerOutParameter that accepts a scale value
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException
} {}
/** /**
* You must also specify the scale for numeric/decimal types: * You must also specify the scale for numeric/decimal types:
@@ -82,8 +82,7 @@ public class CallableStatement extends PreparedStatement implements java.sql.Cal
*/ */
public void registerOutParameter(int parameterIndex, int sqlType, public void registerOutParameter(int parameterIndex, int sqlType,
int scale) throws SQLException int scale) throws SQLException
{ {}
}
// Old api? // Old api?
//public boolean isNull(int parameterIndex) throws SQLException { //public boolean isNull(int parameterIndex) throws SQLException {
@@ -99,7 +98,8 @@ public class CallableStatement extends PreparedStatement implements java.sql.Cal
* @return true if the last parameter read was SQL NULL * @return true if the last parameter read was SQL NULL
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public boolean wasNull() throws SQLException { public boolean wasNull() throws SQLException
{
// check to see if the last access threw an exception // check to see if the last access threw an exception
return false; // fake it for now return false; // fake it for now
} }
@@ -117,7 +117,8 @@ public class CallableStatement extends PreparedStatement implements java.sql.Cal
* @return the parameter value; if the value is SQL NULL, the result is null * @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public String getString(int parameterIndex) throws SQLException { public String getString(int parameterIndex) throws SQLException
{
return null; return null;
} }
//public String getVarChar(int parameterIndex) throws SQLException { //public String getVarChar(int parameterIndex) throws SQLException {
@@ -135,7 +136,8 @@ public class CallableStatement extends PreparedStatement implements java.sql.Cal
* @return the parameter value; if the value is SQL NULL, the result is false * @return the parameter value; if the value is SQL NULL, the result is false
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public boolean getBoolean(int parameterIndex) throws SQLException { public boolean getBoolean(int parameterIndex) throws SQLException
{
return false; return false;
} }
@@ -146,7 +148,8 @@ public class CallableStatement extends PreparedStatement implements java.sql.Cal
* @return the parameter value; if the value is SQL NULL, the result is 0 * @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public byte getByte(int parameterIndex) throws SQLException { public byte getByte(int parameterIndex) throws SQLException
{
return 0; return 0;
} }
@@ -157,7 +160,8 @@ public class CallableStatement extends PreparedStatement implements java.sql.Cal
* @return the parameter value; if the value is SQL NULL, the result is 0 * @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public short getShort(int parameterIndex) throws SQLException { public short getShort(int parameterIndex) throws SQLException
{
return 0; return 0;
} }
@@ -168,7 +172,8 @@ public class CallableStatement extends PreparedStatement implements java.sql.Cal
* @return the parameter value; if the value is SQL NULL, the result is 0 * @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public int getInt(int parameterIndex) throws SQLException { public int getInt(int parameterIndex) throws SQLException
{
return 0; return 0;
} }
@@ -179,7 +184,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @return the parameter value; if the value is SQL NULL, the result is 0 * @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public long getLong(int parameterIndex) throws SQLException { public long getLong(int parameterIndex) throws SQLException
{
return 0; return 0;
} }
@@ -190,7 +196,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @return the parameter value; if the value is SQL NULL, the result is 0 * @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public float getFloat(int parameterIndex) throws SQLException { public float getFloat(int parameterIndex) throws SQLException
{
return (float) 0.0; return (float) 0.0;
} }
@@ -201,7 +208,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @return the parameter value; if the value is SQL NULL, the result is 0 * @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public double getDouble(int parameterIndex) throws SQLException { public double getDouble(int parameterIndex) throws SQLException
{
return 0.0; return 0.0;
} }
@@ -216,7 +224,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public BigDecimal getBigDecimal(int parameterIndex, int scale) public BigDecimal getBigDecimal(int parameterIndex, int scale)
throws SQLException { throws SQLException
{
return null; return null;
} }
@@ -228,7 +237,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @return the parameter value; if the value is SQL NULL, the result is null * @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public byte[] getBytes(int parameterIndex) throws SQLException { public byte[] getBytes(int parameterIndex) throws SQLException
{
return null; return null;
} }
@@ -244,7 +254,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @return the parameter value; if the value is SQL NULL, the result is null * @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public java.sql.Date getDate(int parameterIndex) throws SQLException { public java.sql.Date getDate(int parameterIndex) throws SQLException
{
return null; return null;
} }
@@ -255,7 +266,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @return the parameter value; if the value is SQL NULL, the result is null * @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public java.sql.Time getTime(int parameterIndex) throws SQLException { public java.sql.Time getTime(int parameterIndex) throws SQLException
{
return null; return null;
} }
@@ -267,7 +279,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public java.sql.Timestamp getTimestamp(int parameterIndex) public java.sql.Timestamp getTimestamp(int parameterIndex)
throws SQLException { throws SQLException
{
return null; return null;
} }
@@ -301,7 +314,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public Object getObject(int parameterIndex) public Object getObject(int parameterIndex)
throws SQLException { throws SQLException
{
return null; return null;
} }
} }

View File

@@ -17,7 +17,7 @@ import org.postgresql.largeobject.*;
import org.postgresql.util.*; import org.postgresql.util.*;
/** /**
* $Id: Connection.java,v 1.11 2001/10/09 20:47:35 barry Exp $ * $Id: Connection.java,v 1.12 2001/10/25 05:59:59 momjian Exp $
* *
* A Connection represents a session with a specific database. Within the * A Connection represents a session with a specific database. Within the
* context of a Connection, SQL statements are executed and results are * context of a Connection, SQL statements are executed and results are
@@ -146,8 +146,10 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
public int getSQLType(String pgTypeName) public int getSQLType(String pgTypeName)
{ {
int sqlType = Types.OTHER; // default value int sqlType = Types.OTHER; // default value
for(int i=0;i<jdbc1Types.length;i++) { for (int i = 0;i < jdbc1Types.length;i++)
if(pgTypeName.equals(jdbc1Types[i])) { {
if (pgTypeName.equals(jdbc1Types[i]))
{
sqlType = jdbc1Typei[i]; sqlType = jdbc1Typei[i];
break; break;
} }

View File

@@ -13,7 +13,7 @@ import org.postgresql.util.PSQLException;
/** /**
* This class provides information about the database as a whole. * This class provides information about the database as a whole.
* *
* $Id: DatabaseMetaData.java,v 1.34 2001/10/24 04:31:48 barry Exp $ * $Id: DatabaseMetaData.java,v 1.35 2001/10/25 05:59:59 momjian Exp $
* *
* <p>Many of the methods here return lists of information in ResultSets. You * <p>Many of the methods here return lists of information in ResultSets. You
* can use the normal ResultSet methods such as getString and getInt to * can use the normal ResultSet methods such as getString and getInt to
@@ -1686,9 +1686,11 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
StringBuffer sql = new StringBuffer("select relname,oid,relkind from pg_class where ("); StringBuffer sql = new StringBuffer("select relname,oid,relkind from pg_class where (");
boolean notFirst = false; boolean notFirst = false;
for(int i=0;i<types.length;i++) { for (int i = 0;i < types.length;i++)
{
for (int j = 0;j < getTableTypes.length;j++) for (int j = 0;j < getTableTypes.length;j++)
if(getTableTypes[j][0].equals(types[i])) { if (getTableTypes[j][0].equals(types[i]))
{
if (notFirst) if (notFirst)
sql.append(" or "); sql.append(" or ");
sql.append(getTableTypes[j][1]); sql.append(getTableTypes[j][1]);
@@ -1719,14 +1721,16 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
byte remarks[] = null; byte remarks[] = null;
if(((org.postgresql.ResultSet)dr).getTupleCount()==1) { if (((org.postgresql.ResultSet)dr).getTupleCount() == 1)
{
dr.next(); dr.next();
remarks = dr.getBytes(1); remarks = dr.getBytes(1);
} }
dr.close(); dr.close();
String relKind; String relKind;
switch (r.getBytes(3)[0]) { switch (r.getBytes(3)[0])
{
case (byte) 'r': case (byte) 'r':
relKind = "TABLE"; relKind = "TABLE";
break; break;
@@ -1837,7 +1841,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
Field f[] = new Field[1]; Field f[] = new Field[1];
Vector v = new Vector(); Vector v = new Vector();
f[0] = new Field(connection, new String("TABLE_TYPE"), iVarcharOid, 32); f[0] = new Field(connection, new String("TABLE_TYPE"), iVarcharOid, 32);
for(int i=0;i<getTableTypes.length;i++) { for (int i = 0;i < getTableTypes.length;i++)
{
byte[][] tuple = new byte[1][0]; byte[][] tuple = new byte[1][0];
tuple[0] = getTableTypes[i][0].getBytes(); tuple[0] = getTableTypes[i][0].getBytes();
v.addElement(tuple); v.addElement(tuple);
@@ -1939,11 +1944,13 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" (" + " (" +
" a.attrelid=c.oid"); " a.attrelid=c.oid");
if ((tableNamePattern != null) && ! tableNamePattern.equals("%")) { if ((tableNamePattern != null) && ! tableNamePattern.equals("%"))
{
sql.append(" and c.relname like \'" + tableNamePattern + "\'"); sql.append(" and c.relname like \'" + tableNamePattern + "\'");
} }
if ((columnNamePattern != null) && ! columnNamePattern.equals("%")) { if ((columnNamePattern != null) && ! columnNamePattern.equals("%"))
{
sql.append(" and a.attname like \'" + columnNamePattern + "\'"); sql.append(" and a.attname like \'" + columnNamePattern + "\'");
} }
@@ -1961,7 +1968,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" and a.attnum = d.adnum" + " and a.attnum = d.adnum" +
" ) "); " ) ");
if (!connection.haveMinimumServerVersion("7.2")) { if (!connection.haveMinimumServerVersion("7.2"))
{
/* Only for 7.1 */ /* Only for 7.1 */
sql.append( sql.append(
" left outer join pg_description e on" + " left outer join pg_description e on" +
@@ -1974,7 +1982,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" c.relname, a.attnum"); " c.relname, a.attnum");
java.sql.ResultSet r = connection.ExecSQL(sql.toString()); java.sql.ResultSet r = connection.ExecSQL(sql.toString());
while (r.next()) { while (r.next())
{
byte[][] tuple = new byte[18][0]; byte[][] tuple = new byte[18][0];
String nullFlag = r.getString(6); String nullFlag = r.getString(6);
@@ -1991,10 +2000,13 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// Looking at the psql source, // Looking at the psql source,
// I think the length of a varchar as specified when the table was created // I think the length of a varchar as specified when the table was created
// should be extracted from atttypmod which contains this length + sizeof(int32) // should be extracted from atttypmod which contains this length + sizeof(int32)
if (typname.equals("bpchar") || typname.equals("varchar")) { if (typname.equals("bpchar") || typname.equals("varchar"))
{
int atttypmod = r.getInt(8); int atttypmod = r.getInt(8);
tuple[6] = Integer.toString(atttypmod != -1 ? atttypmod - VARHDRSZ : 0).getBytes(); tuple[6] = Integer.toString(atttypmod != -1 ? atttypmod - VARHDRSZ : 0).getBytes();
} else { }
else
{
tuple[6] = r.getBytes(7); tuple[6] = r.getBytes(7);
} }
@@ -2070,7 +2082,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// This is taken direct from the psql source // This is taken direct from the psql source
java.sql.ResultSet r = connection.ExecSQL("SELECT relname, relacl FROM pg_class, pg_user WHERE ( relkind = 'r' OR relkind = 'i') and relname !~ '^pg_' and relname !~ '^xin[vx][0-9]+' and usesysid = relowner and relname like '" + table.toLowerCase() + "' ORDER BY relname"); java.sql.ResultSet r = connection.ExecSQL("SELECT relname, relacl FROM pg_class, pg_user WHERE ( relkind = 'r' OR relkind = 'i') and relname !~ '^pg_' and relname !~ '^xin[vx][0-9]+' and usesysid = relowner and relname like '" + table.toLowerCase() + "' ORDER BY relname");
while(r.next()) { while (r.next())
{
byte[][] tuple = new byte[8][0]; byte[][] tuple = new byte[8][0];
tuple[0] = tuple[1] = "".getBytes(); tuple[0] = tuple[1] = "".getBytes();
DriverManager.println("relname=\"" + r.getString(1) + "\" relacl=\"" + r.getString(2) + "\""); DriverManager.println("relname=\"" + r.getString(1) + "\" relacl=\"" + r.getString(2) + "\"");
@@ -2247,7 +2260,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
); );
} }
private void importLoop(Vector tuples, java.sql.ResultSet keyRelation) throws SQLException { private void importLoop(Vector tuples, java.sql.ResultSet keyRelation) throws SQLException
{
String s, s2; String s, s2;
String origTable = null, primTable = new String(""), schema; String origTable = null, primTable = new String(""), schema;
int i; int i;
@@ -2257,14 +2271,17 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
s2 = s; s2 = s;
//System.out.println(s); //System.out.println(s);
for (i=0;;i++) { for (i = 0;;i++)
{
s = s.substring(s.indexOf("\\000") + 4); s = s.substring(s.indexOf("\\000") + 4);
if (s.compareTo("")==0) { if (s.compareTo("") == 0)
{
//System.out.println(); //System.out.println();
break; break;
} }
s2 = s.substring(0, s.indexOf("\\000")); s2 = s.substring(0, s.indexOf("\\000"));
switch (i) { switch (i)
{
case 0: case 0:
origTable = s2; origTable = s2;
break; break;
@@ -2287,11 +2304,14 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
byte tuple[][]; byte tuple[][];
// the foreign keys are only on even positions in the Vector. // the foreign keys are only on even positions in the Vector.
for (i=0;i<v.size();i+=2) { for (i = 0;i < v.size();i += 2)
{
stmp = (String)v.elementAt(i); stmp = (String)v.elementAt(i);
for (int j=1;j<=origCols.getColumnCount();j++) { for (int j = 1;j <= origCols.getColumnCount();j++)
if (stmp.compareTo(origCols.getColumnName(j))==0) { {
if (stmp.compareTo(origCols.getColumnName(j)) == 0)
{
tuple = new byte[14][0]; tuple = new byte[14][0];
for (int k = 0;k < 14;k++) for (int k = 0;k < 14;k++)
@@ -2401,7 +2421,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
"where c.relname like '" + table + "' and c.relfilenode=t.tgrelid"); "where c.relname like '" + table + "' and c.relfilenode=t.tgrelid");
Vector tuples = new Vector(); Vector tuples = new Vector();
while (rs.next()) { while (rs.next())
{
importLoop(tuples, rs); importLoop(tuples, rs);
} }
@@ -2577,7 +2598,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
public java.sql.ResultSet getTypeInfo() throws SQLException public java.sql.ResultSet getTypeInfo() throws SQLException
{ {
java.sql.ResultSet rs = connection.ExecSQL("select typname from pg_type"); java.sql.ResultSet rs = connection.ExecSQL("select typname from pg_type");
if(rs!=null) { if (rs != null)
{
Field f[] = new Field[18]; Field f[] = new Field[18];
ResultSet r; // ResultSet for the SQL query that we need to do ResultSet r; // ResultSet for the SQL query that we need to do
Vector v = new Vector(); // The new ResultSet tuple stuff Vector v = new Vector(); // The new ResultSet tuple stuff
@@ -2609,7 +2631,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
byte bnn[] = Integer.toString(typeNoNulls).getBytes(); byte bnn[] = Integer.toString(typeNoNulls).getBytes();
byte bts[] = Integer.toString(typeSearchable).getBytes(); byte bts[] = Integer.toString(typeSearchable).getBytes();
while(rs.next()) { while (rs.next())
{
byte[][] tuple = new byte[18][]; byte[][] tuple = new byte[18][];
String typname = rs.getString(1); String typname = rs.getString(1);
tuple[0] = typname.getBytes(); tuple[0] = typname.getBytes();
@@ -2722,7 +2745,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" AND (i.relam = a.oid)) " + " AND (i.relam = a.oid)) " +
"ORDER BY x.indisunique DESC, " + "ORDER BY x.indisunique DESC, " +
" x.indisclustered, a.amname, i.relname"); " x.indisclustered, a.amname, i.relname");
while (r.next()) { while (r.next())
{
// indkey is an array of column ordinals (integers). In the JDBC // indkey is an array of column ordinals (integers). In the JDBC
// interface, this has to be separated out into a separate // interface, this has to be separated out into a separate
// tuple for each indexed column. Also, getArray() is not yet // tuple for each indexed column. Also, getArray() is not yet
@@ -2731,10 +2755,12 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
StringTokenizer stok = new StringTokenizer(columnOrdinalString); StringTokenizer stok = new StringTokenizer(columnOrdinalString);
int [] columnOrdinals = new int[stok.countTokens()]; int [] columnOrdinals = new int[stok.countTokens()];
int o = 0; int o = 0;
while (stok.hasMoreTokens()) { while (stok.hasMoreTokens())
{
columnOrdinals[o++] = Integer.parseInt(stok.nextToken()); columnOrdinals[o++] = Integer.parseInt(stok.nextToken());
} }
for (int i = 0; i < columnOrdinals.length; i++) { for (int i = 0; i < columnOrdinals.length; i++)
{
byte [] [] tuple = new byte [13] []; byte [] [] tuple = new byte [13] [];
tuple[0] = "".getBytes(); tuple[0] = "".getBytes();
tuple[1] = "".getBytes(); tuple[1] = "".getBytes();

View File

@@ -261,7 +261,8 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
// if the passed string is null, then set this column to null // if the passed string is null, then set this column to null
if (x == null) if (x == null)
setNull(parameterIndex, Types.OTHER); setNull(parameterIndex, Types.OTHER);
else { else
{
StringBuffer b = new StringBuffer(); StringBuffer b = new StringBuffer();
int i; int i;
@@ -294,14 +295,20 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setBytes(int parameterIndex, byte x[]) throws SQLException public void setBytes(int parameterIndex, byte x[]) throws SQLException
{ {
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports the bytea datatype for byte arrays //Version 7.2 supports the bytea datatype for byte arrays
if(null == x){ if (null == x)
{
setNull(parameterIndex, Types.OTHER); setNull(parameterIndex, Types.OTHER);
} else { }
else
{
setString(parameterIndex, PGbytea.toPGString(x)); setString(parameterIndex, PGbytea.toPGString(x));
} }
} else { }
else
{
//Version 7.1 and earlier support done as LargeObjects //Version 7.1 and earlier support done as LargeObjects
LargeObjectManager lom = connection.getLargeObjectAPI(); LargeObjectManager lom = connection.getLargeObjectAPI();
int oid = lom.create(); int oid = lom.create();
@@ -322,9 +329,12 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setDate(int parameterIndex, java.sql.Date x) throws SQLException public void setDate(int parameterIndex, java.sql.Date x) throws SQLException
{ {
if (null == x){ if (null == x)
{
setNull(parameterIndex, Types.OTHER); setNull(parameterIndex, Types.OTHER);
}else{ }
else
{
SimpleDateFormat df = new SimpleDateFormat("''yyyy-MM-dd''"); SimpleDateFormat df = new SimpleDateFormat("''yyyy-MM-dd''");
set(parameterIndex, df.format(x)); set(parameterIndex, df.format(x));
} }
@@ -350,9 +360,12 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setTime(int parameterIndex, Time x) throws SQLException public void setTime(int parameterIndex, Time x) throws SQLException
{ {
if (null == x){ if (null == x)
{
setNull(parameterIndex, Types.OTHER); setNull(parameterIndex, Types.OTHER);
}else{ }
else
{
set(parameterIndex, "'" + x.toString() + "'"); set(parameterIndex, "'" + x.toString() + "'");
} }
} }
@@ -367,9 +380,12 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException
{ {
if (null == x){ if (null == x)
{
setNull(parameterIndex, Types.OTHER); setNull(parameterIndex, Types.OTHER);
}else{ }
else
{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("GMT")); df.setTimeZone(TimeZone.getTimeZone("GMT"));
StringBuffer strBuf = new StringBuffer("'"); StringBuffer strBuf = new StringBuffer("'");
@@ -396,24 +412,32 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException
{ {
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports AsciiStream for all PG text types (char, varchar, text) //Version 7.2 supports AsciiStream for all PG text types (char, varchar, text)
//As the spec/javadoc for this method indicate this is to be used for //As the spec/javadoc for this method indicate this is to be used for
//large String values (i.e. LONGVARCHAR) PG doesn't have a separate //large String values (i.e. LONGVARCHAR) PG doesn't have a separate
//long varchar datatype, but with toast all text datatypes are capable of //long varchar datatype, but with toast all text datatypes are capable of
//handling very large values. Thus the implementation ends up calling //handling very large values. Thus the implementation ends up calling
//setString() since there is no current way to stream the value to the server //setString() since there is no current way to stream the value to the server
try { try
{
InputStreamReader l_inStream = new InputStreamReader(x, "ASCII"); InputStreamReader l_inStream = new InputStreamReader(x, "ASCII");
char[] l_chars = new char[length]; char[] l_chars = new char[length];
int l_charsRead = l_inStream.read(l_chars, 0, length); int l_charsRead = l_inStream.read(l_chars, 0, length);
setString(parameterIndex, new String(l_chars, 0, l_charsRead)); setString(parameterIndex, new String(l_chars, 0, l_charsRead));
} catch (UnsupportedEncodingException l_uee) { }
catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException("postgresql.unusual", l_uee); throw new PSQLException("postgresql.unusual", l_uee);
} catch (IOException l_ioe) { }
catch (IOException l_ioe)
{
throw new PSQLException("postgresql.unusual", l_ioe); throw new PSQLException("postgresql.unusual", l_ioe);
} }
} else { }
else
{
//Version 7.1 supported only LargeObjects by treating everything //Version 7.1 supported only LargeObjects by treating everything
//as binary data //as binary data
setBinaryStream(parameterIndex, x, length); setBinaryStream(parameterIndex, x, length);
@@ -437,24 +461,32 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException
{ {
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports AsciiStream for all PG text types (char, varchar, text) //Version 7.2 supports AsciiStream for all PG text types (char, varchar, text)
//As the spec/javadoc for this method indicate this is to be used for //As the spec/javadoc for this method indicate this is to be used for
//large String values (i.e. LONGVARCHAR) PG doesn't have a separate //large String values (i.e. LONGVARCHAR) PG doesn't have a separate
//long varchar datatype, but with toast all text datatypes are capable of //long varchar datatype, but with toast all text datatypes are capable of
//handling very large values. Thus the implementation ends up calling //handling very large values. Thus the implementation ends up calling
//setString() since there is no current way to stream the value to the server //setString() since there is no current way to stream the value to the server
try { try
{
InputStreamReader l_inStream = new InputStreamReader(x, "UTF-8"); InputStreamReader l_inStream = new InputStreamReader(x, "UTF-8");
char[] l_chars = new char[length]; char[] l_chars = new char[length];
int l_charsRead = l_inStream.read(l_chars, 0, length); int l_charsRead = l_inStream.read(l_chars, 0, length);
setString(parameterIndex, new String(l_chars, 0, l_charsRead)); setString(parameterIndex, new String(l_chars, 0, l_charsRead));
} catch (UnsupportedEncodingException l_uee) { }
catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException("postgresql.unusual", l_uee); throw new PSQLException("postgresql.unusual", l_uee);
} catch (IOException l_ioe) { }
catch (IOException l_ioe)
{
throw new PSQLException("postgresql.unusual", l_ioe); throw new PSQLException("postgresql.unusual", l_ioe);
} }
} else { }
else
{
//Version 7.1 supported only LargeObjects by treating everything //Version 7.1 supported only LargeObjects by treating everything
//as binary data //as binary data
setBinaryStream(parameterIndex, x, length); setBinaryStream(parameterIndex, x, length);
@@ -477,7 +509,8 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException
{ {
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports BinaryStream for for the PG bytea type //Version 7.2 supports BinaryStream for for the PG bytea type
//As the spec/javadoc for this method indicate this is to be used for //As the spec/javadoc for this method indicate this is to be used for
//large binary values (i.e. LONGVARBINARY) PG doesn't have a separate //large binary values (i.e. LONGVARBINARY) PG doesn't have a separate
@@ -486,20 +519,28 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
//setBytes() since there is no current way to stream the value to the server //setBytes() since there is no current way to stream the value to the server
byte[] l_bytes = new byte[length]; byte[] l_bytes = new byte[length];
int l_bytesRead; int l_bytesRead;
try { try
{
l_bytesRead = x.read(l_bytes, 0, length); l_bytesRead = x.read(l_bytes, 0, length);
} catch (IOException l_ioe) { }
catch (IOException l_ioe)
{
throw new PSQLException("postgresql.unusual", l_ioe); throw new PSQLException("postgresql.unusual", l_ioe);
} }
if (l_bytesRead == length) { if (l_bytesRead == length)
{
setBytes(parameterIndex, l_bytes); setBytes(parameterIndex, l_bytes);
} else { }
else
{
//the stream contained less data than they said //the stream contained less data than they said
byte[] l_bytes2 = new byte[l_bytesRead]; byte[] l_bytes2 = new byte[l_bytesRead];
System.arraycopy(l_bytes, 0, l_bytes2, 0, l_bytesRead); System.arraycopy(l_bytes, 0, l_bytes2, 0, l_bytesRead);
setBytes(parameterIndex, l_bytes2); setBytes(parameterIndex, l_bytes2);
} }
} else { }
else
{
//Version 7.1 only supported streams for LargeObjects //Version 7.1 only supported streams for LargeObjects
//but the jdbc spec indicates that streams should be //but the jdbc spec indicates that streams should be
//available for LONGVARBINARY instead //available for LONGVARBINARY instead
@@ -507,19 +548,23 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
int oid = lom.create(); int oid = lom.create();
LargeObject lob = lom.open(oid); LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream(); OutputStream los = lob.getOutputStream();
try { try
{
// could be buffered, but then the OutputStream returned by LargeObject // could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance // is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse! // boost gained, if anything it would be worse!
int c = x.read(); int c = x.read();
int p = 0; int p = 0;
while(c>-1 && p<length) { while (c > -1 && p < length)
{
los.write(c); los.write(c);
c = x.read(); c = x.read();
p++; p++;
} }
los.close(); los.close();
} catch(IOException se) { }
catch (IOException se)
{
throw new PSQLException("postgresql.unusual", se); throw new PSQLException("postgresql.unusual", se);
} }
// lob is closed by the stream so don't call lob.close() // lob is closed by the stream so don't call lob.close()
@@ -565,7 +610,8 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException
{ {
if (x == null){ if (x == null)
{
setNull(parameterIndex, Types.OTHER); setNull(parameterIndex, Types.OTHER);
return ; return ;
} }
@@ -600,9 +646,12 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
setTimestamp(parameterIndex, (Timestamp)x); setTimestamp(parameterIndex, (Timestamp)x);
break; break;
case Types.BIT: case Types.BIT:
if (x instanceof Boolean) { if (x instanceof Boolean)
{
set(parameterIndex, ((Boolean)x).booleanValue() ? "TRUE" : "FALSE"); set(parameterIndex, ((Boolean)x).booleanValue() ? "TRUE" : "FALSE");
} else { }
else
{
throw new PSQLException("postgresql.prep.type"); throw new PSQLException("postgresql.prep.type");
} }
break; break;
@@ -631,7 +680,8 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setObject(int parameterIndex, Object x) throws SQLException public void setObject(int parameterIndex, Object x) throws SQLException
{ {
if (x == null){ if (x == null)
{
setNull(parameterIndex, Types.OTHER); setNull(parameterIndex, Types.OTHER);
return ; return ;
} }
@@ -694,7 +744,8 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
* Returns the SQL statement with the current template values * Returns the SQL statement with the current template values
* substituted. * substituted.
*/ */
public String toString() { public String toString()
{
StringBuffer s = new StringBuffer(); StringBuffer s = new StringBuffer();
int i; int i;

View File

@@ -201,7 +201,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Byte.parseByte(s); return Byte.parseByte(s);
} catch (NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException("postgresql.res.badbyte", s); throw new PSQLException("postgresql.res.badbyte", s);
} }
} }
@@ -224,7 +226,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Short.parseShort(s); return Short.parseShort(s);
} catch (NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException("postgresql.res.badshort", s); throw new PSQLException("postgresql.res.badshort", s);
} }
} }
@@ -247,7 +251,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Integer.parseInt(s); return Integer.parseInt(s);
} catch (NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badint", s); throw new PSQLException ("postgresql.res.badint", s);
} }
} }
@@ -270,7 +276,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Long.parseLong(s); return Long.parseLong(s);
} catch (NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badlong", s); throw new PSQLException ("postgresql.res.badlong", s);
} }
} }
@@ -293,7 +301,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Float.valueOf(s).floatValue(); return Float.valueOf(s).floatValue();
} catch (NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badfloat", s); throw new PSQLException ("postgresql.res.badfloat", s);
} }
} }
@@ -316,7 +326,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Double.valueOf(s).doubleValue(); return Double.valueOf(s).doubleValue();
} catch (NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.baddouble", s); throw new PSQLException ("postgresql.res.baddouble", s);
} }
} }
@@ -342,13 +354,17 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
val = new BigDecimal(s); val = new BigDecimal(s);
} catch (NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badbigdec", s); throw new PSQLException ("postgresql.res.badbigdec", s);
} }
try try
{ {
return val.setScale(scale); return val.setScale(scale);
} catch (ArithmeticException e) { }
catch (ArithmeticException e)
{
throw new PSQLException ("postgresql.res.badbigdec", s); throw new PSQLException ("postgresql.res.badbigdec", s);
} }
} }
@@ -376,17 +392,23 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
throw new PSQLException("postgresql.res.colrange"); throw new PSQLException("postgresql.res.colrange");
//If the data is already binary then just return it //If the data is already binary then just return it
if (binaryCursor) return this_row[columnIndex - 1]; if (binaryCursor)
return this_row[columnIndex - 1];
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports the bytea datatype for byte arrays //Version 7.2 supports the bytea datatype for byte arrays
return PGbytea.toBytes(getString(columnIndex)); return PGbytea.toBytes(getString(columnIndex));
} else { }
else
{
//Version 7.1 and earlier supports LargeObjects for byte arrays //Version 7.1 and earlier supports LargeObjects for byte arrays
wasNullFlag = (this_row[columnIndex - 1] == null); wasNullFlag = (this_row[columnIndex - 1] == null);
// Handle OID's as BLOBS // Handle OID's as BLOBS
if(!wasNullFlag) { if (!wasNullFlag)
if( fields[columnIndex - 1].getOID() == 26) { {
if ( fields[columnIndex - 1].getOID() == 26)
{
LargeObjectManager lom = connection.getLargeObjectAPI(); LargeObjectManager lom = connection.getLargeObjectAPI();
LargeObject lob = lom.open(getInt(columnIndex)); LargeObject lob = lom.open(getInt(columnIndex));
byte buf[] = lob.read(lob.size()); byte buf[] = lob.read(lob.size());
@@ -436,7 +458,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
int min = Integer.parseInt(s.substring(3, 5)); int min = Integer.parseInt(s.substring(3, 5));
int sec = (s.length() == 5) ? 0 : Integer.parseInt(s.substring(6)); int sec = (s.length() == 5) ? 0 : Integer.parseInt(s.substring(6));
return new Time(hr, min, sec); return new Time(hr, min, sec);
} catch (NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badtime", s); throw new PSQLException ("postgresql.res.badtime", s);
} }
} }
@@ -459,9 +483,12 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
boolean subsecond; boolean subsecond;
//if string contains a '.' we have fractional seconds //if string contains a '.' we have fractional seconds
if (s.indexOf('.') == -1) { if (s.indexOf('.') == -1)
{
subsecond = false; subsecond = false;
} else { }
else
{
subsecond = true; subsecond = true;
} }
@@ -479,29 +506,43 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
//if the backend ISO format changes in the future this code will //if the backend ISO format changes in the future this code will
//need to be changed as well //need to be changed as well
char sub = strBuf.charAt(strBuf.length() - 3); char sub = strBuf.charAt(strBuf.length() - 3);
if (sub == '+' || sub == '-') { if (sub == '+' || sub == '-')
{
strBuf.setLength(strBuf.length() - 3); strBuf.setLength(strBuf.length() - 3);
if (subsecond) { if (subsecond)
{
strBuf.append('0').append("GMT").append(s.substring(s.length() - 3, s.length())).append(":00"); strBuf.append('0').append("GMT").append(s.substring(s.length() - 3, s.length())).append(":00");
} else { }
else
{
strBuf.append("GMT").append(s.substring(s.length() - 3, s.length())).append(":00"); strBuf.append("GMT").append(s.substring(s.length() - 3, s.length())).append(":00");
} }
} else if (sub == ':') { }
else if (sub == ':')
{
//we may have found timezone info of format +/-HH:MM, or there is no //we may have found timezone info of format +/-HH:MM, or there is no
//timezone info at all and this is the : preceding the seconds //timezone info at all and this is the : preceding the seconds
char sub2 = strBuf.charAt(strBuf.length() - 5); char sub2 = strBuf.charAt(strBuf.length() - 5);
if (sub2 == '+' || sub2 == '-') { if (sub2 == '+' || sub2 == '-')
{
//we have found timezone info of format +/-HH:MM //we have found timezone info of format +/-HH:MM
strBuf.setLength(strBuf.length() - 5); strBuf.setLength(strBuf.length() - 5);
if (subsecond) { if (subsecond)
{
strBuf.append('0').append("GMT").append(s.substring(s.length() - 5)); strBuf.append('0').append("GMT").append(s.substring(s.length() - 5));
} else { }
else
{
strBuf.append("GMT").append(s.substring(s.length() - 5)); strBuf.append("GMT").append(s.substring(s.length() - 5));
} }
} else if (subsecond) { }
else if (subsecond)
{
strBuf.append('0'); strBuf.append('0');
} }
} else if (subsecond) { }
else if (subsecond)
{
strBuf = strBuf.append('0'); strBuf = strBuf.append('0');
} }
@@ -509,21 +550,33 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
SimpleDateFormat df = null; SimpleDateFormat df = null;
if (s.length()>23 && subsecond) { if (s.length() > 23 && subsecond)
{
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSzzzzzzzzz"); df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSzzzzzzzzz");
} else if (s.length()>23 && !subsecond) { }
else if (s.length() > 23 && !subsecond)
{
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:sszzzzzzzzz"); df = new SimpleDateFormat("yyyy-MM-dd HH:mm:sszzzzzzzzz");
} else if (s.length()>10 && subsecond) { }
else if (s.length() > 10 && subsecond)
{
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
} else if (s.length()>10 && !subsecond) { }
else if (s.length() > 10 && !subsecond)
{
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
} else { }
else
{
df = new SimpleDateFormat("yyyy-MM-dd"); df = new SimpleDateFormat("yyyy-MM-dd");
} }
try { try
{
return new Timestamp(df.parse(s).getTime()); return new Timestamp(df.parse(s).getTime());
} catch(ParseException e) { }
catch (ParseException e)
{
throw new PSQLException("postgresql.res.badtimestamp", new Integer(e.getErrorOffset()), s); throw new PSQLException("postgresql.res.badtimestamp", new Integer(e.getErrorOffset()), s);
} }
} }
@@ -558,19 +611,25 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
if (wasNullFlag) if (wasNullFlag)
return null; return null;
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports AsciiStream for all the PG text types //Version 7.2 supports AsciiStream for all the PG text types
//As the spec/javadoc for this method indicate this is to be used for //As the spec/javadoc for this method indicate this is to be used for
//large text values (i.e. LONGVARCHAR) PG doesn't have a separate //large text values (i.e. LONGVARCHAR) PG doesn't have a separate
//long string datatype, but with toast the text datatype is capable of //long string datatype, but with toast the text datatype is capable of
//handling very large values. Thus the implementation ends up calling //handling very large values. Thus the implementation ends up calling
//getString() since there is no current way to stream the value from the server //getString() since there is no current way to stream the value from the server
try { try
{
return new ByteArrayInputStream(getString(columnIndex).getBytes("ASCII")); return new ByteArrayInputStream(getString(columnIndex).getBytes("ASCII"));
} catch (UnsupportedEncodingException l_uee) { }
catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException("postgresql.unusual", l_uee); throw new PSQLException("postgresql.unusual", l_uee);
} }
} else { }
else
{
// In 7.1 Handle as BLOBS so return the LargeObject input stream // In 7.1 Handle as BLOBS so return the LargeObject input stream
return getBinaryStream(columnIndex); return getBinaryStream(columnIndex);
} }
@@ -594,19 +653,25 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
if (wasNullFlag) if (wasNullFlag)
return null; return null;
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports AsciiStream for all the PG text types //Version 7.2 supports AsciiStream for all the PG text types
//As the spec/javadoc for this method indicate this is to be used for //As the spec/javadoc for this method indicate this is to be used for
//large text values (i.e. LONGVARCHAR) PG doesn't have a separate //large text values (i.e. LONGVARCHAR) PG doesn't have a separate
//long string datatype, but with toast the text datatype is capable of //long string datatype, but with toast the text datatype is capable of
//handling very large values. Thus the implementation ends up calling //handling very large values. Thus the implementation ends up calling
//getString() since there is no current way to stream the value from the server //getString() since there is no current way to stream the value from the server
try { try
{
return new ByteArrayInputStream(getString(columnIndex).getBytes("UTF-8")); return new ByteArrayInputStream(getString(columnIndex).getBytes("UTF-8"));
} catch (UnsupportedEncodingException l_uee) { }
catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException("postgresql.unusual", l_uee); throw new PSQLException("postgresql.unusual", l_uee);
} }
} else { }
else
{
// In 7.1 Handle as BLOBS so return the LargeObject input stream // In 7.1 Handle as BLOBS so return the LargeObject input stream
return getBinaryStream(columnIndex); return getBinaryStream(columnIndex);
} }
@@ -630,7 +695,8 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
if (wasNullFlag) if (wasNullFlag)
return null; return null;
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports BinaryStream for all PG bytea type //Version 7.2 supports BinaryStream for all PG bytea type
//As the spec/javadoc for this method indicate this is to be used for //As the spec/javadoc for this method indicate this is to be used for
//large binary values (i.e. LONGVARBINARY) PG doesn't have a separate //large binary values (i.e. LONGVARBINARY) PG doesn't have a separate
@@ -640,9 +706,12 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
byte b[] = getBytes(columnIndex); byte b[] = getBytes(columnIndex);
if (b != null) if (b != null)
return new ByteArrayInputStream(b); return new ByteArrayInputStream(b);
} else { }
else
{
// In 7.1 Handle as BLOBS so return the LargeObject input stream // In 7.1 Handle as BLOBS so return the LargeObject input stream
if( fields[columnIndex - 1].getOID() == 26) { if ( fields[columnIndex - 1].getOID() == 26)
{
LargeObjectManager lom = connection.getLargeObjectAPI(); LargeObjectManager lom = connection.getLargeObjectAPI();
LargeObject lob = lom.open(getInt(columnIndex)); LargeObject lob = lom.open(getInt(columnIndex));
return lob.getInputStream(); return lob.getInputStream();
@@ -831,7 +900,8 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
field = fields[columnIndex - 1]; field = fields[columnIndex - 1];
// some fields can be null, mainly from those returned by MetaData methods // some fields can be null, mainly from those returned by MetaData methods
if(field==null) { if (field == null)
{
wasNullFlag = true; wasNullFlag = true;
return null; return null;
} }
@@ -867,9 +937,12 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
default: default:
String type = field.getPGType(); String type = field.getPGType();
// if the backend doesn't know the type then coerce to String // if the backend doesn't know the type then coerce to String
if (type.equals("unknown")){ if (type.equals("unknown"))
{
return getString(columnIndex); return getString(columnIndex);
}else{ }
else
{
return connection.getObject(field.getPGType(), getString(columnIndex)); return connection.getObject(field.getPGType(), getString(columnIndex));
} }
} }

View File

@@ -201,24 +201,37 @@ public class ResultSetMetaData implements java.sql.ResultSetMetaData
// FIXME: currently, only types with a SQL92 or SQL3 pendant are implemented - jens@jens.de // FIXME: currently, only types with a SQL92 or SQL3 pendant are implemented - jens@jens.de
// fixed length data types // fixed length data types
if (type_name.equals( "int2" )) return 6; // -32768 to +32768 (5 digits and a sign) if (type_name.equals( "int2" ))
return 6; // -32768 to +32768 (5 digits and a sign)
if (type_name.equals( "int4" ) if (type_name.equals( "int4" )
|| type_name.equals( "oid" )) return 11; // -2147483648 to +2147483647 || type_name.equals( "oid" ))
if (type_name.equals( "int8" )) return 20; // -9223372036854775808 to +9223372036854775807 return 11; // -2147483648 to +2147483647
if (type_name.equals( "money" )) return 12; // MONEY = DECIMAL(9,2) if (type_name.equals( "int8" ))
if (type_name.equals( "float4" )) return 11; // i checked it out ans wasn't able to produce more than 11 digits return 20; // -9223372036854775808 to +9223372036854775807
if (type_name.equals( "float8" )) return 20; // dito, 20 if (type_name.equals( "money" ))
if (type_name.equals( "char" )) return 1; return 12; // MONEY = DECIMAL(9,2)
if (type_name.equals( "bool" )) return 1; if (type_name.equals( "float4" ))
if (type_name.equals( "date" )) return 14; // "01/01/4713 BC" - "31/12/32767 AD" return 11; // i checked it out ans wasn't able to produce more than 11 digits
if (type_name.equals( "time" )) return 8; // 00:00:00-23:59:59 if (type_name.equals( "float8" ))
if (type_name.equals( "timestamp" )) return 22; // hhmmm ... the output looks like this: 1999-08-03 22:22:08+02 return 20; // dito, 20
if (type_name.equals( "char" ))
return 1;
if (type_name.equals( "bool" ))
return 1;
if (type_name.equals( "date" ))
return 14; // "01/01/4713 BC" - "31/12/32767 AD"
if (type_name.equals( "time" ))
return 8; // 00:00:00-23:59:59
if (type_name.equals( "timestamp" ))
return 22; // hhmmm ... the output looks like this: 1999-08-03 22:22:08+02
// variable length fields // variable length fields
typmod -= 4; typmod -= 4;
if (type_name.equals( "bpchar" ) if (type_name.equals( "bpchar" )
|| type_name.equals( "varchar" )) return typmod; // VARHDRSZ=sizeof(int32)=4 || type_name.equals( "varchar" ))
if (type_name.equals( "numeric" )) return ( (typmod >>16) & 0xffff ) return typmod; // VARHDRSZ=sizeof(int32)=4
if (type_name.equals( "numeric" ))
return ( (typmod >> 16) & 0xffff )
+ 1 + ( typmod & 0xffff ); // DECIMAL(p,s) = (p digits).(s digits) + 1 + ( typmod & 0xffff ); // DECIMAL(p,s) = (p digits).(s digits)
// if we don't know better // if we don't know better

View File

@@ -124,8 +124,10 @@ public class Statement extends org.postgresql.Statement implements java.sql.Stat
*/ */
public int getUpdateCount() throws SQLException public int getUpdateCount() throws SQLException
{ {
if (result == null) return -1; if (result == null)
if (((org.postgresql.ResultSet)result).reallyResultSet()) return -1; return -1;
if (((org.postgresql.ResultSet)result).reallyResultSet())
return -1;
return ((org.postgresql.ResultSet)result).getResultCount(); return ((org.postgresql.ResultSet)result).getResultCount();
} }

View File

@@ -49,19 +49,23 @@ public class Array implements java.sql.Array
this.rawString = rs.getFixedString(idx); this.rawString = rs.getFixedString(idx);
} }
public Object getArray() throws SQLException { public Object getArray() throws SQLException
{
return getArray( 1, 0, null ); return getArray( 1, 0, null );
} }
public Object getArray(long index, int count) throws SQLException { public Object getArray(long index, int count) throws SQLException
{
return getArray( index, count, null ); return getArray( index, count, null );
} }
public Object getArray(Map map) throws SQLException { public Object getArray(Map map) throws SQLException
{
return getArray( 1, 0, map ); return getArray( 1, 0, map );
} }
public Object getArray(long index, int count, Map map) throws SQLException { public Object getArray(long index, int count, Map map) throws SQLException
{
if ( map != null ) // For now maps aren't supported. if ( map != null ) // For now maps aren't supported.
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
@@ -70,23 +74,28 @@ public class Array implements java.sql.Array
Object retVal = null; Object retVal = null;
ArrayList array = new ArrayList(); ArrayList array = new ArrayList();
if( rawString != null ) { if ( rawString != null )
{
char[] chars = rawString.toCharArray(); char[] chars = rawString.toCharArray();
StringBuffer sbuf = new StringBuffer(); StringBuffer sbuf = new StringBuffer();
boolean foundOpen = false; boolean foundOpen = false;
boolean insideString = false; boolean insideString = false;
for( int i=0; i<chars.length; i++ ) { for ( int i = 0; i < chars.length; i++ )
if( chars[i] == '{' ) { {
if ( chars[i] == '{' )
{
if ( foundOpen ) // Only supports 1-D arrays for now if ( foundOpen ) // Only supports 1-D arrays for now
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
foundOpen = true; foundOpen = true;
continue; continue;
} }
if( chars[i] == '"' ) { if ( chars[i] == '"' )
{
insideString = !insideString; insideString = !insideString;
continue; continue;
} }
if( (!insideString && chars[i] == ',') || chars[i] == '}' || i == chars.length-1) { if ( (!insideString && chars[i] == ',') || chars[i] == '}' || i == chars.length - 1)
{
if ( chars[i] != '"' && chars[i] != '}' && chars[i] != ',' ) if ( chars[i] != '"' && chars[i] != '}' && chars[i] != ',' )
sbuf.append(chars[i]); sbuf.append(chars[i]);
array.add( sbuf.toString() ); array.add( sbuf.toString() );
@@ -168,30 +177,36 @@ public class Array implements java.sql.Array
return retVal; return retVal;
} }
public int getBaseType() throws SQLException { public int getBaseType() throws SQLException
{
return conn.getSQLType(getBaseTypeName()); return conn.getSQLType(getBaseTypeName());
} }
public String getBaseTypeName() throws SQLException { public String getBaseTypeName() throws SQLException
{
String fType = field.getPGType(); String fType = field.getPGType();
if ( fType.charAt(0) == '_' ) if ( fType.charAt(0) == '_' )
fType = fType.substring(1); fType = fType.substring(1);
return fType; return fType;
} }
public java.sql.ResultSet getResultSet() throws SQLException { public java.sql.ResultSet getResultSet() throws SQLException
{
return getResultSet( 1, 0, null ); return getResultSet( 1, 0, null );
} }
public java.sql.ResultSet getResultSet(long index, int count) throws SQLException { public java.sql.ResultSet getResultSet(long index, int count) throws SQLException
{
return getResultSet( index, count, null ); return getResultSet( index, count, null );
} }
public java.sql.ResultSet getResultSet(Map map) throws SQLException { public java.sql.ResultSet getResultSet(Map map) throws SQLException
{
return getResultSet( 1, 0, map ); return getResultSet( 1, 0, map );
} }
public java.sql.ResultSet getResultSet(long index, int count, java.util.Map map) throws SQLException { public java.sql.ResultSet getResultSet(long index, int count, java.util.Map map) throws SQLException
{
Object array = getArray( index, count, map ); Object array = getArray( index, count, map );
Vector rows = new Vector(); Vector rows = new Vector();
Field[] fields = new Field[2]; Field[] fields = new Field[2];
@@ -201,7 +216,8 @@ public class Array implements java.sql.Array
case Types.BIT: case Types.BIT:
boolean[] booleanArray = (boolean[]) array; boolean[] booleanArray = (boolean[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("bool"), 1); fields[1] = new Field(conn, "VALUE", conn.getOID("bool"), 1);
for( int i=0; i<booleanArray.length; i++ ) { for ( int i = 0; i < booleanArray.length; i++ )
{
byte[][] tuple = new byte[2][0]; byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( (booleanArray[i] ? "YES" : "NO") ); // Value tuple[1] = conn.getEncoding().encode( (booleanArray[i] ? "YES" : "NO") ); // Value
@@ -213,7 +229,8 @@ public class Array implements java.sql.Array
int[] intArray = (int[]) array; int[] intArray = (int[]) array;
if ( fields[1] == null ) if ( fields[1] == null )
fields[1] = new Field(conn, "VALUE", conn.getOID("int4"), 4); fields[1] = new Field(conn, "VALUE", conn.getOID("int4"), 4);
for( int i=0; i<intArray.length; i++ ) { for ( int i = 0; i < intArray.length; i++ )
{
byte[][] tuple = new byte[2][0]; byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( Integer.toString(intArray[i]) ); // Value tuple[1] = conn.getEncoding().encode( Integer.toString(intArray[i]) ); // Value
@@ -223,7 +240,8 @@ public class Array implements java.sql.Array
case Types.BIGINT: case Types.BIGINT:
long[] longArray = (long[]) array; long[] longArray = (long[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("int8"), 8); fields[1] = new Field(conn, "VALUE", conn.getOID("int8"), 8);
for( int i=0; i<longArray.length; i++ ) { for ( int i = 0; i < longArray.length; i++ )
{
byte[][] tuple = new byte[2][0]; byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( Long.toString(longArray[i]) ); // Value tuple[1] = conn.getEncoding().encode( Long.toString(longArray[i]) ); // Value
@@ -233,7 +251,8 @@ public class Array implements java.sql.Array
case Types.NUMERIC: case Types.NUMERIC:
BigDecimal[] bdArray = (BigDecimal[]) array; BigDecimal[] bdArray = (BigDecimal[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("numeric"), -1); fields[1] = new Field(conn, "VALUE", conn.getOID("numeric"), -1);
for( int i=0; i<bdArray.length; i++ ) { for ( int i = 0; i < bdArray.length; i++ )
{
byte[][] tuple = new byte[2][0]; byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( bdArray[i].toString() ); // Value tuple[1] = conn.getEncoding().encode( bdArray[i].toString() ); // Value
@@ -243,7 +262,8 @@ public class Array implements java.sql.Array
case Types.REAL: case Types.REAL:
float[] floatArray = (float[]) array; float[] floatArray = (float[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("float4"), 4); fields[1] = new Field(conn, "VALUE", conn.getOID("float4"), 4);
for( int i=0; i<floatArray.length; i++ ) { for ( int i = 0; i < floatArray.length; i++ )
{
byte[][] tuple = new byte[2][0]; byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( Float.toString(floatArray[i]) ); // Value tuple[1] = conn.getEncoding().encode( Float.toString(floatArray[i]) ); // Value
@@ -253,7 +273,8 @@ public class Array implements java.sql.Array
case Types.DOUBLE: case Types.DOUBLE:
double[] doubleArray = (double[]) array; double[] doubleArray = (double[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("float8"), 8); fields[1] = new Field(conn, "VALUE", conn.getOID("float8"), 8);
for( int i=0; i<doubleArray.length; i++ ) { for ( int i = 0; i < doubleArray.length; i++ )
{
byte[][] tuple = new byte[2][0]; byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( Double.toString(doubleArray[i]) ); // Value tuple[1] = conn.getEncoding().encode( Double.toString(doubleArray[i]) ); // Value
@@ -266,7 +287,8 @@ public class Array implements java.sql.Array
String[] strArray = (String[]) array; String[] strArray = (String[]) array;
if ( fields[1] == null ) if ( fields[1] == null )
fields[1] = new Field(conn, "VALUE", conn.getOID("varchar"), -1); fields[1] = new Field(conn, "VALUE", conn.getOID("varchar"), -1);
for( int i=0; i<strArray.length; i++ ) { for ( int i = 0; i < strArray.length; i++ )
{
byte[][] tuple = new byte[2][0]; byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( strArray[i] ); // Value tuple[1] = conn.getEncoding().encode( strArray[i] ); // Value
@@ -276,7 +298,8 @@ public class Array implements java.sql.Array
case Types.DATE: case Types.DATE:
java.sql.Date[] dateArray = (java.sql.Date[]) array; java.sql.Date[] dateArray = (java.sql.Date[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("date"), 4); fields[1] = new Field(conn, "VALUE", conn.getOID("date"), 4);
for( int i=0; i<dateArray.length; i++ ) { for ( int i = 0; i < dateArray.length; i++ )
{
byte[][] tuple = new byte[2][0]; byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( dateArray[i].toString() ); // Value tuple[1] = conn.getEncoding().encode( dateArray[i].toString() ); // Value
@@ -286,7 +309,8 @@ public class Array implements java.sql.Array
case Types.TIME: case Types.TIME:
java.sql.Time[] timeArray = (java.sql.Time[]) array; java.sql.Time[] timeArray = (java.sql.Time[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("time"), 8); fields[1] = new Field(conn, "VALUE", conn.getOID("time"), 8);
for( int i=0; i<timeArray.length; i++ ) { for ( int i = 0; i < timeArray.length; i++ )
{
byte[][] tuple = new byte[2][0]; byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( timeArray[i].toString() ); // Value tuple[1] = conn.getEncoding().encode( timeArray[i].toString() ); // Value
@@ -296,7 +320,8 @@ public class Array implements java.sql.Array
case Types.TIMESTAMP: case Types.TIMESTAMP:
java.sql.Timestamp[] timestampArray = (java.sql.Timestamp[]) array; java.sql.Timestamp[] timestampArray = (java.sql.Timestamp[]) array;
fields[1] = new Field(conn, "VALUE", conn.getOID("timestamp"), 8); fields[1] = new Field(conn, "VALUE", conn.getOID("timestamp"), 8);
for( int i=0; i<timestampArray.length; i++ ) { for ( int i = 0; i < timestampArray.length; i++ )
{
byte[][] tuple = new byte[2][0]; byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( timestampArray[i].toString() ); // Value tuple[1] = conn.getEncoding().encode( timestampArray[i].toString() ); // Value
@@ -312,6 +337,9 @@ public class Array implements java.sql.Array
return new ResultSet((org.postgresql.jdbc2.Connection)conn, fields, rows, "OK", 1 ); return new ResultSet((org.postgresql.jdbc2.Connection)conn, fields, rows, "OK", 1 );
} }
public String toString() { return rawString; } public String toString()
{
return rawString;
}
} }

View File

@@ -64,8 +64,8 @@ public class CallableStatement extends org.postgresql.jdbc2.PreparedStatement im
* registerOutParameter that accepts a scale value * registerOutParameter that accepts a scale value
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException
} {}
/** /**
* You must also specify the scale for numeric/decimal types: * You must also specify the scale for numeric/decimal types:
@@ -82,8 +82,7 @@ public class CallableStatement extends org.postgresql.jdbc2.PreparedStatement im
*/ */
public void registerOutParameter(int parameterIndex, int sqlType, public void registerOutParameter(int parameterIndex, int sqlType,
int scale) throws SQLException int scale) throws SQLException
{ {}
}
// Old api? // Old api?
//public boolean isNull(int parameterIndex) throws SQLException { //public boolean isNull(int parameterIndex) throws SQLException {
@@ -99,7 +98,8 @@ public class CallableStatement extends org.postgresql.jdbc2.PreparedStatement im
* @return true if the last parameter read was SQL NULL * @return true if the last parameter read was SQL NULL
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public boolean wasNull() throws SQLException { public boolean wasNull() throws SQLException
{
// check to see if the last access threw an exception // check to see if the last access threw an exception
return false; // fake it for now return false; // fake it for now
} }
@@ -117,7 +117,8 @@ public class CallableStatement extends org.postgresql.jdbc2.PreparedStatement im
* @return the parameter value; if the value is SQL NULL, the result is null * @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public String getString(int parameterIndex) throws SQLException { public String getString(int parameterIndex) throws SQLException
{
return null; return null;
} }
//public String getVarChar(int parameterIndex) throws SQLException { //public String getVarChar(int parameterIndex) throws SQLException {
@@ -135,7 +136,8 @@ public class CallableStatement extends org.postgresql.jdbc2.PreparedStatement im
* @return the parameter value; if the value is SQL NULL, the result is false * @return the parameter value; if the value is SQL NULL, the result is false
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public boolean getBoolean(int parameterIndex) throws SQLException { public boolean getBoolean(int parameterIndex) throws SQLException
{
return false; return false;
} }
@@ -146,7 +148,8 @@ public class CallableStatement extends org.postgresql.jdbc2.PreparedStatement im
* @return the parameter value; if the value is SQL NULL, the result is 0 * @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public byte getByte(int parameterIndex) throws SQLException { public byte getByte(int parameterIndex) throws SQLException
{
return 0; return 0;
} }
@@ -157,7 +160,8 @@ public class CallableStatement extends org.postgresql.jdbc2.PreparedStatement im
* @return the parameter value; if the value is SQL NULL, the result is 0 * @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public short getShort(int parameterIndex) throws SQLException { public short getShort(int parameterIndex) throws SQLException
{
return 0; return 0;
} }
@@ -168,7 +172,8 @@ public class CallableStatement extends org.postgresql.jdbc2.PreparedStatement im
* @return the parameter value; if the value is SQL NULL, the result is 0 * @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public int getInt(int parameterIndex) throws SQLException { public int getInt(int parameterIndex) throws SQLException
{
return 0; return 0;
} }
@@ -179,7 +184,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @return the parameter value; if the value is SQL NULL, the result is 0 * @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public long getLong(int parameterIndex) throws SQLException { public long getLong(int parameterIndex) throws SQLException
{
return 0; return 0;
} }
@@ -190,7 +196,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @return the parameter value; if the value is SQL NULL, the result is 0 * @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public float getFloat(int parameterIndex) throws SQLException { public float getFloat(int parameterIndex) throws SQLException
{
return (float) 0.0; return (float) 0.0;
} }
@@ -201,7 +208,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @return the parameter value; if the value is SQL NULL, the result is 0 * @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public double getDouble(int parameterIndex) throws SQLException { public double getDouble(int parameterIndex) throws SQLException
{
return 0.0; return 0.0;
} }
@@ -217,7 +225,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @deprecated in Java2.0 * @deprecated in Java2.0
*/ */
public BigDecimal getBigDecimal(int parameterIndex, int scale) public BigDecimal getBigDecimal(int parameterIndex, int scale)
throws SQLException { throws SQLException
{
return null; return null;
} }
@@ -229,7 +238,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @return the parameter value; if the value is SQL NULL, the result is null * @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public byte[] getBytes(int parameterIndex) throws SQLException { public byte[] getBytes(int parameterIndex) throws SQLException
{
return null; return null;
} }
@@ -245,7 +255,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @return the parameter value; if the value is SQL NULL, the result is null * @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public java.sql.Date getDate(int parameterIndex) throws SQLException { public java.sql.Date getDate(int parameterIndex) throws SQLException
{
return null; return null;
} }
@@ -256,7 +267,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @return the parameter value; if the value is SQL NULL, the result is null * @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public java.sql.Time getTime(int parameterIndex) throws SQLException { public java.sql.Time getTime(int parameterIndex) throws SQLException
{
return null; return null;
} }
@@ -268,7 +280,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public java.sql.Timestamp getTimestamp(int parameterIndex) public java.sql.Timestamp getTimestamp(int parameterIndex)
throws SQLException { throws SQLException
{
return null; return null;
} }
@@ -302,7 +315,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public Object getObject(int parameterIndex) public Object getObject(int parameterIndex)
throws SQLException { throws SQLException
{
return null; return null;
} }

View File

@@ -17,7 +17,7 @@ import org.postgresql.largeobject.*;
import org.postgresql.util.*; import org.postgresql.util.*;
/** /**
* $Id: Connection.java,v 1.13 2001/10/09 20:47:35 barry Exp $ * $Id: Connection.java,v 1.14 2001/10/25 05:59:59 momjian Exp $
* *
* A Connection represents a session with a specific database. Within the * A Connection represents a session with a specific database. Within the
* context of a Connection, SQL statements are executed and results are * context of a Connection, SQL statements are executed and results are
@@ -166,7 +166,8 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
return true; return true;
// ok, test the connection // ok, test the connection
try { try
{
// by sending an empty query. If we are dead, then an SQLException should // by sending an empty query. If we are dead, then an SQLException should
// be thrown // be thrown
java.sql.ResultSet rs = ExecSQL(" "); java.sql.ResultSet rs = ExecSQL(" ");
@@ -175,7 +176,9 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
// By now, we must be alive // By now, we must be alive
return false; return false;
} catch(SQLException se) { }
catch (SQLException se)
{
// Why throw an SQLException as this may fail without throwing one, // Why throw an SQLException as this may fail without throwing one,
// ie isClosed() is called incase the connection has died, and we don't // ie isClosed() is called incase the connection has died, and we don't
// want to find out by an Exception, so instead we return true, as its // want to find out by an Exception, so instead we return true, as its
@@ -208,7 +211,8 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
{ {
// In 7.1 we now test concurrency to see which class to return. If we are not working with a // In 7.1 we now test concurrency to see which class to return. If we are not working with a
// Statement then default to a normal ResultSet object. // Statement then default to a normal ResultSet object.
if(stat!=null) { if (stat != null)
{
if (stat.getResultSetConcurrency() == java.sql.ResultSet.CONCUR_UPDATABLE) if (stat.getResultSetConcurrency() == java.sql.ResultSet.CONCUR_UPDATABLE)
return new org.postgresql.jdbc2.UpdateableResultSet((org.postgresql.jdbc2.Connection)conn, fields, tuples, status, updateCount, insertOID, binaryCursor); return new org.postgresql.jdbc2.UpdateableResultSet((org.postgresql.jdbc2.Connection)conn, fields, tuples, status, updateCount, insertOID, binaryCursor);
} }
@@ -243,9 +247,11 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
*/ */
public Object getObject(String type, String value) throws SQLException public Object getObject(String type, String value) throws SQLException
{ {
if(typemap!=null) { if (typemap != null)
{
SQLData d = (SQLData) typemap.get(type); SQLData d = (SQLData) typemap.get(type);
if(d!=null) { if (d != null)
{
// Handle the type (requires SQLInput & SQLOutput classes to be implemented) // Handle the type (requires SQLInput & SQLOutput classes to be implemented)
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
@@ -263,8 +269,10 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
public int getSQLType(String pgTypeName) public int getSQLType(String pgTypeName)
{ {
int sqlType = Types.OTHER; // default value int sqlType = Types.OTHER; // default value
for(int i=0;i<jdbc2Types.length;i++) { for (int i = 0;i < jdbc2Types.length;i++)
if(pgTypeName.equals(jdbc2Types[i])) { {
if (pgTypeName.equals(jdbc2Types[i]))
{
sqlType = jdbc2Typei[i]; sqlType = jdbc2Typei[i];
break; break;
} }

View File

@@ -13,7 +13,7 @@ import org.postgresql.util.PSQLException;
/** /**
* This class provides information about the database as a whole. * This class provides information about the database as a whole.
* *
* $Id: DatabaseMetaData.java,v 1.39 2001/10/24 17:44:28 momjian Exp $ * $Id: DatabaseMetaData.java,v 1.40 2001/10/25 05:59:59 momjian Exp $
* *
* <p>Many of the methods here return lists of information in ResultSets. You * <p>Many of the methods here return lists of information in ResultSets. You
* can use the normal ResultSet methods such as getString and getInt to * can use the normal ResultSet methods such as getString and getInt to
@@ -1686,9 +1686,11 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
StringBuffer sql = new StringBuffer("select relname,oid,relkind from pg_class where ("); StringBuffer sql = new StringBuffer("select relname,oid,relkind from pg_class where (");
boolean notFirst = false; boolean notFirst = false;
for(int i=0;i<types.length;i++) { for (int i = 0;i < types.length;i++)
{
for (int j = 0;j < getTableTypes.length;j++) for (int j = 0;j < getTableTypes.length;j++)
if(getTableTypes[j][0].equals(types[i])) { if (getTableTypes[j][0].equals(types[i]))
{
if (notFirst) if (notFirst)
sql.append(" or "); sql.append(" or ");
sql.append(getTableTypes[j][1]); sql.append(getTableTypes[j][1]);
@@ -1719,14 +1721,16 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
byte remarks[] = null; byte remarks[] = null;
if(((org.postgresql.ResultSet)dr).getTupleCount()==1) { if (((org.postgresql.ResultSet)dr).getTupleCount() == 1)
{
dr.next(); dr.next();
remarks = dr.getBytes(1); remarks = dr.getBytes(1);
} }
dr.close(); dr.close();
String relKind; String relKind;
switch (r.getBytes(3)[0]) { switch (r.getBytes(3)[0])
{
case (byte) 'r': case (byte) 'r':
relKind = "TABLE"; relKind = "TABLE";
break; break;
@@ -1837,7 +1841,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
Field f[] = new Field[1]; Field f[] = new Field[1];
Vector v = new Vector(); Vector v = new Vector();
f[0] = new Field(connection, new String("TABLE_TYPE"), iVarcharOid, 32); f[0] = new Field(connection, new String("TABLE_TYPE"), iVarcharOid, 32);
for(int i=0;i<getTableTypes.length;i++) { for (int i = 0;i < getTableTypes.length;i++)
{
byte[][] tuple = new byte[2][0]; byte[][] tuple = new byte[2][0];
tuple[0] = getTableTypes[i][0].getBytes(); tuple[0] = getTableTypes[i][0].getBytes();
v.addElement(tuple); v.addElement(tuple);
@@ -1939,11 +1944,13 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" (" + " (" +
" a.attrelid=c.oid"); " a.attrelid=c.oid");
if ((tableNamePattern != null) && ! tableNamePattern.equals("%")) { if ((tableNamePattern != null) && ! tableNamePattern.equals("%"))
{
sql.append(" and c.relname like \'" + tableNamePattern + "\'"); sql.append(" and c.relname like \'" + tableNamePattern + "\'");
} }
if ((columnNamePattern != null) && ! columnNamePattern.equals("%")) { if ((columnNamePattern != null) && ! columnNamePattern.equals("%"))
{
sql.append(" and a.attname like \'" + columnNamePattern + "\'"); sql.append(" and a.attname like \'" + columnNamePattern + "\'");
} }
@@ -1961,7 +1968,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" and a.attnum = d.adnum" + " and a.attnum = d.adnum" +
" ) "); " ) ");
if (!connection.haveMinimumServerVersion("7.2")) { if (!connection.haveMinimumServerVersion("7.2"))
{
/* Only for 7.1 */ /* Only for 7.1 */
sql.append( sql.append(
" left outer join pg_description e on" + " left outer join pg_description e on" +
@@ -1974,7 +1982,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" c.relname, a.attnum"); " c.relname, a.attnum");
java.sql.ResultSet r = connection.ExecSQL(sql.toString()); java.sql.ResultSet r = connection.ExecSQL(sql.toString());
while (r.next()) { while (r.next())
{
byte[][] tuple = new byte[18][0]; byte[][] tuple = new byte[18][0];
String nullFlag = r.getString(6); String nullFlag = r.getString(6);
@@ -1991,10 +2000,13 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// Looking at the psql source, // Looking at the psql source,
// I think the length of a varchar as specified when the table was created // I think the length of a varchar as specified when the table was created
// should be extracted from atttypmod which contains this length + sizeof(int32) // should be extracted from atttypmod which contains this length + sizeof(int32)
if (typname.equals("bpchar") || typname.equals("varchar")) { if (typname.equals("bpchar") || typname.equals("varchar"))
{
int atttypmod = r.getInt(8); int atttypmod = r.getInt(8);
tuple[6] = Integer.toString(atttypmod != -1 ? atttypmod - VARHDRSZ : 0).getBytes(); tuple[6] = Integer.toString(atttypmod != -1 ? atttypmod - VARHDRSZ : 0).getBytes();
} else { }
else
{
tuple[6] = r.getBytes(7); tuple[6] = r.getBytes(7);
} }
@@ -2081,7 +2093,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// This is taken direct from the psql source // This is taken direct from the psql source
java.sql.ResultSet r = connection.ExecSQL("SELECT relname, relacl FROM pg_class, pg_user WHERE ( relkind = 'r' OR relkind = 'i') and relname !~ '^pg_' and relname !~ '^xin[vx][0-9]+' and usesysid = relowner and relname like '" + table.toLowerCase() + "' ORDER BY relname"); java.sql.ResultSet r = connection.ExecSQL("SELECT relname, relacl FROM pg_class, pg_user WHERE ( relkind = 'r' OR relkind = 'i') and relname !~ '^pg_' and relname !~ '^xin[vx][0-9]+' and usesysid = relowner and relname like '" + table.toLowerCase() + "' ORDER BY relname");
while(r.next()) { while (r.next())
{
byte[][] tuple = new byte[8][0]; byte[][] tuple = new byte[8][0];
tuple[0] = tuple[1] = "".getBytes(); tuple[0] = tuple[1] = "".getBytes();
DriverManager.println("relname=\"" + r.getString(1) + "\" relacl=\"" + r.getString(2) + "\""); DriverManager.println("relname=\"" + r.getString(1) + "\" relacl=\"" + r.getString(2) + "\"");
@@ -2260,7 +2273,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
); );
} }
private Vector importLoop(java.sql.ResultSet keyRelation) throws SQLException { private Vector importLoop(java.sql.ResultSet keyRelation) throws SQLException
{
String s, s2; String s, s2;
String origTable = null, primTable = new String(""), schema; String origTable = null, primTable = new String(""), schema;
int i; int i;
@@ -2270,14 +2284,17 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
s2 = s; s2 = s;
// System.out.println(s); // System.out.println(s);
v = new Vector(); v = new Vector();
for (i=0;;i++) { for (i = 0;;i++)
{
s = s.substring(s.indexOf("\\000") + 4); s = s.substring(s.indexOf("\\000") + 4);
if (s.compareTo("")==0) { if (s.compareTo("") == 0)
{
//System.out.println(); //System.out.println();
break; break;
} }
s2 = s.substring(0, s.indexOf("\\000")); s2 = s.substring(0, s.indexOf("\\000"));
switch (i) { switch (i)
{
case 0: case 0:
origTable = s2; origTable = s2;
break; break;
@@ -2300,11 +2317,14 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
byte tuple[][]; byte tuple[][];
// the foreign keys are only on even positions in the Vector. // the foreign keys are only on even positions in the Vector.
for (i=0;i<v.size();i+=2) { for (i = 0;i < v.size();i += 2)
{
stmp = (String)v.elementAt(i); stmp = (String)v.elementAt(i);
for (int j=1;j<=origCols.getColumnCount();j++) { for (int j = 1;j <= origCols.getColumnCount();j++)
if (stmp.compareTo(origCols.getColumnName(j))==0) { {
if (stmp.compareTo(origCols.getColumnName(j)) == 0)
{
tuple = new byte[14][0]; tuple = new byte[14][0];
for (int k = 0;k < 14;k++) for (int k = 0;k < 14;k++)
@@ -2415,7 +2435,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
"where c.relname like '" + table + "' and c.relfilenode=t.tgrelid"); "where c.relname like '" + table + "' and c.relfilenode=t.tgrelid");
Vector tuples = new Vector(); Vector tuples = new Vector();
while (rs.next()) { while (rs.next())
{
tuples.addAll(importLoop(rs)); tuples.addAll(importLoop(rs));
} }
@@ -2591,7 +2612,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
public java.sql.ResultSet getTypeInfo() throws SQLException public java.sql.ResultSet getTypeInfo() throws SQLException
{ {
java.sql.ResultSet rs = connection.ExecSQL("select typname from pg_type"); java.sql.ResultSet rs = connection.ExecSQL("select typname from pg_type");
if(rs!=null) { if (rs != null)
{
Field f[] = new Field[18]; Field f[] = new Field[18];
ResultSet r; // ResultSet for the SQL query that we need to do ResultSet r; // ResultSet for the SQL query that we need to do
Vector v = new Vector(); // The new ResultSet tuple stuff Vector v = new Vector(); // The new ResultSet tuple stuff
@@ -2623,7 +2645,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
byte bnn[] = Integer.toString(typeNoNulls).getBytes(); byte bnn[] = Integer.toString(typeNoNulls).getBytes();
byte bts[] = Integer.toString(typeSearchable).getBytes(); byte bts[] = Integer.toString(typeSearchable).getBytes();
while(rs.next()) { while (rs.next())
{
byte[][] tuple = new byte[18][]; byte[][] tuple = new byte[18][];
String typname = rs.getString(1); String typname = rs.getString(1);
tuple[0] = typname.getBytes(); tuple[0] = typname.getBytes();
@@ -2736,7 +2759,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" AND (i.relam = a.oid)) " + " AND (i.relam = a.oid)) " +
"ORDER BY x.indisunique DESC, " + "ORDER BY x.indisunique DESC, " +
" x.indisclustered, a.amname, i.relname"); " x.indisclustered, a.amname, i.relname");
while (r.next()) { while (r.next())
{
// indkey is an array of column ordinals (integers). In the JDBC // indkey is an array of column ordinals (integers). In the JDBC
// interface, this has to be separated out into a separate // interface, this has to be separated out into a separate
// tuple for each indexed column. Also, getArray() is not yet // tuple for each indexed column. Also, getArray() is not yet
@@ -2745,10 +2769,12 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
StringTokenizer stok = new StringTokenizer(columnOrdinalString); StringTokenizer stok = new StringTokenizer(columnOrdinalString);
int [] columnOrdinals = new int[stok.countTokens()]; int [] columnOrdinals = new int[stok.countTokens()];
int o = 0; int o = 0;
while (stok.hasMoreTokens()) { while (stok.hasMoreTokens())
{
columnOrdinals[o++] = Integer.parseInt(stok.nextToken()); columnOrdinals[o++] = Integer.parseInt(stok.nextToken());
} }
for (int i = 0; i < columnOrdinals.length; i++) { for (int i = 0; i < columnOrdinals.length; i++)
{
byte [] [] tuple = new byte [13] []; byte [] [] tuple = new byte [13] [];
tuple[0] = "".getBytes(); tuple[0] = "".getBytes();
tuple[1] = "".getBytes(); tuple[1] = "".getBytes();

View File

@@ -7,12 +7,14 @@ import java.sql.*;
* This class extends java.sql.BatchUpdateException, and provides our * This class extends java.sql.BatchUpdateException, and provides our
* internationalisation handling. * internationalisation handling.
*/ */
class PBatchUpdateException extends java.sql.BatchUpdateException { class PBatchUpdateException extends java.sql.BatchUpdateException
{
private String message; private String message;
public PBatchUpdateException( public PBatchUpdateException(
String error, Object arg1, Object arg2, int[] updateCounts ) { String error, Object arg1, Object arg2, int[] updateCounts )
{
super(updateCounts); super(updateCounts);
@@ -22,7 +24,8 @@ class PBatchUpdateException extends java.sql.BatchUpdateException {
translate(error, argv); translate(error, argv);
} }
private void translate(String error, Object[] args) { private void translate(String error, Object[] args)
{
message = MessageTranslator.translate(error, args); message = MessageTranslator.translate(error, args);
} }

View File

@@ -118,7 +118,8 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
* This is identical to toString() except it throws an exception if a * This is identical to toString() except it throws an exception if a
* parameter is unused. * parameter is unused.
*/ */
private synchronized String compileQuery() throws SQLException private synchronized String compileQuery()
throws SQLException
{ {
sbuf.setLength(0); sbuf.setLength(0);
int i; int i;
@@ -268,10 +269,12 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
// if the passed string is null, then set this column to null // if the passed string is null, then set this column to null
if (x == null) if (x == null)
setNull(parameterIndex, Types.OTHER); setNull(parameterIndex, Types.OTHER);
else { else
{
// use the shared buffer object. Should never clash but this makes // use the shared buffer object. Should never clash but this makes
// us thread safe! // us thread safe!
synchronized(sbuf) { synchronized (sbuf)
{
sbuf.setLength(0); sbuf.setLength(0);
int i; int i;
@@ -305,14 +308,20 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setBytes(int parameterIndex, byte x[]) throws SQLException public void setBytes(int parameterIndex, byte x[]) throws SQLException
{ {
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports the bytea datatype for byte arrays //Version 7.2 supports the bytea datatype for byte arrays
if(null == x){ if (null == x)
{
setNull(parameterIndex, Types.OTHER); setNull(parameterIndex, Types.OTHER);
} else { }
else
{
setString(parameterIndex, PGbytea.toPGString(x)); setString(parameterIndex, PGbytea.toPGString(x));
} }
} else { }
else
{
//Version 7.1 and earlier support done as LargeObjects //Version 7.1 and earlier support done as LargeObjects
LargeObjectManager lom = connection.getLargeObjectAPI(); LargeObjectManager lom = connection.getLargeObjectAPI();
int oid = lom.create(); int oid = lom.create();
@@ -333,11 +342,15 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setDate(int parameterIndex, java.sql.Date x) throws SQLException public void setDate(int parameterIndex, java.sql.Date x) throws SQLException
{ {
if(null == x){ if (null == x)
{
setNull(parameterIndex, Types.OTHER); setNull(parameterIndex, Types.OTHER);
} else { }
else
{
SimpleDateFormat df = (SimpleDateFormat) tl_df.get(); SimpleDateFormat df = (SimpleDateFormat) tl_df.get();
if(df==null) { if (df == null)
{
df = new SimpleDateFormat("''yyyy-MM-dd''"); df = new SimpleDateFormat("''yyyy-MM-dd''");
tl_df.set(df); tl_df.set(df);
} }
@@ -365,9 +378,12 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setTime(int parameterIndex, Time x) throws SQLException public void setTime(int parameterIndex, Time x) throws SQLException
{ {
if (null == x){ if (null == x)
{
setNull(parameterIndex, Types.OTHER); setNull(parameterIndex, Types.OTHER);
} else { }
else
{
set(parameterIndex, "'" + x.toString() + "'"); set(parameterIndex, "'" + x.toString() + "'");
} }
} }
@@ -382,18 +398,23 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException
{ {
if (null == x){ if (null == x)
{
setNull(parameterIndex, Types.OTHER); setNull(parameterIndex, Types.OTHER);
} else { }
else
{
SimpleDateFormat df = (SimpleDateFormat) tl_tsdf.get(); SimpleDateFormat df = (SimpleDateFormat) tl_tsdf.get();
if(df==null) { if (df == null)
{
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("GMT")); df.setTimeZone(TimeZone.getTimeZone("GMT"));
tl_tsdf.set(df); tl_tsdf.set(df);
} }
// Use the shared StringBuffer // Use the shared StringBuffer
synchronized(sbuf) { synchronized (sbuf)
{
sbuf.setLength(0); sbuf.setLength(0);
sbuf.append("'").append(df.format(x)).append('.').append(x.getNanos() / 10000000).append("+00'"); sbuf.append("'").append(df.format(x)).append('.').append(x.getNanos() / 10000000).append("+00'");
set(parameterIndex, sbuf.toString()); set(parameterIndex, sbuf.toString());
@@ -423,24 +444,32 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException
{ {
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports AsciiStream for all PG text types (char, varchar, text) //Version 7.2 supports AsciiStream for all PG text types (char, varchar, text)
//As the spec/javadoc for this method indicate this is to be used for //As the spec/javadoc for this method indicate this is to be used for
//large String values (i.e. LONGVARCHAR) PG doesn't have a separate //large String values (i.e. LONGVARCHAR) PG doesn't have a separate
//long varchar datatype, but with toast all text datatypes are capable of //long varchar datatype, but with toast all text datatypes are capable of
//handling very large values. Thus the implementation ends up calling //handling very large values. Thus the implementation ends up calling
//setString() since there is no current way to stream the value to the server //setString() since there is no current way to stream the value to the server
try { try
{
InputStreamReader l_inStream = new InputStreamReader(x, "ASCII"); InputStreamReader l_inStream = new InputStreamReader(x, "ASCII");
char[] l_chars = new char[length]; char[] l_chars = new char[length];
int l_charsRead = l_inStream.read(l_chars, 0, length); int l_charsRead = l_inStream.read(l_chars, 0, length);
setString(parameterIndex, new String(l_chars, 0, l_charsRead)); setString(parameterIndex, new String(l_chars, 0, l_charsRead));
} catch (UnsupportedEncodingException l_uee) { }
catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException("postgresql.unusual", l_uee); throw new PSQLException("postgresql.unusual", l_uee);
} catch (IOException l_ioe) { }
catch (IOException l_ioe)
{
throw new PSQLException("postgresql.unusual", l_ioe); throw new PSQLException("postgresql.unusual", l_ioe);
} }
} else { }
else
{
//Version 7.1 supported only LargeObjects by treating everything //Version 7.1 supported only LargeObjects by treating everything
//as binary data //as binary data
setBinaryStream(parameterIndex, x, length); setBinaryStream(parameterIndex, x, length);
@@ -467,24 +496,32 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException
{ {
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports AsciiStream for all PG text types (char, varchar, text) //Version 7.2 supports AsciiStream for all PG text types (char, varchar, text)
//As the spec/javadoc for this method indicate this is to be used for //As the spec/javadoc for this method indicate this is to be used for
//large String values (i.e. LONGVARCHAR) PG doesn't have a separate //large String values (i.e. LONGVARCHAR) PG doesn't have a separate
//long varchar datatype, but with toast all text datatypes are capable of //long varchar datatype, but with toast all text datatypes are capable of
//handling very large values. Thus the implementation ends up calling //handling very large values. Thus the implementation ends up calling
//setString() since there is no current way to stream the value to the server //setString() since there is no current way to stream the value to the server
try { try
{
InputStreamReader l_inStream = new InputStreamReader(x, "UTF-8"); InputStreamReader l_inStream = new InputStreamReader(x, "UTF-8");
char[] l_chars = new char[length]; char[] l_chars = new char[length];
int l_charsRead = l_inStream.read(l_chars, 0, length); int l_charsRead = l_inStream.read(l_chars, 0, length);
setString(parameterIndex, new String(l_chars, 0, l_charsRead)); setString(parameterIndex, new String(l_chars, 0, l_charsRead));
} catch (UnsupportedEncodingException l_uee) { }
catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException("postgresql.unusual", l_uee); throw new PSQLException("postgresql.unusual", l_uee);
} catch (IOException l_ioe) { }
catch (IOException l_ioe)
{
throw new PSQLException("postgresql.unusual", l_ioe); throw new PSQLException("postgresql.unusual", l_ioe);
} }
} else { }
else
{
//Version 7.1 supported only LargeObjects by treating everything //Version 7.1 supported only LargeObjects by treating everything
//as binary data //as binary data
setBinaryStream(parameterIndex, x, length); setBinaryStream(parameterIndex, x, length);
@@ -507,7 +544,8 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException
{ {
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports BinaryStream for for the PG bytea type //Version 7.2 supports BinaryStream for for the PG bytea type
//As the spec/javadoc for this method indicate this is to be used for //As the spec/javadoc for this method indicate this is to be used for
//large binary values (i.e. LONGVARBINARY) PG doesn't have a separate //large binary values (i.e. LONGVARBINARY) PG doesn't have a separate
@@ -516,20 +554,28 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
//setBytes() since there is no current way to stream the value to the server //setBytes() since there is no current way to stream the value to the server
byte[] l_bytes = new byte[length]; byte[] l_bytes = new byte[length];
int l_bytesRead; int l_bytesRead;
try { try
{
l_bytesRead = x.read(l_bytes, 0, length); l_bytesRead = x.read(l_bytes, 0, length);
} catch (IOException l_ioe) { }
catch (IOException l_ioe)
{
throw new PSQLException("postgresql.unusual", l_ioe); throw new PSQLException("postgresql.unusual", l_ioe);
} }
if (l_bytesRead == length) { if (l_bytesRead == length)
{
setBytes(parameterIndex, l_bytes); setBytes(parameterIndex, l_bytes);
} else { }
else
{
//the stream contained less data than they said //the stream contained less data than they said
byte[] l_bytes2 = new byte[l_bytesRead]; byte[] l_bytes2 = new byte[l_bytesRead];
System.arraycopy(l_bytes, 0, l_bytes2, 0, l_bytesRead); System.arraycopy(l_bytes, 0, l_bytes2, 0, l_bytesRead);
setBytes(parameterIndex, l_bytes2); setBytes(parameterIndex, l_bytes2);
} }
} else { }
else
{
//Version 7.1 only supported streams for LargeObjects //Version 7.1 only supported streams for LargeObjects
//but the jdbc spec indicates that streams should be //but the jdbc spec indicates that streams should be
//available for LONGVARBINARY instead //available for LONGVARBINARY instead
@@ -537,19 +583,23 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
int oid = lom.create(); int oid = lom.create();
LargeObject lob = lom.open(oid); LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream(); OutputStream los = lob.getOutputStream();
try { try
{
// could be buffered, but then the OutputStream returned by LargeObject // could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance // is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse! // boost gained, if anything it would be worse!
int c = x.read(); int c = x.read();
int p = 0; int p = 0;
while(c>-1 && p<length) { while (c > -1 && p < length)
{
los.write(c); los.write(c);
c = x.read(); c = x.read();
p++; p++;
} }
los.close(); los.close();
} catch(IOException se) { }
catch (IOException se)
{
throw new PSQLException("postgresql.unusual", se); throw new PSQLException("postgresql.unusual", se);
} }
// lob is closed by the stream so don't call lob.close() // lob is closed by the stream so don't call lob.close()
@@ -595,7 +645,8 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException
{ {
if (x == null){ if (x == null)
{
setNull(parameterIndex, Types.OTHER); setNull(parameterIndex, Types.OTHER);
return ; return ;
} }
@@ -630,9 +681,12 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
setTimestamp(parameterIndex, (Timestamp)x); setTimestamp(parameterIndex, (Timestamp)x);
break; break;
case Types.BIT: case Types.BIT:
if (x instanceof Boolean) { if (x instanceof Boolean)
{
set(parameterIndex, ((Boolean)x).booleanValue() ? "TRUE" : "FALSE"); set(parameterIndex, ((Boolean)x).booleanValue() ? "TRUE" : "FALSE");
} else { }
else
{
throw new PSQLException("postgresql.prep.type"); throw new PSQLException("postgresql.prep.type");
} }
break; break;
@@ -661,7 +715,8 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setObject(int parameterIndex, Object x) throws SQLException public void setObject(int parameterIndex, Object x) throws SQLException
{ {
if (x == null){ if (x == null)
{
setNull(parameterIndex, Types.OTHER); setNull(parameterIndex, Types.OTHER);
return ; return ;
} }
@@ -716,8 +771,10 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
* NB: This is identical to compileQuery() except instead of throwing * NB: This is identical to compileQuery() except instead of throwing
* SQLException if a parameter is null, it places ? instead. * SQLException if a parameter is null, it places ? instead.
*/ */
public String toString() { public String toString()
synchronized(sbuf) { {
synchronized (sbuf)
{
sbuf.setLength(0); sbuf.setLength(0);
int i; int i;
@@ -817,19 +874,23 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
int oid = lom.create(); int oid = lom.create();
LargeObject lob = lom.open(oid); LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream(); OutputStream los = lob.getOutputStream();
try { try
{
// could be buffered, but then the OutputStream returned by LargeObject // could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance // is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse! // boost gained, if anything it would be worse!
int c = l_inStream.read(); int c = l_inStream.read();
int p = 0; int p = 0;
while(c>-1 && p<l_length) { while (c > -1 && p < l_length)
{
los.write(c); los.write(c);
c = l_inStream.read(); c = l_inStream.read();
p++; p++;
} }
los.close(); los.close();
} catch(IOException se) { }
catch (IOException se)
{
throw new PSQLException("postgresql.unusual", se); throw new PSQLException("postgresql.unusual", se);
} }
// lob is closed by the stream so don't call lob.close() // lob is closed by the stream so don't call lob.close()
@@ -842,7 +903,8 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
*/ */
public void setCharacterStream(int i, java.io.Reader x, int length) throws SQLException public void setCharacterStream(int i, java.io.Reader x, int length) throws SQLException
{ {
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports CharacterStream for for the PG text types //Version 7.2 supports CharacterStream for for the PG text types
//As the spec/javadoc for this method indicate this is to be used for //As the spec/javadoc for this method indicate this is to be used for
//large text values (i.e. LONGVARCHAR) PG doesn't have a separate //large text values (i.e. LONGVARCHAR) PG doesn't have a separate
@@ -851,13 +913,18 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
//setString() since there is no current way to stream the value to the server //setString() since there is no current way to stream the value to the server
char[] l_chars = new char[length]; char[] l_chars = new char[length];
int l_charsRead; int l_charsRead;
try { try
{
l_charsRead = x.read(l_chars, 0, length); l_charsRead = x.read(l_chars, 0, length);
} catch (IOException l_ioe) { }
catch (IOException l_ioe)
{
throw new PSQLException("postgresql.unusual", l_ioe); throw new PSQLException("postgresql.unusual", l_ioe);
} }
setString(i, new String(l_chars, 0, l_charsRead)); setString(i, new String(l_chars, 0, l_charsRead));
} else { }
else
{
//Version 7.1 only supported streams for LargeObjects //Version 7.1 only supported streams for LargeObjects
//but the jdbc spec indicates that streams should be //but the jdbc spec indicates that streams should be
//available for LONGVARCHAR instead //available for LONGVARCHAR instead
@@ -865,19 +932,23 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
int oid = lom.create(); int oid = lom.create();
LargeObject lob = lom.open(oid); LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream(); OutputStream los = lob.getOutputStream();
try { try
{
// could be buffered, but then the OutputStream returned by LargeObject // could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance // is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse! // boost gained, if anything it would be worse!
int c = x.read(); int c = x.read();
int p = 0; int p = 0;
while(c>-1 && p<length) { while (c > -1 && p < length)
{
los.write(c); los.write(c);
c = x.read(); c = x.read();
p++; p++;
} }
los.close(); los.close();
} catch(IOException se) { }
catch (IOException se)
{
throw new PSQLException("postgresql.unusual", se); throw new PSQLException("postgresql.unusual", se);
} }
// lob is closed by the stream so don't call lob.close() // lob is closed by the stream so don't call lob.close()
@@ -896,19 +967,23 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
int oid = lom.create(); int oid = lom.create();
LargeObject lob = lom.open(oid); LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream(); OutputStream los = lob.getOutputStream();
try { try
{
// could be buffered, but then the OutputStream returned by LargeObject // could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance // is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse! // boost gained, if anything it would be worse!
int c = l_inStream.read(); int c = l_inStream.read();
int p = 0; int p = 0;
while(c>-1 && p<l_length) { while (c > -1 && p < l_length)
{
los.write(c); los.write(c);
c = l_inStream.read(); c = l_inStream.read();
p++; p++;
} }
los.close(); los.close();
} catch(IOException se) { }
catch (IOException se)
{
throw new PSQLException("postgresql.unusual", se); throw new PSQLException("postgresql.unusual", se);
} }
// lob is closed by the stream so don't call lob.close() // lob is closed by the stream so don't call lob.close()
@@ -937,7 +1012,8 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
{ {
if (cal == null) if (cal == null)
setDate(i, d); setDate(i, d);
else { else
{
cal.setTime(d); cal.setTime(d);
setDate(i, new java.sql.Date(cal.getTime().getTime())); setDate(i, new java.sql.Date(cal.getTime().getTime()));
} }
@@ -950,7 +1026,8 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
{ {
if (cal == null) if (cal == null)
setTime(i, t); setTime(i, t);
else { else
{
cal.setTime(t); cal.setTime(t);
setTime(i, new java.sql.Time(cal.getTime().getTime())); setTime(i, new java.sql.Time(cal.getTime().getTime()));
} }
@@ -963,7 +1040,8 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
{ {
if (cal == null) if (cal == null)
setTimestamp(i, t); setTimestamp(i, t);
else { else
{
cal.setTime(t); cal.setTime(t);
setTimestamp(i, new java.sql.Timestamp(cal.getTime().getTime())); setTimestamp(i, new java.sql.Timestamp(cal.getTime().getTime()));
} }

View File

@@ -133,7 +133,8 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
public void close() throws SQLException public void close() throws SQLException
{ {
//release resources held (memory for tuples) //release resources held (memory for tuples)
if(rows!=null) { if (rows != null)
{
rows = null; rows = null;
} }
} }
@@ -200,7 +201,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Byte.parseByte(s); return Byte.parseByte(s);
} catch (NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException("postgresql.res.badbyte", s); throw new PSQLException("postgresql.res.badbyte", s);
} }
} }
@@ -223,7 +226,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Short.parseShort(s); return Short.parseShort(s);
} catch (NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException("postgresql.res.badshort", s); throw new PSQLException("postgresql.res.badshort", s);
} }
} }
@@ -314,17 +319,23 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
throw new PSQLException("postgresql.res.colrange"); throw new PSQLException("postgresql.res.colrange");
//If the data is already binary then just return it //If the data is already binary then just return it
if (binaryCursor) return this_row[columnIndex - 1]; if (binaryCursor)
return this_row[columnIndex - 1];
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports the bytea datatype for byte arrays //Version 7.2 supports the bytea datatype for byte arrays
return PGbytea.toBytes(getString(columnIndex)); return PGbytea.toBytes(getString(columnIndex));
} else { }
else
{
//Version 7.1 and earlier supports LargeObjects for byte arrays //Version 7.1 and earlier supports LargeObjects for byte arrays
wasNullFlag = (this_row[columnIndex - 1] == null); wasNullFlag = (this_row[columnIndex - 1] == null);
// Handle OID's as BLOBS // Handle OID's as BLOBS
if(!wasNullFlag) { if (!wasNullFlag)
if( fields[columnIndex - 1].getOID() == 26) { {
if ( fields[columnIndex - 1].getOID() == 26)
{
LargeObjectManager lom = connection.getLargeObjectAPI(); LargeObjectManager lom = connection.getLargeObjectAPI();
LargeObject lob = lom.open(getInt(columnIndex)); LargeObject lob = lom.open(getInt(columnIndex));
byte buf[] = lob.read(lob.size()); byte buf[] = lob.read(lob.size());
@@ -405,19 +416,25 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
if (wasNullFlag) if (wasNullFlag)
return null; return null;
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports AsciiStream for all the PG text types //Version 7.2 supports AsciiStream for all the PG text types
//As the spec/javadoc for this method indicate this is to be used for //As the spec/javadoc for this method indicate this is to be used for
//large text values (i.e. LONGVARCHAR) PG doesn't have a separate //large text values (i.e. LONGVARCHAR) PG doesn't have a separate
//long string datatype, but with toast the text datatype is capable of //long string datatype, but with toast the text datatype is capable of
//handling very large values. Thus the implementation ends up calling //handling very large values. Thus the implementation ends up calling
//getString() since there is no current way to stream the value from the server //getString() since there is no current way to stream the value from the server
try { try
{
return new ByteArrayInputStream(getString(columnIndex).getBytes("ASCII")); return new ByteArrayInputStream(getString(columnIndex).getBytes("ASCII"));
} catch (UnsupportedEncodingException l_uee) { }
catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException("postgresql.unusual", l_uee); throw new PSQLException("postgresql.unusual", l_uee);
} }
} else { }
else
{
// In 7.1 Handle as BLOBS so return the LargeObject input stream // In 7.1 Handle as BLOBS so return the LargeObject input stream
return getBinaryStream(columnIndex); return getBinaryStream(columnIndex);
} }
@@ -444,19 +461,25 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
if (wasNullFlag) if (wasNullFlag)
return null; return null;
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports AsciiStream for all the PG text types //Version 7.2 supports AsciiStream for all the PG text types
//As the spec/javadoc for this method indicate this is to be used for //As the spec/javadoc for this method indicate this is to be used for
//large text values (i.e. LONGVARCHAR) PG doesn't have a separate //large text values (i.e. LONGVARCHAR) PG doesn't have a separate
//long string datatype, but with toast the text datatype is capable of //long string datatype, but with toast the text datatype is capable of
//handling very large values. Thus the implementation ends up calling //handling very large values. Thus the implementation ends up calling
//getString() since there is no current way to stream the value from the server //getString() since there is no current way to stream the value from the server
try { try
{
return new ByteArrayInputStream(getString(columnIndex).getBytes("UTF-8")); return new ByteArrayInputStream(getString(columnIndex).getBytes("UTF-8"));
} catch (UnsupportedEncodingException l_uee) { }
catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException("postgresql.unusual", l_uee); throw new PSQLException("postgresql.unusual", l_uee);
} }
} else { }
else
{
// In 7.1 Handle as BLOBS so return the LargeObject input stream // In 7.1 Handle as BLOBS so return the LargeObject input stream
return getBinaryStream(columnIndex); return getBinaryStream(columnIndex);
} }
@@ -480,7 +503,8 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
if (wasNullFlag) if (wasNullFlag)
return null; return null;
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports BinaryStream for all PG bytea type //Version 7.2 supports BinaryStream for all PG bytea type
//As the spec/javadoc for this method indicate this is to be used for //As the spec/javadoc for this method indicate this is to be used for
//large binary values (i.e. LONGVARBINARY) PG doesn't have a separate //large binary values (i.e. LONGVARBINARY) PG doesn't have a separate
@@ -490,9 +514,12 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
byte b[] = getBytes(columnIndex); byte b[] = getBytes(columnIndex);
if (b != null) if (b != null)
return new ByteArrayInputStream(b); return new ByteArrayInputStream(b);
} else { }
else
{
// In 7.1 Handle as BLOBS so return the LargeObject input stream // In 7.1 Handle as BLOBS so return the LargeObject input stream
if( fields[columnIndex - 1].getOID() == 26) { if ( fields[columnIndex - 1].getOID() == 26)
{
LargeObjectManager lom = connection.getLargeObjectAPI(); LargeObjectManager lom = connection.getLargeObjectAPI();
LargeObject lob = lom.open(getInt(columnIndex)); LargeObject lob = lom.open(getInt(columnIndex));
return lob.getInputStream(); return lob.getInputStream();
@@ -695,7 +722,8 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
field = fields[columnIndex - 1]; field = fields[columnIndex - 1];
// some fields can be null, mainly from those returned by MetaData methods // some fields can be null, mainly from those returned by MetaData methods
if(field==null) { if (field == null)
{
wasNullFlag = true; wasNullFlag = true;
return null; return null;
} }
@@ -732,9 +760,12 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
default: default:
String type = field.getPGType(); String type = field.getPGType();
// if the backend doesn't know the type then coerce to String // if the backend doesn't know the type then coerce to String
if (type.equals("unknown")){ if (type.equals("unknown"))
{
return getString(columnIndex); return getString(columnIndex);
}else{ }
else
{
return connection.getObject(field.getPGType(), getString(columnIndex)); return connection.getObject(field.getPGType(), getString(columnIndex));
} }
} }
@@ -795,7 +826,8 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
if (index < 0) if (index < 0)
if (index >= -rows_size) if (index >= -rows_size)
internalIndex = rows_size + index; internalIndex = rows_size + index;
else { else
{
beforeFirst(); beforeFirst();
return false; return false;
} }
@@ -805,7 +837,8 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
//the index is not too large //the index is not too large
if (index <= rows_size) if (index <= rows_size)
internalIndex = index - 1; internalIndex = index - 1;
else { else
{
afterLast(); afterLast();
return false; return false;
} }
@@ -896,7 +929,8 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
if (wasNullFlag) if (wasNullFlag)
return null; return null;
if (connection.haveMinimumCompatibleVersion("7.2")) { if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports AsciiStream for all the PG text types //Version 7.2 supports AsciiStream for all the PG text types
//As the spec/javadoc for this method indicate this is to be used for //As the spec/javadoc for this method indicate this is to be used for
//large text values (i.e. LONGVARCHAR) PG doesn't have a separate //large text values (i.e. LONGVARCHAR) PG doesn't have a separate
@@ -904,7 +938,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
//handling very large values. Thus the implementation ends up calling //handling very large values. Thus the implementation ends up calling
//getString() since there is no current way to stream the value from the server //getString() since there is no current way to stream the value from the server
return new CharArrayReader(getString(i).toCharArray()); return new CharArrayReader(getString(i).toCharArray());
} else { }
else
{
// In 7.1 Handle as BLOBS so return the LargeObject input stream // In 7.1 Handle as BLOBS so return the LargeObject input stream
Encoding encoding = connection.getEncoding(); Encoding encoding = connection.getEncoding();
InputStream input = getBinaryStream(i); InputStream input = getBinaryStream(i);
@@ -1394,7 +1430,8 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
* It's used currently by getStatement() but may also with the new core * It's used currently by getStatement() but may also with the new core
* package. * package.
*/ */
public void setStatement(org.postgresql.jdbc2.Statement statement) { public void setStatement(org.postgresql.jdbc2.Statement statement)
{
this.statement = statement; this.statement = statement;
} }
@@ -1417,7 +1454,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Integer.parseInt(s); return Integer.parseInt(s);
} catch (NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badint", s); throw new PSQLException ("postgresql.res.badint", s);
} }
} }
@@ -1431,7 +1470,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Long.parseLong(s); return Long.parseLong(s);
} catch (NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badlong", s); throw new PSQLException ("postgresql.res.badlong", s);
} }
} }
@@ -1446,14 +1487,19 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
val = new BigDecimal(s); val = new BigDecimal(s);
} catch (NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badbigdec", s); throw new PSQLException ("postgresql.res.badbigdec", s);
} }
if (scale==-1) return val; if (scale == -1)
return val;
try try
{ {
return val.setScale(scale); return val.setScale(scale);
} catch (ArithmeticException e) { }
catch (ArithmeticException e)
{
throw new PSQLException ("postgresql.res.badbigdec", s); throw new PSQLException ("postgresql.res.badbigdec", s);
} }
} }
@@ -1467,7 +1513,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Float.valueOf(s).floatValue(); return Float.valueOf(s).floatValue();
} catch (NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badfloat", s); throw new PSQLException ("postgresql.res.badfloat", s);
} }
} }
@@ -1481,7 +1529,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Double.valueOf(s).doubleValue(); return Double.valueOf(s).doubleValue();
} catch (NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.baddouble", s); throw new PSQLException ("postgresql.res.baddouble", s);
} }
} }
@@ -1509,9 +1559,12 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
boolean subsecond; boolean subsecond;
//if string contains a '.' we have fractional seconds //if string contains a '.' we have fractional seconds
if (s.indexOf('.') == -1) { if (s.indexOf('.') == -1)
{
subsecond = false; subsecond = false;
} else { }
else
{
subsecond = true; subsecond = true;
} }
@@ -1520,7 +1573,8 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
//and java expects three digits if fractional seconds are present instead of two for postgres //and java expects three digits if fractional seconds are present instead of two for postgres
//so this code strips off timezone info and adds on the GMT+/-... //so this code strips off timezone info and adds on the GMT+/-...
//as well as adds a third digit for partial seconds if necessary //as well as adds a third digit for partial seconds if necessary
synchronized(resultSet) { synchronized (resultSet)
{
// We must be synchronized here incase more theads access the ResultSet // We must be synchronized here incase more theads access the ResultSet
// bad practice but possible. Anyhow this is to protect sbuf and // bad practice but possible. Anyhow this is to protect sbuf and
// SimpleDateFormat objects // SimpleDateFormat objects
@@ -1533,35 +1587,53 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
resultSet.sbuf.append(s); resultSet.sbuf.append(s);
char sub = resultSet.sbuf.charAt(resultSet.sbuf.length() - 3); char sub = resultSet.sbuf.charAt(resultSet.sbuf.length() - 3);
if (sub == '+' || sub == '-') { if (sub == '+' || sub == '-')
{
resultSet.sbuf.setLength(resultSet.sbuf.length() - 3); resultSet.sbuf.setLength(resultSet.sbuf.length() - 3);
if (subsecond) { if (subsecond)
{
resultSet.sbuf.append('0').append("GMT").append(s.substring(s.length() - 3)).append(":00"); resultSet.sbuf.append('0').append("GMT").append(s.substring(s.length() - 3)).append(":00");
} else { }
else
{
resultSet.sbuf.append("GMT").append(s.substring(s.length() - 3)).append(":00"); resultSet.sbuf.append("GMT").append(s.substring(s.length() - 3)).append(":00");
} }
} else if (subsecond) { }
else if (subsecond)
{
resultSet.sbuf.append('0'); resultSet.sbuf.append('0');
} }
// could optimize this a tad to remove too many object creations... // could optimize this a tad to remove too many object creations...
SimpleDateFormat df = null; SimpleDateFormat df = null;
if (resultSet.sbuf.length()>23 && subsecond) { if (resultSet.sbuf.length() > 23 && subsecond)
{
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSzzzzzzzzz"); df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSzzzzzzzzz");
} else if (resultSet.sbuf.length()>23 && !subsecond) { }
else if (resultSet.sbuf.length() > 23 && !subsecond)
{
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:sszzzzzzzzz"); df = new SimpleDateFormat("yyyy-MM-dd HH:mm:sszzzzzzzzz");
} else if (resultSet.sbuf.length()>10 && subsecond) { }
else if (resultSet.sbuf.length() > 10 && subsecond)
{
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
} else if (resultSet.sbuf.length()>10 && !subsecond) { }
else if (resultSet.sbuf.length() > 10 && !subsecond)
{
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
} else { }
else
{
df = new SimpleDateFormat("yyyy-MM-dd"); df = new SimpleDateFormat("yyyy-MM-dd");
} }
try { try
{
return new Timestamp(df.parse(resultSet.sbuf.toString()).getTime()); return new Timestamp(df.parse(resultSet.sbuf.toString()).getTime());
} catch(ParseException e) { }
catch (ParseException e)
{
throw new PSQLException("postgresql.res.badtimestamp", new Integer(e.getErrorOffset()), s); throw new PSQLException("postgresql.res.badtimestamp", new Integer(e.getErrorOffset()), s);
} }
} }

View File

@@ -196,24 +196,37 @@ public class ResultSetMetaData implements java.sql.ResultSetMetaData
// FIXME: currently, only types with a SQL92 or SQL3 pendant are implemented - jens@jens.de // FIXME: currently, only types with a SQL92 or SQL3 pendant are implemented - jens@jens.de
// fixed length data types // fixed length data types
if (type_name.equals( "int2" )) return 6; // -32768 to +32768 (5 digits and a sign) if (type_name.equals( "int2" ))
return 6; // -32768 to +32768 (5 digits and a sign)
if (type_name.equals( "int4" ) if (type_name.equals( "int4" )
|| type_name.equals( "oid" )) return 11; // -2147483648 to +2147483647 || type_name.equals( "oid" ))
if (type_name.equals( "int8" )) return 20; // -9223372036854775808 to +9223372036854775807 return 11; // -2147483648 to +2147483647
if (type_name.equals( "money" )) return 12; // MONEY = DECIMAL(9,2) if (type_name.equals( "int8" ))
if (type_name.equals( "float4" )) return 11; // i checked it out ans wasn't able to produce more than 11 digits return 20; // -9223372036854775808 to +9223372036854775807
if (type_name.equals( "float8" )) return 20; // dito, 20 if (type_name.equals( "money" ))
if (type_name.equals( "char" )) return 1; return 12; // MONEY = DECIMAL(9,2)
if (type_name.equals( "bool" )) return 1; if (type_name.equals( "float4" ))
if (type_name.equals( "date" )) return 14; // "01/01/4713 BC" - "31/12/32767 AD" return 11; // i checked it out ans wasn't able to produce more than 11 digits
if (type_name.equals( "time" )) return 8; // 00:00:00-23:59:59 if (type_name.equals( "float8" ))
if (type_name.equals( "timestamp" )) return 22; // hhmmm ... the output looks like this: 1999-08-03 22:22:08+02 return 20; // dito, 20
if (type_name.equals( "char" ))
return 1;
if (type_name.equals( "bool" ))
return 1;
if (type_name.equals( "date" ))
return 14; // "01/01/4713 BC" - "31/12/32767 AD"
if (type_name.equals( "time" ))
return 8; // 00:00:00-23:59:59
if (type_name.equals( "timestamp" ))
return 22; // hhmmm ... the output looks like this: 1999-08-03 22:22:08+02
// variable length fields // variable length fields
typmod -= 4; typmod -= 4;
if (type_name.equals( "bpchar" ) if (type_name.equals( "bpchar" )
|| type_name.equals( "varchar" )) return typmod; // VARHDRSZ=sizeof(int32)=4 || type_name.equals( "varchar" ))
if (type_name.equals( "numeric" )) return ( (typmod >>16) & 0xffff ) return typmod; // VARHDRSZ=sizeof(int32)=4
if (type_name.equals( "numeric" ))
return ( (typmod >> 16) & 0xffff )
+ 1 + ( typmod & 0xffff ); // DECIMAL(p,s) = (p digits).(s digits) + 1 + ( typmod & 0xffff ); // DECIMAL(p,s) = (p digits).(s digits)
// if we don't know better // if we don't know better

View File

@@ -119,7 +119,8 @@ public class Statement extends org.postgresql.Statement implements java.sql.Stat
// New in 7.1, if we have a previous resultset then force it to close // New in 7.1, if we have a previous resultset then force it to close
// This brings us nearer to compliance, and helps memory management. // This brings us nearer to compliance, and helps memory management.
// Internal stuff will call ExecSQL directly, bypassing this. // Internal stuff will call ExecSQL directly, bypassing this.
if(result!=null) { if (result != null)
{
java.sql.ResultSet rs = getResultSet(); java.sql.ResultSet rs = getResultSet();
if (rs != null) if (rs != null)
rs.close(); rs.close();
@@ -144,8 +145,10 @@ public class Statement extends org.postgresql.Statement implements java.sql.Stat
*/ */
public int getUpdateCount() throws SQLException public int getUpdateCount() throws SQLException
{ {
if (result == null) return -1; if (result == null)
if (((org.postgresql.ResultSet)result).reallyResultSet()) return -1; return -1;
if (((org.postgresql.ResultSet)result).reallyResultSet())
return -1;
return ((org.postgresql.ResultSet)result).getResultCount(); return ((org.postgresql.ResultSet)result).getResultCount();
} }
@@ -184,10 +187,13 @@ public class Statement extends org.postgresql.Statement implements java.sql.Stat
int size = batch.size(); int size = batch.size();
int[] result = new int[size]; int[] result = new int[size];
int i = 0; int i = 0;
try { try
{
for (i = 0;i < size;i++) for (i = 0;i < size;i++)
result[i] = this.executeUpdate((String)batch.elementAt(i)); result[i] = this.executeUpdate((String)batch.elementAt(i));
} catch(SQLException e) { }
catch (SQLException e)
{
int[] resultSucceeded = new int[i]; int[] resultSucceeded = new int[i];
System.arraycopy(result, 0, resultSucceeded, 0, i); System.arraycopy(result, 0, resultSucceeded, 0, i);
@@ -197,7 +203,9 @@ public class Statement extends org.postgresql.Statement implements java.sql.Stat
updex.setNextException(e); updex.setNextException(e);
throw updex; throw updex;
} finally { }
finally
{
batch.removeAllElements(); batch.removeAllElements();
} }
return result; return result;

View File

@@ -9,7 +9,8 @@ import java.sql.SQLException;
* For now, the bare minimum is implemented. Later (after 7.1) we will overide * For now, the bare minimum is implemented. Later (after 7.1) we will overide
* the other read methods to optimise them. * the other read methods to optimise them.
*/ */
public class BlobInputStream extends InputStream { public class BlobInputStream extends InputStream
{
/** /**
* The parent LargeObject * The parent LargeObject
*/ */
@@ -38,7 +39,8 @@ public class BlobInputStream extends InputStream {
/** /**
* @param lo LargeObject to read from * @param lo LargeObject to read from
*/ */
public BlobInputStream(LargeObject lo) { public BlobInputStream(LargeObject lo)
{
this(lo, 1024); this(lo, 1024);
} }
@@ -46,7 +48,8 @@ public class BlobInputStream extends InputStream {
* @param lo LargeObject to read from * @param lo LargeObject to read from
* @param bsize buffer size * @param bsize buffer size
*/ */
public BlobInputStream(LargeObject lo,int bsize) { public BlobInputStream(LargeObject lo, int bsize)
{
this.lo = lo; this.lo = lo;
buffer = null; buffer = null;
bpos = 0; bpos = 0;
@@ -56,27 +59,34 @@ public class BlobInputStream extends InputStream {
/** /**
* The minimum required to implement input stream * The minimum required to implement input stream
*/ */
public int read() throws java.io.IOException { public int read() throws java.io.IOException
try { {
if (buffer == null || bpos >= buffer.length) { try
{
if (buffer == null || bpos >= buffer.length)
{
buffer = lo.read(bsize); buffer = lo.read(bsize);
bpos = 0; bpos = 0;
} }
// Handle EOF // Handle EOF
if(bpos >= buffer.length) { if (bpos >= buffer.length)
{
return -1; return -1;
} }
int ret = (buffer[bpos] & 0x7F); int ret = (buffer[bpos] & 0x7F);
if ((buffer[bpos] &0x80) == 0x80) { if ((buffer[bpos] &0x80) == 0x80)
{
ret |= 0x80; ret |= 0x80;
} }
bpos++; bpos++;
return ret; return ret;
} catch(SQLException se) { }
catch (SQLException se)
{
throw new IOException(se.toString()); throw new IOException(se.toString());
} }
} }
@@ -91,11 +101,15 @@ public class BlobInputStream extends InputStream {
* *
* @exception IOException if an I/O error occurs. * @exception IOException if an I/O error occurs.
*/ */
public void close() throws IOException { public void close() throws IOException
try { {
try
{
lo.close(); lo.close();
lo = null; lo = null;
} catch(SQLException se) { }
catch (SQLException se)
{
throw new IOException(se.toString()); throw new IOException(se.toString());
} }
} }
@@ -124,10 +138,14 @@ public class BlobInputStream extends InputStream {
* the mark position becomes invalid. * the mark position becomes invalid.
* @see java.io.InputStream#reset() * @see java.io.InputStream#reset()
*/ */
public synchronized void mark(int readlimit) { public synchronized void mark(int readlimit)
try { {
try
{
mpos = lo.tell(); mpos = lo.tell();
} catch(SQLException se) { }
catch (SQLException se)
{
//throw new IOException(se.toString()); //throw new IOException(se.toString());
} }
} }
@@ -139,10 +157,15 @@ public class BlobInputStream extends InputStream {
* @see java.io.InputStream#mark(int) * @see java.io.InputStream#mark(int)
* @see java.io.IOException * @see java.io.IOException
*/ */
public synchronized void reset() throws IOException { public synchronized void reset()
try { throws IOException
{
try
{
lo.seek(mpos); lo.seek(mpos);
} catch(SQLException se) { }
catch (SQLException se)
{
throw new IOException(se.toString()); throw new IOException(se.toString());
} }
} }
@@ -157,7 +180,8 @@ public class BlobInputStream extends InputStream {
* @see java.io.InputStream#mark(int) * @see java.io.InputStream#mark(int)
* @see java.io.InputStream#reset() * @see java.io.InputStream#reset()
*/ */
public boolean markSupported() { public boolean markSupported()
{
return true; return true;
} }
} }

View File

@@ -7,7 +7,8 @@ import java.sql.SQLException;
/** /**
* This implements a basic output stream that writes to a LargeObject * This implements a basic output stream that writes to a LargeObject
*/ */
public class BlobOutputStream extends OutputStream { public class BlobOutputStream extends OutputStream
{
/** /**
* The parent LargeObject * The parent LargeObject
*/ */
@@ -32,7 +33,8 @@ public class BlobOutputStream extends OutputStream {
* Create an OutputStream to a large object * Create an OutputStream to a large object
* @param lo LargeObject * @param lo LargeObject
*/ */
public BlobOutputStream(LargeObject lo) { public BlobOutputStream(LargeObject lo)
{
this(lo, 1024); this(lo, 1024);
} }
@@ -41,21 +43,27 @@ public class BlobOutputStream extends OutputStream {
* @param lo LargeObject * @param lo LargeObject
* @param bsize The size of the buffer used to improve performance * @param bsize The size of the buffer used to improve performance
*/ */
public BlobOutputStream(LargeObject lo,int bsize) { public BlobOutputStream(LargeObject lo, int bsize)
{
this.lo = lo; this.lo = lo;
this.bsize = bsize; this.bsize = bsize;
buf = new byte[bsize]; buf = new byte[bsize];
bpos = 0; bpos = 0;
} }
public void write(int b) throws java.io.IOException { public void write(int b) throws java.io.IOException
try { {
if(bpos>=bsize) { try
{
if (bpos >= bsize)
{
lo.write(buf); lo.write(buf);
bpos = 0; bpos = 0;
} }
buf[bpos++] = (byte)b; buf[bpos++] = (byte)b;
} catch(SQLException se) { }
catch (SQLException se)
{
throw new IOException(se.toString()); throw new IOException(se.toString());
} }
} }
@@ -70,12 +78,16 @@ public class BlobOutputStream extends OutputStream {
* *
* @exception IOException if an I/O error occurs. * @exception IOException if an I/O error occurs.
*/ */
public void flush() throws IOException { public void flush() throws IOException
try { {
try
{
if (bpos > 0) if (bpos > 0)
lo.write(buf, 0, bpos); lo.write(buf, 0, bpos);
bpos = 0; bpos = 0;
} catch(SQLException se) { }
catch (SQLException se)
{
throw new IOException(se.toString()); throw new IOException(se.toString());
} }
} }
@@ -90,12 +102,16 @@ public class BlobOutputStream extends OutputStream {
* *
* @exception IOException if an I/O error occurs. * @exception IOException if an I/O error occurs.
*/ */
public void close() throws IOException { public void close() throws IOException
try { {
try
{
flush(); flush();
lo.close(); lo.close();
lo = null; lo = null;
} catch(SQLException se) { }
catch (SQLException se)
{
throw new IOException(se.toString()); throw new IOException(se.toString());
} }
} }

View File

@@ -110,15 +110,22 @@ public class LargeObject
*/ */
public void close() throws SQLException public void close() throws SQLException
{ {
if(!closed) { if (!closed)
{
// flush any open output streams // flush any open output streams
if(os!=null) { if (os != null)
try { {
try
{
// we can't call os.close() otherwise we go into an infinite loop! // we can't call os.close() otherwise we go into an infinite loop!
os.flush(); os.flush();
} catch(IOException ioe) { }
catch (IOException ioe)
{
throw new SQLException(ioe.getMessage()); throw new SQLException(ioe.getMessage());
} finally { }
finally
{
os = null; os = null;
} }
} }

View File

@@ -81,8 +81,7 @@ public class LargeObjectManager
* This prevents us being created by mere mortals * This prevents us being created by mere mortals
*/ */
private LargeObjectManager() private LargeObjectManager()
{ {}
}
/** /**
* Constructs the LargeObject API. * Constructs the LargeObject API.

View File

@@ -20,7 +20,7 @@ import org.postgresql.largeobject.*;
* This implements the Blob interface, which is basically another way to * This implements the Blob interface, which is basically another way to
* access a LargeObject. * access a LargeObject.
* *
* $Id: PGblob.java,v 1.1 2000/04/17 20:07:52 peter Exp $ * $Id: PGblob.java,v 1.2 2001/10/25 05:59:59 momjian Exp $
* *
*/ */
public class PGblob implements java.sql.Blob public class PGblob implements java.sql.Blob
@@ -29,22 +29,26 @@ public class PGblob implements java.sql.Blob
private int oid; private int oid;
private LargeObject lo; private LargeObject lo;
public PGblob(org.postgresql.Connection conn,int oid) throws SQLException { public PGblob(org.postgresql.Connection conn, int oid) throws SQLException
{
this.conn = conn; this.conn = conn;
this.oid = oid; this.oid = oid;
LargeObjectManager lom = conn.getLargeObjectAPI(); LargeObjectManager lom = conn.getLargeObjectAPI();
this.lo = lom.open(oid); this.lo = lom.open(oid);
} }
public long length() throws SQLException { public long length() throws SQLException
{
return lo.size(); return lo.size();
} }
public InputStream getBinaryStream() throws SQLException { public InputStream getBinaryStream() throws SQLException
{
return lo.getInputStream(); return lo.getInputStream();
} }
public byte[] getBytes(long pos,int length) throws SQLException { public byte[] getBytes(long pos, int length) throws SQLException
{
lo.seek((int)pos, LargeObject.SEEK_SET); lo.seek((int)pos, LargeObject.SEEK_SET);
return lo.read(length); return lo.read(length);
} }
@@ -52,14 +56,16 @@ public class PGblob implements java.sql.Blob
/* /*
* For now, this is not implemented. * For now, this is not implemented.
*/ */
public long position(byte[] pattern,long start) throws SQLException { public long position(byte[] pattern, long start) throws SQLException
{
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
/* /*
* This should be simply passing the byte value of the pattern Blob * This should be simply passing the byte value of the pattern Blob
*/ */
public long position(Blob pattern,long start) throws SQLException { public long position(Blob pattern, long start) throws SQLException
{
return position(pattern.getBytes(0, (int)pattern.length()), start); return position(pattern.getBytes(0, (int)pattern.length()), start);
} }

View File

@@ -20,7 +20,7 @@ import org.postgresql.largeobject.*;
* This implements the Blob interface, which is basically another way to * This implements the Blob interface, which is basically another way to
* access a LargeObject. * access a LargeObject.
* *
* $Id: PGclob.java,v 1.1 2001/02/16 16:45:01 peter Exp $ * $Id: PGclob.java,v 1.2 2001/10/25 05:59:59 momjian Exp $
* *
*/ */
public class PGclob implements java.sql.Clob public class PGclob implements java.sql.Clob
@@ -29,26 +29,31 @@ public class PGclob implements java.sql.Clob
private int oid; private int oid;
private LargeObject lo; private LargeObject lo;
public PGclob(org.postgresql.Connection conn,int oid) throws SQLException { public PGclob(org.postgresql.Connection conn, int oid) throws SQLException
{
this.conn = conn; this.conn = conn;
this.oid = oid; this.oid = oid;
LargeObjectManager lom = conn.getLargeObjectAPI(); LargeObjectManager lom = conn.getLargeObjectAPI();
this.lo = lom.open(oid); this.lo = lom.open(oid);
} }
public long length() throws SQLException { public long length() throws SQLException
{
return lo.size(); return lo.size();
} }
public InputStream getAsciiStream() throws SQLException { public InputStream getAsciiStream() throws SQLException
{
return lo.getInputStream(); return lo.getInputStream();
} }
public Reader getCharacterStream() throws SQLException { public Reader getCharacterStream() throws SQLException
{
return new InputStreamReader(lo.getInputStream()); return new InputStreamReader(lo.getInputStream());
} }
public String getSubString(long i,int j) throws SQLException { public String getSubString(long i, int j) throws SQLException
{
lo.seek((int)i - 1); lo.seek((int)i - 1);
return new String(lo.read(j)); return new String(lo.read(j));
} }
@@ -56,14 +61,16 @@ public class PGclob implements java.sql.Clob
/* /*
* For now, this is not implemented. * For now, this is not implemented.
*/ */
public long position(String pattern,long start) throws SQLException { public long position(String pattern, long start) throws SQLException
{
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
/* /*
* This should be simply passing the byte value of the pattern Blob * This should be simply passing the byte value of the pattern Blob
*/ */
public long position(Clob pattern,long start) throws SQLException { public long position(Clob pattern, long start) throws SQLException
{
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }

View File

@@ -9,38 +9,48 @@ import java.sql.*;
/** /**
* Executes all known tests for JDBC2 and includes some utility methods. * Executes all known tests for JDBC2 and includes some utility methods.
*/ */
public class JDBC2Tests extends TestSuite { public class JDBC2Tests extends TestSuite
{
/** /**
* Returns the Test database JDBC URL * Returns the Test database JDBC URL
*/ */
public static String getURL() { public static String getURL()
{
return System.getProperty("database"); return System.getProperty("database");
} }
/** /**
* Returns the Postgresql username * Returns the Postgresql username
*/ */
public static String getUser() { public static String getUser()
{
return System.getProperty("username"); return System.getProperty("username");
} }
/** /**
* Returns the user's password * Returns the user's password
*/ */
public static String getPassword() { public static String getPassword()
{
return System.getProperty("password"); return System.getProperty("password");
} }
/** /**
* Helper - opens a connection. * Helper - opens a connection.
*/ */
public static java.sql.Connection openDB() { public static java.sql.Connection openDB()
try { {
try
{
Class.forName("org.postgresql.Driver"); Class.forName("org.postgresql.Driver");
return java.sql.DriverManager.getConnection(JDBC2Tests.getURL(), JDBC2Tests.getUser(), JDBC2Tests.getPassword()); return java.sql.DriverManager.getConnection(JDBC2Tests.getURL(), JDBC2Tests.getUser(), JDBC2Tests.getPassword());
} catch(ClassNotFoundException ex) { }
catch (ClassNotFoundException ex)
{
TestCase.fail(ex.getMessage()); TestCase.fail(ex.getMessage());
} catch(SQLException ex) { }
catch (SQLException ex)
{
TestCase.fail(ex.getMessage()); TestCase.fail(ex.getMessage());
} }
return null; return null;
@@ -50,11 +60,15 @@ public class JDBC2Tests extends TestSuite {
* Helper - closes an open connection. This rewrites SQLException to a failed * Helper - closes an open connection. This rewrites SQLException to a failed
* assertion. It's static so other classes can use it. * assertion. It's static so other classes can use it.
*/ */
public static void closeDB(Connection con) { public static void closeDB(Connection con)
try { {
try
{
if (con != null) if (con != null)
con.close(); con.close();
} catch (SQLException ex) { }
catch (SQLException ex)
{
TestCase.fail(ex.getMessage()); TestCase.fail(ex.getMessage());
} }
} }
@@ -64,19 +78,26 @@ public class JDBC2Tests extends TestSuite {
*/ */
public static void createTable(Connection con, public static void createTable(Connection con,
String table, String table,
String columns) { String columns)
try { {
try
{
Statement st = con.createStatement(); Statement st = con.createStatement();
try { try
{
// Drop the table // Drop the table
dropTable(con, table); dropTable(con, table);
// Now create the table // Now create the table
st.executeUpdate("create table " + table + " (" + columns + ")"); st.executeUpdate("create table " + table + " (" + columns + ")");
} finally { }
finally
{
st.close(); st.close();
} }
} catch(SQLException ex) { }
catch (SQLException ex)
{
TestCase.fail(ex.getMessage()); TestCase.fail(ex.getMessage());
} }
} }
@@ -84,15 +105,22 @@ public class JDBC2Tests extends TestSuite {
/** /**
* Helper - drops a table * Helper - drops a table
*/ */
public static void dropTable(Connection con, String table) { public static void dropTable(Connection con, String table)
try { {
try
{
Statement stmt = con.createStatement(); Statement stmt = con.createStatement();
try { try
{
stmt.executeUpdate("DROP TABLE " + table); stmt.executeUpdate("DROP TABLE " + table);
} catch (SQLException ex) { }
catch (SQLException ex)
{
// ignore // ignore
} }
} catch (SQLException ex) { }
catch (SQLException ex)
{
TestCase.fail(ex.getMessage()); TestCase.fail(ex.getMessage());
} }
} }
@@ -100,11 +128,13 @@ public class JDBC2Tests extends TestSuite {
/** /**
* Helper - generates INSERT SQL - very simple * Helper - generates INSERT SQL - very simple
*/ */
public static String insertSQL(String table, String values) { public static String insertSQL(String table, String values)
{
return insertSQL(table, null, values); return insertSQL(table, null, values);
} }
public static String insertSQL(String table, String columns, String values) { public static String insertSQL(String table, String columns, String values)
{
String s = "INSERT INTO " + table; String s = "INSERT INTO " + table;
if (columns != null) if (columns != null)
@@ -116,15 +146,18 @@ public class JDBC2Tests extends TestSuite {
/** /**
* Helper - generates SELECT SQL - very simple * Helper - generates SELECT SQL - very simple
*/ */
public static String selectSQL(String table, String columns) { public static String selectSQL(String table, String columns)
{
return selectSQL(table, columns, null, null); return selectSQL(table, columns, null, null);
} }
public static String selectSQL(String table, String columns, String where) { public static String selectSQL(String table, String columns, String where)
{
return selectSQL(table, columns, where, null); return selectSQL(table, columns, where, null);
} }
public static String selectSQL(String table, String columns, String where, String other) { public static String selectSQL(String table, String columns, String where, String other)
{
String s = "SELECT " + columns + " FROM " + table; String s = "SELECT " + columns + " FROM " + table;
if (where != null) if (where != null)
@@ -140,7 +173,8 @@ public class JDBC2Tests extends TestSuite {
* @param v value to prefix * @param v value to prefix
* @param l number of digits (0-10) * @param l number of digits (0-10)
*/ */
public static String fix(int v, int l) { public static String fix(int v, int l)
{
String s = "0000000000".substring(0, l) + Integer.toString(v); String s = "0000000000".substring(0, l) + Integer.toString(v);
return s.substring(s.length() - l); return s.substring(s.length() - l);
} }
@@ -148,7 +182,8 @@ public class JDBC2Tests extends TestSuite {
/** /**
* The main entry point for JUnit * The main entry point for JUnit
*/ */
public static TestSuite suite() { public static TestSuite suite()
{
TestSuite suite = new TestSuite(); TestSuite suite = new TestSuite();
// //

View File

@@ -2,8 +2,10 @@ package org.postgresql.test.jdbc2;
import junit.framework.TestCase; import junit.framework.TestCase;
public class ANTTest extends TestCase { public class ANTTest extends TestCase
public ANTTest(String name) { {
public ANTTest(String name)
{
super(name); super(name);
} }
@@ -11,7 +13,8 @@ public class ANTTest extends TestCase {
* This tests the acceptsURL() method with a couple of good and badly formed * This tests the acceptsURL() method with a couple of good and badly formed
* jdbc urls * jdbc urls
*/ */
public void testANT() { public void testANT()
{
String url = System.getProperty("database"); String url = System.getProperty("database");
String usr = System.getProperty("username"); String usr = System.getProperty("username");
String psw = System.getProperty("password"); String psw = System.getProperty("password");

View File

@@ -12,17 +12,20 @@ import java.sql.*;
/** /**
* Test case for Statement.batchExecute() * Test case for Statement.batchExecute()
*/ */
public class BatchExecuteTest extends TestCase { public class BatchExecuteTest extends TestCase
{
private Connection con; private Connection con;
public BatchExecuteTest(String name) { public BatchExecuteTest(String name)
{
super(name); super(name);
} }
// Set up the fixture for this testcase: a connection to a database with // Set up the fixture for this testcase: a connection to a database with
// a table for this test. // a table for this test.
protected void setUp() throws Exception { protected void setUp() throws Exception
{
con = JDBC2Tests.openDB(); con = JDBC2Tests.openDB();
Statement stmt = con.createStatement(); Statement stmt = con.createStatement();
@@ -38,19 +41,22 @@ public class BatchExecuteTest extends TestCase {
} }
// Tear down the fixture for this test case. // Tear down the fixture for this test case.
protected void tearDown() throws Exception { protected void tearDown() throws Exception
{
con.setAutoCommit(true); con.setAutoCommit(true);
JDBC2Tests.dropTable(con, "testbatch"); JDBC2Tests.dropTable(con, "testbatch");
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} }
public void testSupportsBatchUpdates() throws Exception { public void testSupportsBatchUpdates() throws Exception
{
DatabaseMetaData dbmd = con.getMetaData(); DatabaseMetaData dbmd = con.getMetaData();
assertTrue(dbmd.supportsBatchUpdates()); assertTrue(dbmd.supportsBatchUpdates());
} }
private void assertCol1HasValue(int expected) throws Exception { private void assertCol1HasValue(int expected) throws Exception
{
Statement getCol1 = con.createStatement(); Statement getCol1 = con.createStatement();
ResultSet rs = ResultSet rs =
@@ -67,7 +73,8 @@ public class BatchExecuteTest extends TestCase {
getCol1.close(); getCol1.close();
} }
public void testExecuteEmptyBatch() throws Exception { public void testExecuteEmptyBatch() throws Exception
{
Statement stmt = con.createStatement(); Statement stmt = con.createStatement();
int[] updateCount = stmt.executeBatch(); int[] updateCount = stmt.executeBatch();
assertEquals(0, updateCount.length); assertEquals(0, updateCount.length);
@@ -79,7 +86,8 @@ public class BatchExecuteTest extends TestCase {
stmt.close(); stmt.close();
} }
public void testClearBatch() throws Exception { public void testClearBatch() throws Exception
{
Statement stmt = con.createStatement(); Statement stmt = con.createStatement();
stmt.addBatch("UPDATE testbatch SET col1 = col1 + 1 WHERE pk = 1"); stmt.addBatch("UPDATE testbatch SET col1 = col1 + 1 WHERE pk = 1");
@@ -98,21 +106,27 @@ public class BatchExecuteTest extends TestCase {
stmt.close(); stmt.close();
} }
public void testSelectThrowsException() throws Exception { public void testSelectThrowsException() throws Exception
{
Statement stmt = con.createStatement(); Statement stmt = con.createStatement();
stmt.addBatch("UPDATE testbatch SET col1 = col1 + 1 WHERE pk = 1"); stmt.addBatch("UPDATE testbatch SET col1 = col1 + 1 WHERE pk = 1");
stmt.addBatch("SELECT col1 FROM testbatch WHERE pk = 1"); stmt.addBatch("SELECT col1 FROM testbatch WHERE pk = 1");
stmt.addBatch("UPDATE testbatch SET col1 = col1 + 2 WHERE pk = 1"); stmt.addBatch("UPDATE testbatch SET col1 = col1 + 2 WHERE pk = 1");
try { try
{
stmt.executeBatch(); stmt.executeBatch();
fail("Should raise a BatchUpdateException because of the SELECT"); fail("Should raise a BatchUpdateException because of the SELECT");
} catch (BatchUpdateException e) { }
catch (BatchUpdateException e)
{
int [] updateCounts = e.getUpdateCounts(); int [] updateCounts = e.getUpdateCounts();
assertEquals(1, updateCounts.length); assertEquals(1, updateCounts.length);
assertEquals(1, updateCounts[0]); assertEquals(1, updateCounts[0]);
} catch (SQLException e) { }
catch (SQLException e)
{
fail( "Should throw a BatchUpdateException instead of " + fail( "Should throw a BatchUpdateException instead of " +
"a generic SQLException: " + e); "a generic SQLException: " + e);
} }
@@ -120,7 +134,8 @@ public class BatchExecuteTest extends TestCase {
stmt.close(); stmt.close();
} }
public void testPreparedStatement() throws Exception { public void testPreparedStatement() throws Exception
{
PreparedStatement pstmt = con.prepareStatement( PreparedStatement pstmt = con.prepareStatement(
"UPDATE testbatch SET col1 = col1 + ? WHERE PK = ?" ); "UPDATE testbatch SET col1 = col1 + ? WHERE PK = ?" );
@@ -153,7 +168,8 @@ public class BatchExecuteTest extends TestCase {
/** /**
*/ */
public void testTransactionalBehaviour() throws Exception { public void testTransactionalBehaviour() throws Exception
{
Statement stmt = con.createStatement(); Statement stmt = con.createStatement();
stmt.addBatch("UPDATE testbatch SET col1 = col1 + 1 WHERE pk = 1"); stmt.addBatch("UPDATE testbatch SET col1 = col1 + 1 WHERE pk = 1");

View File

@@ -8,13 +8,14 @@ import java.sql.*;
import org.postgresql.largeobject.*; import org.postgresql.largeobject.*;
/** /**
* $Id: BlobTest.java,v 1.2 2001/09/23 04:11:14 momjian Exp $ * $Id: BlobTest.java,v 1.3 2001/10/25 05:59:59 momjian Exp $
* *
* Some simple tests based on problems reported by users. Hopefully these will * Some simple tests based on problems reported by users. Hopefully these will
* help prevent previous problems from re-occuring ;-) * help prevent previous problems from re-occuring ;-)
* *
*/ */
public class BlobTest extends TestCase { public class BlobTest extends TestCase
{
private Connection con; private Connection con;
@@ -22,16 +23,19 @@ public class BlobTest extends TestCase {
private static final int NATIVE_STREAM = 1; // LargeObject API using OutputStream private static final int NATIVE_STREAM = 1; // LargeObject API using OutputStream
private static final int JDBC_STREAM = 2; // JDBC API using OutputStream private static final int JDBC_STREAM = 2; // JDBC API using OutputStream
public BlobTest(String name) { public BlobTest(String name)
{
super(name); super(name);
} }
protected void setUp() throws Exception { protected void setUp() throws Exception
{
con = JDBC2Tests.openDB(); con = JDBC2Tests.openDB();
JDBC2Tests.createTable(con, "testblob", "id name,lo oid"); JDBC2Tests.createTable(con, "testblob", "id name,lo oid");
} }
protected void tearDown() throws Exception { protected void tearDown() throws Exception
{
JDBC2Tests.dropTable(con, "testblob"); JDBC2Tests.dropTable(con, "testblob");
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} }
@@ -39,8 +43,10 @@ public class BlobTest extends TestCase {
/** /**
* Tests one method of uploading a blob to the database * Tests one method of uploading a blob to the database
*/ */
public void testUploadBlob_LOOP() { public void testUploadBlob_LOOP()
try { {
try
{
con.setAutoCommit(false); con.setAutoCommit(false);
assertTrue(!con.getAutoCommit()); assertTrue(!con.getAutoCommit());
@@ -51,7 +57,9 @@ public class BlobTest extends TestCase {
assertTrue(compareBlobs()); assertTrue(compareBlobs());
con.setAutoCommit(true); con.setAutoCommit(true);
} catch(Exception ex) { }
catch (Exception ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
@@ -59,8 +67,10 @@ public class BlobTest extends TestCase {
/** /**
* Tests one method of uploading a blob to the database * Tests one method of uploading a blob to the database
*/ */
public void testUploadBlob_NATIVE() { public void testUploadBlob_NATIVE()
try { {
try
{
con.setAutoCommit(false); con.setAutoCommit(false);
assertTrue(!con.getAutoCommit()); assertTrue(!con.getAutoCommit());
@@ -71,7 +81,9 @@ public class BlobTest extends TestCase {
assertTrue(compareBlobs()); assertTrue(compareBlobs());
con.setAutoCommit(true); con.setAutoCommit(true);
} catch(Exception ex) { }
catch (Exception ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
@@ -81,7 +93,8 @@ public class BlobTest extends TestCase {
* because it always works, and we can use it as a base to test the new * because it always works, and we can use it as a base to test the new
* methods. * methods.
*/ */
private int uploadFile(String file, int method) throws Exception { private int uploadFile(String file, int method) throws Exception
{
LargeObjectManager lom = ((org.postgresql.Connection)con).getLargeObjectAPI(); LargeObjectManager lom = ((org.postgresql.Connection)con).getLargeObjectAPI();
FileInputStream fis = new FileInputStream(file); FileInputStream fis = new FileInputStream(file);
@@ -98,7 +111,8 @@ public class BlobTest extends TestCase {
case LOOP: case LOOP:
buf = new byte[2048]; buf = new byte[2048];
t = 0; t = 0;
while((s=fis.read(buf,0,buf.length))>0) { while ((s = fis.read(buf, 0, buf.length)) > 0)
{
t += s; t += s;
blob.write(buf, 0, s); blob.write(buf, 0, s);
} }
@@ -107,7 +121,8 @@ public class BlobTest extends TestCase {
case NATIVE_STREAM: case NATIVE_STREAM:
os = blob.getOutputStream(); os = blob.getOutputStream();
s = fis.read(); s = fis.read();
while(s>-1) { while (s > -1)
{
os.write(s); os.write(s);
s = fis.read(); s = fis.read();
} }
@@ -141,7 +156,8 @@ public class BlobTest extends TestCase {
* Helper - compares the blobs in a table with a local file. Note this alone * Helper - compares the blobs in a table with a local file. Note this alone
* tests the InputStream methods! * tests the InputStream methods!
*/ */
private boolean compareBlobs() throws Exception { private boolean compareBlobs() throws Exception
{
boolean result = true; boolean result = true;
LargeObjectManager lom = ((org.postgresql.Connection)con).getLargeObjectAPI(); LargeObjectManager lom = ((org.postgresql.Connection)con).getLargeObjectAPI();
@@ -150,7 +166,8 @@ public class BlobTest extends TestCase {
ResultSet rs = st.executeQuery(JDBC2Tests.selectSQL("testblob", "id,lo")); ResultSet rs = st.executeQuery(JDBC2Tests.selectSQL("testblob", "id,lo"));
assertNotNull(rs); assertNotNull(rs);
while(rs.next()) { while (rs.next())
{
String file = rs.getString(1); String file = rs.getString(1);
int oid = rs.getInt(2); int oid = rs.getInt(2);
@@ -161,7 +178,8 @@ public class BlobTest extends TestCase {
int f = fis.read(); int f = fis.read();
int b = bis.read(); int b = bis.read();
int c = 0; int c = 0;
while(f>=0 && b>=0 & result) { while (f >= 0 && b >= 0 & result)
{
result = (f == b); result = (f == b);
f = fis.read(); f = fis.read();
b = bis.read(); b = bis.read();

View File

@@ -10,20 +10,23 @@ import java.sql.*;
* *
* PS: Do you know how difficult it is to type on a train? ;-) * PS: Do you know how difficult it is to type on a train? ;-)
* *
* $Id: ConnectionTest.java,v 1.5 2001/09/23 04:11:14 momjian Exp $ * $Id: ConnectionTest.java,v 1.6 2001/10/25 05:59:59 momjian Exp $
*/ */
public class ConnectionTest extends TestCase { public class ConnectionTest extends TestCase
{
/** /**
* Constructor * Constructor
*/ */
public ConnectionTest(String name) { public ConnectionTest(String name)
{
super(name); super(name);
} }
// Set up the fixture for this testcase: the tables for this test. // Set up the fixture for this testcase: the tables for this test.
protected void setUp() throws Exception { protected void setUp() throws Exception
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
JDBC2Tests.createTable(con, "test_a", "imagename name,image oid,id int4"); JDBC2Tests.createTable(con, "test_a", "imagename name,image oid,id int4");
@@ -33,7 +36,8 @@ public class ConnectionTest extends TestCase {
} }
// Tear down the fixture for this test case. // Tear down the fixture for this test case.
protected void tearDown() throws Exception { protected void tearDown() throws Exception
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
JDBC2Tests.dropTable(con, "test_a"); JDBC2Tests.dropTable(con, "test_a");
@@ -45,8 +49,10 @@ public class ConnectionTest extends TestCase {
/** /**
* Tests the two forms of createStatement() * Tests the two forms of createStatement()
*/ */
public void testCreateStatement() { public void testCreateStatement()
try { {
try
{
java.sql.Connection conn = JDBC2Tests.openDB(); java.sql.Connection conn = JDBC2Tests.openDB();
// A standard Statement // A standard Statement
@@ -59,7 +65,9 @@ public class ConnectionTest extends TestCase {
assertNotNull(stat); assertNotNull(stat);
stat.close(); stat.close();
} catch(SQLException ex) { }
catch (SQLException ex)
{
assertTrue(ex.getMessage(), false); assertTrue(ex.getMessage(), false);
} }
} }
@@ -67,8 +75,10 @@ public class ConnectionTest extends TestCase {
/** /**
* Tests the two forms of prepareStatement() * Tests the two forms of prepareStatement()
*/ */
public void testPrepareStatement() { public void testPrepareStatement()
try { {
try
{
java.sql.Connection conn = JDBC2Tests.openDB(); java.sql.Connection conn = JDBC2Tests.openDB();
String sql = "select source,cost,imageid from test_c"; String sql = "select source,cost,imageid from test_c";
@@ -83,7 +93,9 @@ public class ConnectionTest extends TestCase {
assertNotNull(stat); assertNotNull(stat);
stat.close(); stat.close();
} catch(SQLException ex) { }
catch (SQLException ex)
{
assertTrue(ex.getMessage(), false); assertTrue(ex.getMessage(), false);
} }
} }
@@ -91,21 +103,24 @@ public class ConnectionTest extends TestCase {
/** /**
* Put the test for createPrepareCall here * Put the test for createPrepareCall here
*/ */
public void testPrepareCall() { public void testPrepareCall()
} {}
/** /**
* Test nativeSQL * Test nativeSQL
*/ */
public void testNativeSQL() { public void testNativeSQL()
{
// For now do nothing as it returns itself // For now do nothing as it returns itself
} }
/** /**
* Test autoCommit (both get & set) * Test autoCommit (both get & set)
*/ */
public void testTransactions() { public void testTransactions()
try { {
try
{
java.sql.Connection con = JDBC2Tests.openDB(); java.sql.Connection con = JDBC2Tests.openDB();
java.sql.Statement st; java.sql.Statement st;
java.sql.ResultSet rs; java.sql.ResultSet rs;
@@ -141,7 +156,9 @@ public class ConnectionTest extends TestCase {
rs.close(); rs.close();
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
catch (SQLException ex)
{
assertTrue(ex.getMessage(), false); assertTrue(ex.getMessage(), false);
} }
} }
@@ -149,8 +166,10 @@ public class ConnectionTest extends TestCase {
/** /**
* Simple test to see if isClosed works. * Simple test to see if isClosed works.
*/ */
public void testIsClosed() { public void testIsClosed()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
// Should not say closed // Should not say closed
@@ -161,7 +180,9 @@ public class ConnectionTest extends TestCase {
// Should now say closed // Should now say closed
assertTrue(con.isClosed()); assertTrue(con.isClosed());
} catch(SQLException ex) { }
catch (SQLException ex)
{
assertTrue(ex.getMessage(), false); assertTrue(ex.getMessage(), false);
} }
} }
@@ -169,8 +190,10 @@ public class ConnectionTest extends TestCase {
/** /**
* Test the warnings system * Test the warnings system
*/ */
public void testWarnings() { public void testWarnings()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
String testStr = "This Is OuR TeSt message"; String testStr = "This Is OuR TeSt message";
@@ -194,7 +217,9 @@ public class ConnectionTest extends TestCase {
assertTrue(con.getWarnings() == null); assertTrue(con.getWarnings() == null);
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
catch (SQLException ex)
{
assertTrue(ex.getMessage(), false); assertTrue(ex.getMessage(), false);
} }
} }
@@ -287,8 +312,10 @@ public class ConnectionTest extends TestCase {
/** /**
* JDBC2 Type mappings * JDBC2 Type mappings
*/ */
public void testTypeMaps() { public void testTypeMaps()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
// preserve the current map // preserve the current map
@@ -304,7 +331,9 @@ public class ConnectionTest extends TestCase {
assertEquals(oldmap, con.getTypeMap()); assertEquals(oldmap, con.getTypeMap());
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
catch (SQLException ex)
{
assertTrue(ex.getMessage(), false); assertTrue(ex.getMessage(), false);
} }
} }

View File

@@ -9,30 +9,36 @@ import java.sql.*;
* *
* PS: Do you know how difficult it is to type on a train? ;-) * PS: Do you know how difficult it is to type on a train? ;-)
* *
* $Id: DatabaseMetaDataTest.java,v 1.2 2001/09/10 15:07:58 momjian Exp $ * $Id: DatabaseMetaDataTest.java,v 1.3 2001/10/25 05:59:59 momjian Exp $
*/ */
public class DatabaseMetaDataTest extends TestCase { public class DatabaseMetaDataTest extends TestCase
{
/** /**
* Constructor * Constructor
*/ */
public DatabaseMetaDataTest(String name) { public DatabaseMetaDataTest(String name)
{
super(name); super(name);
} }
/** /**
* The spec says this may return null, but we always do! * The spec says this may return null, but we always do!
*/ */
public void testGetMetaData() { public void testGetMetaData()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData(); DatabaseMetaData dbmd = con.getMetaData();
assertNotNull(dbmd); assertNotNull(dbmd);
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
catch (SQLException ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
@@ -40,8 +46,10 @@ public class DatabaseMetaDataTest extends TestCase {
/** /**
* Test default capabilities * Test default capabilities
*/ */
public void testCapabilities() { public void testCapabilities()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData(); DatabaseMetaData dbmd = con.getMetaData();
@@ -69,14 +77,18 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(!dbmd.supportsIntegrityEnhancementFacility()); assertTrue(!dbmd.supportsIntegrityEnhancementFacility());
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
catch (SQLException ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
public void testJoins() { public void testJoins()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData(); DatabaseMetaData dbmd = con.getMetaData();
@@ -87,13 +99,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(dbmd.supportsLimitedOuterJoins()); assertTrue(dbmd.supportsLimitedOuterJoins());
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
catch (SQLException ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
public void testCursors() { public void testCursors()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData(); DatabaseMetaData dbmd = con.getMetaData();
@@ -103,13 +119,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(!dbmd.supportsPositionedUpdate()); assertTrue(!dbmd.supportsPositionedUpdate());
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
catch (SQLException ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
public void testNulls() { public void testNulls()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData(); DatabaseMetaData dbmd = con.getMetaData();
@@ -132,13 +152,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(dbmd.supportsNonNullableColumns()); assertTrue(dbmd.supportsNonNullableColumns());
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
catch (SQLException ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
public void testLocalFiles() { public void testLocalFiles()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData(); DatabaseMetaData dbmd = con.getMetaData();
@@ -148,13 +172,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(!dbmd.usesLocalFiles()); assertTrue(!dbmd.usesLocalFiles());
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
catch (SQLException ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
public void testIdentifiers() { public void testIdentifiers()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData(); DatabaseMetaData dbmd = con.getMetaData();
@@ -173,13 +201,17 @@ public class DatabaseMetaDataTest extends TestCase {
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
catch (SQLException ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
public void testTables() { public void testTables()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData(); DatabaseMetaData dbmd = con.getMetaData();
@@ -192,13 +224,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(!dbmd.supportsAlterTableWithDropColumn()); assertTrue(!dbmd.supportsAlterTableWithDropColumn());
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
catch (SQLException ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
public void testSelect() { public void testSelect()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData(); DatabaseMetaData dbmd = con.getMetaData();
@@ -219,13 +255,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(dbmd.supportsGroupByBeyondSelect()); // needs checking assertTrue(dbmd.supportsGroupByBeyondSelect()); // needs checking
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
catch (SQLException ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
public void testDBParams() { public void testDBParams()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData(); DatabaseMetaData dbmd = con.getMetaData();
@@ -235,13 +275,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(dbmd.getUserName().equals(JDBC2Tests.getUser())); assertTrue(dbmd.getUserName().equals(JDBC2Tests.getUser()));
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
catch (SQLException ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
public void testDbProductDetails() { public void testDbProductDetails()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
assertTrue(con instanceof org.postgresql.Connection); assertTrue(con instanceof org.postgresql.Connection);
org.postgresql.Connection pc = (org.postgresql.Connection) con; org.postgresql.Connection pc = (org.postgresql.Connection) con;
@@ -254,13 +298,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(dbmd.getDriverName().equals("PostgreSQL Native Driver")); assertTrue(dbmd.getDriverName().equals("PostgreSQL Native Driver"));
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
catch (SQLException ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
public void testDriverVersioning() { public void testDriverVersioning()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
assertTrue(con instanceof org.postgresql.Connection); assertTrue(con instanceof org.postgresql.Connection);
org.postgresql.Connection pc = (org.postgresql.Connection) con; org.postgresql.Connection pc = (org.postgresql.Connection) con;
@@ -274,7 +322,9 @@ public class DatabaseMetaDataTest extends TestCase {
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
catch (SQLException ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }

View File

@@ -5,26 +5,30 @@ import junit.framework.TestCase;
import java.sql.*; import java.sql.*;
/** /**
* $Id: DateTest.java,v 1.2 2001/09/23 04:11:14 momjian Exp $ * $Id: DateTest.java,v 1.3 2001/10/25 05:59:59 momjian Exp $
* *
* Some simple tests based on problems reported by users. Hopefully these will * Some simple tests based on problems reported by users. Hopefully these will
* help prevent previous problems from re-occuring ;-) * help prevent previous problems from re-occuring ;-)
* *
*/ */
public class DateTest extends TestCase { public class DateTest extends TestCase
{
private Connection con; private Connection con;
public DateTest(String name) { public DateTest(String name)
{
super(name); super(name);
} }
protected void setUp() throws Exception { protected void setUp() throws Exception
{
con = JDBC2Tests.openDB(); con = JDBC2Tests.openDB();
JDBC2Tests.createTable(con, "testdate", "dt date"); JDBC2Tests.createTable(con, "testdate", "dt date");
} }
protected void tearDown() throws Exception { protected void tearDown() throws Exception
{
JDBC2Tests.dropTable(con, "testdate"); JDBC2Tests.dropTable(con, "testdate");
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} }
@@ -32,8 +36,10 @@ public class DateTest extends TestCase {
/** /**
* Tests the time methods in ResultSet * Tests the time methods in ResultSet
*/ */
public void testGetDate() { public void testGetDate()
try { {
try
{
Statement stmt = con.createStatement(); Statement stmt = con.createStatement();
assertEquals(1, stmt.executeUpdate(JDBC2Tests.insertSQL("testdate", "'1950-02-07'"))); assertEquals(1, stmt.executeUpdate(JDBC2Tests.insertSQL("testdate", "'1950-02-07'")));
@@ -46,7 +52,9 @@ public class DateTest extends TestCase {
assertEquals(4, stmt.executeUpdate("DELETE FROM " + "testdate")); assertEquals(4, stmt.executeUpdate("DELETE FROM " + "testdate"));
stmt.close(); stmt.close();
} catch(Exception ex) { }
catch (Exception ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
@@ -54,8 +62,10 @@ public class DateTest extends TestCase {
/** /**
* Tests the time methods in PreparedStatement * Tests the time methods in PreparedStatement
*/ */
public void testSetDate() { public void testSetDate()
try { {
try
{
Statement stmt = con.createStatement(); Statement stmt = con.createStatement();
PreparedStatement ps = con.prepareStatement(JDBC2Tests.insertSQL("testdate", "?")); PreparedStatement ps = con.prepareStatement(JDBC2Tests.insertSQL("testdate", "?"));
@@ -78,7 +88,9 @@ public class DateTest extends TestCase {
assertEquals(4, stmt.executeUpdate("DELETE FROM testdate")); assertEquals(4, stmt.executeUpdate("DELETE FROM testdate"));
stmt.close(); stmt.close();
} catch(Exception ex) { }
catch (Exception ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
@@ -86,7 +98,8 @@ public class DateTest extends TestCase {
/** /**
* Helper for the date tests. It tests what should be in the db * Helper for the date tests. It tests what should be in the db
*/ */
private void dateTest() throws SQLException { private void dateTest() throws SQLException
{
Statement st = con.createStatement(); Statement st = con.createStatement();
ResultSet rs; ResultSet rs;
java.sql.Date d; java.sql.Date d;
@@ -120,7 +133,8 @@ public class DateTest extends TestCase {
st.close(); st.close();
} }
private java.sql.Date makeDate(int y, int m, int d) { private java.sql.Date makeDate(int y, int m, int d)
{
return java.sql.Date.valueOf(JDBC2Tests.fix(y, 4) + "-" + return java.sql.Date.valueOf(JDBC2Tests.fix(y, 4) + "-" +
JDBC2Tests.fix(m, 2) + "-" + JDBC2Tests.fix(m, 2) + "-" +
JDBC2Tests.fix(d, 2)); JDBC2Tests.fix(d, 2));

View File

@@ -5,14 +5,16 @@ import junit.framework.TestCase;
import java.sql.*; import java.sql.*;
/** /**
* $Id: DriverTest.java,v 1.2 2001/09/23 04:11:14 momjian Exp $ * $Id: DriverTest.java,v 1.3 2001/10/25 05:59:59 momjian Exp $
* *
* Tests the dynamically created class org.postgresql.Driver * Tests the dynamically created class org.postgresql.Driver
* *
*/ */
public class DriverTest extends TestCase { public class DriverTest extends TestCase
{
public DriverTest(String name) { public DriverTest(String name)
{
super(name); super(name);
} }
@@ -20,8 +22,10 @@ public class DriverTest extends TestCase {
* This tests the acceptsURL() method with a couple of good and badly formed * This tests the acceptsURL() method with a couple of good and badly formed
* jdbc urls * jdbc urls
*/ */
public void testAcceptsURL() { public void testAcceptsURL()
try { {
try
{
// Load the driver (note clients should never do it this way!) // Load the driver (note clients should never do it this way!)
org.postgresql.Driver drv = new org.postgresql.Driver(); org.postgresql.Driver drv = new org.postgresql.Driver();
@@ -38,7 +42,9 @@ public class DriverTest extends TestCase {
assertTrue(!drv.acceptsURL("jdbc:postgres:test")); assertTrue(!drv.acceptsURL("jdbc:postgres:test"));
assertTrue(!drv.acceptsURL("postgresql:test")); assertTrue(!drv.acceptsURL("postgresql:test"));
} catch(SQLException ex) { }
catch (SQLException ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
@@ -49,9 +55,11 @@ public class DriverTest extends TestCase {
/** /**
* Tests the connect method by connecting to the test database * Tests the connect method by connecting to the test database
*/ */
public void testConnect() { public void testConnect()
{
Connection con = null; Connection con = null;
try { try
{
Class.forName("org.postgresql.Driver"); Class.forName("org.postgresql.Driver");
// Test with the url, username & password // Test with the url, username & password
@@ -63,9 +71,13 @@ public class DriverTest extends TestCase {
con = DriverManager.getConnection(JDBC2Tests.getURL() + "?user=" + JDBC2Tests.getUser() + "&password=" + JDBC2Tests.getPassword()); con = DriverManager.getConnection(JDBC2Tests.getURL() + "?user=" + JDBC2Tests.getUser() + "&password=" + JDBC2Tests.getPassword());
assertNotNull(con); assertNotNull(con);
con.close(); con.close();
} catch(ClassNotFoundException ex) { }
catch (ClassNotFoundException ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} catch(SQLException ex) { }
catch (SQLException ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }

View File

@@ -8,17 +8,20 @@ import java.io.*;
/** /**
* Tests for the Encoding class. * Tests for the Encoding class.
* *
* $Id: EncodingTest.java,v 1.2 2001/09/23 04:11:14 momjian Exp $ * $Id: EncodingTest.java,v 1.3 2001/10/25 05:59:59 momjian Exp $
*/ */
public class EncodingTest extends TestCase { public class EncodingTest extends TestCase
{
public EncodingTest(String name) { public EncodingTest(String name)
{
super(name); super(name);
} }
public void testCreation() throws Exception { public void testCreation() throws Exception
{
Encoding encoding; Encoding encoding;
encoding = Encoding.getEncoding("UNICODE", null); encoding = Encoding.getEncoding("UNICODE", null);
assertEquals("UTF", encoding.name().substring(0, 3).toUpperCase()); assertEquals("UTF", encoding.name().substring(0, 3).toUpperCase());
@@ -32,7 +35,8 @@ public class EncodingTest extends TestCase {
encoding.name().toUpperCase().indexOf("UTF") != -1); encoding.name().toUpperCase().indexOf("UTF") != -1);
} }
public void testTransformations() throws Exception { public void testTransformations() throws Exception
{
Encoding encoding = Encoding.getEncoding("UNICODE", null); Encoding encoding = Encoding.getEncoding("UNICODE", null);
assertEquals("ab", encoding.decode(new byte[] { 97, 98 })); assertEquals("ab", encoding.decode(new byte[] { 97, 98 }));
@@ -46,7 +50,8 @@ public class EncodingTest extends TestCase {
encoding.decode(new byte[] { 97 })); encoding.decode(new byte[] { 97 }));
} }
public void testReader() throws Exception { public void testReader() throws Exception
{
Encoding encoding = Encoding.getEncoding("SQL_ASCII", null); Encoding encoding = Encoding.getEncoding("SQL_ASCII", null);
InputStream stream = new ByteArrayInputStream(new byte[] { 97, 98 }); InputStream stream = new ByteArrayInputStream(new byte[] { 97, 98 });
Reader reader = encoding.getDecodingReader(stream); Reader reader = encoding.getDecodingReader(stream);

View File

@@ -6,20 +6,23 @@ import java.sql.*;
import java.math.BigDecimal; import java.math.BigDecimal;
/** /**
* $Id: JBuilderTest.java,v 1.3 2001/09/23 04:11:14 momjian Exp $ * $Id: JBuilderTest.java,v 1.4 2001/10/25 05:59:59 momjian Exp $
* *
* Some simple tests to check that the required components needed for JBuilder * Some simple tests to check that the required components needed for JBuilder
* stay working * stay working
* *
*/ */
public class JBuilderTest extends TestCase { public class JBuilderTest extends TestCase
{
public JBuilderTest(String name) { public JBuilderTest(String name)
{
super(name); super(name);
} }
// Set up the fixture for this testcase: the tables for this test. // Set up the fixture for this testcase: the tables for this test.
protected void setUp() throws Exception { protected void setUp() throws Exception
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
JDBC2Tests.createTable( con, "test_c", JDBC2Tests.createTable( con, "test_c",
@@ -29,7 +32,8 @@ public class JBuilderTest extends TestCase {
} }
// Tear down the fixture for this test case. // Tear down the fixture for this test case.
protected void tearDown() throws Exception { protected void tearDown() throws Exception
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
JDBC2Tests.dropTable(con, "test_c"); JDBC2Tests.dropTable(con, "test_c");
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
@@ -38,15 +42,18 @@ public class JBuilderTest extends TestCase {
/** /**
* This tests that Money types work. JDBCExplorer barfs if this fails. * This tests that Money types work. JDBCExplorer barfs if this fails.
*/ */
public void testMoney() { public void testMoney()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
Statement st = con.createStatement(); Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select cost from test_c"); ResultSet rs = st.executeQuery("select cost from test_c");
assertNotNull(rs); assertNotNull(rs);
while(rs.next()){ while (rs.next())
{
double bd = rs.getDouble(1); double bd = rs.getDouble(1);
} }
@@ -54,7 +61,9 @@ public class JBuilderTest extends TestCase {
st.close(); st.close();
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(Exception ex) { }
catch (Exception ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }

View File

@@ -5,15 +5,17 @@ import junit.framework.TestCase;
import java.sql.*; import java.sql.*;
/** /**
* $Id: MiscTest.java,v 1.2 2001/09/23 04:11:14 momjian Exp $ * $Id: MiscTest.java,v 1.3 2001/10/25 05:59:59 momjian Exp $
* *
* Some simple tests based on problems reported by users. Hopefully these will * Some simple tests based on problems reported by users. Hopefully these will
* help prevent previous problems from re-occuring ;-) * help prevent previous problems from re-occuring ;-)
* *
*/ */
public class MiscTest extends TestCase { public class MiscTest extends TestCase
{
public MiscTest(String name) { public MiscTest(String name)
{
super(name); super(name);
} }
@@ -24,15 +26,18 @@ public class MiscTest extends TestCase {
* *
* Added Feb 13 2001 * Added Feb 13 2001
*/ */
public void testDatabaseSelectNullBug() { public void testDatabaseSelectNullBug()
try { {
try
{
Connection con = JDBC2Tests.openDB(); Connection con = JDBC2Tests.openDB();
Statement st = con.createStatement(); Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select datname from pg_database"); ResultSet rs = st.executeQuery("select datname from pg_database");
assertNotNull(rs); assertNotNull(rs);
while(rs.next()){ while (rs.next())
{
String s = rs.getString(1); String s = rs.getString(1);
} }
@@ -40,7 +45,9 @@ public class MiscTest extends TestCase {
st.close(); st.close();
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(Exception ex) { }
catch (Exception ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }

View File

@@ -5,26 +5,30 @@ import junit.framework.TestCase;
import java.sql.*; import java.sql.*;
/** /**
* $Id: TimeTest.java,v 1.2 2001/09/23 04:11:14 momjian Exp $ * $Id: TimeTest.java,v 1.3 2001/10/25 05:59:59 momjian Exp $
* *
* Some simple tests based on problems reported by users. Hopefully these will * Some simple tests based on problems reported by users. Hopefully these will
* help prevent previous problems from re-occuring ;-) * help prevent previous problems from re-occuring ;-)
* *
*/ */
public class TimeTest extends TestCase { public class TimeTest extends TestCase
{
private Connection con; private Connection con;
public TimeTest(String name) { public TimeTest(String name)
{
super(name); super(name);
} }
protected void setUp() throws Exception { protected void setUp() throws Exception
{
con = JDBC2Tests.openDB(); con = JDBC2Tests.openDB();
JDBC2Tests.createTable(con, "testtime", "tm time"); JDBC2Tests.createTable(con, "testtime", "tm time");
} }
protected void tearDown() throws Exception { protected void tearDown() throws Exception
{
JDBC2Tests.dropTable(con, "testtime"); JDBC2Tests.dropTable(con, "testtime");
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} }
@@ -32,8 +36,10 @@ public class TimeTest extends TestCase {
/** /**
* Tests the time methods in ResultSet * Tests the time methods in ResultSet
*/ */
public void testGetTime() { public void testGetTime()
try { {
try
{
Statement stmt = con.createStatement(); Statement stmt = con.createStatement();
assertEquals(1, stmt.executeUpdate(JDBC2Tests.insertSQL("testtime", "'01:02:03'"))); assertEquals(1, stmt.executeUpdate(JDBC2Tests.insertSQL("testtime", "'01:02:03'")));
@@ -44,7 +50,9 @@ public class TimeTest extends TestCase {
assertEquals(2, stmt.executeUpdate("DELETE FROM testtime")); assertEquals(2, stmt.executeUpdate("DELETE FROM testtime"));
stmt.close(); stmt.close();
} catch(Exception ex) { }
catch (Exception ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
@@ -52,8 +60,10 @@ public class TimeTest extends TestCase {
/** /**
* Tests the time methods in PreparedStatement * Tests the time methods in PreparedStatement
*/ */
public void testSetTime() { public void testSetTime()
try { {
try
{
PreparedStatement ps = con.prepareStatement(JDBC2Tests.insertSQL("testtime", "?")); PreparedStatement ps = con.prepareStatement(JDBC2Tests.insertSQL("testtime", "?"));
Statement stmt = con.createStatement(); Statement stmt = con.createStatement();
@@ -69,7 +79,9 @@ public class TimeTest extends TestCase {
assertEquals(2, stmt.executeUpdate("DELETE FROM testtime")); assertEquals(2, stmt.executeUpdate("DELETE FROM testtime"));
stmt.close(); stmt.close();
ps.close(); ps.close();
} catch(Exception ex) { }
catch (Exception ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
@@ -77,7 +89,8 @@ public class TimeTest extends TestCase {
/** /**
* Helper for the TimeTests. It tests what should be in the db * Helper for the TimeTests. It tests what should be in the db
*/ */
private void timeTest() throws SQLException { private void timeTest() throws SQLException
{
Statement st = con.createStatement(); Statement st = con.createStatement();
ResultSet rs; ResultSet rs;
java.sql.Time t; java.sql.Time t;
@@ -100,7 +113,8 @@ public class TimeTest extends TestCase {
rs.close(); rs.close();
} }
private java.sql.Time makeTime(int h, int m, int s) { private java.sql.Time makeTime(int h, int m, int s)
{
return java.sql.Time.valueOf(JDBC2Tests.fix(h, 2) + ":" + return java.sql.Time.valueOf(JDBC2Tests.fix(h, 2) + ":" +
JDBC2Tests.fix(m, 2) + ":" + JDBC2Tests.fix(m, 2) + ":" +
JDBC2Tests.fix(s, 2)); JDBC2Tests.fix(s, 2));

View File

@@ -5,7 +5,7 @@ import junit.framework.TestCase;
import java.sql.*; import java.sql.*;
/** /**
* $Id: TimestampTest.java,v 1.4 2001/09/29 03:11:11 momjian Exp $ * $Id: TimestampTest.java,v 1.5 2001/10/25 05:59:59 momjian Exp $
* *
* This has been the most controversial pair of methods since 6.5 was released! * This has been the most controversial pair of methods since 6.5 was released!
* *
@@ -13,22 +13,26 @@ import java.sql.*;
* MUST PASS this TestCase!!! * MUST PASS this TestCase!!!
* *
*/ */
public class TimestampTest extends TestCase { public class TimestampTest extends TestCase
{
private Connection con; private Connection con;
public TimestampTest(String name) { public TimestampTest(String name)
{
super(name); super(name);
} }
protected void setUp() throws Exception { protected void setUp() throws Exception
{
con = JDBC2Tests.openDB(); con = JDBC2Tests.openDB();
Statement stmt = con.createStatement(); Statement stmt = con.createStatement();
JDBC2Tests.createTable(con, "testtimestamp", "ts timestamp"); JDBC2Tests.createTable(con, "testtimestamp", "ts timestamp");
} }
protected void tearDown() throws Exception { protected void tearDown() throws Exception
{
JDBC2Tests.dropTable(con, "testtimestamp"); JDBC2Tests.dropTable(con, "testtimestamp");
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} }
@@ -36,8 +40,10 @@ public class TimestampTest extends TestCase {
/** /**
* Tests the time methods in ResultSet * Tests the time methods in ResultSet
*/ */
public void testGetTimestamp() { public void testGetTimestamp()
try { {
try
{
Statement stmt = con.createStatement(); Statement stmt = con.createStatement();
assertEquals(1, stmt.executeUpdate(JDBC2Tests.insertSQL("testtimestamp", assertEquals(1, stmt.executeUpdate(JDBC2Tests.insertSQL("testtimestamp",
@@ -56,7 +62,9 @@ public class TimestampTest extends TestCase {
assertEquals(3, stmt.executeUpdate("DELETE FROM testtimestamp")); assertEquals(3, stmt.executeUpdate("DELETE FROM testtimestamp"));
stmt.close(); stmt.close();
} catch(Exception ex) { }
catch (Exception ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
@@ -64,8 +72,10 @@ public class TimestampTest extends TestCase {
/** /**
* Tests the time methods in PreparedStatement * Tests the time methods in PreparedStatement
*/ */
public void testSetTimestamp() { public void testSetTimestamp()
try { {
try
{
Statement stmt = con.createStatement(); Statement stmt = con.createStatement();
PreparedStatement pstmt = con.prepareStatement(JDBC2Tests.insertSQL("testtimestamp", "?")); PreparedStatement pstmt = con.prepareStatement(JDBC2Tests.insertSQL("testtimestamp", "?"));
@@ -85,7 +95,9 @@ public class TimestampTest extends TestCase {
pstmt.close(); pstmt.close();
stmt.close(); stmt.close();
} catch(Exception ex) { }
catch (Exception ex)
{
fail(ex.getMessage()); fail(ex.getMessage());
} }
} }
@@ -93,7 +105,8 @@ public class TimestampTest extends TestCase {
/** /**
* Helper for the TimeTests. It tests what should be in the db * Helper for the TimeTests. It tests what should be in the db
*/ */
private void timestampTest() throws SQLException { private void timestampTest() throws SQLException
{
Statement stmt = con.createStatement(); Statement stmt = con.createStatement();
ResultSet rs; ResultSet rs;
java.sql.Timestamp t; java.sql.Timestamp t;
@@ -122,7 +135,8 @@ public class TimestampTest extends TestCase {
stmt.close(); stmt.close();
} }
private java.sql.Timestamp getTimestamp(int y, int m, int d, int h, int mn, int se, int f) { private java.sql.Timestamp getTimestamp(int y, int m, int d, int h, int mn, int se, int f)
{
return java.sql.Timestamp.valueOf(JDBC2Tests.fix(y, 4) + "-" + return java.sql.Timestamp.valueOf(JDBC2Tests.fix(y, 4) + "-" +
JDBC2Tests.fix(m, 2) + "-" + JDBC2Tests.fix(m, 2) + "-" +
JDBC2Tests.fix(d, 2) + " " + JDBC2Tests.fix(d, 2) + " " +

View File

@@ -6,17 +6,22 @@ import java.text.*;
/** /**
* A singleton class to translate JDBC driver messages in SQLException's. * A singleton class to translate JDBC driver messages in SQLException's.
*/ */
public class MessageTranslator { public class MessageTranslator
{
// The singleton instance. // The singleton instance.
private static MessageTranslator instance = null; private static MessageTranslator instance = null;
private ResourceBundle bundle; private ResourceBundle bundle;
private MessageTranslator() { private MessageTranslator()
try { {
try
{
bundle = ResourceBundle.getBundle("org.postgresql.errors"); bundle = ResourceBundle.getBundle("org.postgresql.errors");
} catch(MissingResourceException e) { }
catch (MissingResourceException e)
{
// translation files have not been installed. // translation files have not been installed.
bundle = null; bundle = null;
} }
@@ -24,37 +29,48 @@ public class MessageTranslator {
// Synchronized, otherwise multiple threads may perform the test and // Synchronized, otherwise multiple threads may perform the test and
// assign to the singleton instance simultaneously. // assign to the singleton instance simultaneously.
private synchronized final static MessageTranslator getInstance() { private synchronized final static MessageTranslator getInstance()
if (instance == null) { {
if (instance == null)
{
instance = new MessageTranslator(); instance = new MessageTranslator();
} }
return instance; return instance;
} }
public final static String translate(String id, Object[] args) { public final static String translate(String id, Object[] args)
{
MessageTranslator translator = MessageTranslator.getInstance(); MessageTranslator translator = MessageTranslator.getInstance();
return translator._translate(id, args); return translator._translate(id, args);
} }
private final String _translate(String id, Object[] args) { private final String _translate(String id, Object[] args)
{
String message; String message;
if (bundle != null && id != null) { if (bundle != null && id != null)
{
// Now look up a localized message. If one is not found, then use // Now look up a localized message. If one is not found, then use
// the supplied message instead. // the supplied message instead.
try { try
{
message = bundle.getString(id); message = bundle.getString(id);
} catch(MissingResourceException e) { }
catch (MissingResourceException e)
{
message = id; message = id;
} }
} else { }
else
{
message = id; message = id;
} }
// Expand any arguments // Expand any arguments
if (args != null && message != null) { if (args != null && message != null)
{
message = MessageFormat.format(message, args); message = MessageFormat.format(message, args);
} }

View File

@@ -5,16 +5,18 @@ import java.sql.*;
/** /**
* Converts to and from the postgresql bytea datatype used by the backend. * Converts to and from the postgresql bytea datatype used by the backend.
* *
* $Id: PGbytea.java,v 1.1 2001/09/10 15:07:05 momjian Exp $ * $Id: PGbytea.java,v 1.2 2001/10/25 06:00:00 momjian Exp $
*/ */
public class PGbytea { public class PGbytea
{
/** /**
* Converts a PG bytea string (i.e. the text representation * Converts a PG bytea string (i.e. the text representation
* of the bytea data type) into a java byte[] * of the bytea data type) into a java byte[]
*/ */
public static byte[] toBytes(String s) throws SQLException { public static byte[] toBytes(String s) throws SQLException
{
if (s == null) if (s == null)
return null; return null;
int slength = s.length(); int slength = s.length();
@@ -23,20 +25,27 @@ public class PGbytea {
int thebyte; int thebyte;
char nextchar; char nextchar;
char secondchar; char secondchar;
for (int i = 0; i < slength; i++) { for (int i = 0; i < slength; i++)
{
nextchar = s.charAt(i); nextchar = s.charAt(i);
if (nextchar == '\\') { if (nextchar == '\\')
{
secondchar = s.charAt(++i); secondchar = s.charAt(++i);
if (secondchar == '\\') { if (secondchar == '\\')
{
//escaped \ //escaped \
buf[bufpos++] = (byte)'\\'; buf[bufpos++] = (byte)'\\';
} else { }
else
{
thebyte = (secondchar - 48) * 64 + (s.charAt(++i) - 48) * 8 + (s.charAt(++i) - 48); thebyte = (secondchar - 48) * 64 + (s.charAt(++i) - 48) * 8 + (s.charAt(++i) - 48);
if (thebyte > 127) if (thebyte > 127)
thebyte -= 256; thebyte -= 256;
buf[bufpos++] = (byte)thebyte; buf[bufpos++] = (byte)thebyte;
} }
} else { }
else
{
buf[bufpos++] = (byte)nextchar; buf[bufpos++] = (byte)nextchar;
} }
} }
@@ -54,27 +63,34 @@ public class PGbytea {
if (p_buf == null) if (p_buf == null)
return null; return null;
StringBuffer l_strbuf = new StringBuffer(); StringBuffer l_strbuf = new StringBuffer();
for (int i = 0; i < p_buf.length; i++) { for (int i = 0; i < p_buf.length; i++)
{
int l_int = (int)p_buf[i]; int l_int = (int)p_buf[i];
if (l_int < 0) { if (l_int < 0)
{
l_int = 256 + l_int; l_int = 256 + l_int;
} }
//we escape the same non-printable characters as the backend //we escape the same non-printable characters as the backend
//we must escape all 8bit characters otherwise when convering //we must escape all 8bit characters otherwise when convering
//from java unicode to the db character set we may end up with //from java unicode to the db character set we may end up with
//question marks if the character set is SQL_ASCII //question marks if the character set is SQL_ASCII
if (l_int < 040 || l_int > 0176) { if (l_int < 040 || l_int > 0176)
{
//escape charcter with the form \000, but need two \\ because of //escape charcter with the form \000, but need two \\ because of
//the parser //the parser
l_strbuf.append("\\"); l_strbuf.append("\\");
l_strbuf.append((char)(((l_int >> 6) & 0x3) + 48)); l_strbuf.append((char)(((l_int >> 6) & 0x3) + 48));
l_strbuf.append((char)(((l_int >> 3) & 0x7) + 48)); l_strbuf.append((char)(((l_int >> 3) & 0x7) + 48));
l_strbuf.append((char)((l_int & 0x07) + 48)); l_strbuf.append((char)((l_int & 0x07) + 48));
} else if (p_buf[i] == (byte)'\\') { }
else if (p_buf[i] == (byte)'\\')
{
//escape the backslash character as \\, but need four \\\\ because //escape the backslash character as \\, but need four \\\\ because
//of the parser //of the parser
l_strbuf.append("\\\\"); l_strbuf.append("\\\\");
} else { }
else
{
//other characters are left alone //other characters are left alone
l_strbuf.append((char)p_buf[i]); l_strbuf.append((char)p_buf[i]);
} }

View File

@@ -16,7 +16,8 @@ public class PGmoney extends PGobject implements Serializable,Cloneable
/** /**
* @param value of field * @param value of field
*/ */
public PGmoney(double value) { public PGmoney(double value)
{
this(); this();
val = value; val = value;
} }
@@ -47,7 +48,8 @@ public class PGmoney extends PGobject implements Serializable,Cloneable
*/ */
public void setValue(String s) throws SQLException public void setValue(String s) throws SQLException
{ {
try { try
{
String s1; String s1;
boolean negative; boolean negative;
@@ -58,7 +60,8 @@ public class PGmoney extends PGobject implements Serializable,Cloneable
// Strip out any , in currency // Strip out any , in currency
int pos = s1.indexOf(','); int pos = s1.indexOf(',');
while (pos != -1) { while (pos != -1)
{
s1 = s1.substring(0, pos) + s1.substring(pos + 1); s1 = s1.substring(0, pos) + s1.substring(pos + 1);
pos = s1.indexOf(','); pos = s1.indexOf(',');
} }
@@ -66,7 +69,9 @@ public class PGmoney extends PGobject implements Serializable,Cloneable
val = Double.valueOf(s1).doubleValue(); val = Double.valueOf(s1).doubleValue();
val = negative ? -val : val; val = negative ? -val : val;
} catch(NumberFormatException e) { }
catch (NumberFormatException e)
{
throw new PSQLException("postgresql.money", e); throw new PSQLException("postgresql.money", e);
} }
} }
@@ -77,7 +82,8 @@ public class PGmoney extends PGobject implements Serializable,Cloneable
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(obj instanceof PGmoney) { if (obj instanceof PGmoney)
{
PGmoney p = (PGmoney)obj; PGmoney p = (PGmoney)obj;
return val == p.val; return val == p.val;
} }
@@ -97,10 +103,12 @@ public class PGmoney extends PGobject implements Serializable,Cloneable
*/ */
public String getValue() public String getValue()
{ {
if (val < 0) { if (val < 0)
{
return "-$" + ( -val); return "-$" + ( -val);
} }
else { else
{
return "$" + val; return "$" + val;
} }
} }

View File

@@ -23,8 +23,7 @@ public class PGobject implements Serializable,Cloneable
* object. * object.
*/ */
public PGobject() public PGobject()
{ {}
}
/** /**
* This method sets the type of this object. * This method sets the type of this object.

View File

@@ -55,7 +55,8 @@ public class PGtokenizer
// Peter 1998 Jan 6 - Added < and > to the nesting rules // Peter 1998 Jan 6 - Added < and > to the nesting rules
int nest = 0, p, s; int nest = 0, p, s;
for(p=0,s=0;p<string.length();p++) { for (p = 0, s = 0;p < string.length();p++)
{
char c = string.charAt(p); char c = string.charAt(p);
// increase nesting if an open character is found // increase nesting if an open character is found
@@ -66,7 +67,8 @@ public class PGtokenizer
if (c == ')' || c == ']' || c == '>') if (c == ')' || c == ']' || c == '>')
nest--; nest--;
if(nest==0 && c==delim) { if (nest == 0 && c == delim)
{
tokens.addElement(string.substring(s, p)); tokens.addElement(string.substring(s, p));
s = p + 1; // +1 to skip the delimiter s = p + 1; // +1 to skip the delimiter
} }
@@ -74,6 +76,7 @@ public class PGtokenizer
} }
// Don't forget the last token ;-) // Don't forget the last token ;-)
if (s < string.length()) if (s < string.length())
tokens.addElement(string.substring(s)); tokens.addElement(string.substring(s));
@@ -121,8 +124,10 @@ public class PGtokenizer
*/ */
public static String remove(String s, String l, String t) public static String remove(String s, String l, String t)
{ {
if(s.startsWith(l)) s = s.substring(l.length()); if (s.startsWith(l))
if(s.endsWith(t)) s = s.substring(0,s.length()-t.length()); s = s.substring(l.length());
if (s.endsWith(t))
s = s.substring(0, s.length() - t.length());
return s; return s;
} }
@@ -133,7 +138,8 @@ public class PGtokenizer
*/ */
public void remove(String l, String t) public void remove(String l, String t)
{ {
for(int i=0;i<tokens.size();i++) { for (int i = 0;i < tokens.size();i++)
{
tokens.setElementAt(remove((String)tokens.elementAt(i), l, t), i); tokens.setElementAt(remove((String)tokens.elementAt(i), l, t), i);
} }
} }

View File

@@ -14,7 +14,8 @@ public class PSQLException extends SQLException
* This provides the same functionality to SQLException * This provides the same functionality to SQLException
* @param error Error string * @param error Error string
*/ */
public PSQLException(String error) { public PSQLException(String error)
{
super(); super();
translate(error, null); translate(error, null);
} }
@@ -52,7 +53,8 @@ public class PSQLException extends SQLException
Object[] argv = new Object[1]; Object[] argv = new Object[1];
try { try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(baos); PrintWriter pw = new PrintWriter(baos);
pw.println("Exception: " + ex.toString() + "\nStack Trace:\n"); pw.println("Exception: " + ex.toString() + "\nStack Trace:\n");
@@ -62,7 +64,9 @@ public class PSQLException extends SQLException
argv[0] = baos.toString(); argv[0] = baos.toString();
pw.close(); pw.close();
baos.close(); baos.close();
} catch(Exception ioe) { }
catch (Exception ioe)
{
argv[0] = ex.toString() + "\nIO Error on stack trace generation! " + ioe.toString(); argv[0] = ex.toString() + "\nIO Error on stack trace generation! " + ioe.toString();
} }
@@ -81,7 +85,8 @@ public class PSQLException extends SQLException
translate(error, argv); translate(error, argv);
} }
private void translate(String error, Object[] args) { private void translate(String error, Object[] args)
{
message = MessageTranslator.translate(error, args); message = MessageTranslator.translate(error, args);
} }

View File

@@ -125,13 +125,16 @@ public class Serialize
*/ */
public Serialize(org.postgresql.Connection c, String type) throws SQLException public Serialize(org.postgresql.Connection c, String type) throws SQLException
{ {
try { try
{
conn = c; conn = c;
DriverManager.println("Serialize: initializing instance for type: " + type); DriverManager.println("Serialize: initializing instance for type: " + type);
tableName = toPostgreSQL(type); tableName = toPostgreSQL(type);
className = type; className = type;
ourClass = Class.forName(className); ourClass = Class.forName(className);
} catch(ClassNotFoundException cnfe) { }
catch (ClassNotFoundException cnfe)
{
DriverManager.println("Serialize: " + className + " java class not found"); DriverManager.println("Serialize: " + className + " java class not found");
throw new PSQLException("postgresql.serial.noclass", type); throw new PSQLException("postgresql.serial.noclass", type);
} }
@@ -139,15 +142,18 @@ public class Serialize
// Second check, the type must be a table // Second check, the type must be a table
boolean status = false; boolean status = false;
ResultSet rs = conn.ExecSQL("select typname from pg_type,pg_class where typname=relname and typname='" + tableName + "'"); ResultSet rs = conn.ExecSQL("select typname from pg_type,pg_class where typname=relname and typname='" + tableName + "'");
if(rs!=null) { if (rs != null)
if(rs.next()) { {
if (rs.next())
{
status = true; status = true;
DriverManager.println("Serialize: " + tableName + " table found"); DriverManager.println("Serialize: " + tableName + " table found");
} }
rs.close(); rs.close();
} }
// This should never occur, as org.postgresql has it's own internal checks // This should never occur, as org.postgresql has it's own internal checks
if(!status) { if (!status)
{
DriverManager.println("Serialize: " + tableName + " table not found"); DriverManager.println("Serialize: " + tableName + " table not found");
throw new PSQLException("postgresql.serial.table", type); throw new PSQLException("postgresql.serial.table", type);
} }
@@ -178,7 +184,8 @@ public class Serialize
*/ */
public Object fetch(int oid) throws SQLException public Object fetch(int oid) throws SQLException
{ {
try { try
{
DriverManager.println("Serialize.fetch: " + "attempting to instantiate object of type: " + ourClass.getName() ); DriverManager.println("Serialize.fetch: " + "attempting to instantiate object of type: " + ourClass.getName() );
Object obj = ourClass.newInstance(); Object obj = ourClass.newInstance();
DriverManager.println("Serialize.fetch: " + "instantiated object of type: " + ourClass.getName() ); DriverManager.println("Serialize.fetch: " + "instantiated object of type: " + ourClass.getName() );
@@ -195,9 +202,11 @@ public class Serialize
StringBuffer sb = new StringBuffer("select"); StringBuffer sb = new StringBuffer("select");
char sep = ' '; char sep = ' ';
// build a select for the fields. Look for the oid field to use in the where // build a select for the fields. Look for the oid field to use in the where
for(int i=0;i<f.length;i++) { for (int i = 0;i < f.length;i++)
{
String n = f[i].getName(); String n = f[i].getName();
if(n.equals("oid")) { if (n.equals("oid"))
{
hasOID = true; hasOID = true;
oidFIELD = i; oidFIELD = i;
} }
@@ -213,32 +222,47 @@ public class Serialize
DriverManager.println("Serialize.fetch: " + sb.toString()); DriverManager.println("Serialize.fetch: " + sb.toString());
ResultSet rs = conn.ExecSQL(sb.toString()); ResultSet rs = conn.ExecSQL(sb.toString());
if(rs!=null) { if (rs != null)
if(rs.next()) { {
for(int i=0;i<f.length;i++) { if (rs.next())
if( !Modifier.isFinal(f[i].getModifiers()) ) { {
for (int i = 0;i < f.length;i++)
{
if ( !Modifier.isFinal(f[i].getModifiers()) )
{
if ( f[i].getType().getName().equals("short") ) if ( f[i].getType().getName().equals("short") )
f[i].setShort(obj, rs.getShort(i + 1)); f[i].setShort(obj, rs.getShort(i + 1));
else if ( f[i].getType().getName().equals("char") ) else if ( f[i].getType().getName().equals("char") )
f[i].setChar(obj, rs.getString(i + 1).toCharArray()[0]); f[i].setChar(obj, rs.getString(i + 1).toCharArray()[0]);
else if ( f[i].getType().getName().equals("byte")) else if ( f[i].getType().getName().equals("byte"))
f[i].setByte(obj, rs.getByte(i + 1)); f[i].setByte(obj, rs.getByte(i + 1));
else if( f[i].getType().getName().equals("boolean") ) { else if ( f[i].getType().getName().equals("boolean") )
{
// booleans come out of pgsql as a t or an f // booleans come out of pgsql as a t or an f
if( rs.getString(i+1).equals("t") ) f[i].setBoolean(obj, true); if ( rs.getString(i + 1).equals("t") )
else f[i].setBoolean(obj, false); f[i].setBoolean(obj, true);
} else f[i].set(obj,rs.getObject(i+1)); else
f[i].setBoolean(obj, false);
}
else
f[i].set(obj, rs.getObject(i + 1));
} }
} }
} }
rs.close(); rs.close();
} else throw new PSQLException("postgresql.unexpected"); }
else
throw new PSQLException("postgresql.unexpected");
return obj; return obj;
} catch(IllegalAccessException iae) { }
catch (IllegalAccessException iae)
{
throw new SQLException(iae.toString()); throw new SQLException(iae.toString());
} catch(InstantiationException ie) { }
catch (InstantiationException ie)
{
throw new SQLException(ie.toString()); throw new SQLException(ie.toString());
} }
} }
@@ -263,7 +287,8 @@ public class Serialize
*/ */
public int store(Object o) throws SQLException public int store(Object o) throws SQLException
{ {
try { try
{
// NB: we use java.lang.reflect here to prevent confusion with // NB: we use java.lang.reflect here to prevent confusion with
// the org.postgresql.Field // the org.postgresql.Field
@@ -275,9 +300,11 @@ public class Serialize
boolean update = false; boolean update = false;
// Find out if we have an oid value // Find out if we have an oid value
for(int i=0;i<f.length;i++) { for (int i = 0;i < f.length;i++)
{
String n = f[i].getName(); String n = f[i].getName();
if(n.equals("oid")) { if (n.equals("oid"))
{
hasOID = true; hasOID = true;
oidFIELD = i; oidFIELD = i;
// Do update if oid != 0 // Do update if oid != 0
@@ -287,50 +314,64 @@ public class Serialize
StringBuffer sb = new StringBuffer(update ? "update " + tableName + " set" : "insert into " + tableName + " "); StringBuffer sb = new StringBuffer(update ? "update " + tableName + " set" : "insert into " + tableName + " ");
char sep = update ? ' ' : '('; char sep = update ? ' ' : '(';
for(int i=0;i<f.length;i++) { for (int i = 0;i < f.length;i++)
{
String n = f[i].getName(); String n = f[i].getName();
// oid cannot be updated! // oid cannot be updated!
if( n.equals("oid") ) continue; if ( n.equals("oid") )
continue;
sb.append(sep); sb.append(sep);
sep = ','; sep = ',';
sb.append(n); sb.append(n);
if(update) { if (update)
{
sb.append('='); sb.append('=');
// handle unset values // handle unset values
if (f[i].get(o) == null) if (f[i].get(o) == null)
sb.append("null"); sb.append("null");
else if ( else if (
f[i].getType().getName().equals("java.lang.String") f[i].getType().getName().equals("java.lang.String")
|| f[i].getType().getName().equals("char") ) { || f[i].getType().getName().equals("char") )
{
sb.append('\''); sb.append('\'');
// don't allow single qoutes or newlines in the string // don't allow single qoutes or newlines in the string
sb.append(fixString(f[i].get(o).toString())); sb.append(fixString(f[i].get(o).toString()));
sb.append('\''); sb.append('\'');
} else sb.append(f[i].get(o).toString()); }
else
sb.append(f[i].get(o).toString());
} }
} }
if(update) sb.append(" where oid = " + f[oidFIELD].getInt(o) ); if (update)
sb.append(" where oid = " + f[oidFIELD].getInt(o) );
if(!update) { if (!update)
{
sb.append(") values "); sb.append(") values ");
sep = '('; sep = '(';
for(int i=0;i<f.length;i++) { for (int i = 0;i < f.length;i++)
{
String n = f[i].getName(); String n = f[i].getName();
// oid cannot be set! // oid cannot be set!
if( n.equals("oid") ) continue; if ( n.equals("oid") )
continue;
sb.append(sep); sb.append(sep);
sep = ','; sep = ',';
// handle unset values // handle unset values
if (f[i].get(o) == null) sb.append("null"); if (f[i].get(o) == null)
sb.append("null");
else if ( else if (
f[i].getType().getName().equals("java.lang.String") f[i].getType().getName().equals("java.lang.String")
|| f[i].getType().getName().equals("char")) { || f[i].getType().getName().equals("char"))
{
sb.append('\''); sb.append('\'');
// don't allow single quotes or newlines in the string // don't allow single quotes or newlines in the string
sb.append(fixString(f[i].get(o).toString())); sb.append(fixString(f[i].get(o).toString()));
sb.append('\''); sb.append('\'');
} else sb.append(f[i].get(o).toString()); }
else
sb.append(f[i].get(o).toString());
} }
sb.append(')'); sb.append(')');
} }
@@ -339,21 +380,28 @@ public class Serialize
org.postgresql.ResultSet rs = (org.postgresql.ResultSet) conn.ExecSQL(sb.toString()); org.postgresql.ResultSet rs = (org.postgresql.ResultSet) conn.ExecSQL(sb.toString());
// fetch the OID for returning // fetch the OID for returning
if(update) { if (update)
{
// object has oid already, so return it // object has oid already, so return it
if(rs!=null) rs.close(); if (rs != null)
rs.close();
return f[oidFIELD].getInt(o); return f[oidFIELD].getInt(o);
} else { }
else
{
// new record inserted has new oid; rs should be not null // new record inserted has new oid; rs should be not null
int newOID = ((org.postgresql.ResultSet)rs).getInsertedOID(); int newOID = ((org.postgresql.ResultSet)rs).getInsertedOID();
rs.close(); rs.close();
// update the java object's oid field if it has the oid field // update the java object's oid field if it has the oid field
if(hasOID) f[oidFIELD].setInt(o,newOID); if (hasOID)
f[oidFIELD].setInt(o, newOID);
// new object stored, return newly inserted oid // new object stored, return newly inserted oid
return newOID; return newOID;
} }
} catch(IllegalAccessException iae) { }
catch (IllegalAccessException iae)
{
throw new SQLException(iae.toString()); throw new SQLException(iae.toString());
} }
} }
@@ -363,7 +411,8 @@ public class Serialize
* Otherwise, postgres will bomb on the single quote and remove the * Otherwise, postgres will bomb on the single quote and remove the
* the backslashes. * the backslashes.
*/ */
private String fixString(String s) { private String fixString(String s)
{
int idx = -1; int idx = -1;
// handle null // handle null
@@ -371,11 +420,13 @@ public class Serialize
return ""; return "";
// if the string has single quotes in it escape them as '' // if the string has single quotes in it escape them as ''
if ((idx = s.indexOf("'")) > -1) { if ((idx = s.indexOf("'")) > -1)
{
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
StringTokenizer tok = new StringTokenizer(s, "'"); StringTokenizer tok = new StringTokenizer(s, "'");
// handle quote as 1St charater // handle quote as 1St charater
if (idx > 0) buf.append(tok.nextToken()); if (idx > 0)
buf.append(tok.nextToken());
while (tok.hasMoreTokens()) while (tok.hasMoreTokens())
buf.append("''").append(tok.nextToken()); buf.append("''").append(tok.nextToken());
@@ -384,10 +435,12 @@ public class Serialize
} }
// if the string has backslashes in it escape them them as \\ // if the string has backslashes in it escape them them as \\
if ((idx = s.indexOf("\\")) > -1) { if ((idx = s.indexOf("\\")) > -1)
{
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
StringTokenizer tok = new StringTokenizer(s, "\\"); StringTokenizer tok = new StringTokenizer(s, "\\");
if (idx > 0) buf.append(tok.nextToken()); if (idx > 0)
buf.append(tok.nextToken());
while (tok.hasMoreTokens()) while (tok.hasMoreTokens())
buf.append("\\\\").append(tok.nextToken()); buf.append("\\\\").append(tok.nextToken());
@@ -421,13 +474,15 @@ public class Serialize
*/ */
public static void create(org.postgresql.Connection con, Class c) throws SQLException public static void create(org.postgresql.Connection con, Class c) throws SQLException
{ {
if(c.isInterface()) throw new PSQLException("postgresql.serial.interface"); if (c.isInterface())
throw new PSQLException("postgresql.serial.interface");
// See if the table exists // See if the table exists
String tableName = toPostgreSQL(c.getName()); String tableName = toPostgreSQL(c.getName());
ResultSet rs = con.ExecSQL("select relname from pg_class where relname = '" + tableName + "'"); ResultSet rs = con.ExecSQL("select relname from pg_class where relname = '" + tableName + "'");
if( rs.next() ) { if ( rs.next() )
{
DriverManager.println("Serialize.create: table " + tableName + " exists, skipping"); DriverManager.println("Serialize.create: table " + tableName + " exists, skipping");
rs.close(); rs.close();
return ; return ;
@@ -444,25 +499,33 @@ public class Serialize
// java.lang.reflect.Field[] fields = c.getDeclaredFields(); // java.lang.reflect.Field[] fields = c.getDeclaredFields();
// Only store public fields, another limitation! // Only store public fields, another limitation!
java.lang.reflect.Field[] fields = c.getFields(); java.lang.reflect.Field[] fields = c.getFields();
for(int i=0;i<fields.length;i++) { for (int i = 0;i < fields.length;i++)
{
Class type = fields[i].getType(); Class type = fields[i].getType();
// oid is a special field // oid is a special field
if(!fields[i].getName().equals("oid")) { if (!fields[i].getName().equals("oid"))
{
sb.append(sep); sb.append(sep);
sb.append(fields[i].getName()); sb.append(fields[i].getName());
sb.append(' '); sb.append(' ');
sep = ','; sep = ',';
if(type.isArray()) { if (type.isArray())
{
// array handling // array handling
} else { }
else
{
// convert the java type to org.postgresql, recursing if a class // convert the java type to org.postgresql, recursing if a class
// is found // is found
String n = type.getName(); String n = type.getName();
int j = 0; int j = 0;
for(;j<tp.length && !tp[j][0].equals(n);j++); for (;j < tp.length && !tp[j][0].equals(n);j++)
if(j<tp.length) sb.append(tp[j][1]); ;
else { if (j < tp.length)
sb.append(tp[j][1]);
else
{
create(con, type); create(con, type);
sb.append(toPostgreSQL(n)); sb.append(toPostgreSQL(n));
} }
@@ -520,7 +583,8 @@ public class Serialize
// then just use the class name. If the class name is // then just use the class name. If the class name is
// too long throw an exception. // too long throw an exception.
// //
if( name.length() > 31 ) { if ( name.length() > 31 )
{
name = name.substring(name.lastIndexOf(".") + 1); name = name.substring(name.lastIndexOf(".") + 1);
if ( name.length() > 31 ) if ( name.length() > 31 )
throw new PSQLException("postgresql.serial.namelength", name, new Integer(name.length())); throw new PSQLException("postgresql.serial.namelength", name, new Integer(name.length()));

View File

@@ -17,8 +17,7 @@ public class UnixCrypt extends Object
// //
// Null constructor - can't instantiate class // Null constructor - can't instantiate class
private UnixCrypt() private UnixCrypt()
{ {}
}
private static final char[] saltChars = private static final char[] saltChars =
("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./".toCharArray()); ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./".toCharArray());
@@ -434,19 +433,23 @@ public class UnixCrypt extends Object
int results[] = new int[2]; int results[] = new int[2];
PERM_OP(d, c, 4, 0x0f0f0f0f, results); PERM_OP(d, c, 4, 0x0f0f0f0f, results);
d = results[0]; c = results[1]; d = results[0];
c = results[1];
c = HPERM_OP(c, -2, 0xcccc0000); c = HPERM_OP(c, -2, 0xcccc0000);
d = HPERM_OP(d, -2, 0xcccc0000); d = HPERM_OP(d, -2, 0xcccc0000);
PERM_OP(d, c, 1, 0x55555555, results); PERM_OP(d, c, 1, 0x55555555, results);
d = results[0]; c = results[1]; d = results[0];
c = results[1];
PERM_OP(c, d, 8, 0x00ff00ff, results); PERM_OP(c, d, 8, 0x00ff00ff, results);
c = results[0]; d = results[1]; c = results[0];
d = results[1];
PERM_OP(d, c, 1, 0x55555555, results); PERM_OP(d, c, 1, 0x55555555, results);
d = results[0]; c = results[1]; d = results[0];
c = results[1];
d = (((d & 0x000000ff) << 16) | (d & 0x0000ff00) | d = (((d & 0x000000ff) << 16) | (d & 0x0000ff00) |
((d & 0x00ff0000) >>> 16) | ((c & 0xf0000000) >>> 4)); ((d & 0x00ff0000) >>> 16) | ((c & 0xf0000000) >>> 4));
@@ -546,23 +549,29 @@ public class UnixCrypt extends Object
int results[] = new int[2]; int results[] = new int[2];
PERM_OP(right, left, 1, 0x55555555, results); PERM_OP(right, left, 1, 0x55555555, results);
right = results[0]; left = results[1]; right = results[0];
left = results[1];
PERM_OP(left, right, 8, 0x00ff00ff, results); PERM_OP(left, right, 8, 0x00ff00ff, results);
left = results[0]; right = results[1]; left = results[0];
right = results[1];
PERM_OP(right, left, 2, 0x33333333, results); PERM_OP(right, left, 2, 0x33333333, results);
right = results[0]; left = results[1]; right = results[0];
left = results[1];
PERM_OP(left, right, 16, 0x0000ffff, results); PERM_OP(left, right, 16, 0x0000ffff, results);
left = results[0]; right = results[1]; left = results[0];
right = results[1];
PERM_OP(right, left, 4, 0x0f0f0f0f, results); PERM_OP(right, left, 4, 0x0f0f0f0f, results);
right = results[0]; left = results[1]; right = results[0];
left = results[1];
int out[] = new int[2]; int out[] = new int[2];
out[0] = left; out[1] = right; out[0] = left;
out[1] = right;
return (out); return (out);
} }

View File

@@ -40,7 +40,7 @@
* *
* Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved. * Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved.
* *
* $Id: ClientConnection.java,v 1.1 2000/04/17 20:07:55 peter Exp $ * $Id: ClientConnection.java,v 1.2 2001/10/25 06:00:05 momjian Exp $
*/ */
@@ -116,9 +116,12 @@ final class ClientConnection
public Statement createStatement() public Statement createStatement()
throws SQLException throws SQLException
{ {
try { try
{
return getUnderlying().createStatement(); return getUnderlying().createStatement();
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -128,9 +131,12 @@ final class ClientConnection
public Statement createStatement( int resultSetType, int resultSetConcurrency ) public Statement createStatement( int resultSetType, int resultSetConcurrency )
throws SQLException throws SQLException
{ {
try { try
{
return getUnderlying().createStatement( resultSetType, resultSetConcurrency ); return getUnderlying().createStatement( resultSetType, resultSetConcurrency );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -140,9 +146,12 @@ final class ClientConnection
public PreparedStatement prepareStatement( String sql ) public PreparedStatement prepareStatement( String sql )
throws SQLException throws SQLException
{ {
try { try
{
return getUnderlying().prepareStatement( sql ); return getUnderlying().prepareStatement( sql );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -152,9 +161,12 @@ final class ClientConnection
public PreparedStatement prepareStatement( String sql, int resultSetType, int resultSetConcurrency ) public PreparedStatement prepareStatement( String sql, int resultSetType, int resultSetConcurrency )
throws SQLException throws SQLException
{ {
try { try
{
return getUnderlying().prepareStatement( sql, resultSetType, resultSetConcurrency ); return getUnderlying().prepareStatement( sql, resultSetType, resultSetConcurrency );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -164,9 +176,12 @@ final class ClientConnection
public CallableStatement prepareCall( String sql ) public CallableStatement prepareCall( String sql )
throws SQLException throws SQLException
{ {
try { try
{
return getUnderlying().prepareCall( sql ); return getUnderlying().prepareCall( sql );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -176,9 +191,12 @@ final class ClientConnection
public CallableStatement prepareCall( String sql, int resultSetType, int resultSetConcurrency ) public CallableStatement prepareCall( String sql, int resultSetType, int resultSetConcurrency )
throws SQLException throws SQLException
{ {
try { try
{
return getUnderlying().prepareCall( sql, resultSetType, resultSetConcurrency ); return getUnderlying().prepareCall( sql, resultSetType, resultSetConcurrency );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -188,9 +206,12 @@ final class ClientConnection
public String nativeSQL( String sql ) public String nativeSQL( String sql )
throws SQLException throws SQLException
{ {
try { try
{
return getUnderlying().nativeSQL( sql ); return getUnderlying().nativeSQL( sql );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -200,9 +221,12 @@ final class ClientConnection
public DatabaseMetaData getMetaData() public DatabaseMetaData getMetaData()
throws SQLException throws SQLException
{ {
try { try
{
return getUnderlying().getMetaData(); return getUnderlying().getMetaData();
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -212,9 +236,12 @@ final class ClientConnection
public void setCatalog( String catalog ) public void setCatalog( String catalog )
throws SQLException throws SQLException
{ {
try { try
{
getUnderlying().setCatalog( catalog ); getUnderlying().setCatalog( catalog );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -224,9 +251,12 @@ final class ClientConnection
public String getCatalog() public String getCatalog()
throws SQLException throws SQLException
{ {
try { try
{
return getUnderlying().getCatalog(); return getUnderlying().getCatalog();
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -236,9 +266,12 @@ final class ClientConnection
public SQLWarning getWarnings() public SQLWarning getWarnings()
throws SQLException throws SQLException
{ {
try { try
{
return getUnderlying().getWarnings(); return getUnderlying().getWarnings();
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -248,9 +281,12 @@ final class ClientConnection
public void clearWarnings() public void clearWarnings()
throws SQLException throws SQLException
{ {
try { try
{
getUnderlying().clearWarnings(); getUnderlying().clearWarnings();
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -260,9 +296,12 @@ final class ClientConnection
public Map getTypeMap() public Map getTypeMap()
throws SQLException throws SQLException
{ {
try { try
{
return getUnderlying().getTypeMap(); return getUnderlying().getTypeMap();
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -272,9 +311,12 @@ final class ClientConnection
public void setTypeMap( Map map ) public void setTypeMap( Map map )
throws SQLException throws SQLException
{ {
try { try
{
getUnderlying().setTypeMap( map ); getUnderlying().setTypeMap( map );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -287,9 +329,12 @@ final class ClientConnection
// Cannot set auto-commit inside a transaction. // Cannot set auto-commit inside a transaction.
if ( _xaConn.insideGlobalTx() ) if ( _xaConn.insideGlobalTx() )
throw new SQLException( "Cannot commit/rollback a connection managed by the transaction manager" ); throw new SQLException( "Cannot commit/rollback a connection managed by the transaction manager" );
try { try
{
getUnderlying().setAutoCommit( autoCommit ); getUnderlying().setAutoCommit( autoCommit );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -299,9 +344,12 @@ final class ClientConnection
public boolean getAutoCommit() public boolean getAutoCommit()
throws SQLException throws SQLException
{ {
try { try
{
return getUnderlying().getAutoCommit(); return getUnderlying().getAutoCommit();
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -319,9 +367,12 @@ final class ClientConnection
throw new SQLException( "Cannot commit/rollback a read-only transaction" ); throw new SQLException( "Cannot commit/rollback a read-only transaction" );
// This only occurs if not inside a local transaction. // This only occurs if not inside a local transaction.
try { try
{
getUnderlying().commit(); getUnderlying().commit();
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -337,9 +388,12 @@ final class ClientConnection
throw new SQLException( "Cannot commit/rollback a connection managed by the transaction manager" ); throw new SQLException( "Cannot commit/rollback a connection managed by the transaction manager" );
// This only occurs if not inside a local transaction. // This only occurs if not inside a local transaction.
try { try
{
getUnderlying().rollback(); getUnderlying().rollback();
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -349,9 +403,12 @@ final class ClientConnection
public void setReadOnly( boolean readOnly ) public void setReadOnly( boolean readOnly )
throws SQLException throws SQLException
{ {
try { try
{
getUnderlying().setReadOnly( readOnly ); getUnderlying().setReadOnly( readOnly );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -361,9 +418,12 @@ final class ClientConnection
public boolean isReadOnly() public boolean isReadOnly()
throws SQLException throws SQLException
{ {
try { try
{
return getUnderlying().isReadOnly(); return getUnderlying().isReadOnly();
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -373,9 +433,12 @@ final class ClientConnection
public void setTransactionIsolation( int level ) public void setTransactionIsolation( int level )
throws SQLException throws SQLException
{ {
try { try
{
getUnderlying().setTransactionIsolation( level ); getUnderlying().setTransactionIsolation( level );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -385,9 +448,12 @@ final class ClientConnection
public int getTransactionIsolation() public int getTransactionIsolation()
throws SQLException throws SQLException
{ {
try { try
{
return getUnderlying().getTransactionIsolation(); return getUnderlying().getTransactionIsolation();
} catch ( SQLException except ) { }
catch ( SQLException except )
{
notifyError( except ); notifyError( except );
throw except; throw except;
} }
@@ -443,9 +509,12 @@ final class ClientConnection
public String toString() public String toString()
{ {
try { try
{
return getUnderlying().toString(); return getUnderlying().toString();
} catch ( SQLException except ) { }
catch ( SQLException except )
{
return "XAConnection: Connection closed"; return "XAConnection: Connection closed";
} }
} }
@@ -480,9 +549,12 @@ final class ClientConnection
// Must pass the client identifier so XAConnection can determine // Must pass the client identifier so XAConnection can determine
// whether we are still valid. If it tells us we're no longer // whether we are still valid. If it tells us we're no longer
// valid, we have little to do. // valid, we have little to do.
try { try
{
return _xaConn.getUnderlying( _clientId ); return _xaConn.getUnderlying( _clientId );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
_xaConn = null; _xaConn = null;
throw except; throw except;
} }

View File

@@ -40,7 +40,7 @@
* *
* Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved. * Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved.
* *
* $Id: TwoPhaseConnection.java,v 1.1 2000/04/17 20:07:55 peter Exp $ * $Id: TwoPhaseConnection.java,v 1.2 2001/10/25 06:00:05 momjian Exp $
*/ */

View File

@@ -40,7 +40,7 @@
* *
* Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved. * Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved.
* *
* $Id: TxConnection.java,v 1.1 2000/04/17 20:07:56 peter Exp $ * $Id: TxConnection.java,v 1.2 2001/10/25 06:00:05 momjian Exp $
*/ */

View File

@@ -40,7 +40,7 @@
* *
* Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved. * Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved.
* *
* $Id: XAConnectionImpl.java,v 1.1 2000/04/17 20:07:56 peter Exp $ * $Id: XAConnectionImpl.java,v 1.2 2001/10/25 06:00:05 momjian Exp $
*/ */
@@ -185,16 +185,25 @@ public final class XAConnectionImpl
// is no longer useable. This method can be called any number // is no longer useable. This method can be called any number
// of times (e.g. we use it in finalizer). We do not handle // of times (e.g. we use it in finalizer). We do not handle
// transactions, we just kill the connection. // transactions, we just kill the connection.
try { try
if ( _underlying != null ) { {
if ( _underlying != null )
{
_underlying.commit(); _underlying.commit();
_underlying.close(); _underlying.close();
} else if ( _txConn != null ) {
try {
end( _txConn.xid, TMSUCCESS );
} catch ( XAException except ) { }
} }
} finally { else if ( _txConn != null )
{
try
{
end( _txConn.xid, TMSUCCESS );
}
catch ( XAException except )
{ }
}
}
finally
{
_resManager = null; _resManager = null;
_underlying = null; _underlying = null;
_txConn = null; _txConn = null;
@@ -250,13 +259,18 @@ public final class XAConnectionImpl
// If we are part of a global transaction we hope that end/ // If we are part of a global transaction we hope that end/
// start were called properly, but we're not longer in that // start were called properly, but we're not longer in that
// transaction. // transaction.
if ( _underlying != null ) { if ( _underlying != null )
try { {
try
{
_underlying.commit(); _underlying.commit();
} catch ( SQLException except ) { }
catch ( SQLException except )
{
ConnectionEvent event; ConnectionEvent event;
if ( _listener != null ) { if ( _listener != null )
{
event = new ConnectionEvent( this, except ); event = new ConnectionEvent( this, except );
_listener.connectionErrorOccurred( event ); _listener.connectionErrorOccurred( event );
} }
@@ -302,11 +316,16 @@ public final class XAConnectionImpl
// old transaction and are ready to work for a new one. // old transaction and are ready to work for a new one.
// If we are part of a global transaction we hope that end/ // If we are part of a global transaction we hope that end/
// start were called properly. // start were called properly.
if ( _underlying != null ) { if ( _underlying != null )
try { {
try
{
_underlying.commit(); _underlying.commit();
} catch ( SQLException except ) { }
if ( _listener != null ) { catch ( SQLException except )
{
if ( _listener != null )
{
event = new ConnectionEvent( this, except ); event = new ConnectionEvent( this, except );
_listener.connectionErrorOccurred( event ); _listener.connectionErrorOccurred( event );
} }
@@ -314,7 +333,8 @@ public final class XAConnectionImpl
} }
} }
// Notify the listener. // Notify the listener.
if ( _listener != null ) { if ( _listener != null )
{
event = new ConnectionEvent( this ); event = new ConnectionEvent( this );
_listener.connectionClosed( event ); _listener.connectionClosed( event );
} }
@@ -340,7 +360,8 @@ public final class XAConnectionImpl
// If the connection is not two-phase commit we cannot determine // If the connection is not two-phase commit we cannot determine
// whether the error is critical, we just return. If the connection // whether the error is critical, we just return. If the connection
// is two phase commit, but the error is not critical, we return. // is two phase commit, but the error is not critical, we return.
if ( _underlying != null ) { if ( _underlying != null )
{
if ( ! ( _underlying instanceof TwoPhaseConnection ) || if ( ! ( _underlying instanceof TwoPhaseConnection ) ||
! ( (TwoPhaseConnection) _underlying ).isCriticalError( except ) ) ! ( (TwoPhaseConnection) _underlying ).isCriticalError( except ) )
return ; return ;
@@ -355,24 +376,34 @@ public final class XAConnectionImpl
// is rolledback and this connection dies (but close() may // is rolledback and this connection dies (but close() may
// still be called). // still be called).
++_clientId; ++_clientId;
if ( _underlying != null ) { if ( _underlying != null )
try { {
try
{
_underlying.close(); _underlying.close();
} catch ( SQLException e2 ) { }
catch ( SQLException e2 )
{
// Ignore that, we know there's an error. // Ignore that, we know there's an error.
} }
_underlying = null; _underlying = null;
} else if ( _txConn != null ) { }
try { else if ( _txConn != null )
{
try
{
end( _txConn.xid, TMFAIL ); end( _txConn.xid, TMFAIL );
} catch ( XAException e2 ) { }
catch ( XAException e2 )
{
// Ignore that, we know there's an error. // Ignore that, we know there's an error.
} }
_txConn = null; _txConn = null;
} }
// Notify the listener. // Notify the listener.
if ( _listener != null ) { if ( _listener != null )
{
event = new ConnectionEvent( this, except ); event = new ConnectionEvent( this, except );
_listener.connectionErrorOccurred( event ); _listener.connectionErrorOccurred( event );
} }
@@ -406,8 +437,10 @@ public final class XAConnectionImpl
if ( _txConn != null ) if ( _txConn != null )
throw new XAException( XAException.XAER_OUTSIDE ); throw new XAException( XAException.XAER_OUTSIDE );
synchronized ( _resManager ) { synchronized ( _resManager )
if ( flags == TMNOFLAGS ) { {
if ( flags == TMNOFLAGS )
{
// Starting a new transaction. First, make sure it is // Starting a new transaction. First, make sure it is
// not shared with any other connection (need to join // not shared with any other connection (need to join
// for that). // for that).
@@ -418,19 +451,24 @@ public final class XAConnectionImpl
// connection in the context of a transaction and // connection in the context of a transaction and
// register it with the resource manager so it can // register it with the resource manager so it can
// be shared. // be shared.
try { try
{
_txConn = new TxConnection(); _txConn = new TxConnection();
if ( _underlying != null ) { if ( _underlying != null )
{
_txConn.conn = _underlying; _txConn.conn = _underlying;
_underlying = null; _underlying = null;
} else }
else
_txConn.conn = _resManager.newConnection(); _txConn.conn = _resManager.newConnection();
_txConn.xid = xid; _txConn.xid = xid;
_txConn.count = 1; _txConn.count = 1;
_txConn.started = System.currentTimeMillis(); _txConn.started = System.currentTimeMillis();
_txConn.timeout = _txConn.started + ( _resManager.getTransactionTimeout() * 1000 ); _txConn.timeout = _txConn.started + ( _resManager.getTransactionTimeout() * 1000 );
_resManager.setTxConnection( xid, _txConn ); _resManager.setTxConnection( xid, _txConn );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
// If error occured at this point, we can only // If error occured at this point, we can only
// report it as resource manager error. // report it as resource manager error.
if ( _resManager.getLogWriter() != null ) if ( _resManager.getLogWriter() != null )
@@ -438,25 +476,33 @@ public final class XAConnectionImpl
throw new XAException( XAException.XAER_RMERR ); throw new XAException( XAException.XAER_RMERR );
} }
try { try
{
_txConn.conn.setAutoCommit( false ); _txConn.conn.setAutoCommit( false );
try { try
{
if ( _resManager.isolationLevel() != Connection.TRANSACTION_NONE ) if ( _resManager.isolationLevel() != Connection.TRANSACTION_NONE )
_txConn.conn.setTransactionIsolation( _resManager.isolationLevel() ); _txConn.conn.setTransactionIsolation( _resManager.isolationLevel() );
} catch ( SQLException e ) { }
catch ( SQLException e )
{
// The underlying driver might not support this // The underlying driver might not support this
// isolation level that we use by default. // isolation level that we use by default.
} }
if ( _txConn.conn instanceof TwoPhaseConnection ) if ( _txConn.conn instanceof TwoPhaseConnection )
( (TwoPhaseConnection) _txConn.conn ).enableSQLTransactions( false ); ( (TwoPhaseConnection) _txConn.conn ).enableSQLTransactions( false );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
// If error occured at this point, we can only // If error occured at this point, we can only
// report it as resource manager error. // report it as resource manager error.
if ( _resManager.getLogWriter() != null ) if ( _resManager.getLogWriter() != null )
_resManager.getLogWriter().println( "XAConnection: failed to begin a transaction: " + except ); _resManager.getLogWriter().println( "XAConnection: failed to begin a transaction: " + except );
throw new XAException( XAException.XAER_RMERR ); throw new XAException( XAException.XAER_RMERR );
} }
} else if ( flags == TMJOIN || flags == TMRESUME ) { }
else if ( flags == TMJOIN || flags == TMRESUME )
{
// We are joining another transaction with an // We are joining another transaction with an
// existing TxConnection. // existing TxConnection.
_txConn = _resManager.getTxConnection( xid ); _txConn = _resManager.getTxConnection( xid );
@@ -472,11 +518,13 @@ public final class XAConnectionImpl
// If we already have an underlying connection (as we can // If we already have an underlying connection (as we can
// expect to), we should release that underlying connection // expect to), we should release that underlying connection
// and make it available to the resource manager. // and make it available to the resource manager.
if ( _underlying != null ) { if ( _underlying != null )
{
_resManager.releaseConnection( _underlying ); _resManager.releaseConnection( _underlying );
_underlying = null; _underlying = null;
} }
} else }
else
// No other flags supported in start(). // No other flags supported in start().
throw new XAException( XAException.XAER_INVAL ); throw new XAException( XAException.XAER_INVAL );
} }
@@ -494,8 +542,10 @@ public final class XAConnectionImpl
if ( _txConn == null && flags == TMSUSPEND ) if ( _txConn == null && flags == TMSUSPEND )
throw new XAException( XAException.XAER_NOTA ); throw new XAException( XAException.XAER_NOTA );
synchronized ( _resManager ) { synchronized ( _resManager )
if ( flags == TMSUCCESS || flags == TMFAIL) { {
if ( flags == TMSUCCESS || flags == TMFAIL)
{
// We are now leaving a transaction we started or // We are now leaving a transaction we started or
// joined before. We can expect any of prepare/ // joined before. We can expect any of prepare/
// commit/rollback to be called next, so TxConnection // commit/rollback to be called next, so TxConnection
@@ -505,11 +555,14 @@ public final class XAConnectionImpl
// join it for the duration of this operation. // join it for the duration of this operation.
// Make sure the reference count reaches zero by the // Make sure the reference count reaches zero by the
// time we get to prepare. // time we get to prepare.
if ( _txConn == null ) { if ( _txConn == null )
{
_txConn = _resManager.getTxConnection( xid ); _txConn = _resManager.getTxConnection( xid );
if ( _txConn == null ) if ( _txConn == null )
throw new XAException( XAException.XAER_NOTA ); throw new XAException( XAException.XAER_NOTA );
} else { }
else
{
if ( _txConn.xid != null && ! _txConn.xid.equals( xid ) ) if ( _txConn.xid != null && ! _txConn.xid.equals( xid ) )
throw new XAException( XAException.XAER_NOTA ); throw new XAException( XAException.XAER_NOTA );
--_txConn.count; --_txConn.count;
@@ -519,13 +572,17 @@ public final class XAConnectionImpl
// transaction and release the underlying connection. // transaction and release the underlying connection.
// We can expect all other resources to recieved the // We can expect all other resources to recieved the
// same end notification. We don't expect forget to happen. // same end notification. We don't expect forget to happen.
if ( flags == TMFAIL && _txConn.conn != null ) { if ( flags == TMFAIL && _txConn.conn != null )
try { {
try
{
if ( _txConn.conn instanceof TwoPhaseConnection ) if ( _txConn.conn instanceof TwoPhaseConnection )
( (TwoPhaseConnection) _txConn.conn ).enableSQLTransactions( true ); ( (TwoPhaseConnection) _txConn.conn ).enableSQLTransactions( true );
_txConn.conn.rollback(); _txConn.conn.rollback();
_resManager.releaseConnection( _txConn.conn ); _resManager.releaseConnection( _txConn.conn );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
// There is a problem with the underlying // There is a problem with the underlying
// connection, but it was not added to the poll. // connection, but it was not added to the poll.
} }
@@ -534,21 +591,25 @@ public final class XAConnectionImpl
_txConn.xid = null; _txConn.xid = null;
} }
if ( flags == TMSUCCESS) { if ( flags == TMSUCCESS)
{
// We should be looking for a new transaction. // We should be looking for a new transaction.
// Next thing we might be participating in a new // Next thing we might be participating in a new
// transaction while the current one is being // transaction while the current one is being
// rolled back. // rolled back.
_txConn = null; _txConn = null;
} }
} else if ( flags == TMSUSPEND ) { }
else if ( flags == TMSUSPEND )
{
// We no longer take part in this transaction. // We no longer take part in this transaction.
// Possibly we'll be asked to resume later on, but // Possibly we'll be asked to resume later on, but
// right now we have to forget about the transaction // right now we have to forget about the transaction
// and the underlying connection. // and the underlying connection.
--_txConn.count; --_txConn.count;
_txConn = null; _txConn = null;
} else }
else
// No other flags supported in end(). // No other flags supported in end().
throw new XAException( XAException.XAER_INVAL ); throw new XAException( XAException.XAER_INVAL );
} }
@@ -563,15 +624,18 @@ public final class XAConnectionImpl
// General checks. // General checks.
if ( xid == null ) if ( xid == null )
throw new XAException( XAException.XAER_INVAL ); throw new XAException( XAException.XAER_INVAL );
synchronized ( _resManager ) { synchronized ( _resManager )
{
// We have to forget about the transaction, meaning the // We have to forget about the transaction, meaning the
// transaction no longer exists for this or any other // transaction no longer exists for this or any other
// connection. We might be called multiple times. // connection. We might be called multiple times.
txConn = _resManager.setTxConnection( xid, null ); txConn = _resManager.setTxConnection( xid, null );
if ( _txConn == txConn ) if ( _txConn == txConn )
_txConn = null; _txConn = null;
if ( txConn != null ) { if ( txConn != null )
if ( txConn.conn != null ) { {
if ( txConn.conn != null )
{
_resManager.releaseConnection( txConn.conn ); _resManager.releaseConnection( txConn.conn );
txConn.conn = null; txConn.conn = null;
} }
@@ -590,7 +654,8 @@ public final class XAConnectionImpl
if ( xid == null ) if ( xid == null )
throw new XAException( XAException.XAER_INVAL ); throw new XAException( XAException.XAER_INVAL );
synchronized ( _resManager ) { synchronized ( _resManager )
{
// Technically, prepare may be called for any connection, // Technically, prepare may be called for any connection,
// not just this one. // not just this one.
txConn = _resManager.getTxConnection( xid ); txConn = _resManager.getTxConnection( xid );
@@ -612,36 +677,50 @@ public final class XAConnectionImpl
// Since there is no preparation mechanism in a generic // Since there is no preparation mechanism in a generic
// JDBC driver, we only test for read-only transaction // JDBC driver, we only test for read-only transaction
// but do not commit at this point. // but do not commit at this point.
try { try
{
txConn.prepared = true; txConn.prepared = true;
if ( txConn.conn instanceof TwoPhaseConnection ) { if ( txConn.conn instanceof TwoPhaseConnection )
{
// For 2pc connection we ask it to prepare and determine // For 2pc connection we ask it to prepare and determine
// whether it's commiting or read-only. If a rollback // whether it's commiting or read-only. If a rollback
// exception happens, we report it. // exception happens, we report it.
try { try
{
if ( ( (TwoPhaseConnection) txConn.conn ).prepare() ) if ( ( (TwoPhaseConnection) txConn.conn ).prepare() )
return XA_OK; return XA_OK;
else { else
{
txConn.readOnly = true; txConn.readOnly = true;
return XA_RDONLY; return XA_RDONLY;
} }
} catch ( SQLException except ) { }
catch ( SQLException except )
{
throw new XAException( XAException.XA_RBROLLBACK ); throw new XAException( XAException.XA_RBROLLBACK );
} }
} else { }
else
{
// For standard connection we cannot prepare, we can // For standard connection we cannot prepare, we can
// only guess if it's read only. // only guess if it's read only.
if ( txConn.conn.isReadOnly() ) { if ( txConn.conn.isReadOnly() )
{
txConn.readOnly = true; txConn.readOnly = true;
return XA_RDONLY; return XA_RDONLY;
} }
return XA_OK; return XA_OK;
} }
} catch ( SQLException except ) { }
try { catch ( SQLException except )
{
try
{
// Fatal error in the connection, kill it. // Fatal error in the connection, kill it.
txConn.conn.close(); txConn.conn.close();
} catch ( SQLException e ) { } }
catch ( SQLException e )
{ }
txConn.conn = null; txConn.conn = null;
if ( _resManager.getLogWriter() != null ) if ( _resManager.getLogWriter() != null )
_resManager.getLogWriter().println( "XAConnection: failed to commit a transaction: " + except ); _resManager.getLogWriter().println( "XAConnection: failed to commit a transaction: " + except );
@@ -655,7 +734,8 @@ public final class XAConnectionImpl
public Xid[] recover( int flags ) public Xid[] recover( int flags )
throws XAException throws XAException
{ {
synchronized ( _resManager ) { synchronized ( _resManager )
{
return _resManager.getTxRecover(); return _resManager.getTxRecover();
} }
} }
@@ -670,7 +750,8 @@ public final class XAConnectionImpl
if ( xid == null ) if ( xid == null )
throw new XAException( XAException.XAER_INVAL ); throw new XAException( XAException.XAER_INVAL );
synchronized ( _resManager ) { synchronized ( _resManager )
{
// Technically, commit may be called for any connection, // Technically, commit may be called for any connection,
// not just this one. // not just this one.
txConn = _resManager.getTxConnection( xid ); txConn = _resManager.getTxConnection( xid );
@@ -689,25 +770,34 @@ public final class XAConnectionImpl
// This must be a one-phase commite, or the connection // This must be a one-phase commite, or the connection
// should have been prepared before. // should have been prepared before.
if ( onePhase || txConn.prepared ) { if ( onePhase || txConn.prepared )
try { {
try
{
// Prevent multiple commit attempts. // Prevent multiple commit attempts.
txConn.readOnly = true; txConn.readOnly = true;
if ( txConn.conn instanceof TwoPhaseConnection ) if ( txConn.conn instanceof TwoPhaseConnection )
( (TwoPhaseConnection) txConn.conn ).enableSQLTransactions( true ); ( (TwoPhaseConnection) txConn.conn ).enableSQLTransactions( true );
txConn.conn.commit(); txConn.conn.commit();
} catch ( SQLException except ) { }
try { catch ( SQLException except )
{
try
{
// Unknown error in the connection, better kill it. // Unknown error in the connection, better kill it.
txConn.conn.close(); txConn.conn.close();
} catch ( SQLException e ) { } }
catch ( SQLException e )
{ }
txConn.conn = null; txConn.conn = null;
if ( _resManager.getLogWriter() != null ) if ( _resManager.getLogWriter() != null )
_resManager.getLogWriter().println( "XAConnection: failed to commit a transaction: " + except ); _resManager.getLogWriter().println( "XAConnection: failed to commit a transaction: " + except );
// If we cannot commit the transaction, a heuristic tollback. // If we cannot commit the transaction, a heuristic tollback.
throw new XAException( XAException.XA_HEURRB ); throw new XAException( XAException.XA_HEURRB );
} }
} else { }
else
{
// 2pc we should have prepared before. // 2pc we should have prepared before.
if ( ! txConn.prepared ) if ( ! txConn.prepared )
throw new XAException( XAException.XAER_PROTO ); throw new XAException( XAException.XAER_PROTO );
@@ -726,7 +816,8 @@ public final class XAConnectionImpl
if ( xid == null ) if ( xid == null )
throw new XAException( XAException.XAER_INVAL ); throw new XAException( XAException.XAER_INVAL );
synchronized ( _resManager ) { synchronized ( _resManager )
{
// Technically, rollback may be called for any connection, // Technically, rollback may be called for any connection,
// not just this one. // not just this one.
txConn = _resManager.getTxConnection( xid ); txConn = _resManager.getTxConnection( xid );
@@ -740,22 +831,30 @@ public final class XAConnectionImpl
if ( txConn.readOnly || txConn.conn == null ) if ( txConn.readOnly || txConn.conn == null )
return ; return ;
try { try
{
txConn.prepared = false; txConn.prepared = false;
if ( txConn.conn instanceof TwoPhaseConnection ) if ( txConn.conn instanceof TwoPhaseConnection )
( (TwoPhaseConnection) txConn.conn ).enableSQLTransactions( true ); ( (TwoPhaseConnection) txConn.conn ).enableSQLTransactions( true );
txConn.conn.rollback(); txConn.conn.rollback();
} catch ( SQLException except ) { }
try { catch ( SQLException except )
{
try
{
// Unknown error in the connection, better kill it. // Unknown error in the connection, better kill it.
txConn.conn.close(); txConn.conn.close();
} catch ( SQLException e ) { } }
catch ( SQLException e )
{ }
txConn.conn = null; txConn.conn = null;
if ( _resManager.getLogWriter() != null ) if ( _resManager.getLogWriter() != null )
_resManager.getLogWriter().println( "XAConnection: failed to rollback a transaction: " + except ); _resManager.getLogWriter().println( "XAConnection: failed to rollback a transaction: " + except );
// If we cannot commit the transaction, a heuristic tollback. // If we cannot commit the transaction, a heuristic tollback.
throw new XAException( XAException.XA_RBROLLBACK ); throw new XAException( XAException.XA_RBROLLBACK );
} finally { }
finally
{
forget( xid ); forget( xid );
} }
} }
@@ -785,7 +884,8 @@ public final class XAConnectionImpl
if ( seconds == 0 ) if ( seconds == 0 )
seconds = _resManager.getTransactionTimeout(); seconds = _resManager.getTransactionTimeout();
// If a transaction has started, change it's timeout to the new value. // If a transaction has started, change it's timeout to the new value.
if ( _txConn != null ) { if ( _txConn != null )
{
_txConn.timeout = _txConn.started + ( seconds * 1000 ); _txConn.timeout = _txConn.started + ( seconds * 1000 );
return true; return true;
} }
@@ -834,14 +934,16 @@ public final class XAConnectionImpl
if ( clientId != _clientId ) if ( clientId != _clientId )
throw new SQLException( "This application connection has been closed" ); throw new SQLException( "This application connection has been closed" );
if ( _txConn != null ) { if ( _txConn != null )
{
if ( _txConn.timedOut ) if ( _txConn.timedOut )
throw new SQLException( "The transaction has timed out and has been rolledback and closed" ); throw new SQLException( "The transaction has timed out and has been rolledback and closed" );
if ( _txConn.conn == null ) if ( _txConn.conn == null )
throw new SQLException( "The transaction has been terminated and this connection has been closed" ); throw new SQLException( "The transaction has been terminated and this connection has been closed" );
return _txConn.conn; return _txConn.conn;
} }
if ( _underlying == null ) { if ( _underlying == null )
{
_underlying = _resManager.newConnection(); _underlying = _resManager.newConnection();
_underlying.setAutoCommit( true ); _underlying.setAutoCommit( true );
} }

View File

@@ -40,7 +40,7 @@
* *
* Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved. * Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved.
* *
* $Id: XADataSourceImpl.java,v 1.1 2000/04/17 20:07:56 peter Exp $ * $Id: XADataSourceImpl.java,v 1.2 2001/10/25 06:00:05 momjian Exp $
*/ */
@@ -285,7 +285,8 @@ public abstract class XADataSourceImpl
Connection conn; Connection conn;
// Check in the pool first. // Check in the pool first.
if ( ! _pool.empty() ) { if ( ! _pool.empty() )
{
conn = (Connection) _pool.pop(); conn = (Connection) _pool.pop();
return conn; return conn;
} }
@@ -305,7 +306,8 @@ public abstract class XADataSourceImpl
list = new Vector(); list = new Vector();
enum = _txConnections.elements(); enum = _txConnections.elements();
while ( enum.hasMoreElements() ) { while ( enum.hasMoreElements() )
{
txConn = (TxConnection) enum.nextElement(); txConn = (TxConnection) enum.nextElement();
if ( txConn.conn != null && txConn.prepared ) if ( txConn.conn != null && txConn.prepared )
list.add( txConn.xid ); list.add( txConn.xid );
@@ -332,16 +334,20 @@ public abstract class XADataSourceImpl
long timeout; long timeout;
TxConnection txConn; TxConnection txConn;
while ( true ) { while ( true )
{
// Go to sleep for the duration of a transaction // Go to sleep for the duration of a transaction
// timeout. This mean transactions will timeout on average // timeout. This mean transactions will timeout on average
// at _txTimeout * 1.5. // at _txTimeout * 1.5.
try { try
{
Thread.sleep( _txTimeout * 1000 ); Thread.sleep( _txTimeout * 1000 );
} catch ( InterruptedException except ) {
} }
catch ( InterruptedException except )
{}
try { try
{
// Check to see if there are any pooled connections // Check to see if there are any pooled connections
// we can release. We release 10% of the pooled // we can release. We release 10% of the pooled
// connections each time, so in a heavy loaded // connections each time, so in a heavy loaded
@@ -350,41 +356,55 @@ public abstract class XADataSourceImpl
// pooled connections, but connections that happen to // pooled connections, but connections that happen to
// get in and out of a transaction, not that many. // get in and out of a transaction, not that many.
reduce = _pool.size() - ( _pool.size() / 10 ) - 1; reduce = _pool.size() - ( _pool.size() / 10 ) - 1;
if ( reduce >= 0 && _pool.size() > reduce ) { if ( reduce >= 0 && _pool.size() > reduce )
{
if ( getLogWriter() != null ) if ( getLogWriter() != null )
getLogWriter().println( "DataSource " + toString() + getLogWriter().println( "DataSource " + toString() +
": Reducing internal connection pool size from " + ": Reducing internal connection pool size from " +
_pool.size() + " to " + reduce ); _pool.size() + " to " + reduce );
while ( _pool.size() > reduce ) { while ( _pool.size() > reduce )
try { {
try
{
( (Connection) _pool.pop() ).close(); ( (Connection) _pool.pop() ).close();
} catch ( SQLException except ) { } }
catch ( SQLException except )
{ }
} }
} }
} catch ( Exception except ) { } }
catch ( Exception except )
{ }
// Look for all connections inside a transaction that // Look for all connections inside a transaction that
// should have timed out by now. // should have timed out by now.
timeout = System.currentTimeMillis(); timeout = System.currentTimeMillis();
enum = _txConnections.elements(); enum = _txConnections.elements();
while ( enum.hasMoreElements() ) { while ( enum.hasMoreElements() )
{
txConn = (TxConnection) enum.nextElement(); txConn = (TxConnection) enum.nextElement();
// If the transaction timed out, we roll it back and // If the transaction timed out, we roll it back and
// invalidate it, but do not remove it from the transaction // invalidate it, but do not remove it from the transaction
// list yet. We wait for the next iteration, minimizing the // list yet. We wait for the next iteration, minimizing the
// chance of a NOTA exception. // chance of a NOTA exception.
if ( txConn.conn == null ) { if ( txConn.conn == null )
{
_txConnections.remove( txConn.xid ); _txConnections.remove( txConn.xid );
// Chose not to use an iterator so we must // Chose not to use an iterator so we must
// re-enumerate the list after removing // re-enumerate the list after removing
// an element from it. // an element from it.
enum = _txConnections.elements(); enum = _txConnections.elements();
} else if ( txConn.timeout < timeout ) { }
else if ( txConn.timeout < timeout )
{
try { try
{
Connection underlying; Connection underlying;
synchronized ( txConn ) { synchronized ( txConn )
{
if ( txConn.conn == null ) if ( txConn.conn == null )
continue; continue;
if ( getLogWriter() != null ) if ( getLogWriter() != null )
@@ -402,19 +422,27 @@ public abstract class XADataSourceImpl
// Rollback the underlying connection to // Rollback the underlying connection to
// abort the transaction and release the // abort the transaction and release the
// underlying connection to the pool. // underlying connection to the pool.
try { try
{
underlying.rollback(); underlying.rollback();
releaseConnection( underlying ); releaseConnection( underlying );
} catch ( SQLException except ) { }
catch ( SQLException except )
{
if ( getLogWriter() != null ) if ( getLogWriter() != null )
getLogWriter().println( "DataSource " + toString() + getLogWriter().println( "DataSource " + toString() +
": Error aborting timed out transaction: " + except ); ": Error aborting timed out transaction: " + except );
try { try
{
underlying.close(); underlying.close();
} catch ( SQLException e2 ) { } }
catch ( SQLException e2 )
{ }
} }
} }
} catch ( Exception except ) { } }
catch ( Exception except )
{ }
} }
} }
@@ -433,7 +461,8 @@ public abstract class XADataSourceImpl
enum = _txConnections.elements(); enum = _txConnections.elements();
if ( ! enum.hasMoreElements() ) if ( ! enum.hasMoreElements() )
writer.println( "Empty" ); writer.println( "Empty" );
while ( enum.hasMoreElements() ) { while ( enum.hasMoreElements() )
{
buffer = new StringBuffer(); buffer = new StringBuffer();
txConn = (TxConnection) enum.nextElement(); txConn = (TxConnection) enum.nextElement();
buffer.append( "TxConnection " ); buffer.append( "TxConnection " );

View File

@@ -10,10 +10,14 @@ public class CheckVersion
/** /**
* Check for the existence of a class by attempting to load it * Check for the existence of a class by attempting to load it
*/ */
public static boolean checkClass(String c) { public static boolean checkClass(String c)
try { {
try
{
Class.forName(c); Class.forName(c);
} catch(Exception e) { }
catch (Exception e)
{
return false; return false;
} }
return true; return true;
@@ -44,7 +48,8 @@ public class CheckVersion
System.out.println("postgresql.jdbc=" + System.getProperty("postgresql.jdbc")); System.out.println("postgresql.jdbc=" + System.getProperty("postgresql.jdbc"));
// We are running a 1.1 JVM // We are running a 1.1 JVM
if(vmversion.startsWith("1.1")) { if (vmversion.startsWith("1.1"))
{
System.out.println("jdbc1"); System.out.println("jdbc1");
//System.exit(0); //System.exit(0);
} }
@@ -53,7 +58,8 @@ public class CheckVersion
if (vmversion.startsWith("1.2") || if (vmversion.startsWith("1.2") ||
vmversion.startsWith("1.3") || vmversion.startsWith("1.3") ||
checkClass("java.lang.Byte") checkClass("java.lang.Byte")
) { )
{
// Check to see if we have the standard extensions. If so, then // Check to see if we have the standard extensions. If so, then
// we want the enterprise edition, otherwise the jdbc2 driver. // we want the enterprise edition, otherwise the jdbc2 driver.