1
0
mirror of https://github.com/postgres/postgres.git synced 2025-08-05 07:41:25 +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

@@ -56,19 +56,19 @@ public class ImageViewer implements ItemListener
public imageCanvas() public imageCanvas()
{ {
image=null; image = null;
} }
public void setImage(Image img) public void setImage(Image img)
{ {
image=img; image = img;
repaint(); repaint();
} }
// This defines our minimum size // This defines our minimum size
public Dimension getMinimumSize() public Dimension getMinimumSize()
{ {
return new Dimension(400,400); return new Dimension(400, 400);
} }
public Dimension getPreferedSize() public Dimension getPreferedSize()
@@ -88,31 +88,32 @@ 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);
} }
// now set the background // now set the background
Graphics g = bkg.getGraphics(); Graphics g = bkg.getGraphics();
g.setColor(Color.gray); g.setColor(Color.gray);
g.fillRect(0,0,s.width,s.height); g.fillRect(0, 0, s.width, s.height);
// now paint the image over the background // now paint the image over the background
if(image!=null) if (image != null)
g.drawImage(image,0,0,this); g.drawImage(image, 0, 0, this);
// dispose the graphics instance // dispose the graphics instance
g.dispose(); g.dispose();
// paint the image onto the component // paint the image onto the component
gr.drawImage(bkg,0,0,this); gr.drawImage(bkg, 0, 0, this);
} }
} }
public ImageViewer(Frame f,String url,String user,String password) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException public ImageViewer(Frame f, String url, String user, String password) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
{ {
frame = f; frame = f;
@@ -122,65 +123,77 @@ 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();
} }
}; };
m.addActionListener(exitListener); m.addActionListener(exitListener);
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();
} }
}; };
i.addActionListener(removeListener); i.addActionListener(removeListener);
// To the north is a label used to display the current images name // To the north is a label used to display the current images name
f.add("North",label = new Label()); f.add("North", label = new Label());
// We have a panel to the south of the frame containing the controls // We have a panel to the south of the frame containing the controls
Panel p = new Panel(); Panel p = new Panel();
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"));
b.addActionListener(removeListener); b.addActionListener(removeListener);
p.add(b=new Button("Quit")); p.add(b = new Button("Quit"));
b.addActionListener(exitListener); b.addActionListener(exitListener);
f.add("South",p); f.add("South", p);
// And a panel to the west containing the list of available images // And a panel to the west containing the list of available images
f.add("West",list=new List()); f.add("West", list = new List());
list.addItemListener(this); list.addItemListener(this);
// Finally the centre contains our image // Finally the centre contains our image
f.add("Center",canvas = new imageCanvas()); f.add("Center", canvas = new imageCanvas());
// Load the driver // Load the driver
Class.forName("org.postgresql.Driver"); Class.forName("org.postgresql.Driver");
@@ -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);
@@ -241,14 +260,14 @@ public class ImageViewer implements ItemListener
*/ */
public void importImage() public void importImage()
{ {
FileDialog d = new FileDialog(frame,"Import Image",FileDialog.LOAD); FileDialog d = new FileDialog(frame, "Import Image", FileDialog.LOAD);
d.setVisible(true); d.setVisible(true);
String name = d.getFile(); String name = d.getFile();
String dir = d.getDirectory(); String dir = d.getDirectory();
d.dispose(); d.dispose();
// now start the true importer // now start the true importer
Thread t = new importer(db,name,dir); Thread t = new importer(db, name, dir);
//t.setPriority(Thread.MAX_PRIORITY); //t.setPriority(Thread.MAX_PRIORITY);
t.start(); t.start();
} }
@@ -260,22 +279,26 @@ public class ImageViewer implements ItemListener
*/ */
class importer extends Thread class importer extends Thread
{ {
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();
@@ -285,7 +308,7 @@ public class ImageViewer implements ItemListener
byte buf[] = new byte[2048]; byte buf[] = new byte[2048];
// Open the file // Open the file
FileInputStream fis = new FileInputStream(new File(dir,name)); FileInputStream fis = new FileInputStream(new File(dir, name));
// Now create the large object // Now create the large object
int oid = lom.create(); int oid = lom.create();
@@ -295,10 +318,11 @@ 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; {
blob.write(buf,0,s); t += s;
blob.write(buf, 0, s);
} }
// Close the object // Close the object
@@ -309,21 +333,28 @@ public class ImageViewer implements ItemListener
// As we are a different thread to the other window, we must use // As we are a different thread to the other window, we must use
// our own thread // our own thread
stat = db.createStatement(); stat = db.createStatement();
stat.executeUpdate("insert into images values ('"+name+"',"+oid+")"); stat.executeUpdate("insert into images values ('" + name + "'," + oid + ")");
db.commit(); db.commit();
db.setAutoCommit(false); db.setAutoCommit(false);
// 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,17 +367,21 @@ 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) { }
label.setText(ex.toString()+" Have you initialised the database?"); catch (SQLException ex)
{
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
// //
@@ -366,23 +402,27 @@ public class ImageViewer implements ItemListener
// here, because we are not opening any blobs, only deleting // here, because we are not opening any blobs, only deleting
// 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));
} }
} }
rs.close(); rs.close();
// Finally delete any entries for that name // Finally delete any entries for that name
stat.executeUpdate("delete from images where imgname='"+currentImage+"'"); stat.executeUpdate("delete from images where imgname='" + currentImage + "'");
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()
@@ -402,27 +443,36 @@ 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,20 +494,24 @@ 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) { }
System.err.println("Exception caught.\n"+ex); catch (Exception 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) {
log("Unable to load driver", cnfe);
return;
} }
try { catch (ClassNotFoundException cnfe)
{
log("Unable to load driver", cnfe);
return ;
}
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
} }
} }
@@ -87,15 +90,15 @@ public class basic
// updated for 7.1 // updated for 7.1
st.executeUpdate("insert into basic values (4,1)"); st.executeUpdate("insert into basic values (4,1)");
int insertedOID = ((org.postgresql.Statement)st).getInsertedOID(); int insertedOID = ((org.postgresql.Statement)st).getInsertedOID();
System.out.println("Inserted row with oid "+insertedOID); System.out.println("Inserted row with oid " + insertedOID);
// Now change the value of b from 1 to 8 // Now change the value of b from 1 to 8
st.executeUpdate("update basic set b=8"); st.executeUpdate("update basic set b=8");
System.out.println("Updated "+st.getUpdateCount()+" rows"); System.out.println("Updated " + st.getUpdateCount() + " rows");
// Now delete 2 rows // Now delete 2 rows
st.executeUpdate("delete from basic where a<3"); st.executeUpdate("delete from basic where a<3");
System.out.println("deleted "+st.getUpdateCount()+" rows"); System.out.println("deleted " + st.getUpdateCount() + " rows");
// For large inserts, a PreparedStatement is more efficient, because it // For large inserts, a PreparedStatement is more efficient, because it
// supports the idea of precompiling the SQL statement, and to store // supports the idea of precompiling the SQL statement, and to store
@@ -107,9 +110,10 @@ 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(2,i); // "column b" = i ps.setInt(1, 4); // "column a" = 5
ps.setInt(2, i); // "column b" = i
ps.executeUpdate(); // executeUpdate because insert returns no data ps.executeUpdate(); // executeUpdate because insert returns no data
} }
ps.close(); // Always close when we are done with it ps.close(); // Always close when we are done with it
@@ -117,22 +121,26 @@ 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);
} }
rs.close(); // again, you must close the result when done rs.close(); // again, you must close the result when done
} }
// 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,22 +152,25 @@ 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);
} }
rs.close(); // again, you must close the result when done rs.close(); // again, you must close the result when done
} }
// 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);
} }
rs.close(); // again, you must close the result when done rs.close(); // again, you must close the result when done
@@ -184,19 +195,22 @@ public class basic
{ {
System.out.println("PostgreSQL basic test v6.3 rev 1\n"); System.out.println("PostgreSQL basic test v6.3 rev 1\n");
if(args.length<3) if (args.length < 3)
instructions(); instructions();
// This line outputs debug information to stderr. To enable this, simply // This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line // add an extra parameter to the command line
if(args.length>3) if (args.length > 3)
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) { }
System.err.println("Exception caught.\n"+ex); catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace(); ex.printStackTrace();
} }
} }

View File

