1
0
mirror of https://github.com/postgres/postgres.git synced 2025-07-31 22:04:40 +03:00

pgjindent jdbc files. First time jdbc files were formatted.

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

View File

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

View File

@ -19,7 +19,8 @@ import java.util.*;
*
* @author William Webber <william@live.com.au>
*/
public class Unicode {
public class Unicode
{
/**
* The url for the database to connect to.
@ -36,21 +37,25 @@ public class Unicode {
*/
private String password;
private static void usage() {
private static void usage()
{
log("usage: example.Unicode <url> <user> <password>");
}
private static void log(String message) {
private static void log(String 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);
e.printStackTrace();
}
public Unicode(String url, String user, String password) {
public Unicode(String url, String user, String password)
{
this.url = url;
this.user = user;
this.password = password;
@ -60,7 +65,8 @@ public class Unicode {
* Establish and return a connection to the database.
*/
private Connection getConnection() throws SQLException,
ClassNotFoundException {
ClassNotFoundException
{
Class.forName("org.postgresql.Driver");
Properties info = new Properties();
info.put("user", user);
@ -73,14 +79,16 @@ public class Unicode {
* Get string representing a block of 256 consecutive unicode characters.
* We exclude the null character, "'", and "\".
*/
private String getSqlSafeUnicodeBlock(int blockNum) {
private String getSqlSafeUnicodeBlock(int blockNum)
{
if (blockNum < 0 || blockNum > 255)
throw new IllegalArgumentException("blockNum must be from 0 to "
+ "255: " + blockNum);
StringBuffer sb = new StringBuffer(256);
int blockFirst = blockNum * 256;
int blockLast = blockFirst + 256;
for (int i = blockFirst; i < blockLast; i++) {
for (int i = blockFirst; i < blockLast; i++)
{
char c = (char) i;
if (c == '\0' || c == '\'' || c == '\\')
continue;
@ -96,7 +104,8 @@ public class Unicode {
* These should not be used in actual Unicode strings;
* 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)
return false;
else
@ -107,14 +116,19 @@ public class Unicode {
* Report incorrect block retrieval.
*/
private void reportRetrievalError(int blockNum, String block,
String retrieved) {
String retrieved)
{
String message = "Block " + blockNum + " returned incorrectly: ";
int i = 0;
for (i = 0; i < block.length(); i++) {
if (i >= retrieved.length()) {
for (i = 0; i < block.length(); i++)
{
if (i >= retrieved.length())
{
message += "too short";
break;
} else if (retrieved.charAt(i) != block.charAt(i)) {
}
else if (retrieved.charAt(i) != block.charAt(i))
{
message +=
"first changed character at position " + i + ", sent as 0x"
+ Integer.toHexString((int) block.charAt(i))
@ -131,7 +145,8 @@ public class Unicode {
/**
* Do the testing.
*/
public void runTest() {
public void runTest()
{
Connection connection = null;
Statement statement = null;
int blockNum = 0;
@ -140,15 +155,18 @@ public class Unicode {
final int SELECT = 2;
final int LIKE = 3;
int mode = CREATE;
try {
try
{
connection = getConnection();
statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE test_unicode "
+ "( blockNum INT PRIMARY KEY, "
+ "block TEXT );");
mode = INSERT;
for (blockNum = 0; blockNum < 256; blockNum++) {
if (isValidUnicodeBlock(blockNum)) {
for (blockNum = 0; blockNum < 256; blockNum++)
{
if (isValidUnicodeBlock(blockNum))
{
String block = getSqlSafeUnicodeBlock(blockNum);
statement.executeUpdate
("INSERT INTO test_unicode VALUES ( " + blockNum
@ -156,25 +174,31 @@ public class Unicode {
}
}
mode = SELECT;
for (blockNum = 0; blockNum < 256; blockNum++) {
if (isValidUnicodeBlock(blockNum)) {
for (blockNum = 0; blockNum < 256; blockNum++)
{
if (isValidUnicodeBlock(blockNum))
{
String block = getSqlSafeUnicodeBlock(blockNum);
ResultSet rs = statement.executeQuery
("SELECT block FROM test_unicode WHERE blockNum = "
+ blockNum + ";");
if (!rs.next())
log("Could not retrieve block " + blockNum);
else {
else
{
String retrieved = rs.getString(1);
if (!retrieved.equals(block)) {
if (!retrieved.equals(block))
{
reportRetrievalError(blockNum, block, retrieved);
}
}
}
}
mode = LIKE;
for (blockNum = 0; blockNum < 256; blockNum++) {
if (isValidUnicodeBlock(blockNum)) {
for (blockNum = 0; blockNum < 256; blockNum++)
{
if (isValidUnicodeBlock(blockNum))
{
String block = getSqlSafeUnicodeBlock(blockNum);
String likeString = "%" +
block.substring(2, block.length() - 3) + "%" ;
@ -185,8 +209,11 @@ public class Unicode {
log("Could get block " + blockNum + " using LIKE");
}
}
} catch (SQLException sqle) {
switch (mode) {
}
catch (SQLException sqle)
{
switch (mode)
{
case CREATE:
log("Exception creating database", sqle);
break;
@ -203,35 +230,46 @@ public class Unicode {
log("Exception", sqle);
break;
}
} catch (ClassNotFoundException cnfe) {
}
catch (ClassNotFoundException cnfe)
{
log("Unable to load driver", cnfe);
return ;
}
try {
try
{
if (statement != null)
statement.close();
if (connection != null)
connection.close();
} catch (SQLException sqle) {
}
catch (SQLException sqle)
{
log("Exception closing connections", sqle);
}
if (mode > CREATE) {
if (mode > CREATE)
{
// If the backend gets what it regards as garbage on a connection,
// that connection may become unusable. To be safe, we create
// a fresh connection to delete the table.
try {
try
{
connection = getConnection();
statement = connection.createStatement();
statement.executeUpdate("DROP TABLE test_unicode;");
} catch (Exception sqle) {
}
catch (Exception sqle)
{
log("*** ERROR: unable to delete test table "
+ "test_unicode; must be deleted manually", sqle);
}
}
}
public static void main(String [] args) {
if (args.length != 3) {
public static void main(String [] args)
{
if (args.length != 3)
{
usage();
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
* how even the simplest of queries can be implemented.
@ -61,9 +61,12 @@ public class basic
*/
public void cleanup()
{
try {
try
{
st.executeUpdate("drop table basic");
} catch(Exception ex) {
}
catch (Exception ex)
{
// We ignore any errors here
}
}
@ -107,7 +110,8 @@ public class basic
// manner. (DateStyles are PostgreSQL's way of handling different methods
// of representing dates in the Date data type.)
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.executeUpdate(); // executeUpdate because insert returns no data
@ -117,10 +121,12 @@ public class basic
// Finally perform a query on the table
System.out.println("performing a query");
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.
// 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 b = rs.getInt(2); // This shows how to get the value by column
System.out.println(" a=" + a + " b=" + b);
@ -130,9 +136,11 @@ public class basic
// Now run the query again, showing a more efficient way of getting the
// result if you don't know what column number a value is in
System.out.println("performing another query");
rs = st.executeQuery("select * from basic where b>1");
if(rs!=null) {
if (rs != null)
{
// First find out the column numbers.
//
// It's best to do this here, as calling the methods with the column
@ -144,7 +152,8 @@ public class basic
// Now we run through the result set, printing out the result.
// 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 b = rs.getInt(col_b); // This shows how to get the value by column
System.out.println(" a=" + a + " b=" + b);
@ -153,10 +162,12 @@ public class basic
}
// Now test maxrows by setting it to 3 rows
st.setMaxRows(3);
System.out.println("performing a query limited to " + st.getMaxRows());
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 b = rs.getInt(2); // This shows how to get the value by column
System.out.println(" a=" + a + " b=" + b);
@ -193,9 +204,12 @@ public class basic
DriverManager.setLogStream(System.err);
// Now run the tests
try {
try
{
basic test = new basic(args);
} catch(Exception ex) {
}
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace();
}

View File

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

View File

@ -9,7 +9,7 @@ import org.omg.CosNaming.*;
*
* 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
{
@ -20,8 +20,10 @@ public class StockClient
BufferedReader in;
public StockClient(String[] args) {
try {
public StockClient(String[] args)
{
try
{
// We need this for our IO
in = new BufferedReader(new InputStreamReader(System.in));
@ -30,13 +32,15 @@ public class StockClient
// Get a reference to the Naming Service
org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService");
if(nameServiceObj==null) {
if (nameServiceObj == null)
{
System.err.println("nameServiceObj == null");
return ;
}
nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj);
if(nameService==null) {
if (nameService == null)
{
System.err.println("nameService == null");
return ;
}
@ -46,29 +50,37 @@ public class StockClient
new NameComponent("StockDispenser", "Stock")
};
dispenser = stock.StockDispenserHelper.narrow(nameService.resolve(dispName));
if(dispenser==null) {
if (dispenser == null)
{
System.err.println("dispenser == null");
return ;
}
// Now run the front end.
run();
} catch(Exception e) {
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
public static void main(String[] args)
{
new StockClient(args);
}
public void run() {
public void run()
{
// First reserve a StockItem
try {
try
{
item = dispenser.reserveItem();
} catch(Exception e) {
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
System.exit(1);
@ -77,18 +89,23 @@ public class StockClient
mainMenu();
// finally free the StockItem
try {
try
{
dispenser.releaseItem(item);
} catch(Exception e) {
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
System.exit(1);
}
}
private void mainMenu() {
private void mainMenu()
{
boolean run = true;
while(run) {
while (run)
{
System.out.println("\nCORBA Stock System\n");
System.out.println(" 1 Display stock item");
System.out.println(" 2 Remove item from stock");
@ -126,10 +143,13 @@ public class StockClient
}
}
private void displayItem() {
try {
private void displayItem()
{
try
{
int id = getMenu("\nStockID to display", item.getLastID());
if(id>0) {
if (id > 0)
{
item.fetchItem(id);
System.out.println("========================================");
@ -146,7 +166,8 @@ public class StockClient
System.out.println("========================================");
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)
rem = getMenu("How many?", av);
@ -155,70 +176,91 @@ public class StockClient
}
}
} catch(Exception e) {
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
private void bookOut() {
try {
private void bookOut()
{
try
{
int id = getMenu("\nStockID to take out", item.getLastID());
if(id>0) {
if (id > 0)
{
item.fetchItem(id);
int av = item.getAvailable();
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)
rem = getMenu("How many?", av);
if (rem > 0)
item.removeStock(rem);
}
else {
else
{
System.out.println("This item is not in stock.");
int order = item.getOrdered();
if (order > 0)
System.out.println("There are " + item.getOrdered() + " items on order.");
else {
if(item.isItemValid()) {
else
{
if (item.isItemValid())
{
System.out.println("You will need to order some more " + item.getDescription());
order(id);
} else
}
else
System.out.println("This item is now obsolete");
}
}
} else
}
else
System.out.println(item.getDescription() + "\nThis item is out of stock");
} catch(Exception e) {
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
// book an item into stock
private void bookIn() {
try {
private void bookIn()
{
try
{
int id = getMenu("\nStockID to book in", item.getLastID());
item.fetchItem(id);
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)
item.addNewStock(am);
} else
}
else
System.out.println("You don't have any of this item on ordered");
} catch(Exception e) {
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
// Order an item
private void order(int id) {
try {
private void order(int id)
{
try
{
if (id == 0)
id = getMenu("\nStockID to order", item.getLastID());
item.fetchItem(id);
@ -226,50 +268,66 @@ public class StockClient
int am = getMenu("How many do you want to order", 999);
if (am > 0)
item.orderStock(am);
} catch(Exception e) {
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
private void displayAll() {
try {
private void displayAll()
{
try
{
boolean cont = true;
int nr = item.getLastID();
String header = "\nId\tAvail\tOrdered\tDescription";
System.out.println(header);
for(int i=1;i<=nr && cont;i++) {
for (int i = 1;i <= nr && cont;i++)
{
item.fetchItem(i);
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?")))
System.out.println(header);
}
}
} catch(Exception e) {
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
private int getMenu(String title,int max) {
private int getMenu(String title, int max)
{
int v = -1;
while(v<0 || v>max) {
while (v < 0 || v > max)
{
System.out.print(title);
System.out.print(" [0-" + max + "]: ");
System.out.flush();
try {
try
{
v = Integer.parseInt(in.readLine());
} catch(Exception nfe) {
}
catch (Exception nfe)
{
v = -1;
}
}
return v;
}
private boolean yn(String title) {
try {
while(true) {
private boolean yn(String title)
{
try
{
while (true)
{
System.out.print(title);
System.out.flush();
String s = in.readLine();
@ -278,7 +336,9 @@ public class StockClient
if (s.startsWith("n") || s.startsWith("N"))
return false;
}
} catch(Exception nfe) {
}
catch (Exception nfe)
{
System.out.println(nfe.toString());
nfe.printStackTrace();
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
* 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
{
@ -23,29 +23,35 @@ public class StockDB
// the current stock number
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");
System.out.println("Connecting to " + url);
con = DriverManager.getConnection(url, usr, pwd);
st = con.createStatement();
}
public void closeConnection() throws Exception {
public void closeConnection() throws Exception
{
con.close();
}
public void fetchItem(int id) throws Exception {
public void fetchItem(int id) throws Exception
{
this.id = id;
}
public int newItem() throws Exception {
public int newItem() throws Exception
{
// tba
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) {
if (rs != null)
{
rs.next();
String s = rs.getString(1);
rs.close();
@ -54,9 +60,11 @@ public class StockDB
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) {
if (rs != null)
{
rs.next();
int v = rs.getInt(1);
rs.close();
@ -65,9 +73,11 @@ public class StockDB
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) {
if (rs != null)
{
rs.next();
int v = rs.getInt(1);
rs.close();
@ -76,9 +86,11 @@ public class StockDB
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) {
if (rs != null)
{
rs.next();
boolean b = rs.getBoolean(1);
rs.close();
@ -87,25 +99,30 @@ public class StockDB
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 +
" 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);
}
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);
}
public int getLastID() throws SQLException {
public int getLastID() throws SQLException
{
ResultSet rs = st.executeQuery("select max(id) from stock");
if(rs!=null) {
if (rs != null)
{
rs.next();
int v = rs.getInt(1);
rs.close();

View File

@ -5,7 +5,7 @@ import org.omg.CosNaming.*;
/**
* 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
{
@ -17,7 +17,8 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
{
super();
try {
try
{
// get reference to orb
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
@ -25,12 +26,15 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
if (num >= maxObjects)
num = maxObjects;
numObjects = num;
for(int i=0;i<numObjects;i++) {
for (int i = 0;i < numObjects;i++)
{
stock[i] = new StockItemStatus();
stock[i].ref = new StockItemImpl(args, "StockItem" + (i + 1));
orb.connect(stock[i].ref);
}
} catch(org.omg.CORBA.SystemException e) {
}
catch (org.omg.CORBA.SystemException e)
{
e.printStackTrace();
}
}
@ -40,8 +44,10 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
*/
public stock.StockItem reserveItem() throws stock.StockException
{
for(int i=0;i<numObjects;i++) {
if(!stock[i].inUse) {
for (int i = 0;i < numObjects;i++)
{
if (!stock[i].inUse)
{
stock[i].inUse = true;
System.out.println("Reserving slot " + i);
return stock[i].ref;
@ -55,8 +61,10 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
*/
public void releaseItem(stock.StockItem item) throws stock.StockException
{
for(int i=0;i<numObjects;i++) {
if(stock[i].ref.getInstanceName().equals(item.getInstanceName())) {
for (int i = 0;i < numObjects;i++)
{
if (stock[i].ref.getInstanceName().equals(item.getInstanceName()))
{
stock[i].inUse = false;
System.out.println("Releasing slot " + i);
return ;
@ -74,7 +82,8 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
StockItemImpl ref;
boolean inUse;
StockItemStatus() {
StockItemStatus()
{
ref = null;
inUse = false;
}

View File

@ -5,21 +5,25 @@ import org.omg.CosNaming.*;
/**
* 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
{
private StockDB db;
private String instanceName;
public StockItemImpl(String[] args,String iname) {
public StockItemImpl(String[] args, String iname)
{
super();
try {
try
{
db = new StockDB();
db.connect(args[1], args[2], args[3]);
System.out.println("StockDB object " + iname + " created");
instanceName = iname;
} catch(Exception e) {
}
catch (Exception e)
{
e.printStackTrace();
}
}
@ -29,10 +33,14 @@ public class StockItemImpl extends stock._StockItemImplBase
*
* It sets the item to view
*/
public void fetchItem(int id) throws stock.StockException {
try {
public void fetchItem(int id) throws stock.StockException
{
try
{
db.fetchItem(id);
} catch(Exception e) {
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
@ -43,10 +51,14 @@ public class StockItemImpl extends stock._StockItemImplBase
*
* It sets the item to view
*/
public int newItem() throws stock.StockException {
try {
public int newItem() throws stock.StockException
{
try
{
return db.newItem();
} catch(Exception e) {
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
@ -56,10 +68,14 @@ public class StockItemImpl extends stock._StockItemImplBase
*
* It returns the description of a Stock item
*/
public String getDescription() throws stock.StockException {
try {
public String getDescription() throws stock.StockException
{
try
{
return db.getDescription();
} catch(Exception e) {
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
@ -69,10 +85,14 @@ public class StockItemImpl extends stock._StockItemImplBase
*
* It returns the description of a Stock item
*/
public int getAvailable() throws stock.StockException {
try {
public int getAvailable() throws stock.StockException
{
try
{
return db.getAvailable();
} catch(Exception e) {
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
@ -82,10 +102,14 @@ public class StockItemImpl extends stock._StockItemImplBase
*
* It returns the description of a Stock item
*/
public int getOrdered() throws stock.StockException {
try {
public int getOrdered() throws stock.StockException
{
try
{
return db.getOrdered();
} catch(Exception e) {
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
@ -95,10 +119,14 @@ public class StockItemImpl extends stock._StockItemImplBase
*
* It returns the description of a Stock item
*/
public boolean isItemValid() throws stock.StockException {
try {
public boolean isItemValid() throws stock.StockException
{
try
{
return db.isItemValid();
} catch(Exception e) {
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
@ -108,10 +136,14 @@ public class StockItemImpl extends stock._StockItemImplBase
*
* It returns the description of a Stock item
*/
public void addNewStock(int id) throws stock.StockException {
try {
public void addNewStock(int id) throws stock.StockException
{
try
{
db.addNewStock(id);
} catch(Exception e) {
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
@ -121,10 +153,14 @@ public class StockItemImpl extends stock._StockItemImplBase
*
* It returns the description of a Stock item
*/
public void removeStock(int id) throws stock.StockException {
try {
public void removeStock(int id) throws stock.StockException
{
try
{
db.removeStock(id);
} catch(Exception e) {
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
@ -134,10 +170,14 @@ public class StockItemImpl extends stock._StockItemImplBase
*
* It returns the description of a Stock item
*/
public void orderStock(int id) throws stock.StockException {
try {
public void orderStock(int id) throws stock.StockException
{
try
{
db.orderStock(id);
} catch(Exception e) {
}
catch (Exception e)
{
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
*/
public int getLastID() throws stock.StockException {
try {
public int getLastID() throws stock.StockException
{
try
{
return db.getLastID();
} catch(Exception e) {
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
@ -156,7 +200,8 @@ public class StockItemImpl extends stock._StockItemImplBase
/**
* This is used by our Dispenser
*/
public String getInstanceName() {
public String getInstanceName()
{
return instanceName;
}
}

View File

@ -5,7 +5,7 @@ import org.omg.CosNaming.*;
/**
* 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
{
@ -13,7 +13,8 @@ public class StockServer
{
int numInstances = 3;
try {
try
{
// Initialise the ORB
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
@ -25,13 +26,15 @@ public class StockServer
// Get the naming service
org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService");
if(nameServiceObj == null) {
if (nameServiceObj == null)
{
System.err.println("nameServiceObj = null");
return ;
}
org.omg.CosNaming.NamingContext nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj);
if(nameService == null) {
if (nameService == null)
{
System.err.println("nameService = null");
return ;
}
@ -44,7 +47,9 @@ public class StockServer
// Now wait forever for the current thread to die
Thread.currentThread().join();
} catch(Exception e) {
}
catch (Exception e)
{
e.printStackTrace();
}
}

View File

@ -69,9 +69,12 @@ public class datestyle
*/
public void cleanup()
{
try {
try
{
st.executeUpdate("drop table datestyle");
} catch(Exception ex) {
}
catch (Exception ex)
{
// We ignore any errors here
}
}
@ -112,7 +115,8 @@ public class datestyle
{
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.flush();
@ -132,7 +136,8 @@ public class datestyle
if (rs == null)
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.
// In the current implementation of the driver, this is not necessary.
// Here we use this fact to see what the query really returned.
@ -171,9 +176,12 @@ public class datestyle
DriverManager.setLogStream(System.err);
// Now run the tests
try {
try
{
datestyle test = new datestyle(args);
} catch(Exception ex) {
}
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace();
}

View File

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

View File

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

View File

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

View File

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

View File

@ -10,7 +10,7 @@ import org.postgresql.core.*;
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
* backend.
@ -139,8 +139,11 @@ public class PG_Stream
try
{
c = pg_input.read();
if (c < 0) throw new PSQLException("postgresql.stream.eof");
} catch (IOException e) {
if (c < 0)
throw new PSQLException("postgresql.stream.eof");
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
}
return c;
@ -167,7 +170,9 @@ public class PG_Stream
throw new PSQLException("postgresql.stream.eof");
n = n | (b << (8 * i)) ;
}
} catch (IOException e) {
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
}
return n;
@ -194,7 +199,9 @@ public class PG_Stream
throw new PSQLException("postgresql.stream.eof");
n = b | (n << 8);
}
} catch (IOException e) {
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
}
return n;
@ -213,22 +220,29 @@ public class PG_Stream
{
int s = 0;
byte[] rst = byte_buf;
try {
try
{
int buflen = rst.length;
boolean done = false;
while (!done) {
while (s < buflen) {
while (!done)
{
while (s < buflen)
{
int c = pg_input.read();
if (c < 0)
throw new PSQLException("postgresql.stream.eof");
else if (c == 0) {
else if (c == 0)
{
rst[s] = 0;
done = true;
break;
} else {
}
else
{
rst[s++] = (byte)c;
}
if (s >= buflen) { // Grow the buffer
if (s >= buflen)
{ // Grow the buffer
buflen = (int)(buflen * 2); // 100% bigger
byte[] newrst = new byte[buflen];
System.arraycopy(rst, 0, newrst, 0, s);
@ -236,7 +250,9 @@ public class PG_Stream
}
}
}
} catch (IOException e) {
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
}
return encoding.decode(rst, 0, s);
@ -320,7 +336,9 @@ public class PG_Stream
throw new PSQLException("postgresql.stream.eof");
s += w;
}
} catch (IOException e) {
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
}
}
@ -332,9 +350,12 @@ public class PG_Stream
*/
public void flush() throws SQLException
{
try {
try
{
pg_output.flush();
} catch (IOException e) {
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.flush", e);
}
}

View File

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

View File

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

View File

@ -23,7 +23,8 @@ import org.postgresql.util.PSQLException;
* JDBC3.
*/
public abstract class Statement {
public abstract class Statement
{
/** The warnings chain. */
protected SQLWarning warnings = null;
@ -45,8 +46,8 @@ public abstract class Statement {
private static final short BACKSLASH = 2;
private static final short ESC_TIMEDATE = 3;
public Statement() {
}
public Statement()
{}
/**
* Returns the status message from the current Result.<p>
@ -54,7 +55,8 @@ public abstract class Statement {
*
* @return status message from backend
*/
public String getResultStatusString() {
public String getResultStatusString()
{
if (result == null)
return null;
return ((org.postgresql.ResultSet) result).getStatusString();
@ -68,7 +70,8 @@ public abstract class Statement {
* @return the current maximum row limit; zero means unlimited
* @exception SQLException if a database access error occurs
*/
public int getMaxRows() throws SQLException {
public int getMaxRows() throws SQLException
{
return maxrows;
}
@ -79,7 +82,8 @@ public abstract class Statement {
* @exception SQLException if a database access error occurs
* @see getMaxRows
*/
public void setMaxRows(int max) throws SQLException {
public void setMaxRows(int max) throws SQLException
{
maxrows = max;
}
@ -90,7 +94,8 @@ public abstract class Statement {
* @param enable true to enable; false to disable
* @exception SQLException if a database access error occurs
*/
public void setEscapeProcessing(boolean enable) throws SQLException {
public void setEscapeProcessing(boolean enable) throws SQLException
{
escapeProcessing = enable;
}
@ -102,7 +107,8 @@ public abstract class Statement {
* @return the current query timeout limit in seconds; 0 = unlimited
* @exception SQLException if a database access error occurs
*/
public int getQueryTimeout() throws SQLException {
public int getQueryTimeout() throws SQLException
{
return timeout;
}
@ -112,7 +118,8 @@ public abstract class Statement {
* @param seconds - the new query timeout limit in seconds
* @exception SQLException if a database access error occurs
*/
public void setQueryTimeout(int seconds) throws SQLException {
public void setQueryTimeout(int seconds) throws SQLException
{
timeout = seconds;
}
@ -132,7 +139,8 @@ public abstract class Statement {
* @return the first SQLWarning on null
* @exception SQLException if a database access error occurs
*/
public SQLWarning getWarnings() throws SQLException {
public SQLWarning getWarnings() throws SQLException
{
return warnings;
}
@ -146,7 +154,8 @@ public abstract class Statement {
* @return the current max column size limit; zero means unlimited
* @exception SQLException if a database access error occurs
*/
public int getMaxFieldSize() throws SQLException {
public int getMaxFieldSize() throws SQLException
{
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
* @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");
}
@ -167,7 +177,8 @@ public abstract class Statement {
*
* @exception SQLException if a database access error occurs
*/
public void clearWarnings() throws SQLException {
public void clearWarnings() throws SQLException
{
warnings = null;
}
@ -179,7 +190,8 @@ public abstract class Statement {
*
* @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!
}
@ -189,7 +201,8 @@ public abstract class Statement {
* null.
* @return OID of last insert
*/
public int getInsertedOID() throws SQLException {
public int getInsertedOID() throws SQLException
{
if (result == null)
return 0;
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
* @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())
return result;
return null;
@ -220,7 +234,8 @@ public abstract class Statement {
*
* @exception SQLException if a database access error occurs (why?)
*/
public void close() throws SQLException {
public void close() throws SQLException
{
// Force the ResultSet to close
java.sql.ResultSet rs = getResultSet();
if (rs != null)

View File

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

View File

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

View File

@ -8,10 +8,11 @@ import org.postgresql.util.*;
/**
* 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);
@ -59,7 +60,8 @@ public class Encoding {
private final String encoding;
private Encoding(String encoding) {
private Encoding(String encoding)
{
this.encoding = encoding;
}
@ -70,13 +72,19 @@ public class Encoding {
public static Encoding getEncoding(String databaseEncoding,
String passedEncoding)
{
if (passedEncoding != null) {
if (isAvailable(passedEncoding)) {
if (passedEncoding != null)
{
if (isAvailable(passedEncoding))
{
return new Encoding(passedEncoding);
} else {
}
else
{
return defaultEncoding();
}
} else {
}
else
{
return encodingForDatabaseEncoding(databaseEncoding);
}
}
@ -84,15 +92,19 @@ public class 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
// encoding in the JVM we use that. Otherwise we fall back
// to the default encoding of the JVM.
if (encodings.containsKey(databaseEncoding)) {
if (encodings.containsKey(databaseEncoding))
{
String[] candidates = (String[]) encodings.get(databaseEncoding);
for (int i = 0; i < candidates.length; i++) {
if (isAvailable(candidates[i])) {
for (int i = 0; i < candidates.length; i++)
{
if (isAvailable(candidates[i]))
{
return new Encoding(candidates[i]);
}
}
@ -103,21 +115,29 @@ public class Encoding {
/**
* Name of the (JVM) encoding used.
*/
public String name() {
public String name()
{
return encoding;
}
/**
* Encode a string to an array of bytes.
*/
public byte[] encode(String s) throws SQLException {
try {
if (encoding == null) {
public byte[] encode(String s) throws SQLException
{
try
{
if (encoding == null)
{
return s.getBytes();
} else {
}
else
{
return s.getBytes(encoding);
}
} catch (UnsupportedEncodingException e) {
}
catch (UnsupportedEncodingException e)
{
throw new PSQLException("postgresql.stream.encoding", e);
}
}
@ -125,14 +145,21 @@ public class Encoding {
/**
* Decode an array of bytes into a string.
*/
public String decode(byte[] encodedString, int offset, int length) throws SQLException {
try {
if (encoding == null) {
public String decode(byte[] encodedString, int offset, int length) throws SQLException
{
try
{
if (encoding == null)
{
return new String(encodedString, offset, length);
} else {
}
else
{
return new String(encodedString, offset, length, encoding);
}
} catch (UnsupportedEncodingException e) {
}
catch (UnsupportedEncodingException e)
{
throw new PSQLException("postgresql.stream.encoding", e);
}
}
@ -140,21 +167,29 @@ public class Encoding {
/**
* 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);
}
/**
* Get a Reader that decodes the given InputStream.
*/
public Reader getDecodingReader(InputStream in) throws SQLException {
try {
if (encoding == null) {
public Reader getDecodingReader(InputStream in) throws SQLException
{
try
{
if (encoding == null)
{
return new InputStreamReader(in);
} else {
}
else
{
return new InputStreamReader(in, encoding);
}
} catch (UnsupportedEncodingException e) {
}
catch (UnsupportedEncodingException 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.
*/
public static Encoding defaultEncoding() {
public static Encoding defaultEncoding()
{
return DEFAULT_ENCODING;
}
/**
* Test if an encoding is available in the JVM.
*/
private static boolean isAvailable(String encodingName) {
try {
private static boolean isAvailable(String encodingName)
{
try
{
"DUMMY".getBytes(encodingName);
return true;
} catch (UnsupportedEncodingException e) {
}
catch (UnsupportedEncodingException e)
{
return false;
}
}

View File

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

View File

@ -6,7 +6,8 @@ package org.postgresql.core;
* other for jdk1.2+
*/
public interface ObjectPool {
public interface ObjectPool
{
/**
* Adds an object to the pool
* @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
* 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 java.sql.Statement statement;
@ -51,16 +52,19 @@ public class QueryExecutor {
/**
* Execute a query on the backend.
*/
public java.sql.ResultSet execute() throws SQLException {
public java.sql.ResultSet execute() throws SQLException
{
int fqp = 0;
boolean hfr = false;
synchronized(pg_stream) {
synchronized (pg_stream)
{
sendQuery(sql);
while (!hfr || fqp > 0) {
while (!hfr || fqp > 0)
{
int c = pg_stream.ReceiveChar();
switch (c)
@ -77,7 +81,8 @@ public class QueryExecutor {
if (fields != null)
hfr = true;
else {
else
{
sendQuery(" ");
fqp++;
}
@ -120,14 +125,18 @@ public class QueryExecutor {
/**
* Send a query to the backend.
*/
private void sendQuery(String query) throws SQLException {
try {
private void sendQuery(String query) throws SQLException
{
try
{
pg_stream.SendChar('Q');
pg_stream.Send(connection.getEncoding().encode(query));
pg_stream.SendChar(0);
pg_stream.flush();
} catch (IOException e) {
}
catch (IOException 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
*/
private void receiveTuple(boolean isBinary) throws SQLException {
private void receiveTuple(boolean isBinary) throws SQLException
{
if (fields == null)
throw new PSQLException("postgresql.con.tuple");
Object tuple = pg_stream.ReceiveTuple(fields.length, isBinary);
if (isBinary) binaryCursor = true;
if (isBinary)
binaryCursor = true;
if (maxRows == 0 || tuples.size() < maxRows)
tuples.addElement(tuple);
}
@ -149,20 +160,26 @@ public class QueryExecutor {
/**
* Receive command status from the backend.
*/
private void receiveCommandStatus() throws SQLException {
private void receiveCommandStatus() throws SQLException
{
status = pg_stream.ReceiveString(connection.getEncoding());
try {
try
{
// 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(' ')));
}
if (status.startsWith("INSERT")) {
if (status.startsWith("INSERT"))
{
insert_oid = Integer.parseInt(status.substring(1 + status.indexOf(' '),
status.lastIndexOf(' ')));
}
} catch (NumberFormatException nfe) {
}
catch (NumberFormatException nfe)
{
throw new PSQLException("postgresql.con.fathom", status);
}
}
@ -170,14 +187,16 @@ public class QueryExecutor {
/**
* Receive the field descriptions from the back end.
*/
private void receiveFields() throws SQLException {
private void receiveFields() throws SQLException
{
if (fields != null)
throw new PSQLException("postgresql.con.multres");
int size = pg_stream.ReceiveIntegerR(2);
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());
int typeOid = pg_stream.ReceiveIntegerR(4);
int typeLength = pg_stream.ReceiveIntegerR(2);

View File

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

View File

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

View File

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

View File

@ -79,7 +79,8 @@ public class PGbox extends PGobject implements Serializable,Cloneable
*/
public boolean equals(Object obj)
{
if(obj instanceof PGbox) {
if (obj instanceof PGbox)
{
PGbox p = (PGbox)obj;
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]));

View File

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

View File

@ -77,7 +77,8 @@ public class PGline extends PGobject implements Serializable,Cloneable
*/
public boolean equals(Object obj)
{
if(obj instanceof PGline) {
if (obj instanceof PGline)
{
PGline p = (PGline)obj;
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]));

View File

@ -74,7 +74,8 @@ public class PGlseg extends PGobject implements Serializable,Cloneable
*/
public boolean equals(Object obj)
{
if(obj instanceof PGlseg) {
if (obj instanceof PGlseg)
{
PGlseg p = (PGlseg)obj;
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]));

View File

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

View File

@ -62,10 +62,13 @@ public class PGpoint extends PGobject implements Serializable,Cloneable
public void setValue(String s) throws SQLException
{
PGtokenizer t = new PGtokenizer(PGtokenizer.removePara(s), ',');
try {
try
{
x = Double.valueOf(t.getToken(0)).doubleValue();
y = Double.valueOf(t.getToken(1)).doubleValue();
} catch(NumberFormatException e) {
}
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)
{
if(obj instanceof PGpoint) {
if (obj instanceof PGpoint)
{
PGpoint p = (PGpoint)obj;
return x == p.x && y == p.y;
}

View File

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

View File

@ -64,8 +64,8 @@ public class CallableStatement extends PreparedStatement implements java.sql.Cal
* registerOutParameter that accepts a scale value
* @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:
@ -82,8 +82,7 @@ public class CallableStatement extends PreparedStatement implements java.sql.Cal
*/
public void registerOutParameter(int parameterIndex, int sqlType,
int scale) throws SQLException
{
}
{}
// Old api?
//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
* @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
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
* @exception SQLException if a database-access error occurs.
*/
public String getString(int parameterIndex) throws SQLException {
public String getString(int parameterIndex) throws SQLException
{
return null;
}
//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
* @exception SQLException if a database-access error occurs.
*/
public boolean getBoolean(int parameterIndex) throws SQLException {
public boolean getBoolean(int parameterIndex) throws SQLException
{
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
* @exception SQLException if a database-access error occurs.
*/
public byte getByte(int parameterIndex) throws SQLException {
public byte getByte(int parameterIndex) throws SQLException
{
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
* @exception SQLException if a database-access error occurs.
*/
public short getShort(int parameterIndex) throws SQLException {
public short getShort(int parameterIndex) throws SQLException
{
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
* @exception SQLException if a database-access error occurs.
*/
public int getInt(int parameterIndex) throws SQLException {
public int getInt(int parameterIndex) throws SQLException
{
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
* @exception SQLException if a database-access error occurs.
*/
public long getLong(int parameterIndex) throws SQLException {
public long getLong(int parameterIndex) throws SQLException
{
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
* @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;
}
@ -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
* @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;
}
@ -216,7 +224,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @exception SQLException if a database-access error occurs.
*/
public BigDecimal getBigDecimal(int parameterIndex, int scale)
throws SQLException {
throws SQLException
{
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
* @exception SQLException if a database-access error occurs.
*/
public byte[] getBytes(int parameterIndex) throws SQLException {
public byte[] getBytes(int parameterIndex) throws SQLException
{
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
* @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;
}
@ -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
* @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;
}
@ -267,7 +279,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @exception SQLException if a database-access error occurs.
*/
public java.sql.Timestamp getTimestamp(int parameterIndex)
throws SQLException {
throws SQLException
{
return null;
}
@ -301,7 +314,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @exception SQLException if a database-access error occurs.
*/
public Object getObject(int parameterIndex)
throws SQLException {
throws SQLException
{
return null;
}
}

View File

@ -17,7 +17,7 @@ import org.postgresql.largeobject.*;
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
* context of a Connection, SQL statements are executed and results are
@ -146,8 +146,10 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
public int getSQLType(String pgTypeName)
{
int sqlType = Types.OTHER; // default value
for(int i=0;i<jdbc1Types.length;i++) {
if(pgTypeName.equals(jdbc1Types[i])) {
for (int i = 0;i < jdbc1Types.length;i++)
{
if (pgTypeName.equals(jdbc1Types[i]))
{
sqlType = jdbc1Typei[i];
break;
}

View File

@ -13,7 +13,7 @@ import org.postgresql.util.PSQLException;
/**
* 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
* can use the normal ResultSet methods such as getString and getInt to
@ -1686,9 +1686,11 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
StringBuffer sql = new StringBuffer("select relname,oid,relkind from pg_class where (");
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])) {
if (getTableTypes[j][0].equals(types[i]))
{
if (notFirst)
sql.append(" or ");
sql.append(getTableTypes[j][1]);
@ -1719,14 +1721,16 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
byte remarks[] = null;
if(((org.postgresql.ResultSet)dr).getTupleCount()==1) {
if (((org.postgresql.ResultSet)dr).getTupleCount() == 1)
{
dr.next();
remarks = dr.getBytes(1);
}
dr.close();
String relKind;
switch (r.getBytes(3)[0]) {
switch (r.getBytes(3)[0])
{
case (byte) 'r':
relKind = "TABLE";
break;
@ -1837,7 +1841,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
Field f[] = new Field[1];
Vector v = new Vector();
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];
tuple[0] = getTableTypes[i][0].getBytes();
v.addElement(tuple);
@ -1939,11 +1944,13 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" (" +
" a.attrelid=c.oid");
if ((tableNamePattern != null) && ! tableNamePattern.equals("%")) {
if ((tableNamePattern != null) && ! tableNamePattern.equals("%"))
{
sql.append(" and c.relname like \'" + tableNamePattern + "\'");
}
if ((columnNamePattern != null) && ! columnNamePattern.equals("%")) {
if ((columnNamePattern != null) && ! columnNamePattern.equals("%"))
{
sql.append(" and a.attname like \'" + columnNamePattern + "\'");
}
@ -1961,7 +1968,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" and a.attnum = d.adnum" +
" ) ");
if (!connection.haveMinimumServerVersion("7.2")) {
if (!connection.haveMinimumServerVersion("7.2"))
{
/* Only for 7.1 */
sql.append(
" left outer join pg_description e on" +
@ -1974,7 +1982,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" c.relname, a.attnum");
java.sql.ResultSet r = connection.ExecSQL(sql.toString());
while (r.next()) {
while (r.next())
{
byte[][] tuple = new byte[18][0];
String nullFlag = r.getString(6);
@ -1991,10 +2000,13 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// Looking at the psql source,
// 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)
if (typname.equals("bpchar") || typname.equals("varchar")) {
if (typname.equals("bpchar") || typname.equals("varchar"))
{
int atttypmod = r.getInt(8);
tuple[6] = Integer.toString(atttypmod != -1 ? atttypmod - VARHDRSZ : 0).getBytes();
} else {
}
else
{
tuple[6] = r.getBytes(7);
}
@ -2070,7 +2082,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// 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");
while(r.next()) {
while (r.next())
{
byte[][] tuple = new byte[8][0];
tuple[0] = tuple[1] = "".getBytes();
DriverManager.println("relname=\"" + r.getString(1) + "\" relacl=\"" + r.getString(2) + "\"");
@ -2247,7 +2260,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
);
}
private void importLoop(Vector tuples, java.sql.ResultSet keyRelation) throws SQLException {
private void importLoop(Vector tuples, java.sql.ResultSet keyRelation) throws SQLException
{
String s, s2;
String origTable = null, primTable = new String(""), schema;
int i;
@ -2257,14 +2271,17 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
s2 = s;
//System.out.println(s);
for (i=0;;i++) {
for (i = 0;;i++)
{
s = s.substring(s.indexOf("\\000") + 4);
if (s.compareTo("")==0) {
if (s.compareTo("") == 0)
{
//System.out.println();
break;
}
s2 = s.substring(0, s.indexOf("\\000"));
switch (i) {
switch (i)
{
case 0:
origTable = s2;
break;
@ -2287,11 +2304,14 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
byte tuple[][];
// 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);
for (int j=1;j<=origCols.getColumnCount();j++) {
if (stmp.compareTo(origCols.getColumnName(j))==0) {
for (int j = 1;j <= origCols.getColumnCount();j++)
{
if (stmp.compareTo(origCols.getColumnName(j)) == 0)
{
tuple = new byte[14][0];
for (int k = 0;k < 14;k++)
@ -2401,7 +2421,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
"where c.relname like '" + table + "' and c.relfilenode=t.tgrelid");
Vector tuples = new Vector();
while (rs.next()) {
while (rs.next())
{
importLoop(tuples, rs);
}
@ -2577,7 +2598,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
public java.sql.ResultSet getTypeInfo() throws SQLException
{
java.sql.ResultSet rs = connection.ExecSQL("select typname from pg_type");
if(rs!=null) {
if (rs != null)
{
Field f[] = new Field[18];
ResultSet r; // ResultSet for the SQL query that we need to do
Vector v = new Vector(); // The new ResultSet tuple stuff
@ -2609,7 +2631,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
byte bnn[] = Integer.toString(typeNoNulls).getBytes();
byte bts[] = Integer.toString(typeSearchable).getBytes();
while(rs.next()) {
while (rs.next())
{
byte[][] tuple = new byte[18][];
String typname = rs.getString(1);
tuple[0] = typname.getBytes();
@ -2722,7 +2745,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" AND (i.relam = a.oid)) " +
"ORDER BY x.indisunique DESC, " +
" x.indisclustered, a.amname, i.relname");
while (r.next()) {
while (r.next())
{
// indkey is an array of column ordinals (integers). In the JDBC
// interface, this has to be separated out into a separate
// 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);
int [] columnOrdinals = new int[stok.countTokens()];
int o = 0;
while (stok.hasMoreTokens()) {
while (stok.hasMoreTokens())
{
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] [];
tuple[0] = "".getBytes();
tuple[1] = "".getBytes();

View File

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

View File

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

View File

@ -201,24 +201,37 @@ public class ResultSetMetaData implements java.sql.ResultSetMetaData
// FIXME: currently, only types with a SQL92 or SQL3 pendant are implemented - jens@jens.de
// 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" )
|| type_name.equals( "oid" )) return 11; // -2147483648 to +2147483647
if (type_name.equals( "int8" )) return 20; // -9223372036854775808 to +9223372036854775807
if (type_name.equals( "money" )) return 12; // MONEY = DECIMAL(9,2)
if (type_name.equals( "float4" )) return 11; // i checked it out ans wasn't able to produce more than 11 digits
if (type_name.equals( "float8" )) 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
|| type_name.equals( "oid" ))
return 11; // -2147483648 to +2147483647
if (type_name.equals( "int8" ))
return 20; // -9223372036854775808 to +9223372036854775807
if (type_name.equals( "money" ))
return 12; // MONEY = DECIMAL(9,2)
if (type_name.equals( "float4" ))
return 11; // i checked it out ans wasn't able to produce more than 11 digits
if (type_name.equals( "float8" ))
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
typmod -= 4;
if (type_name.equals( "bpchar" )
|| type_name.equals( "varchar" )) return typmod; // VARHDRSZ=sizeof(int32)=4
if (type_name.equals( "numeric" )) return ( (typmod >>16) & 0xffff )
|| type_name.equals( "varchar" ))
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)
// if we don't know better

View File

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

View File

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

View File

@ -64,8 +64,8 @@ public class CallableStatement extends org.postgresql.jdbc2.PreparedStatement im
* registerOutParameter that accepts a scale value
* @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:
@ -82,8 +82,7 @@ public class CallableStatement extends org.postgresql.jdbc2.PreparedStatement im
*/
public void registerOutParameter(int parameterIndex, int sqlType,
int scale) throws SQLException
{
}
{}
// Old api?
//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
* @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
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
* @exception SQLException if a database-access error occurs.
*/
public String getString(int parameterIndex) throws SQLException {
public String getString(int parameterIndex) throws SQLException
{
return null;
}
//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
* @exception SQLException if a database-access error occurs.
*/
public boolean getBoolean(int parameterIndex) throws SQLException {
public boolean getBoolean(int parameterIndex) throws SQLException
{
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
* @exception SQLException if a database-access error occurs.
*/
public byte getByte(int parameterIndex) throws SQLException {
public byte getByte(int parameterIndex) throws SQLException
{
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
* @exception SQLException if a database-access error occurs.
*/
public short getShort(int parameterIndex) throws SQLException {
public short getShort(int parameterIndex) throws SQLException
{
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
* @exception SQLException if a database-access error occurs.
*/
public int getInt(int parameterIndex) throws SQLException {
public int getInt(int parameterIndex) throws SQLException
{
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
* @exception SQLException if a database-access error occurs.
*/
public long getLong(int parameterIndex) throws SQLException {
public long getLong(int parameterIndex) throws SQLException
{
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
* @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;
}
@ -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
* @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;
}
@ -217,7 +225,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @deprecated in Java2.0
*/
public BigDecimal getBigDecimal(int parameterIndex, int scale)
throws SQLException {
throws SQLException
{
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
* @exception SQLException if a database-access error occurs.
*/
public byte[] getBytes(int parameterIndex) throws SQLException {
public byte[] getBytes(int parameterIndex) throws SQLException
{
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
* @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;
}
@ -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
* @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;
}
@ -268,7 +280,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @exception SQLException if a database-access error occurs.
*/
public java.sql.Timestamp getTimestamp(int parameterIndex)
throws SQLException {
throws SQLException
{
return null;
}
@ -302,7 +315,8 @@ public int getInt(int parameterIndex) throws SQLException {
* @exception SQLException if a database-access error occurs.
*/
public Object getObject(int parameterIndex)
throws SQLException {
throws SQLException
{
return null;
}

View File

@ -17,7 +17,7 @@ import org.postgresql.largeobject.*;
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
* context of a Connection, SQL statements are executed and results are
@ -166,7 +166,8 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
return true;
// ok, test the connection
try {
try
{
// by sending an empty query. If we are dead, then an SQLException should
// be thrown
java.sql.ResultSet rs = ExecSQL(" ");
@ -175,7 +176,9 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
// By now, we must be alive
return false;
} catch(SQLException se) {
}
catch (SQLException se)
{
// Why throw an SQLException as this may fail without throwing one,
// 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
@ -208,7 +211,8 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
{
// In 7.1 we now test concurrency to see which class to return. If we are not working with a
// 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);
}
@ -243,9 +247,11 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
*/
public Object getObject(String type, String value) throws SQLException
{
if(typemap!=null) {
if (typemap != null)
{
SQLData d = (SQLData) typemap.get(type);
if(d!=null) {
if (d != null)
{
// Handle the type (requires SQLInput & SQLOutput classes to be implemented)
throw org.postgresql.Driver.notImplemented();
}
@ -263,8 +269,10 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co
public int getSQLType(String pgTypeName)
{
int sqlType = Types.OTHER; // default value
for(int i=0;i<jdbc2Types.length;i++) {
if(pgTypeName.equals(jdbc2Types[i])) {
for (int i = 0;i < jdbc2Types.length;i++)
{
if (pgTypeName.equals(jdbc2Types[i]))
{
sqlType = jdbc2Typei[i];
break;
}

View File

@ -13,7 +13,7 @@ import org.postgresql.util.PSQLException;
/**
* 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
* can use the normal ResultSet methods such as getString and getInt to
@ -1686,9 +1686,11 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
StringBuffer sql = new StringBuffer("select relname,oid,relkind from pg_class where (");
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])) {
if (getTableTypes[j][0].equals(types[i]))
{
if (notFirst)
sql.append(" or ");
sql.append(getTableTypes[j][1]);
@ -1719,14 +1721,16 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
byte remarks[] = null;
if(((org.postgresql.ResultSet)dr).getTupleCount()==1) {
if (((org.postgresql.ResultSet)dr).getTupleCount() == 1)
{
dr.next();
remarks = dr.getBytes(1);
}
dr.close();
String relKind;
switch (r.getBytes(3)[0]) {
switch (r.getBytes(3)[0])
{
case (byte) 'r':
relKind = "TABLE";
break;
@ -1837,7 +1841,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
Field f[] = new Field[1];
Vector v = new Vector();
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];
tuple[0] = getTableTypes[i][0].getBytes();
v.addElement(tuple);
@ -1939,11 +1944,13 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" (" +
" a.attrelid=c.oid");
if ((tableNamePattern != null) && ! tableNamePattern.equals("%")) {
if ((tableNamePattern != null) && ! tableNamePattern.equals("%"))
{
sql.append(" and c.relname like \'" + tableNamePattern + "\'");
}
if ((columnNamePattern != null) && ! columnNamePattern.equals("%")) {
if ((columnNamePattern != null) && ! columnNamePattern.equals("%"))
{
sql.append(" and a.attname like \'" + columnNamePattern + "\'");
}
@ -1961,7 +1968,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" and a.attnum = d.adnum" +
" ) ");
if (!connection.haveMinimumServerVersion("7.2")) {
if (!connection.haveMinimumServerVersion("7.2"))
{
/* Only for 7.1 */
sql.append(
" left outer join pg_description e on" +
@ -1974,7 +1982,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" c.relname, a.attnum");
java.sql.ResultSet r = connection.ExecSQL(sql.toString());
while (r.next()) {
while (r.next())
{
byte[][] tuple = new byte[18][0];
String nullFlag = r.getString(6);
@ -1991,10 +2000,13 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// Looking at the psql source,
// 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)
if (typname.equals("bpchar") || typname.equals("varchar")) {
if (typname.equals("bpchar") || typname.equals("varchar"))
{
int atttypmod = r.getInt(8);
tuple[6] = Integer.toString(atttypmod != -1 ? atttypmod - VARHDRSZ : 0).getBytes();
} else {
}
else
{
tuple[6] = r.getBytes(7);
}
@ -2081,7 +2093,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
// 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");
while(r.next()) {
while (r.next())
{
byte[][] tuple = new byte[8][0];
tuple[0] = tuple[1] = "".getBytes();
DriverManager.println("relname=\"" + r.getString(1) + "\" relacl=\"" + r.getString(2) + "\"");
@ -2260,7 +2273,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
);
}
private Vector importLoop(java.sql.ResultSet keyRelation) throws SQLException {
private Vector importLoop(java.sql.ResultSet keyRelation) throws SQLException
{
String s, s2;
String origTable = null, primTable = new String(""), schema;
int i;
@ -2270,14 +2284,17 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
s2 = s;
// System.out.println(s);
v = new Vector();
for (i=0;;i++) {
for (i = 0;;i++)
{
s = s.substring(s.indexOf("\\000") + 4);
if (s.compareTo("")==0) {
if (s.compareTo("") == 0)
{
//System.out.println();
break;
}
s2 = s.substring(0, s.indexOf("\\000"));
switch (i) {
switch (i)
{
case 0:
origTable = s2;
break;
@ -2300,11 +2317,14 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
byte tuple[][];
// 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);
for (int j=1;j<=origCols.getColumnCount();j++) {
if (stmp.compareTo(origCols.getColumnName(j))==0) {
for (int j = 1;j <= origCols.getColumnCount();j++)
{
if (stmp.compareTo(origCols.getColumnName(j)) == 0)
{
tuple = new byte[14][0];
for (int k = 0;k < 14;k++)
@ -2415,7 +2435,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
"where c.relname like '" + table + "' and c.relfilenode=t.tgrelid");
Vector tuples = new Vector();
while (rs.next()) {
while (rs.next())
{
tuples.addAll(importLoop(rs));
}
@ -2591,7 +2612,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
public java.sql.ResultSet getTypeInfo() throws SQLException
{
java.sql.ResultSet rs = connection.ExecSQL("select typname from pg_type");
if(rs!=null) {
if (rs != null)
{
Field f[] = new Field[18];
ResultSet r; // ResultSet for the SQL query that we need to do
Vector v = new Vector(); // The new ResultSet tuple stuff
@ -2623,7 +2645,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
byte bnn[] = Integer.toString(typeNoNulls).getBytes();
byte bts[] = Integer.toString(typeSearchable).getBytes();
while(rs.next()) {
while (rs.next())
{
byte[][] tuple = new byte[18][];
String typname = rs.getString(1);
tuple[0] = typname.getBytes();
@ -2736,7 +2759,8 @@ public class DatabaseMetaData implements java.sql.DatabaseMetaData
" AND (i.relam = a.oid)) " +
"ORDER BY x.indisunique DESC, " +
" x.indisclustered, a.amname, i.relname");
while (r.next()) {
while (r.next())
{
// indkey is an array of column ordinals (integers). In the JDBC
// interface, this has to be separated out into a separate
// 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);
int [] columnOrdinals = new int[stok.countTokens()];
int o = 0;
while (stok.hasMoreTokens()) {
while (stok.hasMoreTokens())
{
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] [];
tuple[0] = "".getBytes();
tuple[1] = "".getBytes();

View File

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

View File

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

View File

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

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
// 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" )
|| type_name.equals( "oid" )) return 11; // -2147483648 to +2147483647
if (type_name.equals( "int8" )) return 20; // -9223372036854775808 to +9223372036854775807
if (type_name.equals( "money" )) return 12; // MONEY = DECIMAL(9,2)
if (type_name.equals( "float4" )) return 11; // i checked it out ans wasn't able to produce more than 11 digits
if (type_name.equals( "float8" )) 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
|| type_name.equals( "oid" ))
return 11; // -2147483648 to +2147483647
if (type_name.equals( "int8" ))
return 20; // -9223372036854775808 to +9223372036854775807
if (type_name.equals( "money" ))
return 12; // MONEY = DECIMAL(9,2)
if (type_name.equals( "float4" ))
return 11; // i checked it out ans wasn't able to produce more than 11 digits
if (type_name.equals( "float8" ))
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
typmod -= 4;
if (type_name.equals( "bpchar" )
|| type_name.equals( "varchar" )) return typmod; // VARHDRSZ=sizeof(int32)=4
if (type_name.equals( "numeric" )) return ( (typmod >>16) & 0xffff )
|| type_name.equals( "varchar" ))
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)
// if we don't know better

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -20,7 +20,7 @@ import org.postgresql.largeobject.*;
* This implements the Blob interface, which is basically another way to
* 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
@ -29,22 +29,26 @@ public class PGblob implements java.sql.Blob
private int oid;
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;
LargeObjectManager lom = conn.getLargeObjectAPI();
this.lo = lom.open(oid);
}
public long length() throws SQLException {
public long length() throws SQLException
{
return lo.size();
}
public InputStream getBinaryStream() throws SQLException {
public InputStream getBinaryStream() throws SQLException
{
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);
return lo.read(length);
}
@ -52,14 +56,16 @@ public class PGblob implements java.sql.Blob
/*
* 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();
}
/*
* 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);
}

View File

@ -20,7 +20,7 @@ import org.postgresql.largeobject.*;
* This implements the Blob interface, which is basically another way to
* 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
@ -29,26 +29,31 @@ public class PGclob implements java.sql.Clob
private int oid;
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;
LargeObjectManager lom = conn.getLargeObjectAPI();
this.lo = lom.open(oid);
}
public long length() throws SQLException {
public long length() throws SQLException
{
return lo.size();
}
public InputStream getAsciiStream() throws SQLException {
public InputStream getAsciiStream() throws SQLException
{
return lo.getInputStream();
}
public Reader getCharacterStream() throws SQLException {
public Reader getCharacterStream() throws SQLException
{
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);
return new String(lo.read(j));
}
@ -56,14 +61,16 @@ public class PGclob implements java.sql.Clob
/*
* 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();
}
/*
* 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();
}

View File

@ -9,38 +9,48 @@ import java.sql.*;
/**
* 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
*/
public static String getURL() {
public static String getURL()
{
return System.getProperty("database");
}
/**
* Returns the Postgresql username
*/
public static String getUser() {
public static String getUser()
{
return System.getProperty("username");
}
/**
* Returns the user's password
*/
public static String getPassword() {
public static String getPassword()
{
return System.getProperty("password");
}
/**
* Helper - opens a connection.
*/
public static java.sql.Connection openDB() {
try {
public static java.sql.Connection openDB()
{
try
{
Class.forName("org.postgresql.Driver");
return java.sql.DriverManager.getConnection(JDBC2Tests.getURL(), JDBC2Tests.getUser(), JDBC2Tests.getPassword());
} catch(ClassNotFoundException ex) {
}
catch (ClassNotFoundException ex)
{
TestCase.fail(ex.getMessage());
} catch(SQLException ex) {
}
catch (SQLException ex)
{
TestCase.fail(ex.getMessage());
}
return null;
@ -50,11 +60,15 @@ public class JDBC2Tests extends TestSuite {
* Helper - closes an open connection. This rewrites SQLException to a failed
* assertion. It's static so other classes can use it.
*/
public static void closeDB(Connection con) {
try {
public static void closeDB(Connection con)
{
try
{
if (con != null)
con.close();
} catch (SQLException ex) {
}
catch (SQLException ex)
{
TestCase.fail(ex.getMessage());
}
}
@ -64,19 +78,26 @@ public class JDBC2Tests extends TestSuite {
*/
public static void createTable(Connection con,
String table,
String columns) {
try {
String columns)
{
try
{
Statement st = con.createStatement();
try {
try
{
// Drop the table
dropTable(con, table);
// Now create the table
st.executeUpdate("create table " + table + " (" + columns + ")");
} finally {
}
finally
{
st.close();
}
} catch(SQLException ex) {
}
catch (SQLException ex)
{
TestCase.fail(ex.getMessage());
}
}
@ -84,15 +105,22 @@ public class JDBC2Tests extends TestSuite {
/**
* Helper - drops a table
*/
public static void dropTable(Connection con, String table) {
try {
public static void dropTable(Connection con, String table)
{
try
{
Statement stmt = con.createStatement();
try {
try
{
stmt.executeUpdate("DROP TABLE " + table);
} catch (SQLException ex) {
}
catch (SQLException ex)
{
// ignore
}
} catch (SQLException ex) {
}
catch (SQLException ex)
{
TestCase.fail(ex.getMessage());
}
}
@ -100,11 +128,13 @@ public class JDBC2Tests extends TestSuite {
/**
* 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);
}
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;
if (columns != null)
@ -116,15 +146,18 @@ public class JDBC2Tests extends TestSuite {
/**
* 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);
}
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);
}
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;
if (where != null)
@ -140,7 +173,8 @@ public class JDBC2Tests extends TestSuite {
* @param v value to prefix
* @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);
return s.substring(s.length() - l);
}
@ -148,7 +182,8 @@ public class JDBC2Tests extends TestSuite {
/**
* The main entry point for JUnit
*/
public static TestSuite suite() {
public static TestSuite suite()
{
TestSuite suite = new TestSuite();
//

View File

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

View File

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

View File

@ -8,13 +8,14 @@ import java.sql.*;
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
* help prevent previous problems from re-occuring ;-)
*
*/
public class BlobTest extends TestCase {
public class BlobTest extends TestCase
{
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 JDBC_STREAM = 2; // JDBC API using OutputStream
public BlobTest(String name) {
public BlobTest(String name)
{
super(name);
}
protected void setUp() throws Exception {
protected void setUp() throws Exception
{
con = JDBC2Tests.openDB();
JDBC2Tests.createTable(con, "testblob", "id name,lo oid");
}
protected void tearDown() throws Exception {
protected void tearDown() throws Exception
{
JDBC2Tests.dropTable(con, "testblob");
JDBC2Tests.closeDB(con);
}
@ -39,8 +43,10 @@ public class BlobTest extends TestCase {
/**
* Tests one method of uploading a blob to the database
*/
public void testUploadBlob_LOOP() {
try {
public void testUploadBlob_LOOP()
{
try
{
con.setAutoCommit(false);
assertTrue(!con.getAutoCommit());
@ -51,7 +57,9 @@ public class BlobTest extends TestCase {
assertTrue(compareBlobs());
con.setAutoCommit(true);
} catch(Exception ex) {
}
catch (Exception ex)
{
fail(ex.getMessage());
}
}
@ -59,8 +67,10 @@ public class BlobTest extends TestCase {
/**
* Tests one method of uploading a blob to the database
*/
public void testUploadBlob_NATIVE() {
try {
public void testUploadBlob_NATIVE()
{
try
{
con.setAutoCommit(false);
assertTrue(!con.getAutoCommit());
@ -71,7 +81,9 @@ public class BlobTest extends TestCase {
assertTrue(compareBlobs());
con.setAutoCommit(true);
} catch(Exception ex) {
}
catch (Exception ex)
{
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
* 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();
FileInputStream fis = new FileInputStream(file);
@ -98,7 +111,8 @@ public class BlobTest extends TestCase {
case LOOP:
buf = new byte[2048];
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);
}
@ -107,7 +121,8 @@ public class BlobTest extends TestCase {
case NATIVE_STREAM:
os = blob.getOutputStream();
s = fis.read();
while(s>-1) {
while (s > -1)
{
os.write(s);
s = fis.read();
}
@ -141,7 +156,8 @@ public class BlobTest extends TestCase {
* Helper - compares the blobs in a table with a local file. Note this alone
* tests the InputStream methods!
*/
private boolean compareBlobs() throws Exception {
private boolean compareBlobs() throws Exception
{
boolean result = true;
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"));
assertNotNull(rs);
while(rs.next()) {
while (rs.next())
{
String file = rs.getString(1);
int oid = rs.getInt(2);
@ -161,7 +178,8 @@ public class BlobTest extends TestCase {
int f = fis.read();
int b = bis.read();
int c = 0;
while(f>=0 && b>=0 & result) {
while (f >= 0 && b >= 0 & result)
{
result = (f == b);
f = fis.read();
b = bis.read();

View File

@ -10,20 +10,23 @@ import java.sql.*;
*
* PS: Do you know how difficult it is to type on a train? ;-)
*
* $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
*/
public ConnectionTest(String name) {
public ConnectionTest(String name)
{
super(name);
}
// 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();
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.
protected void tearDown() throws Exception {
protected void tearDown() throws Exception
{
Connection con = JDBC2Tests.openDB();
JDBC2Tests.dropTable(con, "test_a");
@ -45,8 +49,10 @@ public class ConnectionTest extends TestCase {
/**
* Tests the two forms of createStatement()
*/
public void testCreateStatement() {
try {
public void testCreateStatement()
{
try
{
java.sql.Connection conn = JDBC2Tests.openDB();
// A standard Statement
@ -59,7 +65,9 @@ public class ConnectionTest extends TestCase {
assertNotNull(stat);
stat.close();
} catch(SQLException ex) {
}
catch (SQLException ex)
{
assertTrue(ex.getMessage(), false);
}
}
@ -67,8 +75,10 @@ public class ConnectionTest extends TestCase {
/**
* Tests the two forms of prepareStatement()
*/
public void testPrepareStatement() {
try {
public void testPrepareStatement()
{
try
{
java.sql.Connection conn = JDBC2Tests.openDB();
String sql = "select source,cost,imageid from test_c";
@ -83,7 +93,9 @@ public class ConnectionTest extends TestCase {
assertNotNull(stat);
stat.close();
} catch(SQLException ex) {
}
catch (SQLException ex)
{
assertTrue(ex.getMessage(), false);
}
}
@ -91,21 +103,24 @@ public class ConnectionTest extends TestCase {
/**
* Put the test for createPrepareCall here
*/
public void testPrepareCall() {
}
public void testPrepareCall()
{}
/**
* Test nativeSQL
*/
public void testNativeSQL() {
public void testNativeSQL()
{
// For now do nothing as it returns itself
}
/**
* Test autoCommit (both get & set)
*/
public void testTransactions() {
try {
public void testTransactions()
{
try
{
java.sql.Connection con = JDBC2Tests.openDB();
java.sql.Statement st;
java.sql.ResultSet rs;
@ -141,7 +156,9 @@ public class ConnectionTest extends TestCase {
rs.close();
JDBC2Tests.closeDB(con);
} catch(SQLException ex) {
}
catch (SQLException ex)
{
assertTrue(ex.getMessage(), false);
}
}
@ -149,8 +166,10 @@ public class ConnectionTest extends TestCase {
/**
* Simple test to see if isClosed works.
*/
public void testIsClosed() {
try {
public void testIsClosed()
{
try
{
Connection con = JDBC2Tests.openDB();
// Should not say closed
@ -161,7 +180,9 @@ public class ConnectionTest extends TestCase {
// Should now say closed
assertTrue(con.isClosed());
} catch(SQLException ex) {
}
catch (SQLException ex)
{
assertTrue(ex.getMessage(), false);
}
}
@ -169,8 +190,10 @@ public class ConnectionTest extends TestCase {
/**
* Test the warnings system
*/
public void testWarnings() {
try {
public void testWarnings()
{
try
{
Connection con = JDBC2Tests.openDB();
String testStr = "This Is OuR TeSt message";
@ -194,7 +217,9 @@ public class ConnectionTest extends TestCase {
assertTrue(con.getWarnings() == null);
JDBC2Tests.closeDB(con);
} catch(SQLException ex) {
}
catch (SQLException ex)
{
assertTrue(ex.getMessage(), false);
}
}
@ -287,8 +312,10 @@ public class ConnectionTest extends TestCase {
/**
* JDBC2 Type mappings
*/
public void testTypeMaps() {
try {
public void testTypeMaps()
{
try
{
Connection con = JDBC2Tests.openDB();
// preserve the current map
@ -304,7 +331,9 @@ public class ConnectionTest extends TestCase {
assertEquals(oldmap, con.getTypeMap());
JDBC2Tests.closeDB(con);
} catch(SQLException ex) {
}
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? ;-)
*
* $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
*/
public DatabaseMetaDataTest(String name) {
public DatabaseMetaDataTest(String name)
{
super(name);
}
/**
* The spec says this may return null, but we always do!
*/
public void testGetMetaData() {
try {
public void testGetMetaData()
{
try
{
Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData();
assertNotNull(dbmd);
JDBC2Tests.closeDB(con);
} catch(SQLException ex) {
}
catch (SQLException ex)
{
fail(ex.getMessage());
}
}
@ -40,8 +46,10 @@ public class DatabaseMetaDataTest extends TestCase {
/**
* Test default capabilities
*/
public void testCapabilities() {
try {
public void testCapabilities()
{
try
{
Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData();
@ -69,14 +77,18 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(!dbmd.supportsIntegrityEnhancementFacility());
JDBC2Tests.closeDB(con);
} catch(SQLException ex) {
}
catch (SQLException ex)
{
fail(ex.getMessage());
}
}
public void testJoins() {
try {
public void testJoins()
{
try
{
Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData();
@ -87,13 +99,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(dbmd.supportsLimitedOuterJoins());
JDBC2Tests.closeDB(con);
} catch(SQLException ex) {
}
catch (SQLException ex)
{
fail(ex.getMessage());
}
}
public void testCursors() {
try {
public void testCursors()
{
try
{
Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData();
@ -103,13 +119,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(!dbmd.supportsPositionedUpdate());
JDBC2Tests.closeDB(con);
} catch(SQLException ex) {
}
catch (SQLException ex)
{
fail(ex.getMessage());
}
}
public void testNulls() {
try {
public void testNulls()
{
try
{
Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData();
@ -132,13 +152,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(dbmd.supportsNonNullableColumns());
JDBC2Tests.closeDB(con);
} catch(SQLException ex) {
}
catch (SQLException ex)
{
fail(ex.getMessage());
}
}
public void testLocalFiles() {
try {
public void testLocalFiles()
{
try
{
Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData();
@ -148,13 +172,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(!dbmd.usesLocalFiles());
JDBC2Tests.closeDB(con);
} catch(SQLException ex) {
}
catch (SQLException ex)
{
fail(ex.getMessage());
}
}
public void testIdentifiers() {
try {
public void testIdentifiers()
{
try
{
Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData();
@ -173,13 +201,17 @@ public class DatabaseMetaDataTest extends TestCase {
JDBC2Tests.closeDB(con);
} catch(SQLException ex) {
}
catch (SQLException ex)
{
fail(ex.getMessage());
}
}
public void testTables() {
try {
public void testTables()
{
try
{
Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData();
@ -192,13 +224,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(!dbmd.supportsAlterTableWithDropColumn());
JDBC2Tests.closeDB(con);
} catch(SQLException ex) {
}
catch (SQLException ex)
{
fail(ex.getMessage());
}
}
public void testSelect() {
try {
public void testSelect()
{
try
{
Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData();
@ -219,13 +255,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(dbmd.supportsGroupByBeyondSelect()); // needs checking
JDBC2Tests.closeDB(con);
} catch(SQLException ex) {
}
catch (SQLException ex)
{
fail(ex.getMessage());
}
}
public void testDBParams() {
try {
public void testDBParams()
{
try
{
Connection con = JDBC2Tests.openDB();
DatabaseMetaData dbmd = con.getMetaData();
@ -235,13 +275,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(dbmd.getUserName().equals(JDBC2Tests.getUser()));
JDBC2Tests.closeDB(con);
} catch(SQLException ex) {
}
catch (SQLException ex)
{
fail(ex.getMessage());
}
}
public void testDbProductDetails() {
try {
public void testDbProductDetails()
{
try
{
Connection con = JDBC2Tests.openDB();
assertTrue(con instanceof org.postgresql.Connection);
org.postgresql.Connection pc = (org.postgresql.Connection) con;
@ -254,13 +298,17 @@ public class DatabaseMetaDataTest extends TestCase {
assertTrue(dbmd.getDriverName().equals("PostgreSQL Native Driver"));
JDBC2Tests.closeDB(con);
} catch(SQLException ex) {
}
catch (SQLException ex)
{
fail(ex.getMessage());
}
}
public void testDriverVersioning() {
try {
public void testDriverVersioning()
{
try
{
Connection con = JDBC2Tests.openDB();
assertTrue(con instanceof org.postgresql.Connection);
org.postgresql.Connection pc = (org.postgresql.Connection) con;
@ -274,7 +322,9 @@ public class DatabaseMetaDataTest extends TestCase {
JDBC2Tests.closeDB(con);
} catch(SQLException ex) {
}
catch (SQLException ex)
{
fail(ex.getMessage());
}
}

View File

@ -5,26 +5,30 @@ import junit.framework.TestCase;
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
* help prevent previous problems from re-occuring ;-)
*
*/
public class DateTest extends TestCase {
public class DateTest extends TestCase
{
private Connection con;
public DateTest(String name) {
public DateTest(String name)
{
super(name);
}
protected void setUp() throws Exception {
protected void setUp() throws Exception
{
con = JDBC2Tests.openDB();
JDBC2Tests.createTable(con, "testdate", "dt date");
}
protected void tearDown() throws Exception {
protected void tearDown() throws Exception
{
JDBC2Tests.dropTable(con, "testdate");
JDBC2Tests.closeDB(con);
}
@ -32,8 +36,10 @@ public class DateTest extends TestCase {
/**
* Tests the time methods in ResultSet
*/
public void testGetDate() {
try {
public void testGetDate()
{
try
{
Statement stmt = con.createStatement();
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"));
stmt.close();
} catch(Exception ex) {
}
catch (Exception ex)
{
fail(ex.getMessage());
}
}
@ -54,8 +62,10 @@ public class DateTest extends TestCase {
/**
* Tests the time methods in PreparedStatement
*/
public void testSetDate() {
try {
public void testSetDate()
{
try
{
Statement stmt = con.createStatement();
PreparedStatement ps = con.prepareStatement(JDBC2Tests.insertSQL("testdate", "?"));
@ -78,7 +88,9 @@ public class DateTest extends TestCase {
assertEquals(4, stmt.executeUpdate("DELETE FROM testdate"));
stmt.close();
} catch(Exception ex) {
}
catch (Exception ex)
{
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
*/
private void dateTest() throws SQLException {
private void dateTest() throws SQLException
{
Statement st = con.createStatement();
ResultSet rs;
java.sql.Date d;
@ -120,7 +133,8 @@ public class DateTest extends TestCase {
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) + "-" +
JDBC2Tests.fix(m, 2) + "-" +
JDBC2Tests.fix(d, 2));

View File

@ -5,14 +5,16 @@ import junit.framework.TestCase;
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
*
*/
public class DriverTest extends TestCase {
public class DriverTest extends TestCase
{
public DriverTest(String name) {
public DriverTest(String 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
* jdbc urls
*/
public void testAcceptsURL() {
try {
public void testAcceptsURL()
{
try
{
// Load the driver (note clients should never do it this way!)
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("postgresql:test"));
} catch(SQLException ex) {
}
catch (SQLException ex)
{
fail(ex.getMessage());
}
}
@ -49,9 +55,11 @@ public class DriverTest extends TestCase {
/**
* Tests the connect method by connecting to the test database
*/
public void testConnect() {
public void testConnect()
{
Connection con = null;
try {
try
{
Class.forName("org.postgresql.Driver");
// Test with the url, username & password
@ -63,9 +71,13 @@ public class DriverTest extends TestCase {
con = DriverManager.getConnection(JDBC2Tests.getURL() + "?user=" + JDBC2Tests.getUser() + "&password=" + JDBC2Tests.getPassword());
assertNotNull(con);
con.close();
} catch(ClassNotFoundException ex) {
}
catch (ClassNotFoundException ex)
{
fail(ex.getMessage());
} catch(SQLException ex) {
}
catch (SQLException ex)
{
fail(ex.getMessage());
}
}

View File

@ -8,17 +8,20 @@ import java.io.*;
/**
* 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);
}
public void testCreation() throws Exception {
public void testCreation() throws Exception
{
Encoding encoding;
encoding = Encoding.getEncoding("UNICODE", null);
assertEquals("UTF", encoding.name().substring(0, 3).toUpperCase());
@ -32,7 +35,8 @@ public class EncodingTest extends TestCase {
encoding.name().toUpperCase().indexOf("UTF") != -1);
}
public void testTransformations() throws Exception {
public void testTransformations() throws Exception
{
Encoding encoding = Encoding.getEncoding("UNICODE", null);
assertEquals("ab", encoding.decode(new byte[] { 97, 98 }));
@ -46,7 +50,8 @@ public class EncodingTest extends TestCase {
encoding.decode(new byte[] { 97 }));
}
public void testReader() throws Exception {
public void testReader() throws Exception
{
Encoding encoding = Encoding.getEncoding("SQL_ASCII", null);
InputStream stream = new ByteArrayInputStream(new byte[] { 97, 98 });
Reader reader = encoding.getDecodingReader(stream);

View File

@ -6,20 +6,23 @@ import java.sql.*;
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
* stay working
*
*/
public class JBuilderTest extends TestCase {
public class JBuilderTest extends TestCase
{
public JBuilderTest(String name) {
public JBuilderTest(String name)
{
super(name);
}
// 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();
JDBC2Tests.createTable( con, "test_c",
@ -29,7 +32,8 @@ public class JBuilderTest extends TestCase {
}
// Tear down the fixture for this test case.
protected void tearDown() throws Exception {
protected void tearDown() throws Exception
{
Connection con = JDBC2Tests.openDB();
JDBC2Tests.dropTable(con, "test_c");
JDBC2Tests.closeDB(con);
@ -38,15 +42,18 @@ public class JBuilderTest extends TestCase {
/**
* This tests that Money types work. JDBCExplorer barfs if this fails.
*/
public void testMoney() {
try {
public void testMoney()
{
try
{
Connection con = JDBC2Tests.openDB();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select cost from test_c");
assertNotNull(rs);
while(rs.next()){
while (rs.next())
{
double bd = rs.getDouble(1);
}
@ -54,7 +61,9 @@ public class JBuilderTest extends TestCase {
st.close();
JDBC2Tests.closeDB(con);
} catch(Exception ex) {
}
catch (Exception ex)
{
fail(ex.getMessage());
}
}

View File

@ -5,15 +5,17 @@ import junit.framework.TestCase;
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
* 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);
}
@ -24,15 +26,18 @@ public class MiscTest extends TestCase {
*
* Added Feb 13 2001
*/
public void testDatabaseSelectNullBug() {
try {
public void testDatabaseSelectNullBug()
{
try
{
Connection con = JDBC2Tests.openDB();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select datname from pg_database");
assertNotNull(rs);
while(rs.next()){
while (rs.next())
{
String s = rs.getString(1);
}
@ -40,7 +45,9 @@ public class MiscTest extends TestCase {
st.close();
JDBC2Tests.closeDB(con);
} catch(Exception ex) {
}
catch (Exception ex)
{
fail(ex.getMessage());
}
}

View File

@ -5,26 +5,30 @@ import junit.framework.TestCase;
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
* help prevent previous problems from re-occuring ;-)
*
*/
public class TimeTest extends TestCase {
public class TimeTest extends TestCase
{
private Connection con;
public TimeTest(String name) {
public TimeTest(String name)
{
super(name);
}
protected void setUp() throws Exception {
protected void setUp() throws Exception
{
con = JDBC2Tests.openDB();
JDBC2Tests.createTable(con, "testtime", "tm time");
}
protected void tearDown() throws Exception {
protected void tearDown() throws Exception
{
JDBC2Tests.dropTable(con, "testtime");
JDBC2Tests.closeDB(con);
}
@ -32,8 +36,10 @@ public class TimeTest extends TestCase {
/**
* Tests the time methods in ResultSet
*/
public void testGetTime() {
try {
public void testGetTime()
{
try
{
Statement stmt = con.createStatement();
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"));
stmt.close();
} catch(Exception ex) {
}
catch (Exception ex)
{
fail(ex.getMessage());
}
}
@ -52,8 +60,10 @@ public class TimeTest extends TestCase {
/**
* Tests the time methods in PreparedStatement
*/
public void testSetTime() {
try {
public void testSetTime()
{
try
{
PreparedStatement ps = con.prepareStatement(JDBC2Tests.insertSQL("testtime", "?"));
Statement stmt = con.createStatement();
@ -69,7 +79,9 @@ public class TimeTest extends TestCase {
assertEquals(2, stmt.executeUpdate("DELETE FROM testtime"));
stmt.close();
ps.close();
} catch(Exception ex) {
}
catch (Exception ex)
{
fail(ex.getMessage());
}
}
@ -77,7 +89,8 @@ public class TimeTest extends TestCase {
/**
* 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();
ResultSet rs;
java.sql.Time t;
@ -100,7 +113,8 @@ public class TimeTest extends TestCase {
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) + ":" +
JDBC2Tests.fix(m, 2) + ":" +
JDBC2Tests.fix(s, 2));

View File

@ -5,7 +5,7 @@ import junit.framework.TestCase;
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!
*
@ -13,22 +13,26 @@ import java.sql.*;
* MUST PASS this TestCase!!!
*
*/
public class TimestampTest extends TestCase {
public class TimestampTest extends TestCase
{
private Connection con;
public TimestampTest(String name) {
public TimestampTest(String name)
{
super(name);
}
protected void setUp() throws Exception {
protected void setUp() throws Exception
{
con = JDBC2Tests.openDB();
Statement stmt = con.createStatement();
JDBC2Tests.createTable(con, "testtimestamp", "ts timestamp");
}
protected void tearDown() throws Exception {
protected void tearDown() throws Exception
{
JDBC2Tests.dropTable(con, "testtimestamp");
JDBC2Tests.closeDB(con);
}
@ -36,8 +40,10 @@ public class TimestampTest extends TestCase {
/**
* Tests the time methods in ResultSet
*/
public void testGetTimestamp() {
try {
public void testGetTimestamp()
{
try
{
Statement stmt = con.createStatement();
assertEquals(1, stmt.executeUpdate(JDBC2Tests.insertSQL("testtimestamp",
@ -56,7 +62,9 @@ public class TimestampTest extends TestCase {
assertEquals(3, stmt.executeUpdate("DELETE FROM testtimestamp"));
stmt.close();
} catch(Exception ex) {
}
catch (Exception ex)
{
fail(ex.getMessage());
}
}
@ -64,8 +72,10 @@ public class TimestampTest extends TestCase {
/**
* Tests the time methods in PreparedStatement
*/
public void testSetTimestamp() {
try {
public void testSetTimestamp()
{
try
{
Statement stmt = con.createStatement();
PreparedStatement pstmt = con.prepareStatement(JDBC2Tests.insertSQL("testtimestamp", "?"));
@ -85,7 +95,9 @@ public class TimestampTest extends TestCase {
pstmt.close();
stmt.close();
} catch(Exception ex) {
}
catch (Exception ex)
{
fail(ex.getMessage());
}
}
@ -93,7 +105,8 @@ public class TimestampTest extends TestCase {
/**
* 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();
ResultSet rs;
java.sql.Timestamp t;
@ -122,7 +135,8 @@ public class TimestampTest extends TestCase {
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) + "-" +
JDBC2Tests.fix(m, 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.
*/
public class MessageTranslator {
public class MessageTranslator
{
// The singleton instance.
private static MessageTranslator instance = null;
private ResourceBundle bundle;
private MessageTranslator() {
try {
private MessageTranslator()
{
try
{
bundle = ResourceBundle.getBundle("org.postgresql.errors");
} catch(MissingResourceException e) {
}
catch (MissingResourceException e)
{
// translation files have not been installed.
bundle = null;
}
@ -24,37 +29,48 @@ public class MessageTranslator {
// Synchronized, otherwise multiple threads may perform the test and
// assign to the singleton instance simultaneously.
private synchronized final static MessageTranslator getInstance() {
if (instance == null) {
private synchronized final static MessageTranslator getInstance()
{
if (instance == null)
{
instance = new MessageTranslator();
}
return instance;
}
public final static String translate(String id, Object[] args) {
public final static String translate(String id, Object[] args)
{
MessageTranslator translator = MessageTranslator.getInstance();
return translator._translate(id, args);
}
private final String _translate(String id, Object[] args) {
private final String _translate(String id, Object[] args)
{
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
// the supplied message instead.
try {
try
{
message = bundle.getString(id);
} catch(MissingResourceException e) {
}
catch (MissingResourceException e)
{
message = id;
}
} else {
}
else
{
message = id;
}
// Expand any arguments
if (args != null && message != null) {
if (args != null && message != null)
{
message = MessageFormat.format(message, args);
}

View File

@ -5,16 +5,18 @@ import java.sql.*;
/**
* Converts to and from the postgresql bytea datatype used by the backend.
*
* $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
* 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)
return null;
int slength = s.length();
@ -23,20 +25,27 @@ public class PGbytea {
int thebyte;
char nextchar;
char secondchar;
for (int i = 0; i < slength; i++) {
for (int i = 0; i < slength; i++)
{
nextchar = s.charAt(i);
if (nextchar == '\\') {
if (nextchar == '\\')
{
secondchar = s.charAt(++i);
if (secondchar == '\\') {
if (secondchar == '\\')
{
//escaped \
buf[bufpos++] = (byte)'\\';
} else {
}
else
{
thebyte = (secondchar - 48) * 64 + (s.charAt(++i) - 48) * 8 + (s.charAt(++i) - 48);
if (thebyte > 127)
thebyte -= 256;
buf[bufpos++] = (byte)thebyte;
}
} else {
}
else
{
buf[bufpos++] = (byte)nextchar;
}
}
@ -54,27 +63,34 @@ public class PGbytea {
if (p_buf == null)
return null;
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];
if (l_int < 0) {
if (l_int < 0)
{
l_int = 256 + l_int;
}
//we escape the same non-printable characters as the backend
//we must escape all 8bit characters otherwise when convering
//from java unicode to the db character set we may end up with
//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
//the parser
l_strbuf.append("\\");
l_strbuf.append((char)(((l_int >> 6) & 0x3) + 48));
l_strbuf.append((char)(((l_int >> 3) & 0x7) + 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
//of the parser
l_strbuf.append("\\\\");
} else {
}
else
{
//other characters are left alone
l_strbuf.append((char)p_buf[i]);
}

View File

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

View File

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

View File

@ -55,7 +55,8 @@ public class PGtokenizer
// Peter 1998 Jan 6 - Added < and > to the nesting rules
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);
// increase nesting if an open character is found
@ -66,7 +67,8 @@ public class PGtokenizer
if (c == ')' || c == ']' || c == '>')
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
}
@ -74,6 +76,7 @@ public class PGtokenizer
}
// Don't forget the last token ;-)
if (s < string.length())
tokens.addElement(string.substring(s));
@ -121,8 +124,10 @@ public class PGtokenizer
*/
public static String remove(String s, String l, String t)
{
if(s.startsWith(l)) s = s.substring(l.length());
if(s.endsWith(t)) s = s.substring(0,s.length()-t.length());
if (s.startsWith(l))
s = s.substring(l.length());
if (s.endsWith(t))
s = s.substring(0, s.length() - t.length());
return s;
}
@ -133,7 +138,8 @@ public class PGtokenizer
*/
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);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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