@@ -87,7 +87,7 @@ public class blobtest
// finally delete the large object // finally delete the large object
ownapi_test3(oid); ownapi_test3(oid);
System.out.println("\n\nOID="+oid); System.out.println("\n\nOID=" + oid);
} }
private int ownapi_test1() throws FileNotFoundException, IOException, SQLException private int ownapi_test1() throws FileNotFoundException, IOException, SQLException
@@ -97,11 +97,11 @@ public class blobtest
// Ok, test 1 is to create a large object. To do this, we use the create // Ok, test 1 is to create a large object. To do this, we use the create
// method. // method.
System.out.println("Creating a large object"); System.out.println("Creating a large object");
int oid = lobj.create(LargeObjectManager.READ|LargeObjectManager.WRITE); int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE);
DriverManager.println("got large object oid="+oid); DriverManager.println("got large object oid=" + oid);
LargeObject obj = lobj.open(oid,LargeObjectManager.WRITE); LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE);
DriverManager.println("got large object obj="+obj); DriverManager.println("got large object obj=" + obj);
// Now open a test file - this class will do // Now open a test file - this class will do
System.out.println("Opening test source object"); System.out.println("Opening test source object");
@@ -110,14 +110,15 @@ public class blobtest
// copy the data // copy the data
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);
tl+=s; tl += s;
} }
DriverManager.println("Copied "+tl+" bytes"); DriverManager.println("Copied " + tl + " bytes");
// Close the object // Close the object
System.out.println("Closing object"); System.out.println("Closing object");
@@ -131,9 +132,9 @@ public class blobtest
System.out.println("Test 2 Reading a large object and save as a file\n"); System.out.println("Test 2 Reading a large object and save as a file\n");
// Now open the large object // Now open the large object
System.out.println("Opening large object "+oid); System.out.println("Opening large object " + oid);
LargeObject obj = lobj.open(oid,LargeObjectManager.READ); LargeObject obj = lobj.open(oid, LargeObjectManager.READ);
DriverManager.println("got obj="+obj); DriverManager.println("got obj=" + obj);
// Now open a test file - this class will do // Now open a test file - this class will do
System.out.println("Opening test destination object"); System.out.println("Opening test destination object");
@@ -142,17 +143,19 @@ public class blobtest
// copy the data // copy the data
System.out.println("Copying large object to file"); System.out.println("Copying large object to file");
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)
obj.read(buf,0,rs); rs = s;
fos.write(buf,0,rs); obj.read(buf, 0, rs);
tl+=rs; fos.write(buf, 0, rs);
s-=rs; tl += rs;
s -= rs;
} }
DriverManager.println("Copied "+tl+"/"+obj.size()+" bytes"); DriverManager.println("Copied " + tl + "/" + obj.size() + " bytes");
// Close the object // Close the object
System.out.println("Closing object"); System.out.println("Closing object");
@@ -164,7 +167,7 @@ public class blobtest
System.out.println("Test 3 Deleting a large object\n"); System.out.println("Test 3 Deleting a large object\n");
// Now open the large object // Now open the large object
System.out.println("Deleting large object "+oid); System.out.println("Deleting large object " + oid);
lobj.unlink(oid); lobj.unlink(oid);
} }
@@ -175,21 +178,23 @@ public class blobtest
System.out.println("Testing JDBC2 Blob interface:"); System.out.println("Testing JDBC2 Blob interface:");
jdbc2api_cleanup(); jdbc2api_cleanup();
System.out.println("Creating Blob on large object "+oid); System.out.println("Creating Blob on large object " + oid);
s.executeUpdate("create table basic (a oid)"); s.executeUpdate("create table basic (a oid)");
System.out.println("Inserting row"); System.out.println("Inserting row");
s.executeUpdate("insert into basic values ("+oid+")"); s.executeUpdate("insert into basic values (" + oid + ")");
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());
System.out.println("Characters 400-500:"); System.out.println("Characters 400-500:");
System.out.write(b.getBytes(400l,100)); System.out.write(b.getBytes(400l, 100));
System.out.println(); System.out.println();
} }
rs.close(); rs.close();
@@ -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,21 +234,25 @@ 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);
} }
// This line outputs debug information to stderr. To enable this, simply // This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line // add an extra parameter to the command line
if(args.length>3) if (args.length > 3)
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) { }
System.err.println("Exception caught.\n"+ex); catch (Exception 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,55 +20,67 @@ 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));
// Initialize the orb // Initialize 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);
// 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 ;
} }
// Resolve the dispenser // Resolve the dispenser
NameComponent[] dispName = { NameComponent[] dispName = {
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; {
while(run) { boolean run = true;
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");
@@ -96,11 +113,11 @@ public class StockClient
System.out.println(" 4 Order item"); System.out.println(" 4 Order item");
System.out.println(" 5 Display all items"); System.out.println(" 5 Display all items");
System.out.println(" 0 Exit"); System.out.println(" 0 Exit");
int i = getMenu("Main",5); int i = getMenu("Main", 5);
switch(i) switch (i)
{ {
case 0: case 0:
run=false; run = false;
break; break;
case 1: case 1:
@@ -126,159 +143,202 @@ public class StockClient
} }
} }
private void displayItem() { private void displayItem()
try { {
int id = getMenu("\nStockID to display",item.getLastID()); try
if(id>0) { {
int id = getMenu("\nStockID to display", item.getLastID());
if (id > 0)
{
item.fetchItem(id); item.fetchItem(id);
System.out.println("========================================"); System.out.println("========================================");
String status = ""; String status = "";
if(!item.isItemValid()) if (!item.isItemValid())
status=" ** Superceded **"; status = " ** Superceded **";
int av = item.getAvailable(); int av = item.getAvailable();
System.out.println(" Stock ID: "+id+status+ System.out.println(" Stock ID: " + id + status +
"\nItems Available: "+av+ "\nItems Available: " + av +
"\nItems on order: "+item.getOrdered()+ "\nItems on order: " + item.getOrdered() +
"\n Description: "+item.getDescription()); "\n Description: " + item.getDescription());
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; {
if(av>1) int rem = 1;
rem=getMenu("How many?",av); if (av > 1)
if(rem>0) rem = getMenu("How many?", av);
if (rem > 0)
item.removeStock(rem); item.removeStock(rem);
} }
} }
} 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 { {
int id = getMenu("\nStockID to take out",item.getLastID()); try
if(id>0) { {
int id = getMenu("\nStockID to take out", item.getLastID());
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; {
if(av>1) int rem = 1;
rem=getMenu("How many?",av); if (av > 1)
if(rem>0) rem = getMenu("How many?", av);
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()) { {
System.out.println("You will need to order some more "+item.getDescription()); if (item.isItemValid())
{
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 }
System.out.println(item.getDescription()+"\nThis item is out of stock"); else
} catch(Exception e) { System.out.println(item.getDescription() + "\nThis item is out of stock");
}
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 { {
int id = getMenu("\nStockID to book in",item.getLastID()); try
{
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()); {
if(am>0) int am = getMenu("How many do you want to book in", item.getOrdered());
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 { {
if(id==0) try
id = getMenu("\nStockID to order",item.getLastID()); {
if (id == 0)
id = getMenu("\nStockID to order", item.getLastID());
item.fetchItem(id); item.fetchItem(id);
System.out.println(item.getDescription()); System.out.println(item.getDescription());
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 { {
boolean cont=true; try
int nr=item.getLastID(); {
boolean cont = true;
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; {
while(v<0 || v>max) { int v = -1;
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) { }
v=-1; catch (Exception nfe)
{
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();
if(s.startsWith("y") || s.startsWith("Y")) if (s.startsWith("y") || s.startsWith("Y"))
return true; return true;
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); {
if(rs!=null) { ResultSet rs = st.executeQuery("select description from stock where id=" + id);
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); {
if(rs!=null) { ResultSet rs = st.executeQuery("select avail from stock where id=" + id);
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); {
if(rs!=null) { ResultSet rs = st.executeQuery("select ordered from stock where id=" + id);
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); {
if(rs!=null) { ResultSet rs = st.executeQuery("select valid from stock where id=" + id);
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+ {
", ordered=ordered-"+amount+ st.executeUpdate("update stock set avail=avail+" + amount +
" where id="+id+" and ordered>="+amount); ", ordered=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+ {
" where id="+id); st.executeUpdate("update stock set avail=avail-" + amount +
" 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+ {
" where id="+id); st.executeUpdate("update stock set ordered=ordered+" + amount +
" 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
{ {
@@ -13,24 +13,28 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
private int numObjects = 0; private int numObjects = 0;
private StockItemStatus[] stock = new StockItemStatus[maxObjects]; private StockItemStatus[] stock = new StockItemStatus[maxObjects];
public StockDispenserImpl(String[] args,String name,int num) public StockDispenserImpl(String[] args, String name, int num)
{ {
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);
// prestart num objects // prestart num objects
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,10 +44,12 @@ 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,15 +61,17 @@ 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 ;
} }
} }
System.out.println("Reserved object not a member of this dispenser"); System.out.println("Reserved object not a member of this dispenser");
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.connect(args[1],args[2],args[3]); db = new StockDB();
System.out.println("StockDB object "+iname+" created"); db.connect(args[1], args[2], args[3]);
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,38 +13,43 @@ 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);
// Create the StockDispenser object // Create the StockDispenser object
StockDispenserImpl dispenser = new StockDispenserImpl(args,"Stock Dispenser",numInstances); StockDispenserImpl dispenser = new StockDispenserImpl(args, "Stock Dispenser", numInstances);
// Export the new object // Export the new object
orb.connect(dispenser); orb.connect(dispenser);
// 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 ;
} }
// bind the dispenser into the naming service // bind the dispenser into the naming service
NameComponent[] dispenserName = { NameComponent[] dispenserName = {
new NameComponent("StockDispenser","Stock") new NameComponent("StockDispenser", "Stock")
}; };
nameService.rebind(dispenserName,dispenser); nameService.rebind(dispenserName, dispenser);
// 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
} }
} }
@@ -91,7 +94,7 @@ public class datestyle
// //
// NB: January = 0 here // NB: January = 0 here
// //
standard = new java.sql.Date(98,0,8); standard = new java.sql.Date(98, 0, 8);
// Now store the result. // Now store the result.
// //
@@ -99,7 +102,7 @@ public class datestyle
// The only way of doing this is by using a PreparedStatement. // The only way of doing this is by using a PreparedStatement.
// //
PreparedStatement ps = db.prepareStatement("insert into datestyle values (?)"); PreparedStatement ps = db.prepareStatement("insert into datestyle values (?)");
ps.setDate(1,standard); ps.setDate(1, standard);
ps.executeUpdate(); ps.executeUpdate();
ps.close(); ps.close();
@@ -112,12 +115,13 @@ 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();
// set the style // set the style
st.executeUpdate("set datestyle='"+styles[i]+"'"); st.executeUpdate("set datestyle='" + styles[i] + "'");
// Now because the driver needs to know what the current style is, // Now because the driver needs to know what the current style is,
// we have to run the following: // we have to run the following:
@@ -129,17 +133,18 @@ public class datestyle
// Throw an exception if there is no result (if the table is empty // Throw an exception if there is no result (if the table is empty
// there should still be a result). // there should still be a result).
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.
if(standard.equals(rs.getDate(1))) if (standard.equals(rs.getDate(1)))
System.out.println(" passed, returned "+rs.getString(1)); System.out.println(" passed, returned " + rs.getString(1));
else else
System.out.println(" failed, returned "+rs.getString(1)); System.out.println(" failed, returned " + rs.getString(1));
} }
rs.close(); rs.close();
} }
@@ -162,19 +167,22 @@ public class datestyle
{ {
System.out.println("PostgreSQL datestyle test v6.3 rev 1\n"); System.out.println("PostgreSQL datestyle test v6.3 rev 1\n");
if(args.length<3) if (args.length < 3)
instructions(); instructions();
// This line outputs debug information to stderr. To enable this, simply // This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line // add an extra parameter to the command line
if(args.length>3) if (args.length > 3)
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) { }
System.err.println("Exception caught.\n"+ex); catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace(); ex.printStackTrace();
} }
} }

View File

@@ -22,32 +22,33 @@ 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")) {
displayResult(dbmd.getProcedures(null,null,null)); if (doTest("getProcedures() - should show all available procedures"))
displayResult(dbmd.getProcedures(null, null, null));
if(doTest("getProcedures() with pattern - should show all circle procedures")) if (doTest("getProcedures() with pattern - should show all circle procedures"))
displayResult(dbmd.getProcedures(null,null,"circle%")); displayResult(dbmd.getProcedures(null, null, "circle%"));
if(doTest("getProcedureColumns() on circle procedures")) if (doTest("getProcedureColumns() on circle procedures"))
displayResult(dbmd.getProcedureColumns(null,null,"circle%",null)); displayResult(dbmd.getProcedureColumns(null, null, "circle%", null));
if(doTest("getTables()")) if (doTest("getTables()"))
displayResult(dbmd.getTables(null,null,null,null)); displayResult(dbmd.getTables(null, null, null, null));
if(doTest("getColumns() - should show all tables, can take a while to run")) if (doTest("getColumns() - should show all tables, can take a while to run"))
displayResult(dbmd.getColumns(null,null,null,null)); displayResult(dbmd.getColumns(null, null, null, null));
if(doTest("getColumns() - should show the test_b table")) if (doTest("getColumns() - should show the test_b table"))
displayResult(dbmd.getColumns(null,null,"test_b",null)); displayResult(dbmd.getColumns(null, null, "test_b", null));
if(doTest("getColumnPrivileges() - should show all tables")) if (doTest("getColumnPrivileges() - should show all tables"))
displayResult(dbmd.getColumnPrivileges(null,null,null,null)); displayResult(dbmd.getColumnPrivileges(null, null, null, null));
if(doTest("getPrimaryKeys()")) if (doTest("getPrimaryKeys()"))
displayResult(dbmd.getPrimaryKeys(null,null,null)); displayResult(dbmd.getPrimaryKeys(null, null, null));
if(doTest("getTypeInfo()")) if (doTest("getTypeInfo()"))
displayResult(dbmd.getTypeInfo()); displayResult(dbmd.getTypeInfo());
} }
@@ -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";
@@ -63,24 +65,27 @@ public class metadata
ResultSet rs = st.executeQuery(sql); ResultSet rs = st.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData(); ResultSetMetaData rsmd = rs.getMetaData();
if(doTest("isCurrency()")) if (doTest("isCurrency()"))
System.out.println("isCurrency on col 1 = "+rsmd.isCurrency(1)+" should be false\nisCurrency on col 4 = "+rsmd.isCurrency(4)+" should be true"); System.out.println("isCurrency on col 1 = " + rsmd.isCurrency(1) + " should be false\nisCurrency on col 4 = " + rsmd.isCurrency(4) + " should be true");
// Finally close the query. Now give the user a chance to display the // Finally close the query. Now give the user a chance to display the
// 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
} }
} }
@@ -123,17 +132,17 @@ public class metadata
st = db.createStatement(); st = db.createStatement();
// This prints the backend's version // This prints the backend's version
System.out.println("Connected to "+dbmd.getDatabaseProductName()+" "+dbmd.getDatabaseProductVersion()); System.out.println("Connected to " + dbmd.getDatabaseProductName() + " " + dbmd.getDatabaseProductVersion());
init(); init();
System.out.println(); System.out.println();
// Now the tests // Now the tests
if(doTest("Test DatabaseMetaData")) if (doTest("Test DatabaseMetaData"))
doDatabaseMetaData(); doDatabaseMetaData();
if(doTest("Test ResultSetMetaData")) if (doTest("Test ResultSetMetaData"))
doResultSetMetaData(); doResultSetMetaData();
System.out.println("\nNow closing the connection"); System.out.println("\nNow closing the connection");
@@ -146,21 +155,26 @@ 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')) { {
c=(char)System.in.read(); while (!(c == 'n' || c == 'y' || c == 'N' || c == 'Y'))
{
c = (char)System.in.read();
} }
} catch(IOException ioe) { }
catch (IOException ioe)
{
return false; return false;
} }
return c=='y' || c=='Y'; return c == 'y' || c == 'Y';
} }
/** /**
@@ -170,26 +184,28 @@ public class metadata
public void displayResult(ResultSet rs) throws SQLException public void displayResult(ResultSet rs) throws SQLException
{ {
ResultSetMetaData rsmd = rs.getMetaData(); ResultSetMetaData rsmd = rs.getMetaData();
int count=0; int count = 0;
// Print the result column names // Print the result column names
int cols = rsmd.getColumnCount(); int cols = rsmd.getColumnCount();
for(int i=1;i<=cols;i++) for (int i = 1;i <= cols;i++)
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"));
else else
System.out.print(o.toString()+(i<cols?"\t":"\n")); System.out.print(o.toString() + (i < cols ? "\t" : "\n"));
} }
} }
System.out.println("Result returned "+count+" rows."); System.out.println("Result returned " + count + " rows.");
// finally close the result set // finally close the result set
rs.close(); rs.close();
@@ -200,43 +216,48 @@ 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 { }
String types[] = null;
if(line.equals("\\d"))
types=allUserTables;
else if(line.equals("\\di"))
types=usrIndices;
else if(line.equals("\\dt"))
types=usrTables;
else if(line.equals("\\ds"))
types=usrSequences;
else if(line.equals("\\dS"))
types=sysTables;
else else
throw new SQLException("Unsupported \\d command: "+line); {
String types[] = null;
if (line.equals("\\d"))
types = allUserTables;
else if (line.equals("\\di"))
types = usrIndices;
else if (line.equals("\\dt"))
types = usrTables;
else if (line.equals("\\ds"))
types = usrSequences;
else if (line.equals("\\dS"))
types = sysTables;
else
throw new SQLException("Unsupported \\d command: " + line);
// Display details about all system tables // Display details about all system tables
// //
// Note: the first two arguments are ignored. To keep to the spec, // Note: the first two arguments are ignored. To keep to the spec,
// you must put null here // you must put null here
// //
displayResult(dbmd.getTables(null,null,"%",types)); displayResult(dbmd.getTables(null, null, "%", types));
} }
} else }
throw new SQLException("Unsupported \\ command: "+line); else
throw new SQLException("Unsupported \\ command: " + line);
} }
private static final String allUserTables[] = {"TABLE","INDEX","SEQUENCE"}; private static final String allUserTables[] = {"TABLE", "INDEX", "SEQUENCE"};
private static final String usrIndices[] = {"INDEX"}; private static final String usrIndices[] = {"INDEX"};
private static final String usrTables[] = {"TABLE"}; private static final String usrTables[] = {"TABLE"};
private static final String usrSequences[] = {"SEQUENCE"}; private static final String usrSequences[] = {"SEQUENCE"};
private static final String sysTables[] = {"SYSTEM TABLE","SYSTEM INDEX"}; private static final String sysTables[] = {"SYSTEM TABLE", "SYSTEM INDEX"};
/** /**
* Display some instructions on how to run the example * Display some instructions on how to run the example
@@ -255,19 +276,22 @@ public class metadata
{ {
System.out.println("PostgreSQL metdata tester v6.4 rev 1\n"); System.out.println("PostgreSQL metdata tester v6.4 rev 1\n");
if(args.length<3) if (args.length < 3)
instructions(); instructions();
// This line outputs debug information to stderr. To enable this, simply // This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line // add an extra parameter to the command line
if(args.length>3) if (args.length > 3)
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) { }
System.err.println("Exception caught.\n"+ex); catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace(); ex.printStackTrace();
} }
} }

View File

@@ -34,7 +34,7 @@ public class psql
st = db.createStatement(); st = db.createStatement();
// This prints the backend's version // This prints the backend's version
System.out.println("Connected to "+dbmd.getDatabaseProductName()+" "+dbmd.getDatabaseProductVersion()); System.out.println("Connected to " + dbmd.getDatabaseProductName() + " " + dbmd.getDatabaseProductVersion());
System.out.println(); System.out.println();
@@ -43,23 +43,28 @@ public class psql
input.resetSyntax(); input.resetSyntax();
input.slashSlashComments(true); // allow // as a comment delimiter input.slashSlashComments(true); // allow // as a comment delimiter
input.eolIsSignificant(false); // treat eol's as spaces input.eolIsSignificant(false); // treat eol's as spaces
input.wordChars(32,126); input.wordChars(32, 126);
input.whitespaceChars(59,59); input.whitespaceChars(59, 59);
// input.quoteChar(39); *** CWJ: messes up literals in query string *** // input.quoteChar(39); *** CWJ: messes up literals in query string ***
// 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)
System.out.print("["+lineno+"] "); { // done added by CWJ to permit \q command
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,31 +80,39 @@ 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");
} }
} }
if(loop) if (loop)
type = st.getMoreResults(); type = st.getMoreResults();
} }
} }
@@ -114,17 +127,19 @@ public class psql
// Print the result column names // Print the result column names
int cols = rsmd.getColumnCount(); int cols = rsmd.getColumnCount();
for(int i=1;i<=cols;i++) for (int i = 1;i <= cols;i++)
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"));
else else
System.out.print(o.toString()+(i<cols?"\t":"\n")); System.out.print(o.toString() + (i < cols ? "\t" : "\n"));
} }
} }
@@ -137,45 +152,50 @@ 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 { }
String types[] = null;
if(line.equals("\\d"))
types=allUserTables;
else if(line.equals("\\di"))
types=usrIndices;
else if(line.equals("\\dt"))
types=usrTables;
else if(line.equals("\\ds"))
types=usrSequences;
else if(line.equals("\\dS"))
types=sysTables;
else else
throw new SQLException("Unsupported \\d command: "+line); {
String types[] = null;
if (line.equals("\\d"))
types = allUserTables;
else if (line.equals("\\di"))
types = usrIndices;
else if (line.equals("\\dt"))
types = usrTables;
else if (line.equals("\\ds"))
types = usrSequences;
else if (line.equals("\\dS"))
types = sysTables;
else
throw new SQLException("Unsupported \\d command: " + line);
// Display details about all system tables // Display details about all system tables
// //
// Note: the first two arguments are ignored. To keep to the spec, // Note: the first two arguments are ignored. To keep to the spec,
// you must put null here // you must put null here
// //
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);
} }
private static final String allUserTables[] = {"TABLE","INDEX","SEQUENCE"}; private static final String allUserTables[] = {"TABLE", "INDEX", "SEQUENCE"};
private static final String usrIndices[] = {"INDEX"}; private static final String usrIndices[] = {"INDEX"};
private static final String usrTables[] = {"TABLE"}; private static final String usrTables[] = {"TABLE"};
private static final String usrSequences[] = {"SEQUENCE"}; private static final String usrSequences[] = {"SEQUENCE"};
private static final String sysTables[] = {"SYSTEM TABLE","SYSTEM INDEX"}; private static final String sysTables[] = {"SYSTEM TABLE", "SYSTEM INDEX"};
/** /**
* Display some instructions on how to run the example * Display some instructions on how to run the example
@@ -194,19 +214,22 @@ public class psql
{ {
System.out.println("PostgreSQL psql example v6.3 rev 1\n"); System.out.println("PostgreSQL psql example v6.3 rev 1\n");
if(args.length<3) if (args.length < 3)
instructions(); instructions();
// This line outputs debug information to stderr. To enable this, simply // This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line // add an extra parameter to the command line
if(args.length>3) if (args.length > 3)
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) { }
System.err.println("Exception caught.\n"+ex); catch (Exception 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
} }
} }
@@ -81,9 +87,10 @@ public class threadsafe
{ {
System.out.println("\nThis test runs three Threads. Two simply insert data into a table, then\nthey perform a query. While they are running, a third thread is running,\nand it load data into, then reads from a Large Object.\n\nIf alls well, this should run without any errors. If so, we are Thread Safe.\nWhy test JDBC & LargeObject's? Because both will run over the network\nconnection, and if locking on the stream isn't done correctly, the backend\nwill get pretty confused!\n"); System.out.println("\nThis test runs three Threads. Two simply insert data into a table, then\nthey perform a query. While they are running, a third thread is running,\nand it load data into, then reads from a Large Object.\n\nIf alls well, this should run without any errors. If so, we are Thread Safe.\nWhy test JDBC & LargeObject's? Because both will run over the network\nconnection, and if locking on the stream isn't done correctly, the backend\nwill get pretty confused!\n");
thread3 thread3=null; thread3 thread3 = null;
try { try
{
// create the two threads // create the two threads
Thread thread0 = Thread.currentThread(); Thread thread0 = Thread.currentThread();
@@ -99,13 +106,15 @@ public class threadsafe
// ok, I know this is bad, but it does the trick here as our main thread // ok, I know this is bad, but it does the trick here as our main thread
// will yield as long as either of the children are still running // will yield as long as either of the children are still running
System.out.println("Waiting for threads to run"); System.out.println("Waiting for threads to run");
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)
thread3.cleanup(); thread3.cleanup();
} }
@@ -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,24 +157,27 @@ 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(2,i); // "column b" = i ps.setInt(1, 4); // "column a" = 5
ps.setInt(2, i); // "column b" = i
ps.executeUpdate(); // executeUpdate because insert returns no data ps.executeUpdate(); // executeUpdate because insert returns no data
// c.commit(); // c.commit();
if((i%50)==0) if ((i % 50) == 0)
DriverManager.println("Thread 1 done "+i+" inserts"); DriverManager.println("Thread 1 done " + i + " inserts");
} }
ps.close(); // Always close when we are done with it ps.close(); // Always close when we are done with it
// Finally perform a query on the table // Finally perform a query on the table
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);
@@ -170,13 +185,15 @@ public class threadsafe
} }
rs.close(); // again, you must close the result when done rs.close(); // again, you must close the result when done
} }
DriverManager.println("Thread 1 read "+cnt+" rows"); DriverManager.println("Thread 1 read " + cnt + " rows");
// 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) { }
System.err.println("Thread 1: "+se.toString()); catch (SQLException se)
{
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,21 +232,23 @@ 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(2,i); // "column b" = i ps.setInt(1, 4); // "column a" = 5
ps.setInt(2, i); // "column b" = i
ps.executeUpdate(); // executeUpdate because insert returns no data ps.executeUpdate(); // executeUpdate because insert returns no data
// c.commit(); // c.commit();
if((i%50)==0) if ((i % 50) == 0)
DriverManager.println("Thread 2 done "+i+" inserts"); DriverManager.println("Thread 2 done " + i + " inserts");
} }
ps.close(); // Always close when we are done with it ps.close(); // Always close when we are done with it
// Finally perform a query on the table // Finally perform a query on the table
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);
@@ -246,13 +269,15 @@ public class threadsafe
} }
rs.close(); // again, you must close the result when done rs.close(); // again, you must close the result when done
} }
DriverManager.println("Thread 2 read "+cnt+" rows"); DriverManager.println("Thread 2 read " + cnt + " rows");
// 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) { }
System.err.println("Thread 2: "+se.toString()); catch (SQLException se)
{
System.err.println("Thread 2: " + se.toString());
se.printStackTrace(); se.printStackTrace();
System.exit(1); System.exit(1);
} }
@@ -272,60 +297,70 @@ 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();
// create a blob // create a blob
lom = ((org.postgresql.Connection)c).getLargeObjectAPI(); lom = ((org.postgresql.Connection)c).getLargeObjectAPI();
oid = lom.create(); oid = lom.create();
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);
lo = lom.open(oid); lo = lom.open(oid);
FileInputStream fis = new FileInputStream("example/threadsafe.java"); FileInputStream fis = new FileInputStream("example/threadsafe.java");
// 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"); {
lo.write(buf,0,rc); DriverManager.println("Thread 3 read block " + bc + " " + bs + " bytes");
lo.write(buf, 0, rc);
bc++; bc++;
bs+=rc; bs += rc;
} }
lo.close(); lo.close();
fis.close(); fis.close();
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); {
if(buf.length>0) { buf = lo.read(buf.length);
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);
DriverManager.println("Block "+bc+" got "+s); DriverManager.println("Block " + bc + " got " + s);
} }
} }
lo.close(); lo.close();
System.out.println("Thread 3 finished"); System.out.println("Thread 3 finished");
} catch(Exception se) { }
System.err.println("Thread 3: "+se.toString()); catch (Exception se)
{
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) { {
System.out.println("Thread 3: Removing blob oid="+oid); if (lom != null && oid != 0)
{
System.out.println("Thread 3: Removing blob oid=" + oid);
lom.delete(oid); lom.delete(oid);
} }
} }
@@ -348,19 +383,22 @@ public class threadsafe
{ {
System.out.println("PostgreSQL Thread Safety test v6.4 rev 1\n"); System.out.println("PostgreSQL Thread Safety test v6.4 rev 1\n");
if(args.length<3) if (args.length < 3)
instructions(); instructions();
// This line outputs debug information to stderr. To enable this, simply // This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line // add an extra parameter to the command line
if(args.length>3) if (args.length > 3)
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) { }
System.err.println("Exception caught.\n"+ex); catch (Exception 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.
@@ -108,9 +107,9 @@ public abstract class Connection
// Throw an exception if the user or password properties are missing // Throw an exception if the user or password properties are missing
// This occasionally occurs when the client uses the properties version // This occasionally occurs when the client uses the properties version
// of getConnection(), and is a common question on the email lists // of getConnection(), and is a common question on the email lists
if(info.getProperty("user")==null) if (info.getProperty("user") == null)
throw new PSQLException("postgresql.con.user"); throw new PSQLException("postgresql.con.user");
if(info.getProperty("password")==null) if (info.getProperty("password") == null)
throw new PSQLException("postgresql.con.pass"); throw new PSQLException("postgresql.con.pass");
this_driver = d; this_driver = d;
@@ -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,26 +133,30 @@ 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) { }
throw new PSQLException ("postgresql.con.failed",e); catch (IOException e)
{
throw new PSQLException ("postgresql.con.failed", e);
} }
// Now we need to construct and send a startup packet // Now we need to construct and send a startup packet
try try
{ {
// Ver 6.3 code // Ver 6.3 code
pg_stream.SendInteger(4+4+SM_DATABASE+SM_USER+SM_OPTIONS+SM_UNUSED+SM_TTY,4); pg_stream.SendInteger(4 + 4 + SM_DATABASE + SM_USER + SM_OPTIONS + SM_UNUSED + SM_TTY, 4);
pg_stream.SendInteger(PG_PROTOCOL_LATEST_MAJOR,2); pg_stream.SendInteger(PG_PROTOCOL_LATEST_MAJOR, 2);
pg_stream.SendInteger(PG_PROTOCOL_LATEST_MINOR,2); pg_stream.SendInteger(PG_PROTOCOL_LATEST_MINOR, 2);
pg_stream.Send(database.getBytes(),SM_DATABASE); pg_stream.Send(database.getBytes(), SM_DATABASE);
// This last send includes the unused fields // This last send includes the unused fields
pg_stream.Send(PG_USER.getBytes(),SM_USER+SM_OPTIONS+SM_UNUSED+SM_TTY); pg_stream.Send(PG_USER.getBytes(), SM_USER + SM_OPTIONS + SM_UNUSED + SM_TTY);
// now flush the startup packets to the backend // now flush the startup packets to the backend
pg_stream.flush(); pg_stream.flush();
@@ -158,9 +164,10 @@ 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)
{ {
case 'E': case 'E':
// An error occured, so pass the error message to the // An error occured, so pass the error message to the
@@ -176,16 +183,17 @@ 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();
salt = new String(rst,0,2); salt = new String(rst, 0, 2);
DriverManager.println("Salt="+salt); DriverManager.println("Salt=" + salt);
} }
// now send the auth packet // now send the auth packet
switch(areq) switch (areq)
{ {
case AUTH_REQ_OK: case AUTH_REQ_OK:
break; break;
@@ -200,39 +208,43 @@ public abstract class Connection
case AUTH_REQ_PASSWORD: case AUTH_REQ_PASSWORD:
DriverManager.println("postgresql: PASSWORD"); DriverManager.println("postgresql: PASSWORD");
pg_stream.SendInteger(5+PG_PASSWORD.length(),4); pg_stream.SendInteger(5 + PG_PASSWORD.length(), 4);
pg_stream.Send(PG_PASSWORD.getBytes()); pg_stream.Send(PG_PASSWORD.getBytes());
pg_stream.SendInteger(0,1); pg_stream.SendInteger(0, 1);
pg_stream.flush(); pg_stream.flush();
break; break;
case AUTH_REQ_CRYPT: case AUTH_REQ_CRYPT:
DriverManager.println("postgresql: CRYPT"); DriverManager.println("postgresql: CRYPT");
String crypted = UnixCrypt.crypt(salt,PG_PASSWORD); String crypted = UnixCrypt.crypt(salt, PG_PASSWORD);
pg_stream.SendInteger(5+crypted.length(),4); pg_stream.SendInteger(5 + crypted.length(), 4);
pg_stream.Send(crypted.getBytes()); pg_stream.Send(crypted.getBytes());
pg_stream.SendInteger(0,1); pg_stream.SendInteger(0, 1);
pg_stream.flush(); pg_stream.flush();
break; break;
default: default:
throw new PSQLException("postgresql.con.auth",new Integer(areq)); throw new PSQLException("postgresql.con.auth", new Integer(areq));
} }
break; break;
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) { }
throw new PSQLException("postgresql.con.failed",e); catch (IOException 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);
@@ -310,7 +324,7 @@ public abstract class Connection
DriverManager.println(msg); DriverManager.println(msg);
// Add the warning to the chain // Add the warning to the chain
if(firstWarning!=null) if (firstWarning != null)
firstWarning.setNextWarning(new SQLWarning(msg)); firstWarning.setNextWarning(new SQLWarning(msg));
else else
firstWarning = new SQLWarning(msg); firstWarning = new SQLWarning(msg);
@@ -344,7 +358,7 @@ public abstract class Connection
*/ */
public java.sql.ResultSet ExecSQL(String sql) throws SQLException public java.sql.ResultSet ExecSQL(String sql) throws SQLException
{ {
return ExecSQL(sql,null); return ExecSQL(sql, null);
} }
/** /**
@@ -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;
} }
@@ -450,8 +465,8 @@ public abstract class Connection
*/ */
public Fastpath getFastpathAPI() throws SQLException public Fastpath getFastpathAPI() throws SQLException
{ {
if(fastpath==null) if (fastpath == null)
fastpath = new Fastpath(this,pg_stream); fastpath = new Fastpath(this, pg_stream);
return fastpath; return fastpath;
} }
@@ -479,7 +494,7 @@ public abstract class Connection
*/ */
public LargeObjectManager getLargeObjectAPI() throws SQLException public LargeObjectManager getLargeObjectAPI() throws SQLException
{ {
if(largeobject==null) if (largeobject == null)
largeobject = new LargeObjectManager(this); largeobject = new LargeObjectManager(this);
return largeobject; return largeobject;
} }
@@ -506,17 +521,19 @@ public abstract class Connection
* @exception SQLException if value is not correct for this type * @exception SQLException if value is not correct for this type
* @see org.postgresql.util.Serialize * @see org.postgresql.util.Serialize
*/ */
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); {
objectTypes.put(type,ser); Serialize ser = new Serialize(this, type);
objectTypes.put(type, ser);
return ser.fetch(Integer.parseInt(value)); return ser.fetch(Integer.parseInt(value));
} }
@@ -525,25 +542,32 @@ 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) { }
throw new PSQLException("postgresql.con.creobj",type,ex); catch (Exception ex)
{
throw new PSQLException("postgresql.con.creobj", type, ex);
} }
// should never be reached // should never be reached
@@ -559,33 +583,39 @@ 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); {
objectTypes.put(type,ser); Serialize ser = new Serialize(this, type);
objectTypes.put(type, ser);
return ser.store(o); return ser.store(o);
} }
// 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(x instanceof Serialize) if (x instanceof Serialize)
return ((Serialize)x).store(o); return ((Serialize)x).store(o);
// 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) { }
throw new PSQLException("postgresql.con.strobjex",ex); catch (Exception ex)
{
throw new PSQLException("postgresql.con.strobjex", ex);
} }
} }
@@ -609,9 +639,9 @@ public abstract class Connection
* *
* @see org.postgresql.util.PGobject * @see org.postgresql.util.PGobject
*/ */
public void addDataType(String type,String name) public void addDataType(String type, String name)
{ {
objectTypes.put(type,name); objectTypes.put(type, name);
} }
// This holds the available types // This holds the available types
@@ -636,8 +666,8 @@ public abstract class Connection
// This initialises the objectTypes hashtable // This initialises the objectTypes hashtable
private void initObjectTypes() private void initObjectTypes()
{ {
for(int i=0;i<defaultObjectTypes.length;i++) for (int i = 0;i < defaultObjectTypes.length;i++)
objectTypes.put(defaultObjectTypes[i][0],defaultObjectTypes[i][1]); objectTypes.put(defaultObjectTypes[i][0], defaultObjectTypes[i][1]);
} }
// These are required by other common classes // These are required by other common classes
@@ -647,7 +677,7 @@ public abstract class Connection
* This returns a resultset. It must be overridden, so that the correct * This returns a resultset. It must be overridden, so that the correct
* version (from jdbc1 or jdbc2) are returned. * version (from jdbc1 or jdbc2) are returned.
*/ */
public abstract java.sql.ResultSet getResultSet(org.postgresql.Connection conn,java.sql.Statement stat, Field[] fields, Vector tuples, String status, int updateCount,int insertOID, boolean binaryCursor) throws SQLException; public abstract java.sql.ResultSet getResultSet(org.postgresql.Connection conn, java.sql.Statement stat, Field[] fields, Vector tuples, String status, int updateCount, int insertOID, boolean binaryCursor) throws SQLException;
/** /**
* In some cases, it is desirable to immediately release a Connection's * In some cases, it is desirable to immediately release a Connection's
@@ -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")){ {
ExecSQL("begin;"+getIsolationLevelSQL()); if (haveMinimumServerVersion("7.1"))
}else{ {
ExecSQL("begin;" + getIsolationLevelSQL());
}
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()); {
}else{ ExecSQL("commit;begin;" + getIsolationLevelSQL());
}
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()); {
}else{ ExecSQL("rollback; begin;" + getIsolationLevelSQL());
}
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;
@@ -918,7 +982,7 @@ public abstract class Connection
break; break;
default: default:
throw new PSQLException("postgresql.con.isolevel",new Integer(isolationLevel)); throw new PSQLException("postgresql.con.isolevel", new Integer(isolationLevel));
} }
return sb.toString(); return sb.toString();
} }
@@ -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");
@@ -1017,8 +1083,8 @@ public abstract class Connection
String pgType = result.getString(1); String pgType = result.getString(1);
Integer iOid = new Integer(oid); Integer iOid = new Integer(oid);
sqlType = new Integer(getSQLType(result.getString(1))); sqlType = new Integer(getSQLType(result.getString(1)));
sqlTypeCache.put(iOid,sqlType); sqlTypeCache.put(iOid, sqlType);
pgTypeCache.put(iOid,pgType); pgTypeCache.put(iOid, pgType);
result.close(); result.close();
} }
@@ -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

@@ -28,7 +28,7 @@ public class Field
* @param oid the OID of the field * @param oid the OID of the field
* @param len the length of the field * @param len the length of the field
*/ */
public Field(Connection conn, String name, int oid, int length,int mod) public Field(Connection conn, String name, int oid, int length, int mod)
{ {
this.conn = conn; this.conn = conn;
this.name = name; this.name = name;
@@ -47,7 +47,7 @@ public class Field
*/ */
public Field(Connection conn, String name, int oid, int length) public Field(Connection conn, String name, int oid, int length)
{ {
this(conn,name,oid,length,0); this(conn, name, oid, length, 0);
} }
/** /**

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.
@@ -100,7 +100,7 @@ public class PG_Stream
*/ */
public void Send(byte buf[], int siz) throws IOException public void Send(byte buf[], int siz) throws IOException
{ {
Send(buf,0,siz); Send(buf, 0, siz);
} }
/** /**
@@ -116,10 +116,10 @@ public class PG_Stream
{ {
int i; int i;
pg_output.write(buf, off, ((buf.length-off) < siz ? (buf.length-off) : siz)); pg_output.write(buf, off, ((buf.length - off) < siz ? (buf.length - off) : siz));
if((buf.length-off) < siz) if ((buf.length - off) < siz)
{ {
for (i = buf.length-off ; i < siz ; ++i) for (i = buf.length - off ; i < siz ; ++i)
{ {
pg_output.write(0); pg_output.write(0);
} }
@@ -139,9 +139,12 @@ 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");
throw new PSQLException("postgresql.stream.ioerror",e); }
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
} }
return c; return c;
} }
@@ -167,8 +170,10 @@ 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) { }
throw new PSQLException("postgresql.stream.ioerror",e); catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
} }
return n; return n;
} }
@@ -194,8 +199,10 @@ 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) { }
throw new PSQLException("postgresql.stream.ioerror",e); catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
} }
return n; return n;
} }
@@ -213,31 +220,40 @@ 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)
buflen = (int)(buflen*2); // 100% bigger { // Grow the buffer
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);
rst = newrst; rst = newrst;
} }
} }
} }
} catch (IOException e) { }
throw new PSQLException("postgresql.stream.ioerror",e); catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
} }
return encoding.decode(rst, 0, s); return encoding.decode(rst, 0, s);
} }
@@ -254,7 +270,7 @@ public class PG_Stream
*/ */
public byte[][] ReceiveTuple(int nf, boolean bin) throws SQLException public byte[][] ReceiveTuple(int nf, boolean bin) throws SQLException
{ {
int i, bim = (nf + 7)/8; int i, bim = (nf + 7) / 8;
byte[] bitmask = Receive(bim); byte[] bitmask = Receive(bim);
byte[][] answer = bytePoolDim2.allocByte(nf); byte[][] answer = bytePoolDim2.allocByte(nf);
@@ -295,7 +311,7 @@ public class PG_Stream
private byte[] Receive(int siz) throws SQLException private byte[] Receive(int siz) throws SQLException
{ {
byte[] answer = bytePoolDim1.allocByte(siz); byte[] answer = bytePoolDim1.allocByte(siz);
Receive(answer,0,siz); Receive(answer, 0, siz);
return answer; return answer;
} }
@@ -307,7 +323,7 @@ public class PG_Stream
* @param siz number of bytes to read * @param siz number of bytes to read
* @exception SQLException if a data I/O error occurs * @exception SQLException if a data I/O error occurs
*/ */
public void Receive(byte[] b,int off,int siz) throws SQLException public void Receive(byte[] b, int off, int siz) throws SQLException
{ {
int s = 0; int s = 0;
@@ -315,13 +331,15 @@ public class PG_Stream
{ {
while (s < siz) while (s < siz)
{ {
int w = pg_input.read(b, off+s, siz - s); int w = pg_input.read(b, off + s, siz - s);
if (w < 0) if (w < 0)
throw new PSQLException("postgresql.stream.eof"); throw new PSQLException("postgresql.stream.eof");
s += w; s += w;
} }
} catch (IOException e) { }
throw new PSQLException("postgresql.stream.ioerror",e); catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
} }
} }
@@ -332,10 +350,13 @@ 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) { }
throw new PSQLException("postgresql.stream.flush",e); catch (IOException e)
{
throw new PSQLException("postgresql.stream.flush", e);
} }
} }

View File

@@ -1,47 +1,47 @@
/** /**
* Redistribution and use of this software and associated documentation * Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided * ("Software"), with or without modification, are permitted provided
* that the following conditions are met: * that the following conditions are met:
* *
* 1. Redistributions of source code must retain copyright * 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a * statements and notices. Redistributions must also contain a
* copy of this document. * copy of this document.
* *
* 2. Redistributions in binary form must reproduce the * 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the * above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other * following disclaimer in the documentation and/or other
* materials provided with the distribution. * materials provided with the distribution.
* *
* 3. The name "Exolab" must not be used to endorse or promote * 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written * products derived from this Software without prior written
* permission of Exoffice Technologies. For written permission, * permission of Exoffice Technologies. For written permission,
* please contact info@exolab.org. * please contact info@exolab.org.
* *
* 4. Products derived from this Software may not be called "Exolab" * 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written * nor may "Exolab" appear in their names without prior written
* permission of Exoffice Technologies. Exolab is a registered * permission of Exoffice Technologies. Exolab is a registered
* trademark of Exoffice Technologies. * trademark of Exoffice Technologies.
* *
* 5. Due credit should be given to the Exolab Project * 5. Due credit should be given to the Exolab Project
* (http://www.exolab.org/). * (http://www.exolab.org/).
* *
* THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE. * OF THE POSSIBILITY OF SUCH DAMAGE.
* *
* 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 $
*/ */
package org.postgresql; package org.postgresql;
@@ -194,10 +194,10 @@ public class PostgresqlDataSource
* Each datasource maintains it's own driver, in case of * Each datasource maintains it's own driver, in case of
* driver-specific setup (e.g. pools, log writer). * driver-specific setup (e.g. pools, log writer).
*/ */
// FIXME // FIXME
// private transient postgresql.Driver _driver; // private transient postgresql.Driver _driver;
private transient org.postgresql.Driver _driver; private transient org.postgresql.Driver _driver;
//--------- //---------
@@ -223,21 +223,25 @@ 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.
// FIXME // FIXME
// _driver = new postgresql.Driver(); // _driver = new postgresql.Driver();
_driver = new org.postgresql.Driver(); _driver = new org.postgresql.Driver();
//----------- //-----------
//FIXME //FIXME
// _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,12 +311,13 @@ 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 );
// Method seems to be unavailable. Commented it out. // Method seems to be unavailable. Commented it out.
//---------- //----------
_logWriter = writer; _logWriter = 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

@@ -42,7 +42,7 @@ public abstract class ResultSet
* @param updateCount the number of rows affected by the operation * @param updateCount the number of rows affected by the operation
* @param cursor the positioned update/delete cursor name * @param cursor the positioned update/delete cursor name
*/ */
public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount,int insertOID, boolean binaryCursor) public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount, int insertOID, boolean binaryCursor)
{ {
this.connection = conn; this.connection = conn;
this.fields = fields; this.fields = fields;
@@ -69,7 +69,7 @@ public abstract class ResultSet
*/ */
public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount) public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount)
{ {
this(conn,fields,tuples,status,updateCount,0,false); this(conn, fields, tuples, status, updateCount, 0, false);
} }
/** /**
@@ -166,7 +166,7 @@ public abstract class ResultSet
*/ */
public int getColumnOID(int field) public int getColumnOID(int field)
{ {
return fields[field-1].getOID(); return fields[field -1].getOID();
} }
/** /**
@@ -190,20 +190,23 @@ 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
wasNullFlag = (this_row[col - 1] == null); wasNullFlag = (this_row[col - 1] == null);
if(wasNullFlag) if (wasNullFlag)
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);
} }
return s; return s;

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;
@@ -42,11 +43,11 @@ public abstract class Statement {
// Static variables for parsing SQL when escapeProcessing is true. // Static variables for parsing SQL when escapeProcessing is true.
private static final short IN_SQLCODE = 0; private static final short IN_SQLCODE = 0;
private static final short IN_STRING = 1; private static final short IN_STRING = 1;
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,10 +234,11 @@ 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)
rs.close(); rs.close();
// Disasociate it from us (For Garbage Collection) // Disasociate it from us (For Garbage Collection)
@@ -249,28 +264,28 @@ public abstract class Statement {
int i = -1; int i = -1;
int len = sql.length(); int len = sql.length();
while(++i < len) while (++i < len)
{ {
char c = sql.charAt(i); char c = sql.charAt(i);
switch(state) switch (state)
{ {
case IN_SQLCODE: case IN_SQLCODE:
if(c == '\'') // start of a string? if (c == '\'') // start of a string?
state = IN_STRING; state = IN_STRING;
else if(c == '{') // start of an escape code? else if (c == '{') // start of an escape code?
if(i+1 < len) if (i + 1 < len)
{ {
char next = sql.charAt(i+1); char next = sql.charAt(i + 1);
if(next == 'd') if (next == 'd')
{ {
state = ESC_TIMEDATE; state = ESC_TIMEDATE;
i++; i++;
break; break;
} }
else if(next == 't') else if (next == 't')
{ {
state = ESC_TIMEDATE; state = ESC_TIMEDATE;
i += (i+2 < len && sql.charAt(i+2) == 's') ? 2 : 1; i += (i + 2 < len && sql.charAt(i + 2) == 's') ? 2 : 1;
break; break;
} }
} }
@@ -278,9 +293,9 @@ public abstract class Statement {
break; break;
case IN_STRING: case IN_STRING:
if(c == '\'') // end of string? if (c == '\'') // end of string?
state = IN_SQLCODE; state = IN_SQLCODE;
else if(c == '\\') // a backslash? else if (c == '\\') // a backslash?
state = BACKSLASH; state = BACKSLASH;
newsql.append(c); newsql.append(c);
@@ -293,7 +308,7 @@ public abstract class Statement {
break; break;
case ESC_TIMEDATE: case ESC_TIMEDATE:
if(c == '}') if (c == '}')
state = IN_SQLCODE; // end of escape code. state = IN_SQLCODE; // end of escape code.
else else
newsql.append(c); newsql.append(c);

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.
@@ -13,21 +14,23 @@ public class BytePoolDim1 {
/** /**
* The pools not currently in use * The pools not currently in use
*/ */
ObjectPool notusemap[] = new ObjectPool[maxsize+1]; ObjectPool notusemap[] = new ObjectPool[maxsize + 1];
/** /**
* The pools currently in use * The pools currently in use
*/ */
ObjectPool inusemap[] = new ObjectPool[maxsize+1]; ObjectPool inusemap[] = new ObjectPool[maxsize + 1];
/** /**
* *
*/ */
byte binit[][] = new byte[maxsize+1][0]; byte binit[][] = new byte[maxsize + 1][0];
/** /**
* 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,10 +73,11 @@ 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 ;
ObjectPool not_usel = notusemap[b.length]; ObjectPool not_usel = notusemap[b.length];
ObjectPool in_usel = inusemap[b.length]; ObjectPool in_usel = inusemap[b.length];
@@ -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,9 +38,11 @@ public class BytePoolDim2 {
*/ */
} }
public void release(byte[][] b){ public void release(byte[][] b)
if(b.length > maxsize){ {
return; if (b.length > maxsize)
{
return ;
} }
ObjectPool not_usel = notusemap[b.length]; ObjectPool not_usel = notusemap[b.length];
ObjectPool in_usel = inusemap[b.length]; ObjectPool in_usel = inusemap[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,8 +21,9 @@ 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;
arr = newarr; arr = newarr;
@@ -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,13 +44,15 @@ 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; {
while(p<cursize && !arr[p].equals(o)) int p = 0;
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,15 +77,17 @@ 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;
arr = newarr; arr = newarr;
@@ -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

@@ -40,10 +40,10 @@ public class Fastpath
* @param conn org.postgresql.Connection to attach to * @param conn org.postgresql.Connection to attach to
* @param stream The network stream to the backend * @param stream The network stream to the backend
*/ */
public Fastpath(org.postgresql.Connection conn,org.postgresql.PG_Stream stream) public Fastpath(org.postgresql.Connection conn, org.postgresql.PG_Stream stream)
{ {
this.conn=conn; this.conn = conn;
this.stream=stream; this.stream = stream;
//DriverManager.println("Fastpath initialised"); //DriverManager.println("Fastpath initialised");
} }
@@ -56,29 +56,33 @@ public class Fastpath
* @return null if no data, Integer if an integer result, or byte[] otherwise * @return null if no data, Integer if an integer result, or byte[] otherwise
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
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);
stream.SendInteger(0,1); stream.SendInteger(0, 1);
stream.SendInteger(fnid,4); stream.SendInteger(fnid, 4);
stream.SendInteger(args.length,4); stream.SendInteger(args.length, 4);
for(int i=0;i<args.length;i++) for (int i = 0;i < args.length;i++)
args[i].send(stream); args[i].send(stream);
// This is needed, otherwise data can be lost // This is needed, otherwise data can be lost
stream.flush(); stream.flush();
} catch(IOException ioe) { }
throw new PSQLException("postgresql.fp.send",new Integer(fnid),ioe); catch (IOException ioe)
{
throw new PSQLException("postgresql.fp.send", new Integer(fnid), ioe);
} }
// Now handle the result // Now handle the result
@@ -95,10 +99,11 @@ 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)
{ {
case 'V': case 'V':
break; break;
@@ -111,11 +116,12 @@ public class Fastpath
//DriverManager.println("G: size="+sz); //debug //DriverManager.println("G: size="+sz); //debug
// 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;
} }
break; break;
@@ -123,7 +129,7 @@ public class Fastpath
//------------------------------ //------------------------------
// Error message returned // Error message returned
case 'E': case 'E':
throw new PSQLException("postgresql.fp.error",stream.ReceiveString(conn.getEncoding())); throw new PSQLException("postgresql.fp.error", stream.ReceiveString(conn.getEncoding()));
//------------------------------ //------------------------------
// Notice from backend // Notice from backend
@@ -144,7 +150,7 @@ public class Fastpath
break; break;
default: default:
throw new PSQLException("postgresql.fp.protocol",new Character((char)in)); throw new PSQLException("postgresql.fp.protocol", new Character((char)in));
} }
} }
} }
@@ -170,10 +176,10 @@ public class Fastpath
* occurs. * occurs.
* @see org.postgresql.LargeObject * @see org.postgresql.LargeObject
*/ */
public Object fastpath(String name,boolean resulttype,FastpathArg[] args) throws SQLException public Object fastpath(String name, boolean resulttype, FastpathArg[] args) throws SQLException
{ {
//DriverManager.println("Fastpath: calling "+name); //DriverManager.println("Fastpath: calling "+name);
return fastpath(getID(name),resulttype,args); return fastpath(getID(name), resulttype, args);
} }
/** /**
@@ -183,11 +189,11 @@ public class Fastpath
* @return integer result * @return integer result
* @exception SQLException if a database-access error occurs or no result * @exception SQLException if a database-access error occurs or no result
*/ */
public int getInteger(String name,FastpathArg[] args) throws SQLException public int getInteger(String name, FastpathArg[] args) throws SQLException
{ {
Integer i = (Integer)fastpath(name,true,args); Integer i = (Integer)fastpath(name, true, args);
if(i==null) if (i == null)
throw new PSQLException("postgresql.fp.expint",name); throw new PSQLException("postgresql.fp.expint", name);
return i.intValue(); return i.intValue();
} }
@@ -198,9 +204,9 @@ public class Fastpath
* @return byte[] array containing result * @return byte[] array containing result
* @exception SQLException if a database-access error occurs or no result * @exception SQLException if a database-access error occurs or no result
*/ */
public byte[] getData(String name,FastpathArg[] args) throws SQLException public byte[] getData(String name, FastpathArg[] args) throws SQLException
{ {
return (byte[])fastpath(name,false,args); return (byte[])fastpath(name, false, args);
} }
/** /**
@@ -214,9 +220,9 @@ public class Fastpath
* @param name Function name * @param name Function name
* @param fnid Function id * @param fnid Function id
*/ */
public void addFunction(String name,int fnid) public void addFunction(String name, int fnid)
{ {
func.put(name,new Integer(fnid)); func.put(name, new Integer(fnid));
} }
/** /**
@@ -253,8 +259,9 @@ 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)));
} }
} }
@@ -279,8 +286,8 @@ public class Fastpath
// //
// so, until we know we can do this (needs testing, on the TODO list) // so, until we know we can do this (needs testing, on the TODO list)
// for now, we throw the exception and do no lookups. // for now, we throw the exception and do no lookups.
if(id==null) if (id == null)
throw new PSQLException("postgresql.fp.unknown",name); throw new PSQLException("postgresql.fp.unknown", name);
return id.intValue(); return id.intValue();
} }

View File

@@ -43,8 +43,8 @@ public class FastpathArg
*/ */
public FastpathArg(int value) public FastpathArg(int value)
{ {
type=true; type = true;
this.value=value; this.value = value;
} }
/** /**
@@ -53,8 +53,8 @@ public class FastpathArg
*/ */
public FastpathArg(byte bytes[]) public FastpathArg(byte bytes[])
{ {
type=false; type = false;
this.bytes=bytes; this.bytes = bytes;
} }
/** /**
@@ -63,11 +63,11 @@ public class FastpathArg
* @param off offset within array * @param off offset within array
* @param len length of data to include * @param len length of data to include
*/ */
public FastpathArg(byte buf[],int off,int len) public FastpathArg(byte buf[], int off, int len)
{ {
type=false; type = false;
bytes = new byte[len]; bytes = new byte[len];
System.arraycopy(buf,off,bytes,0,len); System.arraycopy(buf, off, bytes, 0, len);
} }
/** /**
@@ -92,13 +92,16 @@ 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

@@ -7,7 +7,7 @@ import org.postgresql.util.*;
/** /**
* This represents the box datatype within org.postgresql. * This represents the box datatype within org.postgresql.
*/ */
public class PGbox extends PGobject implements Serializable,Cloneable public class PGbox extends PGobject implements Serializable, Cloneable
{ {
/** /**
* These are the two points. * These are the two points.
@@ -20,18 +20,18 @@ public class PGbox extends PGobject implements Serializable,Cloneable
* @param x2 second x coordinate * @param x2 second x coordinate
* @param y2 second y coordinate * @param y2 second y coordinate
*/ */
public PGbox(double x1,double y1,double x2,double y2) public PGbox(double x1, double y1, double x2, double y2)
{ {
this(); this();
this.point[0] = new PGpoint(x1,y1); this.point[0] = new PGpoint(x1, y1);
this.point[1] = new PGpoint(x2,y2); this.point[1] = new PGpoint(x2, y2);
} }
/** /**
* @param p1 first point * @param p1 first point
* @param p2 second point * @param p2 second point
*/ */
public PGbox(PGpoint p1,PGpoint p2) public PGbox(PGpoint p1, PGpoint p2)
{ {
this(); this();
this.point[0] = p1; this.point[0] = p1;
@@ -65,9 +65,9 @@ public class PGbox extends PGobject implements Serializable,Cloneable
*/ */
public void setValue(String value) throws SQLException public void setValue(String value) throws SQLException
{ {
PGtokenizer t = new PGtokenizer(value,','); PGtokenizer t = new PGtokenizer(value, ',');
if(t.getSize() != 2) if (t.getSize() != 2)
throw new PSQLException("postgresql.geo.box",value); throw new PSQLException("postgresql.geo.box", value);
point[0] = new PGpoint(t.getToken(0)); point[0] = new PGpoint(t.getToken(0));
point[1] = new PGpoint(t.getToken(1)); point[1] = new PGpoint(t.getToken(1));
@@ -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]));
@@ -92,7 +93,7 @@ public class PGbox extends PGobject implements Serializable,Cloneable
*/ */
public Object clone() public Object clone()
{ {
return new PGbox((PGpoint)point[0].clone(),(PGpoint)point[1].clone()); return new PGbox((PGpoint)point[0].clone(), (PGpoint)point[1].clone());
} }
/** /**
@@ -100,6 +101,6 @@ public class PGbox extends PGobject implements Serializable,Cloneable
*/ */
public String getValue() public String getValue()
{ {
return point[0].toString()+","+point[1].toString(); return point[0].toString() + "," + point[1].toString();
} }
} }

View File

@@ -8,7 +8,7 @@ import org.postgresql.util.*;
* This represents org.postgresql's circle datatype, consisting of a point and * This represents org.postgresql's circle datatype, consisting of a point and
* a radius * a radius
*/ */
public class PGcircle extends PGobject implements Serializable,Cloneable public class PGcircle extends PGobject implements Serializable, Cloneable
{ {
/** /**
* This is the centre point * This is the centre point
@@ -25,16 +25,16 @@ public class PGcircle extends PGobject implements Serializable,Cloneable
* @param y coordinate of centre * @param y coordinate of centre
* @param r radius of circle * @param r radius of circle
*/ */
public PGcircle(double x,double y,double r) public PGcircle(double x, double y, double r)
{ {
this(new PGpoint(x,y),r); this(new PGpoint(x, y), r);
} }
/** /**
* @param c PGpoint describing the circle's centre * @param c PGpoint describing the circle's centre
* @param r radius of circle * @param r radius of circle
*/ */
public PGcircle(PGpoint c,double r) public PGcircle(PGpoint c, double r)
{ {
this(); this();
this.center = c; this.center = c;
@@ -65,15 +65,18 @@ public class PGcircle extends PGobject implements Serializable,Cloneable
*/ */
public void setValue(String s) throws SQLException public void setValue(String s) throws SQLException
{ {
PGtokenizer t = new PGtokenizer(PGtokenizer.removeAngle(s),','); PGtokenizer t = new PGtokenizer(PGtokenizer.removeAngle(s), ',');
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) { }
throw new PSQLException("postgresql.geo.circle",e); catch (NumberFormatException e)
{
throw new PSQLException("postgresql.geo.circle", e);
} }
} }
@@ -83,9 +86,10 @@ 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;
} }
return false; return false;
} }
@@ -95,7 +99,7 @@ public class PGcircle extends PGobject implements Serializable,Cloneable
*/ */
public Object clone() public Object clone()
{ {
return new PGcircle((PGpoint)center.clone(),radius); return new PGcircle((PGpoint)center.clone(), radius);
} }
/** /**
@@ -103,6 +107,6 @@ public class PGcircle extends PGobject implements Serializable,Cloneable
*/ */
public String getValue() public String getValue()
{ {
return "<"+center+","+radius+">"; return "<" + center + "," + radius + ">";
} }
} }

View File

@@ -10,7 +10,7 @@ import org.postgresql.util.*;
* Currently line is not yet implemented in the backend, but this class * Currently line is not yet implemented in the backend, but this class
* ensures that when it's done were ready for it. * ensures that when it's done were ready for it.
*/ */
public class PGline extends PGobject implements Serializable,Cloneable public class PGline extends PGobject implements Serializable, Cloneable
{ {
/** /**
* These are the two points. * These are the two points.
@@ -23,16 +23,16 @@ public class PGline extends PGobject implements Serializable,Cloneable
* @param x2 coordinate for second point * @param x2 coordinate for second point
* @param y2 coordinate for second point * @param y2 coordinate for second point
*/ */
public PGline(double x1,double y1,double x2,double y2) public PGline(double x1, double y1, double x2, double y2)
{ {
this(new PGpoint(x1,y1),new PGpoint(x2,y2)); this(new PGpoint(x1, y1), new PGpoint(x2, y2));
} }
/** /**
* @param p1 first point * @param p1 first point
* @param p2 second point * @param p2 second point
*/ */
public PGline(PGpoint p1,PGpoint p2) public PGline(PGpoint p1, PGpoint p2)
{ {
this(); this();
this.point[0] = p1; this.point[0] = p1;
@@ -63,9 +63,9 @@ public class PGline extends PGobject implements Serializable,Cloneable
*/ */
public void setValue(String s) throws SQLException public void setValue(String s) throws SQLException
{ {
PGtokenizer t = new PGtokenizer(PGtokenizer.removeBox(s),','); PGtokenizer t = new PGtokenizer(PGtokenizer.removeBox(s), ',');
if(t.getSize() != 2) if (t.getSize() != 2)
throw new PSQLException("postgresql.geo.line",s); throw new PSQLException("postgresql.geo.line", s);
point[0] = new PGpoint(t.getToken(0)); point[0] = new PGpoint(t.getToken(0));
point[1] = new PGpoint(t.getToken(1)); point[1] = new PGpoint(t.getToken(1));
@@ -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]));
@@ -90,7 +91,7 @@ public class PGline extends PGobject implements Serializable,Cloneable
*/ */
public Object clone() public Object clone()
{ {
return new PGline((PGpoint)point[0].clone(),(PGpoint)point[1].clone()); return new PGline((PGpoint)point[0].clone(), (PGpoint)point[1].clone());
} }
/** /**
@@ -98,6 +99,6 @@ public class PGline extends PGobject implements Serializable,Cloneable
*/ */
public String getValue() public String getValue()
{ {
return "["+point[0]+","+point[1]+"]"; return "[" + point[0] + "," + point[1] + "]";
} }
} }

View File

@@ -7,7 +7,7 @@ import org.postgresql.util.*;
/** /**
* This implements a lseg (line segment) consisting of two points * This implements a lseg (line segment) consisting of two points
*/ */
public class PGlseg extends PGobject implements Serializable,Cloneable public class PGlseg extends PGobject implements Serializable, Cloneable
{ {
/** /**
* These are the two points. * These are the two points.
@@ -20,16 +20,16 @@ public class PGlseg extends PGobject implements Serializable,Cloneable
* @param x2 coordinate for second point * @param x2 coordinate for second point
* @param y2 coordinate for second point * @param y2 coordinate for second point
*/ */
public PGlseg(double x1,double y1,double x2,double y2) public PGlseg(double x1, double y1, double x2, double y2)
{ {
this(new PGpoint(x1,y1),new PGpoint(x2,y2)); this(new PGpoint(x1, y1), new PGpoint(x2, y2));
} }
/** /**
* @param p1 first point * @param p1 first point
* @param p2 second point * @param p2 second point
*/ */
public PGlseg(PGpoint p1,PGpoint p2) public PGlseg(PGpoint p1, PGpoint p2)
{ {
this(); this();
this.point[0] = p1; this.point[0] = p1;
@@ -60,8 +60,8 @@ public class PGlseg extends PGobject implements Serializable,Cloneable
*/ */
public void setValue(String s) throws SQLException public void setValue(String s) throws SQLException
{ {
PGtokenizer t = new PGtokenizer(PGtokenizer.removeBox(s),','); PGtokenizer t = new PGtokenizer(PGtokenizer.removeBox(s), ',');
if(t.getSize() != 2) if (t.getSize() != 2)
throw new PSQLException("postgresql.geo.lseg"); throw new PSQLException("postgresql.geo.lseg");
point[0] = new PGpoint(t.getToken(0)); point[0] = new PGpoint(t.getToken(0));
@@ -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]));
@@ -87,7 +88,7 @@ public class PGlseg extends PGobject implements Serializable,Cloneable
*/ */
public Object clone() public Object clone()
{ {
return new PGlseg((PGpoint)point[0].clone(),(PGpoint)point[1].clone()); return new PGlseg((PGpoint)point[0].clone(), (PGpoint)point[1].clone());
} }
/** /**
@@ -95,6 +96,6 @@ public class PGlseg extends PGobject implements Serializable,Cloneable
*/ */
public String getValue() public String getValue()
{ {
return "["+point[0]+","+point[1]+"]"; return "[" + point[0] + "," + point[1] + "]";
} }
} }

View File

@@ -7,7 +7,7 @@ import org.postgresql.util.*;
/** /**
* This implements a path (a multiple segmented line, which may be closed) * This implements a path (a multiple segmented line, which may be closed)
*/ */
public class PGpath extends PGobject implements Serializable,Cloneable public class PGpath extends PGobject implements Serializable, Cloneable
{ {
/** /**
* True if the path is open, false if closed * True if the path is open, false if closed
@@ -23,7 +23,7 @@ public class PGpath extends PGobject implements Serializable,Cloneable
* @param points the PGpoints that define the path * @param points the PGpoints that define the path
* @param open True if the path is open, false if closed * @param open True if the path is open, false if closed
*/ */
public PGpath(PGpoint[] points,boolean open) public PGpath(PGpoint[] points, boolean open)
{ {
this(); this();
this.points = points; this.points = points;
@@ -55,19 +55,23 @@ 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, ',');
int npoints = t.getSize(); int npoints = t.getSize();
points = new PGpoint[npoints]; points = new PGpoint[npoints];
for(int p=0;p<npoints;p++) for (int p = 0;p < npoints;p++)
points[p] = new PGpoint(t.getToken(p)); points[p] = new PGpoint(t.getToken(p));
} }
@@ -77,17 +81,18 @@ 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)
return false; return false;
if(p.open != open) if (p.open != open)
return false; return false;
for(int i=0;i<points.length;i++) for (int i = 0;i < points.length;i++)
if(!points[i].equals(p.points[i])) if (!points[i].equals(p.points[i]))
return false; return false;
return true; return true;
@@ -101,9 +106,9 @@ public class PGpath extends PGobject implements Serializable,Cloneable
public Object clone() public Object clone()
{ {
PGpoint ary[] = new PGpoint[points.length]; PGpoint ary[] = new PGpoint[points.length];
for(int i=0;i<points.length;i++) for (int i = 0;i < points.length;i++)
ary[i]=(PGpoint)points[i].clone(); ary[i] = (PGpoint)points[i].clone();
return new PGpath(ary,open); return new PGpath(ary, open);
} }
/** /**
@@ -111,13 +116,15 @@ public class PGpath extends PGobject implements Serializable,Cloneable
*/ */
public String getValue() public String getValue()
{ {
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 ? "]" : ")");
return b.toString(); return b.toString();
} }

View File

@@ -12,7 +12,7 @@ import org.postgresql.util.*;
* *
* <p>It maps to the point datatype in org.postgresql. * <p>It maps to the point datatype in org.postgresql.
*/ */
public class PGpoint extends PGobject implements Serializable,Cloneable public class PGpoint extends PGobject implements Serializable, Cloneable
{ {
/** /**
* The X coordinate of the point * The X coordinate of the point
@@ -28,7 +28,7 @@ public class PGpoint extends PGobject implements Serializable,Cloneable
* @param x coordinate * @param x coordinate
* @param y coordinate * @param y coordinate
*/ */
public PGpoint(double x,double y) public PGpoint(double x, double y)
{ {
this(); this();
this.x = x; this.x = x;
@@ -61,12 +61,15 @@ 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) { }
throw new PSQLException("postgresql.geo.point",e.toString()); catch (NumberFormatException e)
{
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;
} }
@@ -88,7 +92,7 @@ public class PGpoint extends PGobject implements Serializable,Cloneable
*/ */
public Object clone() public Object clone()
{ {
return new PGpoint(x,y); return new PGpoint(x, y);
} }
/** /**
@@ -96,7 +100,7 @@ public class PGpoint extends PGobject implements Serializable,Cloneable
*/ */
public String getValue() public String getValue()
{ {
return "("+x+","+y+")"; return "(" + x + "," + y + ")";
} }
/** /**
@@ -104,9 +108,9 @@ public class PGpoint extends PGobject implements Serializable,Cloneable
* @param x integer amount to add on the x axis * @param x integer amount to add on the x axis
* @param y integer amount to add on the y axis * @param y integer amount to add on the y axis
*/ */
public void translate(int x,int y) public void translate(int x, int y)
{ {
translate((double)x,(double)y); translate((double)x, (double)y);
} }
/** /**
@@ -114,7 +118,7 @@ public class PGpoint extends PGobject implements Serializable,Cloneable
* @param x double amount to add on the x axis * @param x double amount to add on the x axis
* @param y double amount to add on the y axis * @param y double amount to add on the y axis
*/ */
public void translate(double x,double y) public void translate(double x, double y)
{ {
this.x += x; this.x += x;
this.y += y; this.y += y;
@@ -125,9 +129,9 @@ public class PGpoint extends PGobject implements Serializable,Cloneable
* @param x integer coordinate * @param x integer coordinate
* @param y integer coordinate * @param y integer coordinate
*/ */
public void move(int x,int y) public void move(int x, int y)
{ {
setLocation(x,y); setLocation(x, y);
} }
/** /**
@@ -135,7 +139,7 @@ public class PGpoint extends PGobject implements Serializable,Cloneable
* @param x double coordinate * @param x double coordinate
* @param y double coordinate * @param y double coordinate
*/ */
public void move(double x,double y) public void move(double x, double y)
{ {
this.x = x; this.x = x;
this.y = y; this.y = y;
@@ -148,9 +152,9 @@ public class PGpoint extends PGobject implements Serializable,Cloneable
* @param y integer coordinate * @param y integer coordinate
* @see java.awt.Point * @see java.awt.Point
*/ */
public void setLocation(int x,int y) public void setLocation(int x, int y)
{ {
move((double)x,(double)y); move((double)x, (double)y);
} }
/** /**
@@ -161,7 +165,7 @@ public class PGpoint extends PGobject implements Serializable,Cloneable
*/ */
public void setLocation(Point p) public void setLocation(Point p)
{ {
setLocation(p.x,p.y); setLocation(p.x, p.y);
} }
} }

View File

@@ -7,7 +7,7 @@ import org.postgresql.util.*;
/** /**
* This implements the polygon datatype within PostgreSQL. * This implements the polygon datatype within PostgreSQL.
*/ */
public class PGpolygon extends PGobject implements Serializable,Cloneable public class PGpolygon extends PGobject implements Serializable, Cloneable
{ {
/** /**
* The points defining the polygon * The points defining the polygon
@@ -49,10 +49,10 @@ public class PGpolygon 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), ',');
int npoints = t.getSize(); int npoints = t.getSize();
points = new PGpoint[npoints]; points = new PGpoint[npoints];
for(int p=0;p<npoints;p++) for (int p = 0;p < npoints;p++)
points[p] = new PGpoint(t.getToken(p)); points[p] = new PGpoint(t.getToken(p));
} }
@@ -62,14 +62,15 @@ 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)
return false; return false;
for(int i=0;i<points.length;i++) for (int i = 0;i < points.length;i++)
if(!points[i].equals(p.points[i])) if (!points[i].equals(p.points[i]))
return false; return false;
return true; return true;
@@ -83,7 +84,7 @@ public class PGpolygon extends PGobject implements Serializable,Cloneable
public Object clone() public Object clone()
{ {
PGpoint ary[] = new PGpoint[points.length]; PGpoint ary[] = new PGpoint[points.length];
for(int i=0;i<points.length;i++) for (int i = 0;i < points.length;i++)
ary[i] = (PGpoint)points[i].clone(); ary[i] = (PGpoint)points[i].clone();
return new PGpolygon(ary); return new PGpolygon(ary);
} }
@@ -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

@@ -44,9 +44,9 @@ public class CallableStatement extends PreparedStatement implements java.sql.Cal
/** /**
* @exception SQLException on failure * @exception SQLException on failure
*/ */
CallableStatement(Connection c,String q) throws SQLException CallableStatement(Connection c, String q) throws SQLException
{ {
super(c,q); super(c, q);
} }
/** /**
@@ -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
@@ -122,7 +122,7 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
*/ */
public java.sql.DatabaseMetaData getMetaData() throws SQLException public java.sql.DatabaseMetaData getMetaData() throws SQLException
{ {
if(metadata==null) if (metadata == null)
metadata = new DatabaseMetaData(this); metadata = new DatabaseMetaData(this);
return metadata; return metadata;
} }
@@ -131,10 +131,10 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
* This overides the method in org.postgresql.Connection and returns a * This overides the method in org.postgresql.Connection and returns a
* ResultSet. * ResultSet.
*/ */
public java.sql.ResultSet getResultSet(org.postgresql.Connection conn,java.sql.Statement stat, Field[] fields, Vector tuples, String status, int updateCount,int insertOID, boolean binaryCursor) throws SQLException public java.sql.ResultSet getResultSet(org.postgresql.Connection conn, java.sql.Statement stat, Field[] fields, Vector tuples, String status, int updateCount, int insertOID, boolean binaryCursor) throws SQLException
{ {
// in jdbc1 stat is ignored. // in jdbc1 stat is ignored.
return new org.postgresql.jdbc1.ResultSet((org.postgresql.jdbc1.Connection)conn,fields,tuples,status,updateCount,insertOID,binaryCursor); return new org.postgresql.jdbc1.ResultSet((org.postgresql.jdbc1.Connection)conn, fields, tuples, status, updateCount, insertOID, binaryCursor);
} }
@@ -146,9 +146,11 @@ 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])) { {
sqlType=jdbc1Typei[i]; if (pgTypeName.equals(jdbc1Types[i]))
{
sqlType = jdbc1Typei[i];
break; break;
} }
} }
@@ -166,19 +168,19 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
*/ */
private static final String jdbc1Types[] = { private static final String jdbc1Types[] = {
"int2", "int2",
"int4","oid", "int4", "oid",
"int8", "int8",
"cash","money", "cash", "money",
"numeric", "numeric",
"float4", "float4",
"float8", "float8",
"bpchar","char","char2","char4","char8","char16", "bpchar", "char", "char2", "char4", "char8", "char16",
"varchar","text","name","filename", "varchar", "text", "name", "filename",
"bytea", "bytea",
"bool", "bool",
"date", "date",
"time", "time",
"abstime","timestamp" "abstime", "timestamp"
}; };
/** /**
@@ -190,19 +192,19 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
*/ */
private static final int jdbc1Typei[] = { private static final int jdbc1Typei[] = {
Types.SMALLINT, Types.SMALLINT,
Types.INTEGER,Types.INTEGER, Types.INTEGER, Types.INTEGER,
Types.BIGINT, Types.BIGINT,
Types.DOUBLE,Types.DOUBLE, Types.DOUBLE, Types.DOUBLE,
Types.NUMERIC, Types.NUMERIC,
Types.REAL, Types.REAL,
Types.DOUBLE, Types.DOUBLE,
Types.CHAR,Types.CHAR,Types.CHAR,Types.CHAR,Types.CHAR,Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR,
Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.BINARY, Types.BINARY,
Types.BIT, Types.BIT,
Types.DATE, Types.DATE,
Types.TIME, Types.TIME,
Types.TIMESTAMP,Types.TIMESTAMP Types.TIMESTAMP, Types.TIMESTAMP
}; };

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
@@ -1522,15 +1522,15 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
f[0] = new Field(connection, "PROCEDURE_CAT", iVarcharOid, 32); f[0] = new Field(connection, "PROCEDURE_CAT", iVarcharOid, 32);
f[1] = new Field(connection, "PROCEDURE_SCHEM", iVarcharOid, 32); f[1] = new Field(connection, "PROCEDURE_SCHEM", iVarcharOid, 32);
f[2] = new Field(connection, "PROCEDURE_NAME", iVarcharOid, 32); f[2] = new Field(connection, "PROCEDURE_NAME", iVarcharOid, 32);
f[3] = f[4] = f[5] = new Field(connection,"reserved",iVarcharOid,32); // null; // reserved, must be null for now f[3] = f[4] = f[5] = new Field(connection, "reserved", iVarcharOid, 32); // null; // reserved, must be null for now
f[6] = new Field(connection, "REMARKS", iVarcharOid, 8192); f[6] = new Field(connection, "REMARKS", iVarcharOid, 8192);
f[7] = new Field(connection, "PROCEDURE_TYPE", iInt2Oid, 2); f[7] = new Field(connection, "PROCEDURE_TYPE", iInt2Oid, 2);
// If the pattern is null, then set it to the default // If the pattern is null, then set it to the default
if(procedureNamePattern==null) if (procedureNamePattern == null)
procedureNamePattern="%"; procedureNamePattern = "%";
r = connection.ExecSQL("select proname, proretset from pg_proc where proname like '"+procedureNamePattern.toLowerCase()+"' order by proname"); r = connection.ExecSQL("select proname, proretset from pg_proc where proname like '" + procedureNamePattern.toLowerCase() + "' order by proname");
while (r.next()) while (r.next())
{ {
@@ -1600,11 +1600,11 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// Implementation note: This is required for Borland's JBuilder to work // Implementation note: This is required for Borland's JBuilder to work
public java.sql.ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException public java.sql.ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException
{ {
if(procedureNamePattern==null) if (procedureNamePattern == null)
procedureNamePattern="%"; procedureNamePattern = "%";
if(columnNamePattern==null) if (columnNamePattern == null)
columnNamePattern="%"; columnNamePattern = "%";
// for now, this returns an empty result set. // for now, this returns an empty result set.
Field f[] = new Field[13]; Field f[] = new Field[13];
@@ -1665,11 +1665,11 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
public java.sql.ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String types[]) throws SQLException public java.sql.ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String types[]) throws SQLException
{ {
// Handle default value for types // Handle default value for types
if(types==null) if (types == null)
types = defaultTableTypes; types = defaultTableTypes;
if(tableNamePattern==null) if (tableNamePattern == null)
tableNamePattern="%"; tableNamePattern = "%";
// the field descriptors for the new ResultSet // the field descriptors for the new ResultSet
Field f[] = new Field[5]; Field f[] = new Field[5];
@@ -1685,14 +1685,16 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// Now form the query // Now form the query
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++) {
if(getTableTypes[j][0].equals(types[i])) { for (int j = 0;j < getTableTypes.length;j++)
if(notFirst) if (getTableTypes[j][0].equals(types[i]))
{
if (notFirst)
sql.append(" or "); sql.append(" or ");
sql.append(getTableTypes[j][1]); sql.append(getTableTypes[j][1]);
notFirst=true; notFirst = true;
} }
} }
@@ -1712,21 +1714,23 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// Fetch the description for the table (if any) // Fetch the description for the table (if any)
String getDescriptionStatement = String getDescriptionStatement =
connection.haveMinimumServerVersion("7.2") ? connection.haveMinimumServerVersion("7.2") ?
"select obj_description("+r.getInt(2)+",'pg_class')" : "select obj_description(" + r.getInt(2) + ",'pg_class')" :
"select description from pg_description where objoid=" + r.getInt(2); "select description from pg_description where objoid=" + r.getInt(2);
java.sql.ResultSet dr = connection.ExecSQL(getDescriptionStatement); java.sql.ResultSet dr = connection.ExecSQL(getDescriptionStatement);
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;
@@ -1746,7 +1750,7 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
tuple[0] = null; // Catalog name tuple[0] = null; // Catalog name
tuple[1] = null; // Schema name tuple[1] = null; // Schema name
tuple[2] = r.getBytes(1); // Table name tuple[2] = r.getBytes(1); // Table name
tuple[3] = (relKind==null) ? null : relKind.getBytes(); // Table type tuple[3] = (relKind == null) ? null : relKind.getBytes(); // Table type
tuple[4] = remarks; // Remarks tuple[4] = remarks; // Remarks
v.addElement(tuple); v.addElement(tuple);
} }
@@ -1773,7 +1777,7 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// These are the default tables, used when NULL is passed to getTables // These are the default tables, used when NULL is passed to getTables
// The choice of these provide the same behaviour as psql's \d // The choice of these provide the same behaviour as psql's \d
private static final String defaultTableTypes[] = { private static final String defaultTableTypes[] = {
"TABLE","VIEW","INDEX","SEQUENCE" "TABLE", "VIEW", "INDEX", "SEQUENCE"
}; };
/** /**
@@ -1795,10 +1799,10 @@ 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();
byte[][] tuple = new byte[1][0]; byte[][] tuple = new byte[1][0];
f[0] = new Field(connection,"TABLE_SCHEM",iVarcharOid,32); f[0] = new Field(connection, "TABLE_SCHEM", iVarcharOid, 32);
tuple[0] = "".getBytes(); tuple[0] = "".getBytes();
v.addElement(tuple); v.addElement(tuple);
return new ResultSet(connection,f,v,"OK",1); return new ResultSet(connection, f, v, "OK", 1);
} }
/** /**
@@ -1836,13 +1840,14 @@ 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);
} }
return new ResultSet(connection,f,v,"OK",1); return new ResultSet(connection, f, v, "OK", 1);
} }
/** /**
@@ -1914,7 +1919,7 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
f[13] = new Field(connection, "SQL_DATA_TYPE", iInt4Oid, 4); f[13] = new Field(connection, "SQL_DATA_TYPE", iInt4Oid, 4);
f[14] = new Field(connection, "SQL_DATETIME_SUB", iInt4Oid, 4); f[14] = new Field(connection, "SQL_DATETIME_SUB", iInt4Oid, 4);
f[15] = new Field(connection, "CHAR_OCTET_LENGTH", iVarcharOid, 32); f[15] = new Field(connection, "CHAR_OCTET_LENGTH", iVarcharOid, 32);
f[16] = new Field(connection, "ORDINAL_POSITION", iInt4Oid,4); f[16] = new Field(connection, "ORDINAL_POSITION", iInt4Oid, 4);
f[17] = new Field(connection, "IS_NULLABLE", iVarcharOid, 32); f[17] = new Field(connection, "IS_NULLABLE", iVarcharOid, 32);
StringBuffer sql = new StringBuffer(512); StringBuffer sql = new StringBuffer(512);
@@ -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);
} }
@@ -2051,35 +2063,36 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
Field f[] = new Field[8]; Field f[] = new Field[8];
Vector v = new Vector(); Vector v = new Vector();
if(table==null) if (table == null)
table="%"; table = "%";
if(columnNamePattern==null) if (columnNamePattern == null)
columnNamePattern="%"; columnNamePattern = "%";
else else
columnNamePattern=columnNamePattern.toLowerCase(); columnNamePattern = columnNamePattern.toLowerCase();
f[0] = new Field(connection,"TABLE_CAT",iVarcharOid,32); f[0] = new Field(connection, "TABLE_CAT", iVarcharOid, 32);
f[1] = new Field(connection,"TABLE_SCHEM",iVarcharOid,32); f[1] = new Field(connection, "TABLE_SCHEM", iVarcharOid, 32);
f[2] = new Field(connection,"TABLE_NAME",iVarcharOid,32); f[2] = new Field(connection, "TABLE_NAME", iVarcharOid, 32);
f[3] = new Field(connection,"COLUMN_NAME",iVarcharOid,32); f[3] = new Field(connection, "COLUMN_NAME", iVarcharOid, 32);
f[4] = new Field(connection,"GRANTOR",iVarcharOid,32); f[4] = new Field(connection, "GRANTOR", iVarcharOid, 32);
f[5] = new Field(connection,"GRANTEE",iVarcharOid,32); f[5] = new Field(connection, "GRANTEE", iVarcharOid, 32);
f[6] = new Field(connection,"PRIVILEGE",iVarcharOid,32); f[6] = new Field(connection, "PRIVILEGE", iVarcharOid, 32);
f[7] = new Field(connection,"IS_GRANTABLE",iVarcharOid,32); f[7] = new Field(connection, "IS_GRANTABLE", iVarcharOid, 32);
// 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) + "\"");
// For now, don't add to the result as relacl needs to be processed. // For now, don't add to the result as relacl needs to be processed.
//v.addElement(tuple); //v.addElement(tuple);
} }
return new ResultSet(connection,f,v,"OK",1); return new ResultSet(connection, f, v, "OK", 1);
} }
/** /**
@@ -2234,11 +2247,11 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
"'' AS TABLE_SCHEM," + "'' AS TABLE_SCHEM," +
"bc.relname AS TABLE_NAME," + "bc.relname AS TABLE_NAME," +
"a.attname AS COLUMN_NAME," + "a.attname AS COLUMN_NAME," +
"a.attnum as KEY_SEQ,"+ "a.attnum as KEY_SEQ," +
"ic.relname as PK_NAME " + "ic.relname as PK_NAME " +
" FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a" + " FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a" +
" WHERE bc.relkind = 'r' " + // -- not indices " WHERE bc.relkind = 'r' " + // -- not indices
" and upper(bc.relname) = upper('"+table+"')" + " and upper(bc.relname) = upper('" + table + "')" +
" and i.indrelid = bc.oid" + " and i.indrelid = bc.oid" +
" and i.indexrelid = ic.oid" + " and i.indexrelid = ic.oid" +
" and ic.oid = a.attrelid" + " and ic.oid = a.attrelid" +
@@ -2247,67 +2260,74 @@ 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 origTable=null, primTable=new String(""), schema; String s, s2;
String origTable = null, primTable = new String(""), schema;
int i; int i;
Vector v=new Vector(); Vector v = new Vector();
s=keyRelation.getString(1); s = keyRelation.getString(1);
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); {
if (s.compareTo("")==0) { s = s.substring(s.indexOf("\\000") + 4);
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;
case 1: case 1:
primTable=s2; primTable = s2;
break; break;
case 2: case 2:
schema=s2; schema = s2;
break; break;
default: default:
v.addElement(s2); v.addElement(s2);
} }
} }
java.sql.ResultSet rstmp=connection.ExecSQL("select * from "+origTable+" where 1=0"); java.sql.ResultSet rstmp = connection.ExecSQL("select * from " + origTable + " where 1=0");
java.sql.ResultSetMetaData origCols=rstmp.getMetaData(); java.sql.ResultSetMetaData origCols = rstmp.getMetaData();
String stmp; String stmp;
// Vector tuples=new Vector(); // Vector tuples=new Vector();
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) { {
tuple=new byte[14][0]; if (stmp.compareTo(origCols.getColumnName(j)) == 0)
{
tuple = new byte[14][0];
for (int k=0;k<14;k++) for (int k = 0;k < 14;k++)
tuple[k]=null; tuple[k] = null;
//PKTABLE_NAME //PKTABLE_NAME
tuple[2]=primTable.getBytes(); tuple[2] = primTable.getBytes();
//PKTABLE_COLUMN //PKTABLE_COLUMN
stmp=(String)v.elementAt(i+1); stmp = (String)v.elementAt(i + 1);
tuple[3]=stmp.getBytes(); tuple[3] = stmp.getBytes();
//FKTABLE_NAME //FKTABLE_NAME
tuple[6]=origTable.getBytes(); tuple[6] = origTable.getBytes();
//FKCOLUMN_NAME //FKCOLUMN_NAME
tuple[7]=origCols.getColumnName(j).getBytes(); tuple[7] = origCols.getColumnName(j).getBytes();
//KEY_SEQ //KEY_SEQ
tuple[8]=Integer.toString(j).getBytes(); tuple[8] = Integer.toString(j).getBytes();
tuples.addElement(tuple); tuples.addElement(tuple);
@@ -2378,34 +2398,35 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// Added by Ola Sundell <ola@miranda.org> // Added by Ola Sundell <ola@miranda.org>
// FIXME: error checking galore! // FIXME: error checking galore!
java.sql.ResultSet rsret; java.sql.ResultSet rsret;
Field f[]=new Field[14]; Field f[] = new Field[14];
byte tuple[][]; byte tuple[][];
f[0]=new Field(connection, "PKTABLE_CAT", iVarcharOid, 32); f[0] = new Field(connection, "PKTABLE_CAT", iVarcharOid, 32);
f[1]=new Field(connection, "PKTABLE_SCHEM", iVarcharOid, 32); f[1] = new Field(connection, "PKTABLE_SCHEM", iVarcharOid, 32);
f[2]=new Field(connection, "PKTABLE_NAME", iVarcharOid, 32); f[2] = new Field(connection, "PKTABLE_NAME", iVarcharOid, 32);
f[3]=new Field(connection, "PKCOLUMN_NAME", iVarcharOid, 32); f[3] = new Field(connection, "PKCOLUMN_NAME", iVarcharOid, 32);
f[4]=new Field(connection, "FKTABLE_CAT", iVarcharOid, 32); f[4] = new Field(connection, "FKTABLE_CAT", iVarcharOid, 32);
f[5]=new Field(connection, "FKTABLE_SCHEM", iVarcharOid, 32); f[5] = new Field(connection, "FKTABLE_SCHEM", iVarcharOid, 32);
f[6]=new Field(connection, "FKTABLE_NAME", iVarcharOid, 32); f[6] = new Field(connection, "FKTABLE_NAME", iVarcharOid, 32);
f[7]=new Field(connection, "FKCOLUMN_NAME", iVarcharOid, 32); f[7] = new Field(connection, "FKCOLUMN_NAME", iVarcharOid, 32);
f[8]=new Field(connection, "KEY_SEQ", iInt2Oid, 2); f[8] = new Field(connection, "KEY_SEQ", iInt2Oid, 2);
f[9]=new Field(connection, "UPDATE_RULE", iInt2Oid, 2); f[9] = new Field(connection, "UPDATE_RULE", iInt2Oid, 2);
f[10]=new Field(connection, "DELETE_RULE", iInt2Oid, 2); f[10] = new Field(connection, "DELETE_RULE", iInt2Oid, 2);
f[11]=new Field(connection, "FK_NAME", iVarcharOid, 32); f[11] = new Field(connection, "FK_NAME", iVarcharOid, 32);
f[12]=new Field(connection, "PK_NAME", iVarcharOid, 32); f[12] = new Field(connection, "PK_NAME", iVarcharOid, 32);
f[13]=new Field(connection, "DEFERRABILITY", iInt2Oid, 2); f[13] = new Field(connection, "DEFERRABILITY", iInt2Oid, 2);
java.sql.ResultSet rs=connection.ExecSQL("select t.tgargs "+ java.sql.ResultSet rs = connection.ExecSQL("select t.tgargs " +
"from pg_class as c, pg_trigger as t "+ "from pg_class as c, pg_trigger as t " +
"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);
} }
rsret=new ResultSet(connection, f, tuples, "OK", 1); rsret = new ResultSet(connection, f, tuples, "OK", 1);
return rsret; return rsret;
} }
@@ -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,9 +2631,10 @@ 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();
tuple[1] = Integer.toString(connection.getSQLType(typname)).getBytes(); tuple[1] = Integer.toString(connection.getSQLType(typname)).getBytes();
tuple[2] = b9; // for now tuple[2] = b9; // for now
@@ -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

@@ -93,7 +93,7 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
for (i = 0 ; i < inStrings.length ; ++i) for (i = 0 ; i < inStrings.length ; ++i)
{ {
if (inStrings[i] == null) if (inStrings[i] == null)
throw new PSQLException("postgresql.prep.param",new Integer(i + 1)); throw new PSQLException("postgresql.prep.param", new Integer(i + 1));
s.append (templateStrings[i]); s.append (templateStrings[i]);
s.append (inStrings[i]); s.append (inStrings[i]);
} }
@@ -118,7 +118,7 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
for (i = 0 ; i < inStrings.length ; ++i) for (i = 0 ; i < inStrings.length ; ++i)
{ {
if (inStrings[i] == null) if (inStrings[i] == null)
throw new PSQLException("postgresql.prep.param",new Integer(i + 1)); throw new PSQLException("postgresql.prep.param", new Integer(i + 1));
s.append (templateStrings[i]); s.append (templateStrings[i]);
s.append (inStrings[i]); s.append (inStrings[i]);
} }
@@ -259,9 +259,10 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
public void setString(int parameterIndex, String x) throws SQLException public void setString(int parameterIndex, String x) throws SQLException
{ {
// 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,21 +295,27 @@ 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); {
} else { setNull(parameterIndex, Types.OTHER);
}
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();
LargeObject lob = lom.open(oid); LargeObject lob = lom.open(oid);
lob.write(x); lob.write(x);
lob.close(); lob.close();
setInt(parameterIndex,oid); setInt(parameterIndex, oid);
} }
} }
@@ -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); {
}else{ setNull(parameterIndex, Types.OTHER);
}
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); {
}else{ setNull(parameterIndex, Types.OTHER);
}
else
{
set(parameterIndex, "'" + x.toString() + "'"); set(parameterIndex, "'" + x.toString() + "'");
} }
} }
@@ -367,13 +380,16 @@ 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); {
}else{ setNull(parameterIndex, Types.OTHER);
}
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("'");
strBuf.append(df.format(x)).append('.').append(x.getNanos()/10000000).append("+00'"); strBuf.append(df.format(x)).append('.').append(x.getNanos() / 10000000).append("+00'");
set(parameterIndex, strBuf.toString()); set(parameterIndex, strBuf.toString());
} }
} }
@@ -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) {
throw new PSQLException("postgresql.unusual",l_uee);
} catch (IOException l_ioe) {
throw new PSQLException("postgresql.unusual",l_ioe);
} }
} else { catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException("postgresql.unusual", l_uee);
}
catch (IOException l_ioe)
{
throw new PSQLException("postgresql.unusual", l_ioe);
}
}
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) {
throw new PSQLException("postgresql.unusual",l_uee);
} catch (IOException l_ioe) {
throw new PSQLException("postgresql.unusual",l_ioe);
} }
} else { catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException("postgresql.unusual", l_uee);
}
catch (IOException l_ioe)
{
throw new PSQLException("postgresql.unusual", l_ioe);
}
}
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); {
} catch (IOException l_ioe) { l_bytesRead = x.read(l_bytes, 0, length);
throw new PSQLException("postgresql.unusual",l_ioe);
} }
if (l_bytesRead == length) { catch (IOException l_ioe)
{
throw new PSQLException("postgresql.unusual", l_ioe);
}
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,23 +548,27 @@ 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) { }
throw new PSQLException("postgresql.unusual",se); catch (IOException 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()
setInt(parameterIndex,oid); setInt(parameterIndex, oid);
} }
} }
@@ -565,9 +610,10 @@ 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); {
return; setNull(parameterIndex, Types.OTHER);
return ;
} }
switch (targetSqlType) switch (targetSqlType)
{ {
@@ -600,15 +646,18 @@ 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;
case Types.BINARY: case Types.BINARY:
case Types.VARBINARY: case Types.VARBINARY:
setObject(parameterIndex,x); setObject(parameterIndex, x);
break; break;
case Types.OTHER: case Types.OTHER:
setString(parameterIndex, ((PGobject)x).getValue()); setString(parameterIndex, ((PGobject)x).getValue());
@@ -631,9 +680,10 @@ 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); {
return; setNull(parameterIndex, Types.OTHER);
return ;
} }
if (x instanceof String) if (x instanceof String)
setString(parameterIndex, (String)x); setString(parameterIndex, (String)x);
@@ -682,7 +732,7 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
for (i = 0 ; i < inStrings.length ; ++i) for (i = 0 ; i < inStrings.length ; ++i)
{ {
if (inStrings[i] == null) if (inStrings[i] == null)
throw new PSQLException("postgresql.prep.param",new Integer(i + 1)); throw new PSQLException("postgresql.prep.param", new Integer(i + 1));
s.append (templateStrings[i]); s.append (templateStrings[i]);
s.append (inStrings[i]); s.append (inStrings[i]);
} }
@@ -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

@@ -72,7 +72,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
*/ */
public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount, int insertOID, boolean binaryCursor) public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount, int insertOID, boolean binaryCursor)
{ {
super(conn,fields,tuples,status,updateCount,insertOID,binaryCursor); super(conn, fields, tuples, status, updateCount, insertOID, binaryCursor);
} }
/** /**
@@ -88,7 +88,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
*/ */
public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount) public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount)
{ {
super(conn,fields,tuples,status,updateCount,0,false); super(conn, fields, tuples, status, updateCount, 0, false);
} }
/** /**
@@ -159,7 +159,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
throw new PSQLException("postgresql.res.colrange"); throw new PSQLException("postgresql.res.colrange");
wasNullFlag = (this_row[columnIndex - 1] == null); wasNullFlag = (this_row[columnIndex - 1] == null);
if(wasNullFlag) if (wasNullFlag)
return null; return null;
Encoding encoding = connection.getEncoding(); Encoding encoding = connection.getEncoding();
@@ -201,8 +201,10 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Byte.parseByte(s); return Byte.parseByte(s);
} catch (NumberFormatException e) { }
throw new PSQLException("postgresql.res.badbyte",s); catch (NumberFormatException e)
{
throw new PSQLException("postgresql.res.badbyte", s);
} }
} }
return 0; // SQL NULL return 0; // SQL NULL
@@ -224,8 +226,10 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Short.parseShort(s); return Short.parseShort(s);
} catch (NumberFormatException e) { }
throw new PSQLException("postgresql.res.badshort",s); catch (NumberFormatException e)
{
throw new PSQLException("postgresql.res.badshort", s);
} }
} }
return 0; // SQL NULL return 0; // SQL NULL
@@ -247,8 +251,10 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Integer.parseInt(s); return Integer.parseInt(s);
} catch (NumberFormatException e) { }
throw new PSQLException ("postgresql.res.badint",s); catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badint", s);
} }
} }
return 0; // SQL NULL return 0; // SQL NULL
@@ -270,8 +276,10 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Long.parseLong(s); return Long.parseLong(s);
} catch (NumberFormatException e) { }
throw new PSQLException ("postgresql.res.badlong",s); catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badlong", s);
} }
} }
return 0; // SQL NULL return 0; // SQL NULL
@@ -293,8 +301,10 @@ 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) { }
throw new PSQLException ("postgresql.res.badfloat",s); catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badfloat", s);
} }
} }
return 0; // SQL NULL return 0; // SQL NULL
@@ -316,8 +326,10 @@ 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) { }
throw new PSQLException ("postgresql.res.baddouble",s); catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.baddouble", s);
} }
} }
return 0; // SQL NULL return 0; // SQL NULL
@@ -342,14 +354,18 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
val = new BigDecimal(s); val = new BigDecimal(s);
} catch (NumberFormatException e) { }
throw new PSQLException ("postgresql.res.badbigdec",s); catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badbigdec", s);
} }
try try
{ {
return val.setScale(scale); return val.setScale(scale);
} catch (ArithmeticException e) { }
throw new PSQLException ("postgresql.res.badbigdec",s); catch (ArithmeticException e)
{
throw new PSQLException ("postgresql.res.badbigdec", s);
} }
} }
return null; // SQL NULL return null; // SQL NULL
@@ -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());
@@ -409,7 +431,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
public java.sql.Date getDate(int columnIndex) throws SQLException public java.sql.Date getDate(int columnIndex) throws SQLException
{ {
String s = getString(columnIndex); String s = getString(columnIndex);
if(s==null) if (s == null)
return null; return null;
return java.sql.Date.valueOf(s); return java.sql.Date.valueOf(s);
} }
@@ -432,12 +454,14 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
{ {
if (s.length() != 5 && s.length() != 8) if (s.length() != 5 && s.length() != 8)
throw new NumberFormatException("Wrong Length!"); throw new NumberFormatException("Wrong Length!");
int hr = Integer.parseInt(s.substring(0,2)); int hr = Integer.parseInt(s.substring(0, 2));
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) { }
throw new PSQLException ("postgresql.res.badtime",s); catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badtime", s);
} }
} }
return null; // SQL NULL return null; // SQL NULL
@@ -454,14 +478,17 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
public Timestamp getTimestamp(int columnIndex) throws SQLException public Timestamp getTimestamp(int columnIndex) throws SQLException
{ {
String s = getString(columnIndex); String s = getString(columnIndex);
if(s==null) if (s == null)
return null; return null;
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;
} }
@@ -478,30 +505,44 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
//hours, and the use of the : for delimiter between hours and minutes) //hours, and the use of the : for delimiter between hours and minutes)
//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); {
if (subsecond) { strBuf.setLength(strBuf.length() - 3);
strBuf.append('0').append("GMT").append(s.substring(s.length()-3, s.length())).append(":00"); if (subsecond)
} else { {
strBuf.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 if (sub == ':') { else
{
strBuf.append("GMT").append(s.substring(s.length() - 3, s.length())).append(":00");
}
}
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)); {
} else { strBuf.append('0').append("GMT").append(s.substring(s.length() - 5));
strBuf.append("GMT").append(s.substring(s.length()-5));
} }
} else if (subsecond) { else
{
strBuf.append("GMT").append(s.substring(s.length() - 5));
}
}
else if (subsecond)
{
strBuf.append('0'); strBuf.append('0');
} }
} else if (subsecond) { }
else if (subsecond)
{
strBuf = strBuf.append('0'); strBuf = strBuf.append('0');
} }
@@ -509,22 +550,34 @@ 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) { }
throw new PSQLException("postgresql.res.badtimestamp",new Integer(e.getErrorOffset()),s); catch (ParseException e)
{
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,8 +900,9 @@ 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;
} }
@@ -847,7 +917,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
case Types.BIGINT: case Types.BIGINT:
return new Long(getLong(columnIndex)); return new Long(getLong(columnIndex));
case Types.NUMERIC: case Types.NUMERIC:
return getBigDecimal(columnIndex, ((field.getMod()-4) & 0xffff)); return getBigDecimal(columnIndex, ((field.getMod() - 4) & 0xffff));
case Types.REAL: case Types.REAL:
return new Float(getFloat(columnIndex)); return new Float(getFloat(columnIndex));
case Types.DOUBLE: case Types.DOUBLE:
@@ -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));
} }
} }
@@ -908,8 +981,8 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
for (i = 0 ; i < fields.length; ++i) for (i = 0 ; i < fields.length; ++i)
if (fields[i].getName().equalsIgnoreCase(columnName)) if (fields[i].getName().equalsIgnoreCase(columnName))
return (i+1); return (i + 1);
throw new PSQLException ("postgresql.res.colname",columnName); throw new PSQLException ("postgresql.res.colname", columnName);
} }
} }

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
@@ -248,9 +261,9 @@ public class ResultSetMetaData implements java.sql.ResultSetMetaData
public String getColumnName(int column) throws SQLException public String getColumnName(int column) throws SQLException
{ {
Field f = getField(column); Field f = getField(column);
if(f!=null) if (f != null)
return f.getName(); return f.getName();
return "field"+column; return "field" + column;
} }
/** /**
@@ -295,8 +308,8 @@ public class ResultSetMetaData implements java.sql.ResultSetMetaData
return 0; return 0;
case Types.NUMERIC: case Types.NUMERIC:
Field f = getField(column); Field f = getField(column);
if(f != null) if (f != null)
return ((0xFFFF0000)&f.getMod())>>16; return ((0xFFFF0000)&f.getMod()) >> 16;
else else
return 0; return 0;
default: default:
@@ -332,8 +345,8 @@ public class ResultSetMetaData implements java.sql.ResultSetMetaData
return 0; return 0;
case Types.NUMERIC: case Types.NUMERIC:
Field f = getField(column); Field f = getField(column);
if(f != null) if (f != null)
return (((0x0000FFFF)&f.getMod())-4); return (((0x0000FFFF)&f.getMod()) - 4);
else else
return 0; return 0;
default: default:

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,20 +49,24 @@ 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();
if (index < 1) if (index < 1)
@@ -70,24 +74,29 @@ 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( foundOpen ) // Only supports 1-D arrays for now if ( chars[i] == '{' )
{
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() );
sbuf = new StringBuffer(); sbuf = new StringBuffer();
@@ -97,10 +106,10 @@ public class Array implements java.sql.Array
} }
} }
String[] arrayContents = (String[]) array.toArray( new String[array.size()] ); String[] arrayContents = (String[]) array.toArray( new String[array.size()] );
if( count == 0 ) if ( count == 0 )
count = arrayContents.length; count = arrayContents.length;
index--; index--;
if( index+count > arrayContents.length ) if ( index + count > arrayContents.length )
throw new PSQLException("postgresql.arr.range"); throw new PSQLException("postgresql.arr.range");
int i = 0; int i = 0;
@@ -108,55 +117,55 @@ public class Array implements java.sql.Array
{ {
case Types.BIT: case Types.BIT:
retVal = new boolean[ count ]; retVal = new boolean[ count ];
for( ; count > 0; count-- ) for ( ; count > 0; count-- )
((boolean[])retVal)[i++] = ResultSet.toBoolean( arrayContents[(int)index++] ); ((boolean[])retVal)[i++] = ResultSet.toBoolean( arrayContents[(int)index++] );
break; break;
case Types.SMALLINT: case Types.SMALLINT:
case Types.INTEGER: case Types.INTEGER:
retVal = new int[ count ]; retVal = new int[ count ];
for( ; count > 0; count-- ) for ( ; count > 0; count-- )
((int[])retVal)[i++] = ResultSet.toInt( arrayContents[(int)index++] ); ((int[])retVal)[i++] = ResultSet.toInt( arrayContents[(int)index++] );
break; break;
case Types.BIGINT: case Types.BIGINT:
retVal = new long[ count ]; retVal = new long[ count ];
for( ; count > 0; count-- ) for ( ; count > 0; count-- )
((long[])retVal)[i++] = ResultSet.toLong( arrayContents[(int)index++] ); ((long[])retVal)[i++] = ResultSet.toLong( arrayContents[(int)index++] );
break; break;
case Types.NUMERIC: case Types.NUMERIC:
retVal = new BigDecimal[ count ]; retVal = new BigDecimal[ count ];
for( ; count > 0; count-- ) for ( ; count > 0; count-- )
((BigDecimal[])retVal)[i] = ResultSet.toBigDecimal( arrayContents[(int)index++], 0 ); ((BigDecimal[])retVal)[i] = ResultSet.toBigDecimal( arrayContents[(int)index++], 0 );
break; break;
case Types.REAL: case Types.REAL:
retVal = new float[ count ]; retVal = new float[ count ];
for( ; count > 0; count-- ) for ( ; count > 0; count-- )
((float[])retVal)[i++] = ResultSet.toFloat( arrayContents[(int)index++] ); ((float[])retVal)[i++] = ResultSet.toFloat( arrayContents[(int)index++] );
break; break;
case Types.DOUBLE: case Types.DOUBLE:
retVal = new double[ count ]; retVal = new double[ count ];
for( ; count > 0; count-- ) for ( ; count > 0; count-- )
((double[])retVal)[i++] = ResultSet.toDouble( arrayContents[(int)index++] ); ((double[])retVal)[i++] = ResultSet.toDouble( arrayContents[(int)index++] );
break; break;
case Types.CHAR: case Types.CHAR:
case Types.VARCHAR: case Types.VARCHAR:
retVal = new String[ count ]; retVal = new String[ count ];
for( ; count > 0; count-- ) for ( ; count > 0; count-- )
((String[])retVal)[i++] = arrayContents[(int)index++]; ((String[])retVal)[i++] = arrayContents[(int)index++];
break; break;
case Types.DATE: case Types.DATE:
retVal = new java.sql.Date[ count ]; retVal = new java.sql.Date[ count ];
for( ; count > 0; count-- ) for ( ; count > 0; count-- )
((java.sql.Date[])retVal)[i++] = ResultSet.toDate( arrayContents[(int)index++] ); ((java.sql.Date[])retVal)[i++] = ResultSet.toDate( arrayContents[(int)index++] );
break; break;
case Types.TIME: case Types.TIME:
retVal = new java.sql.Time[ count ]; retVal = new java.sql.Time[ count ];
for( ; count > 0; count-- ) for ( ; count > 0; count-- )
((java.sql.Time[])retVal)[i++] = ResultSet.toTime( arrayContents[(int)index++] ); ((java.sql.Time[])retVal)[i++] = ResultSet.toTime( arrayContents[(int)index++] );
break; break;
case Types.TIMESTAMP: case Types.TIMESTAMP:
retVal = new Timestamp[ count ]; retVal = new Timestamp[ count ];
StringBuffer sbuf = null; StringBuffer sbuf = null;
for( ; count > 0; count-- ) for ( ; count > 0; count-- )
((java.sql.Timestamp[])retVal)[i++] = ResultSet.toTimestamp( arrayContents[(int)index], rs ); ((java.sql.Timestamp[])retVal)[i++] = ResultSet.toTimestamp( arrayContents[(int)index], rs );
break; break;
@@ -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,21 +216,23 @@ 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
rows.addElement(tuple); rows.addElement(tuple);
} }
case Types.SMALLINT: case Types.SMALLINT:
fields[1] = new Field(conn, "VALUE", conn.getOID("int2"), 2); fields[1] = new Field(conn, "VALUE", conn.getOID("int2"), 2);
case Types.INTEGER: case Types.INTEGER:
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
rows.addElement(tuple); rows.addElement(tuple);
} }
@@ -223,9 +240,10 @@ 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
rows.addElement(tuple); rows.addElement(tuple);
} }
@@ -233,9 +251,10 @@ 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
rows.addElement(tuple); rows.addElement(tuple);
} }
@@ -243,9 +262,10 @@ 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
rows.addElement(tuple); rows.addElement(tuple);
} }
@@ -253,9 +273,10 @@ 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
rows.addElement(tuple); rows.addElement(tuple);
} }
@@ -264,11 +285,12 @@ public class Array implements java.sql.Array
fields[1] = new Field(conn, "VALUE", conn.getOID("char"), 1); fields[1] = new Field(conn, "VALUE", conn.getOID("char"), 1);
case Types.VARCHAR: case Types.VARCHAR:
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
rows.addElement(tuple); rows.addElement(tuple);
} }
@@ -276,9 +298,10 @@ 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
rows.addElement(tuple); rows.addElement(tuple);
} }
@@ -286,9 +309,10 @@ 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
rows.addElement(tuple); rows.addElement(tuple);
} }
@@ -296,9 +320,10 @@ 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
rows.addElement(tuple); rows.addElement(tuple);
} }
@@ -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

@@ -44,9 +44,9 @@ public class CallableStatement extends org.postgresql.jdbc2.PreparedStatement im
/** /**
* @exception SQLException on failure * @exception SQLException on failure
*/ */
public CallableStatement(Connection c,String q) throws SQLException public CallableStatement(Connection c, String q) throws SQLException
{ {
super(c,q); super(c, q);
} }
/** /**
@@ -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;
} }
@@ -328,7 +342,7 @@ public int getInt(int parameterIndex) throws SQLException {
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public Object getObject(int i,java.util.Map map) throws SQLException public Object getObject(int i, java.util.Map map) throws SQLException
{ {
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
@@ -338,22 +352,22 @@ public int getInt(int parameterIndex) throws SQLException {
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public java.sql.Date getDate(int i,java.util.Calendar cal) throws SQLException public java.sql.Date getDate(int i, java.util.Calendar cal) throws SQLException
{ {
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public Time getTime(int i,java.util.Calendar cal) throws SQLException public Time getTime(int i, java.util.Calendar cal) throws SQLException
{ {
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public Timestamp getTimestamp(int i,java.util.Calendar cal) throws SQLException public Timestamp getTimestamp(int i, java.util.Calendar cal) throws SQLException
{ {
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public void registerOutParameter(int parameterIndex, int sqlType,String typeName) throws SQLException public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException
{ {
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }

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
@@ -56,7 +56,7 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
{ {
// The spec says default of TYPE_FORWARD_ONLY but everyone is used to // The spec says default of TYPE_FORWARD_ONLY but everyone is used to
// using TYPE_SCROLL_INSENSITIVE // using TYPE_SCROLL_INSENSITIVE
return createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY); return createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);
} }
/** /**
@@ -69,7 +69,7 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
* @return a new Statement object * @return a new Statement object
* @exception SQLException passed through from the constructor * @exception SQLException passed through from the constructor
*/ */
public java.sql.Statement createStatement(int resultSetType,int resultSetConcurrency) throws SQLException public java.sql.Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException
{ {
Statement s = new Statement(this); Statement s = new Statement(this);
s.setResultSetType(resultSetType); s.setResultSetType(resultSetType);
@@ -98,12 +98,12 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
*/ */
public java.sql.PreparedStatement prepareStatement(String sql) throws SQLException public java.sql.PreparedStatement prepareStatement(String sql) throws SQLException
{ {
return prepareStatement(sql,java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY); return prepareStatement(sql, java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);
} }
public java.sql.PreparedStatement prepareStatement(String sql,int resultSetType,int resultSetConcurrency) throws SQLException public java.sql.PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{ {
PreparedStatement s = new PreparedStatement(this,sql); PreparedStatement s = new PreparedStatement(this, sql);
s.setResultSetType(resultSetType); s.setResultSetType(resultSetType);
s.setResultSetConcurrency(resultSetConcurrency); s.setResultSetConcurrency(resultSetConcurrency);
return s; return s;
@@ -130,10 +130,10 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
*/ */
public java.sql.CallableStatement prepareCall(String sql) throws SQLException public java.sql.CallableStatement prepareCall(String sql) throws SQLException
{ {
return prepareCall(sql,java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY); return prepareCall(sql, java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);
} }
public java.sql.CallableStatement prepareCall(String sql,int resultSetType,int resultSetConcurrency) throws SQLException public java.sql.CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{ {
throw new PSQLException("postgresql.con.call"); throw new PSQLException("postgresql.con.call");
//CallableStatement s = new CallableStatement(this,sql); //CallableStatement s = new CallableStatement(this,sql);
@@ -162,20 +162,23 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
public boolean isClosed() throws SQLException public boolean isClosed() throws SQLException
{ {
// If the stream is gone, then close() was called // If the stream is gone, then close() was called
if(pg_stream == null) if (pg_stream == null)
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(" ");
if(rs!=null) if (rs != null)
rs.close(); rs.close();
// 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
@@ -195,7 +198,7 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
*/ */
public java.sql.DatabaseMetaData getMetaData() throws SQLException public java.sql.DatabaseMetaData getMetaData() throws SQLException
{ {
if(metadata==null) if (metadata == null)
metadata = new DatabaseMetaData(this); metadata = new DatabaseMetaData(this);
return metadata; return metadata;
} }
@@ -204,16 +207,17 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
* This overides the method in org.postgresql.Connection and returns a * This overides the method in org.postgresql.Connection and returns a
* ResultSet. * ResultSet.
*/ */
public java.sql.ResultSet getResultSet(org.postgresql.Connection conn, java.sql.Statement stat,Field[] fields, Vector tuples, String status, int updateCount, int insertOID, boolean binaryCursor) throws SQLException public java.sql.ResultSet getResultSet(org.postgresql.Connection conn, java.sql.Statement stat, Field[] fields, Vector tuples, String status, int updateCount, int insertOID, boolean binaryCursor) throws SQLException
{ {
// 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) {
return new org.postgresql.jdbc2.UpdateableResultSet((org.postgresql.jdbc2.Connection)conn,fields,tuples,status,updateCount,insertOID,binaryCursor); 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.ResultSet((org.postgresql.jdbc2.Connection)conn,fields,tuples,status,updateCount,insertOID,binaryCursor); return new org.postgresql.jdbc2.ResultSet((org.postgresql.jdbc2.Connection)conn, fields, tuples, status, updateCount, insertOID, binaryCursor);
} }
// ***************** // *****************
@@ -230,7 +234,7 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
public void setTypeMap(java.util.Map map) throws SQLException public void setTypeMap(java.util.Map map) throws SQLException
{ {
// new in 7.1 // new in 7.1
typemap=map; typemap = map;
} }
/** /**
@@ -241,18 +245,20 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
* @exception SQLException if value is not correct for this type * @exception SQLException if value is not correct for this type
* @see org.postgresql.util.Serialize * @see org.postgresql.util.Serialize
*/ */
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();
} }
} }
// Default to the original method // Default to the original method
return super.getObject(type,value); return super.getObject(type, value);
} }
/* An implementation of the abstract method in the parent class. /* An implementation of the abstract method in the parent class.
@@ -263,9 +269,11 @@ 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])) { {
sqlType=jdbc2Typei[i]; if (pgTypeName.equals(jdbc2Types[i]))
{
sqlType = jdbc2Typei[i];
break; break;
} }
} }
@@ -283,19 +291,19 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
*/ */
private static final String jdbc2Types[] = { private static final String jdbc2Types[] = {
"int2", "int2",
"int4","oid", "int4", "oid",
"int8", "int8",
"cash","money", "cash", "money",
"numeric", "numeric",
"float4", "float4",
"float8", "float8",
"bpchar","char","char2","char4","char8","char16", "bpchar", "char", "char2", "char4", "char8", "char16",
"varchar","text","name","filename", "varchar", "text", "name", "filename",
"bytea", "bytea",
"bool", "bool",
"date", "date",
"time", "time",
"abstime","timestamp", "abstime", "timestamp",
"_bool", "_char", "_int2", "_int4", "_text", "_bool", "_char", "_int2", "_int4", "_text",
"_oid", "_varchar", "_int8", "_float4", "_float8", "_oid", "_varchar", "_int8", "_float4", "_float8",
"_abstime", "_date", "_time", "_timestamp", "_numeric", "_abstime", "_date", "_time", "_timestamp", "_numeric",
@@ -311,19 +319,19 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
*/ */
private static final int jdbc2Typei[] = { private static final int jdbc2Typei[] = {
Types.SMALLINT, Types.SMALLINT,
Types.INTEGER,Types.INTEGER, Types.INTEGER, Types.INTEGER,
Types.BIGINT, Types.BIGINT,
Types.DOUBLE,Types.DOUBLE, Types.DOUBLE, Types.DOUBLE,
Types.NUMERIC, Types.NUMERIC,
Types.REAL, Types.REAL,
Types.DOUBLE, Types.DOUBLE,
Types.CHAR,Types.CHAR,Types.CHAR,Types.CHAR,Types.CHAR,Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR,
Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.BINARY, Types.BINARY,
Types.BIT, Types.BIT,
Types.DATE, Types.DATE,
Types.TIME, Types.TIME,
Types.TIMESTAMP,Types.TIMESTAMP, Types.TIMESTAMP, Types.TIMESTAMP,
Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY,
Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY,
Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY,

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
@@ -1522,15 +1522,15 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
f[0] = new Field(connection, "PROCEDURE_CAT", iVarcharOid, 32); f[0] = new Field(connection, "PROCEDURE_CAT", iVarcharOid, 32);
f[1] = new Field(connection, "PROCEDURE_SCHEM", iVarcharOid, 32); f[1] = new Field(connection, "PROCEDURE_SCHEM", iVarcharOid, 32);
f[2] = new Field(connection, "PROCEDURE_NAME", iVarcharOid, 32); f[2] = new Field(connection, "PROCEDURE_NAME", iVarcharOid, 32);
f[3] = f[4] = f[5] = new Field(connection,"reserved",iVarcharOid,32); // null; // reserved, must be null for now f[3] = f[4] = f[5] = new Field(connection, "reserved", iVarcharOid, 32); // null; // reserved, must be null for now
f[6] = new Field(connection, "REMARKS", iVarcharOid, 8192); f[6] = new Field(connection, "REMARKS", iVarcharOid, 8192);
f[7] = new Field(connection, "PROCEDURE_TYPE", iInt2Oid, 2); f[7] = new Field(connection, "PROCEDURE_TYPE", iInt2Oid, 2);
// If the pattern is null, then set it to the default // If the pattern is null, then set it to the default
if(procedureNamePattern==null) if (procedureNamePattern == null)
procedureNamePattern="%"; procedureNamePattern = "%";
r = connection.ExecSQL("select proname, proretset from pg_proc where proname like '"+procedureNamePattern.toLowerCase()+"' order by proname"); r = connection.ExecSQL("select proname, proretset from pg_proc where proname like '" + procedureNamePattern.toLowerCase() + "' order by proname");
while (r.next()) while (r.next())
{ {
@@ -1600,11 +1600,11 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// Implementation note: This is required for Borland's JBuilder to work // Implementation note: This is required for Borland's JBuilder to work
public java.sql.ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException public java.sql.ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException
{ {
if(procedureNamePattern==null) if (procedureNamePattern == null)
procedureNamePattern="%"; procedureNamePattern = "%";
if(columnNamePattern==null) if (columnNamePattern == null)
columnNamePattern="%"; columnNamePattern = "%";
// for now, this returns an empty result set. // for now, this returns an empty result set.
Field f[] = new Field[13]; Field f[] = new Field[13];
@@ -1665,11 +1665,11 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
public java.sql.ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String types[]) throws SQLException public java.sql.ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String types[]) throws SQLException
{ {
// Handle default value for types // Handle default value for types
if(types==null) if (types == null)
types = defaultTableTypes; types = defaultTableTypes;
if(tableNamePattern==null) if (tableNamePattern == null)
tableNamePattern="%"; tableNamePattern = "%";
// the field descriptors for the new ResultSet // the field descriptors for the new ResultSet
Field f[] = new Field[5]; Field f[] = new Field[5];
@@ -1685,14 +1685,16 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// Now form the query // Now form the query
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++) {
if(getTableTypes[j][0].equals(types[i])) { for (int j = 0;j < getTableTypes.length;j++)
if(notFirst) if (getTableTypes[j][0].equals(types[i]))
{
if (notFirst)
sql.append(" or "); sql.append(" or ");
sql.append(getTableTypes[j][1]); sql.append(getTableTypes[j][1]);
notFirst=true; notFirst = true;
} }
} }
@@ -1712,21 +1714,23 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// Fetch the description for the table (if any) // Fetch the description for the table (if any)
String getDescriptionStatement = String getDescriptionStatement =
connection.haveMinimumServerVersion("7.2") ? connection.haveMinimumServerVersion("7.2") ?
"select obj_description("+r.getInt(2)+",'pg_class')" : "select obj_description(" + r.getInt(2) + ",'pg_class')" :
"select description from pg_description where objoid=" + r.getInt(2); "select description from pg_description where objoid=" + r.getInt(2);
java.sql.ResultSet dr = connection.ExecSQL(getDescriptionStatement); java.sql.ResultSet dr = connection.ExecSQL(getDescriptionStatement);
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;
@@ -1746,7 +1750,7 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
tuple[0] = null; // Catalog name tuple[0] = null; // Catalog name
tuple[1] = null; // Schema name tuple[1] = null; // Schema name
tuple[2] = r.getBytes(1); // Table name tuple[2] = r.getBytes(1); // Table name
tuple[3] = (relKind==null) ? null : relKind.getBytes(); // Table type tuple[3] = (relKind == null) ? null : relKind.getBytes(); // Table type
tuple[4] = remarks; // Remarks tuple[4] = remarks; // Remarks
v.addElement(tuple); v.addElement(tuple);
} }
@@ -1773,7 +1777,7 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// These are the default tables, used when NULL is passed to getTables // These are the default tables, used when NULL is passed to getTables
// The choice of these provide the same behaviour as psql's \d // The choice of these provide the same behaviour as psql's \d
private static final String defaultTableTypes[] = { private static final String defaultTableTypes[] = {
"TABLE","VIEW","INDEX","SEQUENCE" "TABLE", "VIEW", "INDEX", "SEQUENCE"
}; };
/** /**
@@ -1795,10 +1799,10 @@ 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();
byte[][] tuple = new byte[1][0]; byte[][] tuple = new byte[1][0];
f[0] = new Field(connection,"TABLE_SCHEM",iVarcharOid,32); f[0] = new Field(connection, "TABLE_SCHEM", iVarcharOid, 32);
tuple[0] = "".getBytes(); tuple[0] = "".getBytes();
v.addElement(tuple); v.addElement(tuple);
return new ResultSet(connection,f,v,"OK",1); return new ResultSet(connection, f, v, "OK", 1);
} }
/** /**
@@ -1836,13 +1840,14 @@ 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);
} }
return new ResultSet(connection,f,v,"OK",1); return new ResultSet(connection, f, v, "OK", 1);
} }
/** /**
@@ -1914,7 +1919,7 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
f[13] = new Field(connection, "SQL_DATA_TYPE", iInt4Oid, 4); f[13] = new Field(connection, "SQL_DATA_TYPE", iInt4Oid, 4);
f[14] = new Field(connection, "SQL_DATETIME_SUB", iInt4Oid, 4); f[14] = new Field(connection, "SQL_DATETIME_SUB", iInt4Oid, 4);
f[15] = new Field(connection, "CHAR_OCTET_LENGTH", iVarcharOid, 32); f[15] = new Field(connection, "CHAR_OCTET_LENGTH", iVarcharOid, 32);
f[16] = new Field(connection, "ORDINAL_POSITION", iInt4Oid,4); f[16] = new Field(connection, "ORDINAL_POSITION", iInt4Oid, 4);
f[17] = new Field(connection, "IS_NULLABLE", iVarcharOid, 32); f[17] = new Field(connection, "IS_NULLABLE", iVarcharOid, 32);
StringBuffer sql = new StringBuffer(512); StringBuffer sql = new StringBuffer(512);
@@ -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);
} }
@@ -2062,35 +2074,36 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
Field f[] = new Field[8]; Field f[] = new Field[8];
Vector v = new Vector(); Vector v = new Vector();
if(table==null) if (table == null)
table="%"; table = "%";
if(columnNamePattern==null) if (columnNamePattern == null)
columnNamePattern="%"; columnNamePattern = "%";
else else
columnNamePattern=columnNamePattern.toLowerCase(); columnNamePattern = columnNamePattern.toLowerCase();
f[0] = new Field(connection,"TABLE_CAT",iVarcharOid,32); f[0] = new Field(connection, "TABLE_CAT", iVarcharOid, 32);
f[1] = new Field(connection,"TABLE_SCHEM",iVarcharOid,32); f[1] = new Field(connection, "TABLE_SCHEM", iVarcharOid, 32);
f[2] = new Field(connection,"TABLE_NAME",iVarcharOid,32); f[2] = new Field(connection, "TABLE_NAME", iVarcharOid, 32);
f[3] = new Field(connection,"COLUMN_NAME",iVarcharOid,32); f[3] = new Field(connection, "COLUMN_NAME", iVarcharOid, 32);
f[4] = new Field(connection,"GRANTOR",iVarcharOid,32); f[4] = new Field(connection, "GRANTOR", iVarcharOid, 32);
f[5] = new Field(connection,"GRANTEE",iVarcharOid,32); f[5] = new Field(connection, "GRANTEE", iVarcharOid, 32);
f[6] = new Field(connection,"PRIVILEGE",iVarcharOid,32); f[6] = new Field(connection, "PRIVILEGE", iVarcharOid, 32);
f[7] = new Field(connection,"IS_GRANTABLE",iVarcharOid,32); f[7] = new Field(connection, "IS_GRANTABLE", iVarcharOid, 32);
// 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) + "\"");
// For now, don't add to the result as relacl needs to be processed. // For now, don't add to the result as relacl needs to be processed.
//v.addElement(tuple); //v.addElement(tuple);
} }
return new ResultSet(connection,f,v,"OK",1); return new ResultSet(connection, f, v, "OK", 1);
} }
/** /**
@@ -2247,11 +2260,11 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
"'' AS TABLE_SCHEM," + "'' AS TABLE_SCHEM," +
"bc.relname AS TABLE_NAME," + "bc.relname AS TABLE_NAME," +
"a.attname AS COLUMN_NAME," + "a.attname AS COLUMN_NAME," +
"a.attnum as KEY_SEQ,"+ "a.attnum as KEY_SEQ," +
"ic.relname as PK_NAME " + "ic.relname as PK_NAME " +
" FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a" + " FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a" +
" WHERE bc.relkind = 'r' " + // -- not indices " WHERE bc.relkind = 'r' " + // -- not indices
" and upper(bc.relname) = upper('"+table+"')" + " and upper(bc.relname) = upper('" + table + "')" +
" and i.indrelid = bc.oid" + " and i.indrelid = bc.oid" +
" and i.indexrelid = ic.oid" + " and i.indexrelid = ic.oid" +
" and ic.oid = a.attrelid" + " and ic.oid = a.attrelid" +
@@ -2260,74 +2273,81 @@ 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 origTable=null, primTable=new String(""), schema; String s, s2;
String origTable = null, primTable = new String(""), schema;
int i; int i;
Vector v; Vector v;
s=keyRelation.getString(1); s = keyRelation.getString(1);
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); {
if (s.compareTo("")==0) { s = s.substring(s.indexOf("\\000") + 4);
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;
case 1: case 1:
primTable=s2; primTable = s2;
break; break;
case 2: case 2:
schema=s2; schema = s2;
break; break;
default: default:
v.add(s2); v.add(s2);
} }
} }
java.sql.ResultSet rstmp=connection.ExecSQL("select * from "+origTable+" where 1=0"); java.sql.ResultSet rstmp = connection.ExecSQL("select * from " + origTable + " where 1=0");
java.sql.ResultSetMetaData origCols=rstmp.getMetaData(); java.sql.ResultSetMetaData origCols = rstmp.getMetaData();
String stmp; String stmp;
Vector tuples=new Vector(); Vector tuples = new Vector();
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) { {
tuple=new byte[14][0]; if (stmp.compareTo(origCols.getColumnName(j)) == 0)
{
tuple = new byte[14][0];
for (int k=0;k<14;k++) for (int k = 0;k < 14;k++)
tuple[k]=null; tuple[k] = null;
//PKTABLE_NAME //PKTABLE_NAME
tuple[2]=primTable.getBytes(); tuple[2] = primTable.getBytes();
//PKTABLE_COLUMN //PKTABLE_COLUMN
stmp=(String)v.elementAt(i+1); stmp = (String)v.elementAt(i + 1);
tuple[3]=stmp.getBytes(); tuple[3] = stmp.getBytes();
//FKTABLE_NAME //FKTABLE_NAME
tuple[6]=origTable.getBytes(); tuple[6] = origTable.getBytes();
//FKCOLUMN_NAME //FKCOLUMN_NAME
tuple[7]=origCols.getColumnName(j).getBytes(); tuple[7] = origCols.getColumnName(j).getBytes();
//KEY_SEQ //KEY_SEQ
tuple[8]=Integer.toString(j).getBytes(); tuple[8] = Integer.toString(j).getBytes();
tuples.add(tuple); tuples.add(tuple);
/* /*
System.out.println(origCols.getColumnName(j)+ System.out.println(origCols.getColumnName(j)+
": "+j+" -> "+primTable+": "+ ": "+j+" -> "+primTable+": "+
(String)v.elementAt(i+1)); (String)v.elementAt(i+1));
*/ */
break; break;
} }
} }
@@ -2392,34 +2412,35 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// Added by Ola Sundell <ola@miranda.org> // Added by Ola Sundell <ola@miranda.org>
// FIXME: error checking galore! // FIXME: error checking galore!
java.sql.ResultSet rsret; java.sql.ResultSet rsret;
Field f[]=new Field[14]; Field f[] = new Field[14];
byte tuple[][]; byte tuple[][];
f[0]=new Field(connection, "PKTABLE_CAT", iVarcharOid, 32); f[0] = new Field(connection, "PKTABLE_CAT", iVarcharOid, 32);
f[1]=new Field(connection, "PKTABLE_SCHEM", iVarcharOid, 32); f[1] = new Field(connection, "PKTABLE_SCHEM", iVarcharOid, 32);
f[2]=new Field(connection, "PKTABLE_NAME", iVarcharOid, 32); f[2] = new Field(connection, "PKTABLE_NAME", iVarcharOid, 32);
f[3]=new Field(connection, "PKCOLUMN_NAME", iVarcharOid, 32); f[3] = new Field(connection, "PKCOLUMN_NAME", iVarcharOid, 32);
f[4]=new Field(connection, "FKTABLE_CAT", iVarcharOid, 32); f[4] = new Field(connection, "FKTABLE_CAT", iVarcharOid, 32);
f[5]=new Field(connection, "FKTABLE_SCHEM", iVarcharOid, 32); f[5] = new Field(connection, "FKTABLE_SCHEM", iVarcharOid, 32);
f[6]=new Field(connection, "FKTABLE_NAME", iVarcharOid, 32); f[6] = new Field(connection, "FKTABLE_NAME", iVarcharOid, 32);
f[7]=new Field(connection, "FKCOLUMN_NAME", iVarcharOid, 32); f[7] = new Field(connection, "FKCOLUMN_NAME", iVarcharOid, 32);
f[8]=new Field(connection, "KEY_SEQ", iInt2Oid, 2); f[8] = new Field(connection, "KEY_SEQ", iInt2Oid, 2);
f[9]=new Field(connection, "UPDATE_RULE", iInt2Oid, 2); f[9] = new Field(connection, "UPDATE_RULE", iInt2Oid, 2);
f[10]=new Field(connection, "DELETE_RULE", iInt2Oid, 2); f[10] = new Field(connection, "DELETE_RULE", iInt2Oid, 2);
f[11]=new Field(connection, "FK_NAME", iVarcharOid, 32); f[11] = new Field(connection, "FK_NAME", iVarcharOid, 32);
f[12]=new Field(connection, "PK_NAME", iVarcharOid, 32); f[12] = new Field(connection, "PK_NAME", iVarcharOid, 32);
f[13]=new Field(connection, "DEFERRABILITY", iInt2Oid, 2); f[13] = new Field(connection, "DEFERRABILITY", iInt2Oid, 2);
java.sql.ResultSet rs=connection.ExecSQL("select t.tgargs "+ java.sql.ResultSet rs = connection.ExecSQL("select t.tgargs " +
"from pg_class as c, pg_trigger as t "+ "from pg_class as c, pg_trigger as t " +
"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));
} }
rsret=new ResultSet(connection, f, tuples, "OK", 1); rsret = new ResultSet(connection, f, tuples, "OK", 1);
return rsret; return rsret;
} }
@@ -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,9 +2645,10 @@ 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();
tuple[1] = Integer.toString(connection.getSQLType(typname)).getBytes(); tuple[1] = Integer.toString(connection.getSQLType(typname)).getBytes();
tuple[2] = b9; // for now tuple[2] = b9; // for now
@@ -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();
@@ -2802,14 +2828,14 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
* @return true if so; false otherwise * @return true if so; false otherwise
* @exception SQLException - if a database access error occurs * @exception SQLException - if a database access error occurs
*/ */
public boolean supportsResultSetConcurrency(int type,int concurrency) throws SQLException public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException
{ {
// These combinations are not supported! // These combinations are not supported!
if(type == java.sql.ResultSet.TYPE_SCROLL_SENSITIVE) if (type == java.sql.ResultSet.TYPE_SCROLL_SENSITIVE)
return false; return false;
// We don't yet support Updateable ResultSets // We don't yet support Updateable ResultSets
if(concurrency == java.sql.ResultSet.CONCUR_UPDATABLE) if (concurrency == java.sql.ResultSet.CONCUR_UPDATABLE)
return false; return false;
// Everything else we do // Everything else we do

View File

@@ -7,23 +7,26 @@ 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);
Object[] argv = new Object[2]; Object[] argv = new Object[2];
argv[0] = arg1; argv[0] = arg1;
argv[1] = arg2; argv[1] = arg2;
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);
} }
// Overides Throwable // Overides Throwable

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;
@@ -126,7 +127,7 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
for (i = 0 ; i < inStrings.length ; ++i) for (i = 0 ; i < inStrings.length ; ++i)
{ {
if (inStrings[i] == null) if (inStrings[i] == null)
throw new PSQLException("postgresql.prep.param",new Integer(i + 1)); throw new PSQLException("postgresql.prep.param", new Integer(i + 1));
sbuf.append (templateStrings[i]).append (inStrings[i]); sbuf.append (templateStrings[i]).append (inStrings[i]);
} }
sbuf.append(templateStrings[inStrings.length]); sbuf.append(templateStrings[inStrings.length]);
@@ -266,12 +267,14 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
public void setString(int parameterIndex, String x) throws SQLException public void setString(int parameterIndex, String x) throws SQLException
{ {
// 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,21 +308,27 @@ 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); {
} else { setNull(parameterIndex, Types.OTHER);
}
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();
LargeObject lob = lom.open(oid); LargeObject lob = lom.open(oid);
lob.write(x); lob.write(x);
lob.close(); lob.close();
setInt(parameterIndex,oid); setInt(parameterIndex, oid);
} }
} }
@@ -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); {
} else { setNull(parameterIndex, Types.OTHER);
}
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); {
} else { setNull(parameterIndex, Types.OTHER);
}
else
{
set(parameterIndex, "'" + x.toString() + "'"); set(parameterIndex, "'" + x.toString() + "'");
} }
} }
@@ -382,20 +398,25 @@ 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); {
} else { setNull(parameterIndex, Types.OTHER);
}
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) {
throw new PSQLException("postgresql.unusual",l_uee);
} catch (IOException l_ioe) {
throw new PSQLException("postgresql.unusual",l_ioe);
} }
} else { catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException("postgresql.unusual", l_uee);
}
catch (IOException l_ioe)
{
throw new PSQLException("postgresql.unusual", l_ioe);
}
}
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) {
throw new PSQLException("postgresql.unusual",l_uee);
} catch (IOException l_ioe) {
throw new PSQLException("postgresql.unusual",l_ioe);
} }
} else { catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException("postgresql.unusual", l_uee);
}
catch (IOException l_ioe)
{
throw new PSQLException("postgresql.unusual", l_ioe);
}
}
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); {
} catch (IOException l_ioe) { l_bytesRead = x.read(l_bytes, 0, length);
throw new PSQLException("postgresql.unusual",l_ioe);
} }
if (l_bytesRead == length) { catch (IOException l_ioe)
{
throw new PSQLException("postgresql.unusual", l_ioe);
}
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,23 +583,27 @@ 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) { }
throw new PSQLException("postgresql.unusual",se); catch (IOException 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()
setInt(parameterIndex,oid); setInt(parameterIndex, oid);
} }
} }
@@ -595,9 +645,10 @@ 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); {
return; setNull(parameterIndex, Types.OTHER);
return ;
} }
switch (targetSqlType) switch (targetSqlType)
{ {
@@ -630,15 +681,18 @@ 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;
case Types.BINARY: case Types.BINARY:
case Types.VARBINARY: case Types.VARBINARY:
setObject(parameterIndex,x); setObject(parameterIndex, x);
break; break;
case Types.OTHER: case Types.OTHER:
setString(parameterIndex, ((PGobject)x).getValue()); setString(parameterIndex, ((PGobject)x).getValue());
@@ -661,9 +715,10 @@ 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); {
return; setNull(parameterIndex, Types.OTHER);
return ;
} }
if (x instanceof String) if (x instanceof String)
setString(parameterIndex, (String)x); setString(parameterIndex, (String)x);
@@ -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;
@@ -794,7 +851,7 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
public java.sql.ResultSetMetaData getMetaData() throws SQLException public java.sql.ResultSetMetaData getMetaData() throws SQLException
{ {
java.sql.ResultSet rs = getResultSet(); java.sql.ResultSet rs = getResultSet();
if(rs!=null) if (rs != null)
return rs.getMetaData(); return rs.getMetaData();
// Does anyone really know what this method does? // Does anyone really know what this method does?
@@ -809,7 +866,7 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
/** /**
* Sets a Blob * Sets a Blob
*/ */
public void setBlob(int i,Blob x) throws SQLException public void setBlob(int i, Blob x) throws SQLException
{ {
InputStream l_inStream = x.getBinaryStream(); InputStream l_inStream = x.getBinaryStream();
int l_length = (int) x.length(); int l_length = (int) x.length();
@@ -817,32 +874,37 @@ 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) { }
throw new PSQLException("postgresql.unusual",se); catch (IOException 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()
setInt(i,oid); setInt(i, oid);
} }
/** /**
* This is similar to setBinaryStream except it uses a Reader instead of * This is similar to setBinaryStream except it uses a Reader instead of
* InputStream. * InputStream.
*/ */
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); {
} catch (IOException l_ioe) { l_charsRead = x.read(l_chars, 0, length);
throw new PSQLException("postgresql.unusual",l_ioe);
} }
setString(i, new String(l_chars,0,l_charsRead)); catch (IOException l_ioe)
} else { {
throw new PSQLException("postgresql.unusual", l_ioe);
}
setString(i, new String(l_chars, 0, l_charsRead));
}
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,30 +932,34 @@ 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) { }
throw new PSQLException("postgresql.unusual",se); catch (IOException 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()
setInt(i,oid); setInt(i, oid);
} }
} }
/** /**
* New in 7.1 * New in 7.1
*/ */
public void setClob(int i,Clob x) throws SQLException public void setClob(int i, Clob x) throws SQLException
{ {
InputStream l_inStream = x.getAsciiStream(); InputStream l_inStream = x.getAsciiStream();
int l_length = (int) x.length(); int l_length = (int) x.length();
@@ -896,23 +967,27 @@ 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) { }
throw new PSQLException("postgresql.unusual",se); catch (IOException 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()
setInt(i,oid); setInt(i, oid);
} }
/** /**
@@ -920,12 +995,12 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
* *
* New in 7,1 * New in 7,1
*/ */
public void setNull(int i,int t,String s) throws SQLException public void setNull(int i, int t, String s) throws SQLException
{ {
setNull(i,t); setNull(i, t);
} }
public void setRef(int i,Ref x) throws SQLException public void setRef(int i, Ref x) throws SQLException
{ {
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
@@ -933,39 +1008,42 @@ public class PreparedStatement extends Statement implements java.sql.PreparedSta
/** /**
* New in 7,1 * New in 7,1
*/ */
public void setDate(int i,java.sql.Date d,java.util.Calendar cal) throws SQLException public void setDate(int i, java.sql.Date d, java.util.Calendar cal) throws SQLException
{
if (cal == null)
setDate(i, d);
else
{ {
if(cal==null)
setDate(i,d);
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()));
} }
} }
/** /**
* New in 7,1 * New in 7,1
*/ */
public void setTime(int i,Time t,java.util.Calendar cal) throws SQLException public void setTime(int i, Time t, java.util.Calendar cal) throws SQLException
{
if (cal == null)
setTime(i, t);
else
{ {
if(cal==null)
setTime(i,t);
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()));
} }
} }
/** /**
* New in 7,1 * New in 7,1
*/ */
public void setTimestamp(int i,Timestamp t,java.util.Calendar cal) throws SQLException public void setTimestamp(int i, Timestamp t, java.util.Calendar cal) throws SQLException
{
if (cal == null)
setTimestamp(i, t);
else
{ {
if(cal==null)
setTimestamp(i,t);
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

@@ -74,9 +74,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
* @param updateCount the number of rows affected by the operation * @param updateCount the number of rows affected by the operation
* @param cursor the positioned update/delete cursor name * @param cursor the positioned update/delete cursor name
*/ */
public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount,int insertOID, boolean binaryCursor) public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount, int insertOID, boolean binaryCursor)
{ {
super(conn,fields,tuples,status,updateCount,insertOID,binaryCursor); super(conn, fields, tuples, status, updateCount, insertOID, binaryCursor);
} }
/** /**
@@ -92,7 +92,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
*/ */
public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount) public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount)
{ {
super(conn,fields,tuples,status,updateCount,0,false); super(conn, fields, tuples, status, updateCount, 0, false);
} }
/** /**
@@ -133,8 +133,9 @@ 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;
} }
} }
@@ -165,7 +166,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
throw new PSQLException("postgresql.res.colrange"); throw new PSQLException("postgresql.res.colrange");
wasNullFlag = (this_row[columnIndex - 1] == null); wasNullFlag = (this_row[columnIndex - 1] == null);
if(wasNullFlag) if (wasNullFlag)
return null; return null;
Encoding encoding = connection.getEncoding(); Encoding encoding = connection.getEncoding();
@@ -200,8 +201,10 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Byte.parseByte(s); return Byte.parseByte(s);
} catch (NumberFormatException e) { }
throw new PSQLException("postgresql.res.badbyte",s); catch (NumberFormatException e)
{
throw new PSQLException("postgresql.res.badbyte", s);
} }
} }
return 0; // SQL NULL return 0; // SQL NULL
@@ -223,8 +226,10 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Short.parseShort(s); return Short.parseShort(s);
} catch (NumberFormatException e) { }
throw new PSQLException("postgresql.res.badshort",s); catch (NumberFormatException e)
{
throw new PSQLException("postgresql.res.badshort", s);
} }
} }
return 0; // SQL NULL return 0; // SQL NULL
@@ -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();
@@ -689,14 +716,15 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
throw new PSQLException("postgresql.res.colrange"); throw new PSQLException("postgresql.res.colrange");
wasNullFlag = (this_row[columnIndex - 1] == null); wasNullFlag = (this_row[columnIndex - 1] == null);
if(wasNullFlag) if (wasNullFlag)
return null; return null;
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;
} }
@@ -712,7 +740,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
return new Long(getLong(columnIndex)); return new Long(getLong(columnIndex));
case Types.NUMERIC: case Types.NUMERIC:
return getBigDecimal return getBigDecimal
(columnIndex, (field.getMod()==-1)?-1:((field.getMod()-4) & 0xffff)); (columnIndex, (field.getMod() == -1) ? -1 : ((field.getMod() - 4) & 0xffff));
case Types.REAL: case Types.REAL:
return new Float(getFloat(columnIndex)); return new Float(getFloat(columnIndex));
case Types.DOUBLE: case Types.DOUBLE:
@@ -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));
} }
} }
@@ -774,8 +805,8 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
final int flen = fields.length; final int flen = fields.length;
for (i = 0 ; i < flen; ++i) for (i = 0 ; i < flen; ++i)
if (fields[i].getName().equalsIgnoreCase(columnName)) if (fields[i].getName().equalsIgnoreCase(columnName))
return (i+1); return (i + 1);
throw new PSQLException ("postgresql.res.colname",columnName); throw new PSQLException ("postgresql.res.colname", columnName);
} }
// ** JDBC 2 Extensions ** // ** JDBC 2 Extensions **
@@ -785,17 +816,18 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
// index is 1-based, but internally we use 0-based indices // index is 1-based, but internally we use 0-based indices
int internalIndex; int internalIndex;
if (index==0) if (index == 0)
throw new SQLException("Cannot move to index of 0"); throw new SQLException("Cannot move to index of 0");
final int rows_size = rows.size(); final int rows_size = rows.size();
//if index<0, count from the end of the result set, but check //if index<0, count from the end of the result set, but check
//to be sure that it is not beyond the first index //to be sure that it is not beyond the first index
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;
} }
@@ -804,13 +836,14 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
//find the correct place, assuming that //find the correct place, assuming that
//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;
} }
current_row=internalIndex; current_row = internalIndex;
this_row = (byte [][])rows.elementAt(internalIndex); this_row = (byte [][])rows.elementAt(internalIndex);
return true; return true;
} }
@@ -857,17 +890,17 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
public java.sql.Array getArray(int i) throws SQLException public java.sql.Array getArray(int i) throws SQLException
{ {
wasNullFlag = (this_row[i - 1] == null); wasNullFlag = (this_row[i - 1] == null);
if(wasNullFlag) if (wasNullFlag)
return null; return null;
if (i < 1 || i > fields.length) if (i < 1 || i > fields.length)
throw new PSQLException("postgresql.res.colrange"); throw new PSQLException("postgresql.res.colrange");
return (java.sql.Array) new org.postgresql.jdbc2.Array( connection, i, fields[i-1], this ); return (java.sql.Array) new org.postgresql.jdbc2.Array( connection, i, fields[i - 1], this );
} }
public java.math.BigDecimal getBigDecimal(int columnIndex) throws SQLException public java.math.BigDecimal getBigDecimal(int columnIndex) throws SQLException
{ {
return getBigDecimal(columnIndex,-1); return getBigDecimal(columnIndex, -1);
} }
public java.math.BigDecimal getBigDecimal(String columnName) throws SQLException public java.math.BigDecimal getBigDecimal(String columnName) throws SQLException
@@ -882,7 +915,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
public Blob getBlob(int i) throws SQLException public Blob getBlob(int i) throws SQLException
{ {
return new org.postgresql.largeobject.PGblob(connection,getInt(i)); return new org.postgresql.largeobject.PGblob(connection, getInt(i));
} }
public java.io.Reader getCharacterStream(String columnName) throws SQLException public java.io.Reader getCharacterStream(String columnName) throws SQLException
@@ -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);
@@ -925,7 +961,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
*/ */
public Clob getClob(int i) throws SQLException public Clob getClob(int i) throws SQLException
{ {
return new org.postgresql.largeobject.PGclob(connection,getInt(i)); return new org.postgresql.largeobject.PGclob(connection, getInt(i));
} }
public int getConcurrency() throws SQLException public int getConcurrency() throws SQLException
@@ -936,7 +972,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
return CONCUR_READ_ONLY; return CONCUR_READ_ONLY;
} }
public java.sql.Date getDate(int i,java.util.Calendar cal) throws SQLException public java.sql.Date getDate(int i, java.util.Calendar cal) throws SQLException
{ {
// new in 7.1: If I read the specs, this should use cal only if we don't // new in 7.1: If I read the specs, this should use cal only if we don't
// store the timezone, and if we do, then act just like getDate()? // store the timezone, and if we do, then act just like getDate()?
@@ -944,7 +980,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
return getDate(i); return getDate(i);
} }
public Time getTime(int i,java.util.Calendar cal) throws SQLException public Time getTime(int i, java.util.Calendar cal) throws SQLException
{ {
// new in 7.1: If I read the specs, this should use cal only if we don't // new in 7.1: If I read the specs, this should use cal only if we don't
// store the timezone, and if we do, then act just like getTime()? // store the timezone, and if we do, then act just like getTime()?
@@ -952,7 +988,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
return getTime(i); return getTime(i);
} }
public Timestamp getTimestamp(int i,java.util.Calendar cal) throws SQLException public Timestamp getTimestamp(int i, java.util.Calendar cal) throws SQLException
{ {
// new in 7.1: If I read the specs, this should use cal only if we don't // new in 7.1: If I read the specs, this should use cal only if we don't
// store the timezone, and if we do, then act just like getDate()? // store the timezone, and if we do, then act just like getDate()?
@@ -960,19 +996,19 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
return getTimestamp(i); return getTimestamp(i);
} }
public java.sql.Date getDate(String c,java.util.Calendar cal) throws SQLException public java.sql.Date getDate(String c, java.util.Calendar cal) throws SQLException
{ {
return getDate(findColumn(c),cal); return getDate(findColumn(c), cal);
} }
public Time getTime(String c,java.util.Calendar cal) throws SQLException public Time getTime(String c, java.util.Calendar cal) throws SQLException
{ {
return getTime(findColumn(c),cal); return getTime(findColumn(c), cal);
} }
public Timestamp getTimestamp(String c,java.util.Calendar cal) throws SQLException public Timestamp getTimestamp(String c, java.util.Calendar cal) throws SQLException
{ {
return getTimestamp(findColumn(c),cal); return getTimestamp(findColumn(c), cal);
} }
public int getFetchDirection() throws SQLException public int getFetchDirection() throws SQLException
@@ -989,9 +1025,9 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
return rows.size(); return rows.size();
} }
public Object getObject(String columnName,java.util.Map map) throws SQLException public Object getObject(String columnName, java.util.Map map) throws SQLException
{ {
return getObject(findColumn(columnName),map); return getObject(findColumn(columnName), map);
} }
/** /**
@@ -999,7 +1035,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
* an object based on that mapping. The class must implement the SQLData * an object based on that mapping. The class must implement the SQLData
* interface. * interface.
*/ */
public Object getObject(int i,java.util.Map map) throws SQLException public Object getObject(int i, java.util.Map map) throws SQLException
{ {
/* In preparation /* In preparation
SQLInput s = new PSQLInput(this,i); SQLInput s = new PSQLInput(this,i);
@@ -1068,7 +1104,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
public boolean isLast() throws SQLException public boolean isLast() throws SQLException
{ {
final int rows_size = rows.size(); final int rows_size = rows.size();
return (current_row == rows_size -1 && rows_size > 0); return (current_row == rows_size - 1 && rows_size > 0);
} }
public boolean last() throws SQLException public boolean last() throws SQLException
@@ -1110,7 +1146,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
public boolean relative(int rows) throws SQLException public boolean relative(int rows) throws SQLException
{ {
//have to add 1 since absolute expects a 1-based index //have to add 1 since absolute expects a 1-based index
return absolute(current_row+1+rows); return absolute(current_row + 1 + rows);
} }
public boolean rowDeleted() throws SQLException public boolean rowDeleted() throws SQLException
@@ -1160,7 +1196,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
int length int length
) throws SQLException ) throws SQLException
{ {
updateAsciiStream(findColumn(columnName),x,length); updateAsciiStream(findColumn(columnName), x, length);
} }
public void updateBigDecimal(int columnIndex, public void updateBigDecimal(int columnIndex,
@@ -1175,7 +1211,7 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
java.math.BigDecimal x java.math.BigDecimal x
) throws SQLException ) throws SQLException
{ {
updateBigDecimal(findColumn(columnName),x); updateBigDecimal(findColumn(columnName), x);
} }
public void updateBinaryStream(int columnIndex, public void updateBinaryStream(int columnIndex,
@@ -1192,37 +1228,37 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
int length int length
) throws SQLException ) throws SQLException
{ {
updateBinaryStream(findColumn(columnName),x,length); updateBinaryStream(findColumn(columnName), x, length);
} }
public void updateBoolean(int columnIndex,boolean x) throws SQLException public void updateBoolean(int columnIndex, boolean x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
notUpdateable(); notUpdateable();
} }
public void updateBoolean(String columnName,boolean x) throws SQLException public void updateBoolean(String columnName, boolean x) throws SQLException
{ {
updateBoolean(findColumn(columnName),x); updateBoolean(findColumn(columnName), x);
} }
public void updateByte(int columnIndex,byte x) throws SQLException public void updateByte(int columnIndex, byte x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
notUpdateable(); notUpdateable();
} }
public void updateByte(String columnName,byte x) throws SQLException public void updateByte(String columnName, byte x) throws SQLException
{ {
updateByte(findColumn(columnName),x); updateByte(findColumn(columnName), x);
} }
public void updateBytes(String columnName,byte[] x) throws SQLException public void updateBytes(String columnName, byte[] x) throws SQLException
{ {
updateBytes(findColumn(columnName),x); updateBytes(findColumn(columnName), x);
} }
public void updateBytes(int columnIndex,byte[] x) throws SQLException public void updateBytes(int columnIndex, byte[] x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
notUpdateable(); notUpdateable();
@@ -1242,62 +1278,62 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
int length int length
) throws SQLException ) throws SQLException
{ {
updateCharacterStream(findColumn(columnName),x,length); updateCharacterStream(findColumn(columnName), x, length);
} }
public void updateDate(int columnIndex,java.sql.Date x) throws SQLException public void updateDate(int columnIndex, java.sql.Date x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
notUpdateable(); notUpdateable();
} }
public void updateDate(String columnName,java.sql.Date x) throws SQLException public void updateDate(String columnName, java.sql.Date x) throws SQLException
{ {
updateDate(findColumn(columnName),x); updateDate(findColumn(columnName), x);
} }
public void updateDouble(int columnIndex,double x) throws SQLException public void updateDouble(int columnIndex, double x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
notUpdateable(); notUpdateable();
} }
public void updateDouble(String columnName,double x) throws SQLException public void updateDouble(String columnName, double x) throws SQLException
{ {
updateDouble(findColumn(columnName),x); updateDouble(findColumn(columnName), x);
} }
public void updateFloat(int columnIndex,float x) throws SQLException public void updateFloat(int columnIndex, float x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
notUpdateable(); notUpdateable();
} }
public void updateFloat(String columnName,float x) throws SQLException public void updateFloat(String columnName, float x) throws SQLException
{ {
updateFloat(findColumn(columnName),x); updateFloat(findColumn(columnName), x);
} }
public void updateInt(int columnIndex,int x) throws SQLException public void updateInt(int columnIndex, int x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
notUpdateable(); notUpdateable();
} }
public void updateInt(String columnName,int x) throws SQLException public void updateInt(String columnName, int x) throws SQLException
{ {
updateInt(findColumn(columnName),x); updateInt(findColumn(columnName), x);
} }
public void updateLong(int columnIndex,long x) throws SQLException public void updateLong(int columnIndex, long x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
notUpdateable(); notUpdateable();
} }
public void updateLong(String columnName,long x) throws SQLException public void updateLong(String columnName, long x) throws SQLException
{ {
updateLong(findColumn(columnName),x); updateLong(findColumn(columnName), x);
} }
public void updateNull(int columnIndex) throws SQLException public void updateNull(int columnIndex) throws SQLException
@@ -1311,26 +1347,26 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
updateNull(findColumn(columnName)); updateNull(findColumn(columnName));
} }
public void updateObject(int columnIndex,Object x) throws SQLException public void updateObject(int columnIndex, Object x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
notUpdateable(); notUpdateable();
} }
public void updateObject(String columnName,Object x) throws SQLException public void updateObject(String columnName, Object x) throws SQLException
{ {
updateObject(findColumn(columnName),x); updateObject(findColumn(columnName), x);
} }
public void updateObject(int columnIndex,Object x,int scale) throws SQLException public void updateObject(int columnIndex, Object x, int scale) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
notUpdateable(); notUpdateable();
} }
public void updateObject(String columnName,Object x,int scale) throws SQLException public void updateObject(String columnName, Object x, int scale) throws SQLException
{ {
updateObject(findColumn(columnName),x,scale); updateObject(findColumn(columnName), x, scale);
} }
public void updateRow() throws SQLException public void updateRow() throws SQLException
@@ -1339,48 +1375,48 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
notUpdateable(); notUpdateable();
} }
public void updateShort(int columnIndex,short x) throws SQLException public void updateShort(int columnIndex, short x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
notUpdateable(); notUpdateable();
} }
public void updateShort(String columnName,short x) throws SQLException public void updateShort(String columnName, short x) throws SQLException
{ {
updateShort(findColumn(columnName),x); updateShort(findColumn(columnName), x);
} }
public void updateString(int columnIndex,String x) throws SQLException public void updateString(int columnIndex, String x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
notUpdateable(); notUpdateable();
} }
public void updateString(String columnName,String x) throws SQLException public void updateString(String columnName, String x) throws SQLException
{ {
updateString(findColumn(columnName),x); updateString(findColumn(columnName), x);
} }
public void updateTime(int columnIndex,Time x) throws SQLException public void updateTime(int columnIndex, Time x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
notUpdateable(); notUpdateable();
} }
public void updateTime(String columnName,Time x) throws SQLException public void updateTime(String columnName, Time x) throws SQLException
{ {
updateTime(findColumn(columnName),x); updateTime(findColumn(columnName), x);
} }
public void updateTimestamp(int columnIndex,Timestamp x) throws SQLException public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
notUpdateable(); notUpdateable();
} }
public void updateTimestamp(String columnName,Timestamp x) throws SQLException public void updateTimestamp(String columnName, Timestamp x) throws SQLException
{ {
updateTimestamp(findColumn(columnName),x); updateTimestamp(findColumn(columnName), x);
} }
// helper method. Throws an SQLException when an update is not possible // helper method. Throws an SQLException when an update is not possible
@@ -1394,8 +1430,9 @@ 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;
} }
//----------------- Formatting Methods ------------------- //----------------- Formatting Methods -------------------
@@ -1417,8 +1454,10 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Integer.parseInt(s); return Integer.parseInt(s);
} catch (NumberFormatException e) { }
throw new PSQLException ("postgresql.res.badint",s); catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badint", s);
} }
} }
return 0; // SQL NULL return 0; // SQL NULL
@@ -1431,8 +1470,10 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
return Long.parseLong(s); return Long.parseLong(s);
} catch (NumberFormatException e) { }
throw new PSQLException ("postgresql.res.badlong",s); catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badlong", s);
} }
} }
return 0; // SQL NULL return 0; // SQL NULL
@@ -1446,15 +1487,20 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
try try
{ {
val = new BigDecimal(s); val = new BigDecimal(s);
} catch (NumberFormatException e) {
throw new PSQLException ("postgresql.res.badbigdec",s);
} }
if (scale==-1) return val; catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badbigdec", s);
}
if (scale == -1)
return val;
try try
{ {
return val.setScale(scale); return val.setScale(scale);
} catch (ArithmeticException e) { }
throw new PSQLException ("postgresql.res.badbigdec",s); catch (ArithmeticException e)
{
throw new PSQLException ("postgresql.res.badbigdec", s);
} }
} }
return null; // SQL NULL return null; // SQL NULL
@@ -1467,8 +1513,10 @@ 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) { }
throw new PSQLException ("postgresql.res.badfloat",s); catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.badfloat", s);
} }
} }
return 0; // SQL NULL return 0; // SQL NULL
@@ -1481,8 +1529,10 @@ 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) { }
throw new PSQLException ("postgresql.res.baddouble",s); catch (NumberFormatException e)
{
throw new PSQLException ("postgresql.res.baddouble", s);
} }
} }
return 0; // SQL NULL return 0; // SQL NULL
@@ -1490,28 +1540,31 @@ public class ResultSet extends org.postgresql.ResultSet implements java.sql.Resu
public static java.sql.Date toDate(String s) throws SQLException public static java.sql.Date toDate(String s) throws SQLException
{ {
if(s==null) if (s == null)
return null; return null;
return java.sql.Date.valueOf(s); return java.sql.Date.valueOf(s);
} }
public static Time toTime(String s) throws SQLException public static Time toTime(String s) throws SQLException
{ {
if(s==null) if (s == null)
return null; // SQL NULL return null; // SQL NULL
return java.sql.Time.valueOf(s); return java.sql.Time.valueOf(s);
} }
public static Timestamp toTimestamp(String s, ResultSet resultSet) throws SQLException public static Timestamp toTimestamp(String s, ResultSet resultSet) throws SQLException
{ {
if(s==null) if (s == null)
return null; return null;
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,49 +1573,68 @@ 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
// First time? // First time?
if(resultSet.sbuf==null) if (resultSet.sbuf == null)
resultSet.sbuf = new StringBuffer(); resultSet.sbuf = new StringBuffer();
resultSet.sbuf.setLength(0); resultSet.sbuf.setLength(0);
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); {
if (subsecond) { resultSet.sbuf.setLength(resultSet.sbuf.length() - 3);
resultSet.sbuf.append('0').append("GMT").append(s.substring(s.length()-3)).append(":00"); if (subsecond)
} else { {
resultSet.sbuf.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 if (subsecond) { else
{
resultSet.sbuf.append("GMT").append(s.substring(s.length() - 3)).append(":00");
}
}
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) { }
throw new PSQLException("postgresql.res.badtimestamp",new Integer(e.getErrorOffset()),s); catch (ParseException e)
{
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
@@ -243,9 +256,9 @@ public class ResultSetMetaData implements java.sql.ResultSetMetaData
public String getColumnName(int column) throws SQLException public String getColumnName(int column) throws SQLException
{ {
Field f = getField(column); Field f = getField(column);
if(f!=null) if (f != null)
return f.getName(); return f.getName();
return "field"+column; return "field" + column;
} }
/** /**
@@ -290,8 +303,8 @@ public class ResultSetMetaData implements java.sql.ResultSetMetaData
return 0; return 0;
case Types.NUMERIC: case Types.NUMERIC:
Field f = getField(column); Field f = getField(column);
if(f != null) if (f != null)
return ((0xFFFF0000)&f.getMod())>>16; return ((0xFFFF0000)&f.getMod()) >> 16;
else else
return 0; return 0;
default: default:
@@ -327,8 +340,8 @@ public class ResultSetMetaData implements java.sql.ResultSetMetaData
return 0; return 0;
case Types.NUMERIC: case Types.NUMERIC:
Field f = getField(column); Field f = getField(column);
if(f != null) if (f != null)
return (((0x0000FFFF)&f.getMod())-4); return (((0x0000FFFF)&f.getMod()) - 4);
else else
return 0; return 0;
default: default:

View File

@@ -25,7 +25,7 @@ import org.postgresql.util.*;
public class Statement extends org.postgresql.Statement implements java.sql.Statement public class Statement extends org.postgresql.Statement implements java.sql.Statement
{ {
private Connection connection; // The connection who created us private Connection connection; // The connection who created us
private Vector batch=null; private Vector batch = null;
private int resultsettype; // the resultset type to return private int resultsettype; // the resultset type to return
private int concurrency; // is it updateable or not? private int concurrency; // is it updateable or not?
@@ -119,14 +119,15 @@ 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();
} }
// New in 7.1, pass Statement so that ExecSQL can customise to it // New in 7.1, pass Statement so that ExecSQL can customise to it
result = connection.ExecSQL(sql,this); result = connection.ExecSQL(sql, this);
// New in 7.1, required for ResultSet.getStatement() to work // New in 7.1, required for ResultSet.getStatement() to work
((org.postgresql.jdbc2.ResultSet)result).setStatement(this); ((org.postgresql.jdbc2.ResultSet)result).setStatement(this);
@@ -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();
} }
@@ -166,30 +169,33 @@ public class Statement extends org.postgresql.Statement implements java.sql.Stat
public void addBatch(String sql) throws SQLException public void addBatch(String sql) throws SQLException
{ {
if(batch==null) if (batch == null)
batch=new Vector(); batch = new Vector();
batch.addElement(sql); batch.addElement(sql);
} }
public void clearBatch() throws SQLException public void clearBatch() throws SQLException
{ {
if(batch!=null) if (batch != null)
batch.removeAllElements(); batch.removeAllElements();
} }
public int[] executeBatch() throws SQLException public int[] executeBatch() throws SQLException
{ {
if(batch==null) if (batch == null)
batch=new Vector(); batch = new Vector();
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++) {
result[i]=this.executeUpdate((String)batch.elementAt(i)); for (i = 0;i < size;i++)
} catch(SQLException e) { result[i] = this.executeUpdate((String)batch.elementAt(i));
}
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);
PBatchUpdateException updex = PBatchUpdateException updex =
new PBatchUpdateException("postgresql.stat.batch.error", new PBatchUpdateException("postgresql.stat.batch.error",
@@ -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;
@@ -246,7 +254,7 @@ public class Statement extends org.postgresql.Statement implements java.sql.Stat
*/ */
public void setResultSetConcurrency(int value) throws SQLException public void setResultSetConcurrency(int value) throws SQLException
{ {
concurrency=value; concurrency = value;
} }
/** /**
@@ -254,6 +262,6 @@ public class Statement extends org.postgresql.Statement implements java.sql.Stat
*/ */
public void setResultSetType(int value) throws SQLException public void setResultSetType(int value) throws SQLException
{ {
resultsettype=value; resultsettype = value;
} }
} }

View File

@@ -40,9 +40,9 @@ public class UpdateableResultSet extends org.postgresql.jdbc2.ResultSet
* @param updateCount the number of rows affected by the operation * @param updateCount the number of rows affected by the operation
* @param cursor the positioned update/delete cursor name * @param cursor the positioned update/delete cursor name
*/ */
public UpdateableResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount,int insertOID, boolean binaryCursor) public UpdateableResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount, int insertOID, boolean binaryCursor)
{ {
super(conn,fields,tuples,status,updateCount,insertOID,binaryCursor); super(conn, fields, tuples, status, updateCount, insertOID, binaryCursor);
} }
/** /**
@@ -145,19 +145,19 @@ public class UpdateableResultSet extends org.postgresql.jdbc2.ResultSet
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public void updateBoolean(int columnIndex,boolean x) throws SQLException public void updateBoolean(int columnIndex, boolean x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public void updateByte(int columnIndex,byte x) throws SQLException public void updateByte(int columnIndex, byte x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public void updateBytes(int columnIndex,byte[] x) throws SQLException public void updateBytes(int columnIndex, byte[] x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
@@ -172,31 +172,31 @@ public class UpdateableResultSet extends org.postgresql.jdbc2.ResultSet
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public void updateDate(int columnIndex,java.sql.Date x) throws SQLException public void updateDate(int columnIndex, java.sql.Date x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public void updateDouble(int columnIndex,double x) throws SQLException public void updateDouble(int columnIndex, double x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public void updateFloat(int columnIndex,float x) throws SQLException public void updateFloat(int columnIndex, float x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public void updateInt(int columnIndex,int x) throws SQLException public void updateInt(int columnIndex, int x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public void updateLong(int columnIndex,long x) throws SQLException public void updateLong(int columnIndex, long x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
@@ -208,13 +208,13 @@ public class UpdateableResultSet extends org.postgresql.jdbc2.ResultSet
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public void updateObject(int columnIndex,Object x) throws SQLException public void updateObject(int columnIndex, Object x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public void updateObject(int columnIndex,Object x,int scale) throws SQLException public void updateObject(int columnIndex, Object x, int scale) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
@@ -226,25 +226,25 @@ public class UpdateableResultSet extends org.postgresql.jdbc2.ResultSet
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public void updateShort(int columnIndex,short x) throws SQLException public void updateShort(int columnIndex, short x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public void updateString(int columnIndex,String x) throws SQLException public void updateString(int columnIndex, String x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public void updateTime(int columnIndex,Time x) throws SQLException public void updateTime(int columnIndex, Time x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();
} }
public void updateTimestamp(int columnIndex,Timestamp x) throws SQLException public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException
{ {
// only sub-classes implement CONCUR_UPDATEABLE // only sub-classes implement CONCUR_UPDATEABLE
throw org.postgresql.Driver.notImplemented(); throw org.postgresql.Driver.notImplemented();

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
*/ */
@@ -33,50 +34,59 @@ public class BlobInputStream extends InputStream {
/** /**
* The mark position * The mark position
*/ */
private int mpos=0; private int mpos = 0;
/** /**
* @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);
} }
/** /**
* @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; {
buffer=null; this.lo = lo;
bpos=0; buffer = null;
this.bsize=bsize; bpos = 0;
this.bsize = bsize;
} }
/** /**
* 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
buffer=lo.read(bsize); {
bpos=0; if (buffer == null || bpos >= buffer.length)
{
buffer = lo.read(bsize);
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 { {
mpos=lo.tell(); try
} catch(SQLException se) { {
mpos = lo.tell();
}
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,8 +33,9 @@ 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.bsize=bsize; this.lo = lo;
buf=new byte[bsize]; this.bsize = bsize;
bpos=0; buf = new byte[bsize];
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 { {
if(bpos>0) try
lo.write(buf,0,bpos); {
bpos=0; if (bpos > 0)
} catch(SQLException se) { lo.write(buf, 0, bpos);
bpos = 0;
}
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

@@ -64,7 +64,7 @@ public class LargeObject
private BlobOutputStream os; // The current output stream private BlobOutputStream os; // The current output stream
private boolean closed=false; // true when we are closed private boolean closed = false; // true when we are closed
/** /**
* This opens a large object. * This opens a large object.
@@ -78,7 +78,7 @@ public class LargeObject
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
* @see org.postgresql.largeobject.LargeObjectManager * @see org.postgresql.largeobject.LargeObjectManager
*/ */
protected LargeObject(Fastpath fp,int oid,int mode) throws SQLException protected LargeObject(Fastpath fp, int oid, int mode) throws SQLException
{ {
this.fp = fp; this.fp = fp;
this.oid = oid; this.oid = oid;
@@ -86,7 +86,7 @@ public class LargeObject
FastpathArg args[] = new FastpathArg[2]; FastpathArg args[] = new FastpathArg[2];
args[0] = new FastpathArg(oid); args[0] = new FastpathArg(oid);
args[1] = new FastpathArg(mode); args[1] = new FastpathArg(mode);
this.fd = fp.getInteger("lo_open",args); this.fd = fp.getInteger("lo_open", args);
} }
/* Release large object resources during garbage cleanup */ /* Release large object resources during garbage cleanup */
@@ -110,24 +110,31 @@ 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 { }
os=null; finally
{
os = null;
} }
} }
// finally close // finally close
FastpathArg args[] = new FastpathArg[1]; FastpathArg args[] = new FastpathArg[1];
args[0] = new FastpathArg(fd); args[0] = new FastpathArg(fd);
fp.fastpath("lo_close",false,args); // true here as we dont care!! fp.fastpath("lo_close", false, args); // true here as we dont care!!
closed=true; closed = true;
} }
} }
@@ -145,7 +152,7 @@ public class LargeObject
FastpathArg args[] = new FastpathArg[2]; FastpathArg args[] = new FastpathArg[2];
args[0] = new FastpathArg(fd); args[0] = new FastpathArg(fd);
args[1] = new FastpathArg(len); args[1] = new FastpathArg(len);
return fp.getData("loread",args); return fp.getData("loread", args);
// This version allows us to break this down into 4k blocks // This version allows us to break this down into 4k blocks
//if(len<=4048) { //if(len<=4048) {
@@ -181,12 +188,12 @@ public class LargeObject
* @return the number of bytes actually read * @return the number of bytes actually read
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public int read(byte buf[],int off,int len) throws SQLException public int read(byte buf[], int off, int len) throws SQLException
{ {
byte b[] = read(len); byte b[] = read(len);
if(b.length<len) if (b.length < len)
len=b.length; len = b.length;
System.arraycopy(b,0,buf,off,len); System.arraycopy(b, 0, buf, off, len);
return len; return len;
} }
@@ -201,7 +208,7 @@ public class LargeObject
FastpathArg args[] = new FastpathArg[2]; FastpathArg args[] = new FastpathArg[2];
args[0] = new FastpathArg(fd); args[0] = new FastpathArg(fd);
args[1] = new FastpathArg(buf); args[1] = new FastpathArg(buf);
fp.fastpath("lowrite",false,args); fp.fastpath("lowrite", false, args);
} }
/** /**
@@ -212,10 +219,10 @@ public class LargeObject
* @param len number of bytes to write * @param len number of bytes to write
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public void write(byte buf[],int off,int len) throws SQLException public void write(byte buf[], int off, int len) throws SQLException
{ {
byte data[] = new byte[len]; byte data[] = new byte[len];
System.arraycopy(buf,off,data,0,len); System.arraycopy(buf, off, data, 0, len);
write(data); write(data);
} }
@@ -229,13 +236,13 @@ public class LargeObject
* @param ref Either SEEK_SET, SEEK_CUR or SEEK_END * @param ref Either SEEK_SET, SEEK_CUR or SEEK_END
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public void seek(int pos,int ref) throws SQLException public void seek(int pos, int ref) throws SQLException
{ {
FastpathArg args[] = new FastpathArg[3]; FastpathArg args[] = new FastpathArg[3];
args[0] = new FastpathArg(fd); args[0] = new FastpathArg(fd);
args[1] = new FastpathArg(pos); args[1] = new FastpathArg(pos);
args[2] = new FastpathArg(ref); args[2] = new FastpathArg(ref);
fp.fastpath("lo_lseek",false,args); fp.fastpath("lo_lseek", false, args);
} }
/** /**
@@ -249,7 +256,7 @@ public class LargeObject
*/ */
public void seek(int pos) throws SQLException public void seek(int pos) throws SQLException
{ {
seek(pos,SEEK_SET); seek(pos, SEEK_SET);
} }
/** /**
@@ -260,7 +267,7 @@ public class LargeObject
{ {
FastpathArg args[] = new FastpathArg[1]; FastpathArg args[] = new FastpathArg[1];
args[0] = new FastpathArg(fd); args[0] = new FastpathArg(fd);
return fp.getInteger("lo_tell",args); return fp.getInteger("lo_tell", args);
} }
/** /**
@@ -276,9 +283,9 @@ public class LargeObject
public int size() throws SQLException public int size() throws SQLException
{ {
int cp = tell(); int cp = tell();
seek(0,SEEK_END); seek(0, SEEK_END);
int sz = tell(); int sz = tell();
seek(cp,SEEK_SET); seek(cp, SEEK_SET);
return sz; return sz;
} }
@@ -305,7 +312,7 @@ public class LargeObject
*/ */
public OutputStream getOutputStream() throws SQLException public OutputStream getOutputStream() throws SQLException
{ {
if(os==null) if (os == null)
os = new BlobOutputStream(this); os = new BlobOutputStream(this);
return os; return os;
} }

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.
@@ -113,7 +112,7 @@ public class LargeObjectManager
" or proname = 'loread'" + " or proname = 'loread'" +
" or proname = 'lowrite'"); " or proname = 'lowrite'");
if(res==null) if (res == null)
throw new PSQLException("postgresql.lo.init"); throw new PSQLException("postgresql.lo.init");
fp.addFunctions(res); fp.addFunctions(res);
@@ -131,7 +130,7 @@ public class LargeObjectManager
*/ */
public LargeObject open(int oid) throws SQLException public LargeObject open(int oid) throws SQLException
{ {
return new LargeObject(fp,oid,READWRITE); return new LargeObject(fp, oid, READWRITE);
} }
/** /**
@@ -142,9 +141,9 @@ public class LargeObjectManager
* @return LargeObject instance providing access to the object * @return LargeObject instance providing access to the object
* @exception SQLException on error * @exception SQLException on error
*/ */
public LargeObject open(int oid,int mode) throws SQLException public LargeObject open(int oid, int mode) throws SQLException
{ {
return new LargeObject(fp,oid,mode); return new LargeObject(fp, oid, mode);
} }
/** /**
@@ -159,7 +158,7 @@ public class LargeObjectManager
{ {
FastpathArg args[] = new FastpathArg[1]; FastpathArg args[] = new FastpathArg[1];
args[0] = new FastpathArg(READWRITE); args[0] = new FastpathArg(READWRITE);
return fp.getInteger("lo_creat",args); return fp.getInteger("lo_creat", args);
} }
/** /**
@@ -173,7 +172,7 @@ public class LargeObjectManager
{ {
FastpathArg args[] = new FastpathArg[1]; FastpathArg args[] = new FastpathArg[1];
args[0] = new FastpathArg(mode); args[0] = new FastpathArg(mode);
return fp.getInteger("lo_creat",args); return fp.getInteger("lo_creat", args);
} }
/** /**
@@ -186,7 +185,7 @@ public class LargeObjectManager
{ {
FastpathArg args[] = new FastpathArg[1]; FastpathArg args[] = new FastpathArg[1];
args[0] = new FastpathArg(oid); args[0] = new FastpathArg(oid);
fp.fastpath("lo_unlink",false,args); fp.fastpath("lo_unlink", false, args);
} }
/** /**

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,38 +29,44 @@ 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.oid=oid; this.conn = conn;
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);
} }
/* /*
* 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,41 +29,48 @@ 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.oid=oid; this.conn = conn;
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));
} }
/* /*
* 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,8 +182,9 @@ 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();
// //
// Add one line per class in our test cases. These should be in order of // Add one line per class in our test cases. These should be in order of

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,10 +13,11 @@ 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 usr=System.getProperty("username"); String url = System.getProperty("database");
String psw=System.getProperty("password"); String usr = System.getProperty("username");
String psw = System.getProperty("password");
assertNotNull(url); assertNotNull(url);
assertNotNull(usr); assertNotNull(usr);

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,19 +73,21 @@ 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);
stmt.addBatch("UPDATE testbatch SET col1 = col1 + 1 WHERE pk = 1"); stmt.addBatch("UPDATE testbatch SET col1 = col1 + 1 WHERE pk = 1");
stmt.clearBatch(); stmt.clearBatch();
updateCount = stmt.executeBatch(); updateCount = stmt.executeBatch();
assertEquals(0,updateCount.length); assertEquals(0, updateCount.length);
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,22 +134,23 @@ 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 = ?" );
// Note that the first parameter changes for every statement in the // Note that the first parameter changes for every statement in the
// batch, whereas the second parameter remains constant. // batch, whereas the second parameter remains constant.
pstmt.setInt(1,1); pstmt.setInt(1, 1);
pstmt.setInt(2,1); pstmt.setInt(2, 1);
pstmt.addBatch(); pstmt.addBatch();
assertCol1HasValue(0); assertCol1HasValue(0);
pstmt.setInt(1,2); pstmt.setInt(1, 2);
pstmt.addBatch(); pstmt.addBatch();
assertCol1HasValue(0); assertCol1HasValue(0);
pstmt.setInt(1,4); pstmt.setInt(1, 4);
pstmt.addBatch(); pstmt.addBatch();
assertCol1HasValue(0); assertCol1HasValue(0);
@@ -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");
@@ -170,9 +186,9 @@ public class BatchExecuteTest extends TestCase {
assertCol1HasValue(0); assertCol1HasValue(0);
int[] updateCounts = stmt.executeBatch(); int[] updateCounts = stmt.executeBatch();
assertEquals(2,updateCounts.length); assertEquals(2, updateCounts.length);
assertEquals(1,updateCounts[0]); assertEquals(1, updateCounts[0]);
assertEquals(1,updateCounts[1]); assertEquals(1, updateCounts[1]);
assertCol1HasValue(12); assertCol1HasValue(12);
con.commit(); con.commit();

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);
@@ -89,27 +102,29 @@ public class BlobTest extends TestCase {
int oid = lom.create(LargeObjectManager.READWRITE); int oid = lom.create(LargeObjectManager.READWRITE);
LargeObject blob = lom.open(oid); LargeObject blob = lom.open(oid);
int s,t; int s, t;
byte buf[]; byte buf[];
OutputStream os; OutputStream os;
switch(method) switch (method)
{ {
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; {
blob.write(buf,0,s); t += s;
blob.write(buf, 0, s);
} }
break; break;
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();
} }
os.close(); os.close();
break; break;
@@ -117,12 +132,12 @@ public class BlobTest extends TestCase {
case JDBC_STREAM: case JDBC_STREAM:
File f = new File(file); File f = new File(file);
PreparedStatement ps = con.prepareStatement(JDBC2Tests.insertSQL("testblob", "?")); PreparedStatement ps = con.prepareStatement(JDBC2Tests.insertSQL("testblob", "?"));
ps.setBinaryStream(1,fis,(int) f.length()); ps.setBinaryStream(1, fis, (int) f.length());
ps.execute(); ps.execute();
break; break;
default: default:
assertTrue("Unknown method in uploadFile",false); assertTrue("Unknown method in uploadFile", false);
} }
blob.close(); blob.close();
@@ -130,7 +145,7 @@ public class BlobTest extends TestCase {
// Insert into the table // Insert into the table
Statement st = con.createStatement(); Statement st = con.createStatement();
st.executeUpdate(JDBC2Tests.insertSQL("testblob", "id,lo","'"+file+"',"+oid)); st.executeUpdate(JDBC2Tests.insertSQL("testblob", "id,lo", "'" + file + "'," + oid));
con.commit(); con.commit();
st.close(); st.close();
@@ -141,8 +156,9 @@ 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);
@@ -158,19 +175,20 @@ public class BlobTest extends TestCase {
LargeObject blob = lom.open(oid); LargeObject blob = lom.open(oid);
InputStream bis = blob.getInputStream(); InputStream bis = blob.getInputStream();
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); {
f=fis.read(); result = (f == b);
b=bis.read(); f = fis.read();
b = bis.read();
c++; c++;
} }
result=result && f==-1 && b==-1; result = result && f == -1 && b == -1;
if(!result) if (!result)
System.out.println("\nBlob compare failed at "+c+" of "+blob.size()); System.out.println("\nBlob compare failed at " + c + " of " + blob.size());
blob.close(); blob.close();
fis.close(); fis.close();

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
@@ -55,20 +61,24 @@ public class ConnectionTest extends TestCase {
stat.close(); stat.close();
// Ask for Updateable ResultSets // Ask for Updateable ResultSets
stat = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_UPDATABLE); stat = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE);
assertNotNull(stat); assertNotNull(stat);
stat.close(); stat.close();
} catch(SQLException ex) { }
assertTrue(ex.getMessage(),false); catch (SQLException ex)
{
assertTrue(ex.getMessage(), false);
} }
} }
/** /**
* 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";
@@ -79,33 +89,38 @@ public class ConnectionTest extends TestCase {
stat.close(); stat.close();
// Ask for Updateable ResultSets // Ask for Updateable ResultSets
stat = conn.prepareStatement(sql,java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_UPDATABLE); stat = conn.prepareStatement(sql, java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE);
assertNotNull(stat); assertNotNull(stat);
stat.close(); stat.close();
} catch(SQLException ex) { }
assertTrue(ex.getMessage(),false); catch (SQLException ex)
{
assertTrue(ex.getMessage(), false);
} }
} }
/** /**
* 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,16 +156,20 @@ public class ConnectionTest extends TestCase {
rs.close(); rs.close();
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
assertTrue(ex.getMessage(),false); catch (SQLException ex)
{
assertTrue(ex.getMessage(), false);
} }
} }
/** /**
* 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,16 +180,20 @@ public class ConnectionTest extends TestCase {
// Should now say closed // Should now say closed
assertTrue(con.isClosed()); assertTrue(con.isClosed());
} catch(SQLException ex) { }
assertTrue(ex.getMessage(),false); catch (SQLException ex)
{
assertTrue(ex.getMessage(), false);
} }
} }
/** /**
* 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";
@@ -191,11 +214,13 @@ public class ConnectionTest extends TestCase {
// Finally test clearWarnings() this time there must be something to delete // Finally test clearWarnings() this time there must be something to delete
con.clearWarnings(); con.clearWarnings();
assertTrue(con.getWarnings()==null); assertTrue(con.getWarnings() == null);
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
assertTrue(ex.getMessage(),false); catch (SQLException ex)
{
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,8 +331,10 @@ public class ConnectionTest extends TestCase {
assertEquals(oldmap, con.getTypeMap()); assertEquals(oldmap, con.getTypeMap());
JDBC2Tests.closeDB(con); JDBC2Tests.closeDB(con);
} catch(SQLException ex) { }
assertTrue(ex.getMessage(),false); catch (SQLException ex)
{
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;
@@ -250,17 +294,21 @@ public class DatabaseMetaDataTest extends TestCase {
assertNotNull(dbmd); assertNotNull(dbmd);
assertTrue(dbmd.getDatabaseProductName().equals("PostgreSQL")); assertTrue(dbmd.getDatabaseProductName().equals("PostgreSQL"));
assertTrue(dbmd.getDatabaseProductVersion().startsWith(Integer.toString(pc.this_driver.getMajorVersion())+"."+Integer.toString(pc.this_driver.getMinorVersion()))); assertTrue(dbmd.getDatabaseProductVersion().startsWith(Integer.toString(pc.this_driver.getMajorVersion()) + "." + Integer.toString(pc.this_driver.getMinorVersion())));
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;
@@ -269,12 +317,14 @@ public class DatabaseMetaDataTest extends TestCase {
assertNotNull(dbmd); assertNotNull(dbmd);
assertTrue(dbmd.getDriverVersion().equals(pc.this_driver.getVersion())); assertTrue(dbmd.getDriverVersion().equals(pc.this_driver.getVersion()));
assertTrue(dbmd.getDriverMajorVersion()==pc.this_driver.getMajorVersion()); assertTrue(dbmd.getDriverMajorVersion() == pc.this_driver.getMajorVersion());
assertTrue(dbmd.getDriverMinorVersion()==pc.this_driver.getMinorVersion()); assertTrue(dbmd.getDriverMinorVersion() == pc.this_driver.getMinorVersion());
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,23 +55,29 @@ 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; {
try { Connection con = null;
try
{
Class.forName("org.postgresql.Driver"); Class.forName("org.postgresql.Driver");
// Test with the url, username & password // Test with the url, username & password
con = DriverManager.getConnection(JDBC2Tests.getURL(),JDBC2Tests.getUser(),JDBC2Tests.getPassword()); con = DriverManager.getConnection(JDBC2Tests.getURL(), JDBC2Tests.getUser(), JDBC2Tests.getPassword());
assertNotNull(con); assertNotNull(con);
con.close(); con.close();
// Test with the username in the url // Test with the username in the url
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,12 +50,13 @@ 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);
assertEquals(97, reader.read()); assertEquals(97, reader.read());
assertEquals(98, reader.read()); assertEquals(98, reader.read());
assertEquals(-1, reader.read()); assertEquals( -1, reader.read());
} }
} }

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,38 +29,49 @@ 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);
} }
return message; return message;

View File

@@ -5,17 +5,19 @@ 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();
byte[] buf = new byte[slength]; byte[] buf = new byte[slength];
@@ -23,25 +25,32 @@ 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 { }
thebyte = (secondchar-48)*64 + (s.charAt(++i)-48)*8 + (s.charAt(++i)-48); else
{
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;
} }
} }
byte[] l_return = new byte[bufpos]; byte[] l_return = new byte[bufpos];
System.arraycopy(buf,0,l_return,0,bufpos); System.arraycopy(buf, 0, l_return, 0, bufpos);
return l_return; return l_return;
} }
@@ -51,30 +60,37 @@ public class PGbytea {
*/ */
public static String toPGString(byte[] p_buf) throws SQLException public static String toPGString(byte[] p_buf) throws SQLException
{ {
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

@@ -6,7 +6,7 @@ import java.sql.*;
/** /**
* This implements a class that handles the PostgreSQL money and cash types * This implements a class that handles the PostgreSQL money and cash types
*/ */
public class PGmoney extends PGobject implements Serializable,Cloneable public class PGmoney extends PGobject implements Serializable, Cloneable
{ {
/** /**
* The value of the field * The value of the field
@@ -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,16 +60,19 @@ 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(',');
} }
val = Double.valueOf(s1).doubleValue(); val = Double.valueOf(s1).doubleValue();
val = negative ? -val : val; val = negative ? -val : val;
} catch(NumberFormatException e) { }
throw new PSQLException("postgresql.money",e); catch (NumberFormatException 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,11 +103,13 @@ 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

@@ -13,7 +13,7 @@ import java.util.*;
* handlers via a call to org.postgresql.Connection. These handlers * handlers via a call to org.postgresql.Connection. These handlers
* must extend this class. * must extend this class.
*/ */
public class PGobject implements Serializable,Cloneable public class PGobject implements Serializable, Cloneable
{ {
protected String type; protected String type;
protected String value; protected String value;
@@ -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.
@@ -75,7 +74,7 @@ public class PGobject implements Serializable,Cloneable
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(obj instanceof PGobject) if (obj instanceof PGobject)
return ((PGobject)obj).getValue().equals(getValue()); return ((PGobject)obj).getValue().equals(getValue());
return false; return false;
} }
@@ -86,8 +85,8 @@ public class PGobject implements Serializable,Cloneable
public Object clone() public Object clone()
{ {
PGobject obj = new PGobject(); PGobject obj = new PGobject();
obj.type=type; obj.type = type;
obj.value=value; obj.value = value;
return obj; return obj;
} }

View File

@@ -31,9 +31,9 @@ public class PGtokenizer
* @param string containing tokens * @param string containing tokens
* @param delim single character to split the tokens * @param delim single character to split the tokens
*/ */
public PGtokenizer(String string,char delim) public PGtokenizer(String string, char delim)
{ {
tokenize(string,delim); tokenize(string, delim);
} }
/** /**
@@ -42,7 +42,7 @@ public class PGtokenizer
* @param string containing tokens * @param string containing tokens
* @param delim single character to split the tokens * @param delim single character to split the tokens
*/ */
public int tokenize(String string,char delim) public int tokenize(String string, char delim)
{ {
tokens = new Vector(); tokens = new Vector();
@@ -53,28 +53,31 @@ public class PGtokenizer
// (usualls PGpoint) imbedded within a token. // (usualls PGpoint) imbedded within a token.
// //
// 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
if(c == '(' || c == '[' || c == '<') if (c == '(' || c == '[' || c == '<')
nest++; nest++;
// decrease nesting if a close character is found // decrease nesting if a close character is found
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)); {
s=p+1; // +1 to skip the delimiter tokens.addElement(string.substring(s, p));
s = p + 1; // +1 to skip the delimiter
} }
} }
// 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));
return tokens.size(); return tokens.size();
@@ -107,9 +110,9 @@ public class PGtokenizer
* @param delim The delimiter to use * @param delim The delimiter to use
* @return A new instance of PGtokenizer based on the token * @return A new instance of PGtokenizer based on the token
*/ */
public PGtokenizer tokenizeToken(int n,char delim) public PGtokenizer tokenizeToken(int n, char delim)
{ {
return new PGtokenizer(getToken(n),delim); return new PGtokenizer(getToken(n), delim);
} }
/** /**
@@ -119,10 +122,12 @@ public class PGtokenizer
* @param t Trailing string to remove * @param t Trailing string to remove
* @return String without the lead/trailing strings * @return String without the lead/trailing strings
*/ */
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;
} }
@@ -131,10 +136,11 @@ public class PGtokenizer
* @param l Leading string to remove * @param l Leading string to remove
* @param t Trailing string to remove * @param t Trailing string to remove
*/ */
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);
} }
} }
@@ -145,7 +151,7 @@ public class PGtokenizer
*/ */
public static String removePara(String s) public static String removePara(String s)
{ {
return remove(s,"(",")"); return remove(s, "(", ")");
} }
/** /**
@@ -154,7 +160,7 @@ public class PGtokenizer
*/ */
public void removePara() public void removePara()
{ {
remove("(",")"); remove("(", ")");
} }
/** /**
@@ -164,7 +170,7 @@ public class PGtokenizer
*/ */
public static String removeBox(String s) public static String removeBox(String s)
{ {
return remove(s,"[","]"); return remove(s, "[", "]");
} }
/** /**
@@ -173,7 +179,7 @@ public class PGtokenizer
*/ */
public void removeBox() public void removeBox()
{ {
remove("[","]"); remove("[", "]");
} }
/** /**
@@ -183,7 +189,7 @@ public class PGtokenizer
*/ */
public static String removeAngle(String s) public static String removeAngle(String s)
{ {
return remove(s,"<",">"); return remove(s, "<", ">");
} }
/** /**
@@ -192,6 +198,6 @@ public class PGtokenizer
*/ */
public void removeAngle() public void removeAngle()
{ {
remove("<",">"); remove("<", ">");
} }
} }

View File

@@ -14,9 +14,10 @@ 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);
} }
/** /**
@@ -24,21 +25,21 @@ public class PSQLException extends SQLException
* @param error Error string or standard message id * @param error Error string or standard message id
* @param args Array of arguments * @param args Array of arguments
*/ */
public PSQLException(String error,Object[] args) public PSQLException(String error, Object[] args)
{ {
//super(); //super();
translate(error,args); translate(error, args);
} }
/** /**
* Helper version for 1 arg * Helper version for 1 arg
*/ */
public PSQLException(String error,Object arg) public PSQLException(String error, Object arg)
{ {
super(); super();
Object[] argv = new Object[1]; Object[] argv = new Object[1];
argv[0] = arg; argv[0] = arg;
translate(error,argv); translate(error, argv);
} }
/** /**
@@ -46,43 +47,47 @@ public class PSQLException extends SQLException
* some unusual Exception's. It allows the originiating Exceptions stack * some unusual Exception's. It allows the originiating Exceptions stack
* trace to be returned. * trace to be returned.
*/ */
public PSQLException(String error,Exception ex) public PSQLException(String error, Exception ex)
{ {
super(); super();
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");
ex.printStackTrace(pw); ex.printStackTrace(pw);
pw.println("End of Stack Trace"); pw.println("End of Stack Trace");
pw.flush(); pw.flush();
argv[0] = baos.toString(); argv[0] = baos.toString();
pw.close(); pw.close();
baos.close(); baos.close();
} catch(Exception ioe) { }
argv[0] = ex.toString()+"\nIO Error on stack trace generation! "+ioe.toString(); catch (Exception ioe)
{
argv[0] = ex.toString() + "\nIO Error on stack trace generation! " + ioe.toString();
} }
translate(error,argv); translate(error, argv);
} }
/** /**
* Helper version for 2 args * Helper version for 2 args
*/ */
public PSQLException(String error,Object arg1,Object arg2) public PSQLException(String error, Object arg1, Object arg2)
{ {
super(); super();
Object[] argv = new Object[2]; Object[] argv = new Object[2];
argv[0] = arg1; argv[0] = arg1;
argv[1] = arg2; argv[1] = arg2;
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

@@ -123,33 +123,39 @@ public class Serialize
* This creates an instance that can be used to serialize or deserialize * This creates an instance that can be used to serialize or deserialize
* a Java object from a PostgreSQL table. * a Java object from a PostgreSQL table.
*/ */
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);
} }
// 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);
} }
// Finally cache the fields within the table // Finally cache the fields within the table
} }
@@ -157,7 +163,7 @@ public class Serialize
/** /**
* Constructor when Object is passed in * Constructor when Object is passed in
*/ */
public Serialize(org.postgresql.Connection c,Object o) throws SQLException public Serialize(org.postgresql.Connection c, Object o) throws SQLException
{ {
this(c, o.getClass().getName()); this(c, o.getClass().getName());
} }
@@ -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() );
@@ -189,21 +196,23 @@ public class Serialize
// used getFields to get only public fields. We have no way to set values // used getFields to get only public fields. We have no way to set values
// for other declarations. Maybe look for setFieldName() methods? // for other declarations. Maybe look for setFieldName() methods?
java.lang.reflect.Field f[] = ourClass.getFields(); java.lang.reflect.Field f[] = ourClass.getFields();
boolean hasOID=false; boolean hasOID = false;
int oidFIELD=-1; int oidFIELD = -1;
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; {
oidFIELD=i; hasOID = true;
oidFIELD = i;
} }
sb.append(sep); sb.append(sep);
sb.append(n); sb.append(n);
sep=','; sep = ',';
} }
sb.append(" from "); sb.append(" from ");
sb.append(tableName); sb.append(tableName);
@@ -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()) ) { {
if( f[i].getType().getName().equals("short") ) for (int i = 0;i < f.length;i++)
f[i].setShort(obj, rs.getShort(i+1)); {
else if( f[i].getType().getName().equals("char") ) if ( !Modifier.isFinal(f[i].getModifiers()) )
f[i].setChar(obj, rs.getString(i+1).toCharArray()[0]); {
else if( f[i].getType().getName().equals("byte")) if ( f[i].getType().getName().equals("short") )
f[i].setByte(obj, rs.getByte(i+1)); f[i].setShort(obj, rs.getShort(i + 1));
else if( f[i].getType().getName().equals("boolean") ) { else if ( f[i].getType().getName().equals("char") )
f[i].setChar(obj, rs.getString(i + 1).toCharArray()[0]);
else if ( f[i].getType().getName().equals("byte"))
f[i].setByte(obj, rs.getByte(i + 1));
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,74 +287,91 @@ 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
// don't save private fields since we would not be able to fetch them // don't save private fields since we would not be able to fetch them
java.lang.reflect.Field f[] = ourClass.getFields(); java.lang.reflect.Field f[] = ourClass.getFields();
boolean hasOID=false; boolean hasOID = false;
int oidFIELD=-1; int oidFIELD = -1;
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; {
oidFIELD=i; hasOID = true;
oidFIELD = i;
// Do update if oid != 0 // Do update if oid != 0
update = f[i].getInt(o) > 0; update = f[i].getInt(o) > 0;
} }
} }
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)
else if( sb.append("null");
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,25 +420,29 @@ 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());
s = buf.toString(); s = buf.toString();
} }
// 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());
s = buf.toString(); s = buf.toString();
@@ -406,9 +459,9 @@ public class Serialize
* @param o Object to base table on * @param o Object to base table on
* @exception SQLException on error * @exception SQLException on error
*/ */
public static void create(org.postgresql.Connection con,Object o) throws SQLException public static void create(org.postgresql.Connection con, Object o) throws SQLException
{ {
create(con,o.getClass()); create(con, o.getClass());
} }
/** /**
@@ -419,18 +472,20 @@ public class Serialize
* @param o Class to base table on * @param o Class to base table on
* @exception SQLException on error * @exception SQLException on error
*/ */
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 ;
} }
// else table not found, so create it // else table not found, so create it
@@ -439,30 +494,38 @@ public class Serialize
StringBuffer sb = new StringBuffer("create table "); StringBuffer sb = new StringBuffer("create table ");
sb.append(tableName); sb.append(tableName);
char sep='('; char sep = '(';
// 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));
} }
@@ -478,12 +541,12 @@ public class Serialize
// This is used to translate between Java primitives and PostgreSQL types. // This is used to translate between Java primitives and PostgreSQL types.
private static final String tp[][] = { private static final String tp[][] = {
// {"boolean", "int1"}, // {"boolean", "int1"},
{"boolean", "bool"}, {"boolean", "bool"},
{"double", "float8"}, {"double", "float8"},
{"float", "float4"}, {"float", "float4"},
{"int", "int4"}, {"int", "int4"},
// {"long", "int4"}, // {"long", "int4"},
{"long", "int8"}, {"long", "int8"},
{"short", "int2"}, {"short", "int2"},
{"java.lang.String", "text"}, {"java.lang.String", "text"},
@@ -511,7 +574,7 @@ public class Serialize
{ {
name = name.toLowerCase(); name = name.toLowerCase();
if(name.indexOf("_")>-1) if (name.indexOf("_") > -1)
throw new PSQLException("postgresql.serial.underscore"); throw new PSQLException("postgresql.serial.underscore");
// Postgres table names can only be 32 character long. // Postgres table names can only be 32 character long.
@@ -520,12 +583,13 @@ 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()));
} }
return name.replace('.','_'); return name.replace('.', '_');
} }
@@ -540,7 +604,7 @@ public class Serialize
public static String toClassName(String name) throws SQLException public static String toClassName(String name) throws SQLException
{ {
name = name.toLowerCase(); name = name.toLowerCase();
return name.replace('_','.'); return name.replace('_', '.');
} }
} }

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());
@@ -379,7 +378,7 @@ public class UnixCrypt extends Object
{ {
int value = (int)b; int value = (int)b;
return(value >= 0 ? value : value + 256); return (value >= 0 ? value : value + 256);
} }
private static int fourBytesToInt(byte b[], int offset) private static int fourBytesToInt(byte b[], int offset)
@@ -391,7 +390,7 @@ public class UnixCrypt extends Object
value |= (byteToUnsigned(b[offset++]) << 16); value |= (byteToUnsigned(b[offset++]) << 16);
value |= (byteToUnsigned(b[offset++]) << 24); value |= (byteToUnsigned(b[offset++]) << 24);
return(value); return (value);
} }
private static final void intToFourBytes(int iValue, byte b[], int offset) private static final void intToFourBytes(int iValue, byte b[], int offset)
@@ -421,7 +420,7 @@ public class UnixCrypt extends Object
t = ((a << (16 - n)) ^ a) & m; t = ((a << (16 - n)) ^ a) & m;
a = a ^ t ^ (t >>> (16 - n)); a = a ^ t ^ (t >>> (16 - n));
return(a); return (a);
} }
private static int [] des_set_key(byte key[]) private static int [] des_set_key(byte key[])
@@ -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));
@@ -455,9 +458,9 @@ public class UnixCrypt extends Object
int s, t; int s, t;
int j = 0; int j = 0;
for(int i = 0; i < ITERATIONS; i ++) for (int i = 0; i < ITERATIONS; i ++)
{ {
if(shifts2[i]) if (shifts2[i])
{ {
c = (c >>> 2) | (c << 26); c = (c >>> 2) | (c << 26);
d = (d >>> 2) | (d << 26); d = (d >>> 2) | (d << 26);
@@ -471,16 +474,16 @@ public class UnixCrypt extends Object
c &= 0x0fffffff; c &= 0x0fffffff;
d &= 0x0fffffff; d &= 0x0fffffff;
s = skb[0][ (c ) & 0x3f ]| s = skb[0][ (c ) & 0x3f ] |
skb[1][((c >>> 6) & 0x03) | ((c >>> 7) & 0x3c)]| skb[1][((c >>> 6) & 0x03) | ((c >>> 7) & 0x3c)] |
skb[2][((c >>> 13) & 0x0f) | ((c >>> 14) & 0x30)]| skb[2][((c >>> 13) & 0x0f) | ((c >>> 14) & 0x30)] |
skb[3][((c >>> 20) & 0x01) | ((c >>> 21) & 0x06) | skb[3][((c >>> 20) & 0x01) | ((c >>> 21) & 0x06) |
((c >>> 22) & 0x38)]; ((c >>> 22) & 0x38)];
t = skb[4][ (d ) & 0x3f ]| t = skb[4][ (d ) & 0x3f ] |
skb[5][((d >>> 7) & 0x03) | ((d >>> 8) & 0x3c)]| skb[5][((d >>> 7) & 0x03) | ((d >>> 8) & 0x3c)] |
skb[6][ (d >>>15) & 0x3f ]| skb[6][ (d >>> 15) & 0x3f ] |
skb[7][((d >>>21) & 0x0f) | ((d >>> 22) & 0x30)]; skb[7][((d >>> 21) & 0x0f) | ((d >>> 22) & 0x30)];
schedule[j++] = ((t << 16) | (s & 0x0000ffff)) & 0xffffffff; schedule[j++] = ((t << 16) | (s & 0x0000ffff)) & 0xffffffff;
s = ((s >>> 16) | (t & 0xffff0000)); s = ((s >>> 16) | (t & 0xffff0000));
@@ -488,7 +491,7 @@ public class UnixCrypt extends Object
s = (s << 4) | (s >>> 28); s = (s << 4) | (s >>> 28);
schedule[j++] = s & 0xffffffff; schedule[j++] = s & 0xffffffff;
} }
return(schedule); return (schedule);
} }
private static final int D_ENCRYPT private static final int D_ENCRYPT
@@ -514,7 +517,7 @@ public class UnixCrypt extends Object
SPtrans[4][(u >>> 16) & 0x3f] | SPtrans[4][(u >>> 16) & 0x3f] |
SPtrans[6][(u >>> 24) & 0x3f]; SPtrans[6][(u >>> 24) & 0x3f];
return(L); return (L);
} }
private static final int [] body(int schedule[], int Eswap0, int Eswap1) private static final int [] body(int schedule[], int Eswap0, int Eswap1)
@@ -523,9 +526,9 @@ public class UnixCrypt extends Object
int right = 0; int right = 0;
int t = 0; int t = 0;
for(int j = 0; j < 25; j ++) for (int j = 0; j < 25; j ++)
{ {
for(int i = 0; i < ITERATIONS * 2; i += 4) for (int i = 0; i < ITERATIONS * 2; i += 4)
{ {
left = D_ENCRYPT(left, right, i, Eswap0, Eswap1, schedule); left = D_ENCRYPT(left, right, i, Eswap0, Eswap1, schedule);
right = D_ENCRYPT(right, left, i + 2, Eswap0, Eswap1, schedule); right = D_ENCRYPT(right, left, i + 2, Eswap0, Eswap1, schedule);
@@ -546,25 +549,31 @@ 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);
} }
/** /**
@@ -579,7 +588,7 @@ public class UnixCrypt extends Object
*/ */
public static final String crypt(String salt, String original) public static final String crypt(String salt, String original)
{ {
while(salt.length() < 2) while (salt.length() < 2)
salt += "A"; salt += "A";
StringBuffer buffer = new StringBuffer(" "); StringBuffer buffer = new StringBuffer(" ");
@@ -595,10 +604,10 @@ public class UnixCrypt extends Object
byte key[] = new byte[8]; byte key[] = new byte[8];
for(int i = 0; i < key.length; i ++) for (int i = 0; i < key.length; i ++)
key[i] = (byte)0; key[i] = (byte)0;
for(int i = 0; i < key.length && i < original.length(); i ++) for (int i = 0; i < key.length && i < original.length(); i ++)
{ {
int iChar = (int)original.charAt(i); int iChar = (int)original.charAt(i);
@@ -614,18 +623,18 @@ public class UnixCrypt extends Object
intToFourBytes(out[1], b, 4); intToFourBytes(out[1], b, 4);
b[8] = 0; b[8] = 0;
for(int i = 2, y = 0, u = 0x80; i < 13; i ++) for (int i = 2, y = 0, u = 0x80; i < 13; i ++)
{ {
for(int j = 0, c = 0; j < 6; j ++) for (int j = 0, c = 0; j < 6; j ++)
{ {
c <<= 1; c <<= 1;
if(((int)b[y] & u) != 0) if (((int)b[y] & u) != 0)
c |= 1; c |= 1;
u >>>= 1; u >>>= 1;
if(u == 0) if (u == 0)
{ {
y++; y++;
u = 0x80; u = 0x80;
@@ -633,7 +642,7 @@ public class UnixCrypt extends Object
buffer.setCharAt(i, (char)cov_2char[c]); buffer.setCharAt(i, (char)cov_2char[c]);
} }
} }
return(buffer.toString()); return (buffer.toString());
} }
/** /**

View File

@@ -1,47 +1,47 @@
/** /**
* Redistribution and use of this software and associated documentation * Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided * ("Software"), with or without modification, are permitted provided
* that the following conditions are met: * that the following conditions are met:
* *
* 1. Redistributions of source code must retain copyright * 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a * statements and notices. Redistributions must also contain a
* copy of this document. * copy of this document.
* *
* 2. Redistributions in binary form must reproduce the * 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the * above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other * following disclaimer in the documentation and/or other
* materials provided with the distribution. * materials provided with the distribution.
* *
* 3. The name "Exolab" must not be used to endorse or promote * 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written * products derived from this Software without prior written
* permission of Exoffice Technologies. For written permission, * permission of Exoffice Technologies. For written permission,
* please contact info@exolab.org. * please contact info@exolab.org.
* *
* 4. Products derived from this Software may not be called "Exolab" * 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written * nor may "Exolab" appear in their names without prior written
* permission of Exoffice Technologies. Exolab is a registered * permission of Exoffice Technologies. Exolab is a registered
* trademark of Exoffice Technologies. * trademark of Exoffice Technologies.
* *
* 5. Due credit should be given to the Exolab Project * 5. Due credit should be given to the Exolab Project
* (http://www.exolab.org/). * (http://www.exolab.org/).
* *
* THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE. * OF THE POSSIBILITY OF SUCH DAMAGE.
* *
* 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 $
*/ */
package org.postgresql.xa; package org.postgresql.xa;
@@ -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;
} }
@@ -398,7 +464,7 @@ final class ClientConnection
throws SQLException throws SQLException
{ {
if ( _xaConn == null ) if ( _xaConn == null )
return; return ;
// Notify the XA connection that we are no longer going // Notify the XA connection that we are no longer going
// to be used. Whether the underlying connection is released, // to be used. Whether the underlying connection is released,
@@ -428,9 +494,9 @@ final class ClientConnection
*/ */
/* Deprecated: see XAConnection._clientId /* Deprecated: see XAConnection._clientId
void terminate() void terminate()
{ {
_xaConn = null; _xaConn = null;
} }
*/ */
@@ -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

@@ -1,47 +1,47 @@
/** /**
* Redistribution and use of this software and associated documentation * Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided * ("Software"), with or without modification, are permitted provided
* that the following conditions are met: * that the following conditions are met:
* *
* 1. Redistributions of source code must retain copyright * 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a * statements and notices. Redistributions must also contain a
* copy of this document. * copy of this document.
* *
* 2. Redistributions in binary form must reproduce the * 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the * above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other * following disclaimer in the documentation and/or other
* materials provided with the distribution. * materials provided with the distribution.
* *
* 3. The name "Exolab" must not be used to endorse or promote * 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written * products derived from this Software without prior written
* permission of Exoffice Technologies. For written permission, * permission of Exoffice Technologies. For written permission,
* please contact info@exolab.org. * please contact info@exolab.org.
* *
* 4. Products derived from this Software may not be called "Exolab" * 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written * nor may "Exolab" appear in their names without prior written
* permission of Exoffice Technologies. Exolab is a registered * permission of Exoffice Technologies. Exolab is a registered
* trademark of Exoffice Technologies. * trademark of Exoffice Technologies.
* *
* 5. Due credit should be given to the Exolab Project * 5. Due credit should be given to the Exolab Project
* (http://www.exolab.org/). * (http://www.exolab.org/).
* *
* THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE. * OF THE POSSIBILITY OF SUCH DAMAGE.
* *
* 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 $
*/ */
package org.postgresql.xa; package org.postgresql.xa;

View File

@@ -1,47 +1,47 @@
/** /**
* Redistribution and use of this software and associated documentation * Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided * ("Software"), with or without modification, are permitted provided
* that the following conditions are met: * that the following conditions are met:
* *
* 1. Redistributions of source code must retain copyright * 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a * statements and notices. Redistributions must also contain a
* copy of this document. * copy of this document.
* *
* 2. Redistributions in binary form must reproduce the * 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the * above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other * following disclaimer in the documentation and/or other
* materials provided with the distribution. * materials provided with the distribution.
* *
* 3. The name "Exolab" must not be used to endorse or promote * 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written * products derived from this Software without prior written
* permission of Exoffice Technologies. For written permission, * permission of Exoffice Technologies. For written permission,
* please contact info@exolab.org. * please contact info@exolab.org.
* *
* 4. Products derived from this Software may not be called "Exolab" * 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written * nor may "Exolab" appear in their names without prior written
* permission of Exoffice Technologies. Exolab is a registered * permission of Exoffice Technologies. Exolab is a registered
* trademark of Exoffice Technologies. * trademark of Exoffice Technologies.
* *
* 5. Due credit should be given to the Exolab Project * 5. Due credit should be given to the Exolab Project
* (http://www.exolab.org/). * (http://www.exolab.org/).
* *
* THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE. * OF THE POSSIBILITY OF SUCH DAMAGE.
* *
* 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 $
*/ */
package org.postgresql.xa; package org.postgresql.xa;

View File

@@ -1,47 +1,47 @@
/** /**
* Redistribution and use of this software and associated documentation * Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided * ("Software"), with or without modification, are permitted provided
* that the following conditions are met: * that the following conditions are met:
* *
* 1. Redistributions of source code must retain copyright * 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a * statements and notices. Redistributions must also contain a
* copy of this document. * copy of this document.
* *
* 2. Redistributions in binary form must reproduce the * 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the * above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other * following disclaimer in the documentation and/or other
* materials provided with the distribution. * materials provided with the distribution.
* *
* 3. The name "Exolab" must not be used to endorse or promote * 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written * products derived from this Software without prior written
* permission of Exoffice Technologies. For written permission, * permission of Exoffice Technologies. For written permission,
* please contact info@exolab.org. * please contact info@exolab.org.
* *
* 4. Products derived from this Software may not be called "Exolab" * 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written * nor may "Exolab" appear in their names without prior written
* permission of Exoffice Technologies. Exolab is a registered * permission of Exoffice Technologies. Exolab is a registered
* trademark of Exoffice Technologies. * trademark of Exoffice Technologies.
* *
* 5. Due credit should be given to the Exolab Project * 5. Due credit should be given to the Exolab Project
* (http://www.exolab.org/). * (http://www.exolab.org/).
* *
* THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE. * OF THE POSSIBILITY OF SUCH DAMAGE.
* *
* 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 $
*/ */
package org.postgresql.xa; package org.postgresql.xa;
@@ -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 );
} }
@@ -296,25 +310,31 @@ public final class XAConnectionImpl
// We have to expect being called by a ClientConnection that we // We have to expect being called by a ClientConnection that we
// no longer regard as valid. That's acceptable, we just ignore. // no longer regard as valid. That's acceptable, we just ignore.
if ( clientId != _clientId ) if ( clientId != _clientId )
return; return ;
// If we are handling an underlying connection, we commit the // If we are handling an underlying connection, we commit the
// 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 );
} }
return; return ;
} }
} }
// 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 );
} }
@@ -335,19 +355,20 @@ public final class XAConnectionImpl
ConnectionEvent event; ConnectionEvent event;
if ( clientId != _clientId ) if ( clientId != _clientId )
return; return ;
// 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 ;
if ( _txConn.conn == null || if ( _txConn.conn == null ||
! ( _txConn.conn instanceof TwoPhaseConnection ) || ! ( _txConn.conn instanceof TwoPhaseConnection ) ||
! ( (TwoPhaseConnection) _txConn.conn ).isCriticalError( except ) ) ! ( (TwoPhaseConnection) _txConn.conn ).isCriticalError( except ) )
return; return ;
} }
// The client connection is no longer useable, the underlying // The client connection is no longer useable, the underlying
@@ -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 );
@@ -685,29 +766,38 @@ public final class XAConnectionImpl
// If connection has been prepared and is read-only, // If connection has been prepared and is read-only,
// nothing to do at this stage. // nothing to do at this stage.
if ( txConn.readOnly ) if ( txConn.readOnly )
return; return ;
// 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 );
@@ -738,24 +829,32 @@ public final class XAConnectionImpl
// been terminated any other way, nothing to do // been terminated any other way, nothing to do
// either. // either.
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

@@ -1,47 +1,47 @@
/** /**
* Redistribution and use of this software and associated documentation * Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided * ("Software"), with or without modification, are permitted provided
* that the following conditions are met: * that the following conditions are met:
* *
* 1. Redistributions of source code must retain copyright * 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a * statements and notices. Redistributions must also contain a
* copy of this document. * copy of this document.
* *
* 2. Redistributions in binary form must reproduce the * 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the * above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other * following disclaimer in the documentation and/or other
* materials provided with the distribution. * materials provided with the distribution.
* *
* 3. The name "Exolab" must not be used to endorse or promote * 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written * products derived from this Software without prior written
* permission of Exoffice Technologies. For written permission, * permission of Exoffice Technologies. For written permission,
* please contact info@exolab.org. * please contact info@exolab.org.
* *
* 4. Products derived from this Software may not be called "Exolab" * 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written * nor may "Exolab" appear in their names without prior written
* permission of Exoffice Technologies. Exolab is a registered * permission of Exoffice Technologies. Exolab is a registered
* trademark of Exoffice Technologies. * trademark of Exoffice Technologies.
* *
* 5. Due credit should be given to the Exolab Project * 5. Due credit should be given to the Exolab Project
* (http://www.exolab.org/). * (http://www.exolab.org/).
* *
* THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE. * OF THE POSSIBILITY OF SUCH DAMAGE.
* *
* 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 $
*/ */
package org.postgresql.xa; package org.postgresql.xa;
@@ -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;
@@ -41,28 +45,30 @@ public class CheckVersion
{ {
String vmversion = System.getProperty("java.vm.version"); String vmversion = System.getProperty("java.vm.version");
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);
} }
else else
// We are running a 1.2 or 1.3 JVM // We are running a 1.2 or 1.3 JVM
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.
if(checkClass("javax.sql.DataSource")) if (checkClass("javax.sql.DataSource"))
System.out.println("enterprise"); System.out.println("enterprise");
else else
System.out.println("jdbc2"); System.out.println("jdbc2");
//System.exit(0); //System.exit(0);
} }
System.setProperty("postgresql.jdbc","yoyo"); System.setProperty("postgresql.jdbc", "yoyo");
} }
} }