Commit d2e27b06 authored by Bruce Momjian's avatar Bruce Momjian

pgjindent jdbc files. First time jdbc files were formatted.

parent b81844b1
......@@ -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;
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);
}
......
......@@ -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
}
}
......@@ -87,15 +90,15 @@ public class basic
// updated for 7.1
st.executeUpdate("insert into basic values (4,1)");
int insertedOID = ((org.postgresql.Statement)st).getInsertedOID();
System.out.println("Inserted row with oid "+insertedOID);
System.out.println("Inserted row with oid " + insertedOID);
// Now change the value of b from 1 to 8
st.executeUpdate("update basic set b=8");
System.out.println("Updated "+st.getUpdateCount()+" rows");
System.out.println("Updated " + st.getUpdateCount() + " rows");
// Now delete 2 rows
st.executeUpdate("delete from basic where a<3");
System.out.println("deleted "+st.getUpdateCount()+" rows");
System.out.println("deleted " + st.getUpdateCount() + " rows");
// For large inserts, a PreparedStatement is more efficient, because it
// supports the idea of precompiling the SQL statement, and to store
......@@ -107,9 +110,10 @@ public class basic
// manner. (DateStyles are PostgreSQL's way of handling different methods
// of representing dates in the Date data type.)
PreparedStatement ps = db.prepareStatement("insert into basic values (?,?)");
for(int i=2;i<5;i++) {
ps.setInt(1,4); // "column a" = 5
ps.setInt(2,i); // "column b" = 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
}
ps.close(); // Always close when we are done with it
......@@ -117,22 +121,26 @@ 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);
System.out.println(" a=" + a + " b=" + b);
}
rs.close(); // again, you must close the result when done
}
// 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,22 +152,25 @@ 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);
System.out.println(" a=" + a + " b=" + b);
}
rs.close(); // again, you must close the result when done
}
// Now test maxrows by setting it to 3 rows
st.setMaxRows(3);
System.out.println("performing a query limited to "+st.getMaxRows());
System.out.println("performing a query limited to " + st.getMaxRows());
rs = st.executeQuery("select a, b from basic");
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);
System.out.println(" a=" + a + " b=" + b);
}
rs.close(); // again, you must close the result when done
......@@ -184,19 +195,22 @@ public class basic
{
System.out.println("PostgreSQL basic test v6.3 rev 1\n");
if(args.length<3)
if (args.length < 3)
instructions();
// This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line
if(args.length>3)
if (args.length > 3)
DriverManager.setLogStream(System.err);
// Now run the tests
try {
try
{
basic test = new basic(args);
} catch(Exception ex) {
System.err.println("Exception caught.\n"+ex);
}
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace();
}
}
......
......@@ -87,7 +87,7 @@ public class blobtest
// finally delete the large object
ownapi_test3(oid);
System.out.println("\n\nOID="+oid);
System.out.println("\n\nOID=" + oid);
}
private int ownapi_test1() throws FileNotFoundException, IOException, SQLException
......@@ -97,11 +97,11 @@ public class blobtest
// Ok, test 1 is to create a large object. To do this, we use the create
// method.
System.out.println("Creating a large object");
int oid = lobj.create(LargeObjectManager.READ|LargeObjectManager.WRITE);
DriverManager.println("got large object oid="+oid);
int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE);
DriverManager.println("got large object oid=" + oid);
LargeObject obj = lobj.open(oid,LargeObjectManager.WRITE);
DriverManager.println("got large object obj="+obj);
LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE);
DriverManager.println("got large object obj=" + obj);
// Now open a test file - this class will do
System.out.println("Opening test source object");
......@@ -110,14 +110,15 @@ public class blobtest
// copy the data
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) {
System.out.println("Block size="+s+" offset="+tl);
int s, tl = 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);
tl+=s;
obj.write(buf, 0, s);
tl += s;
}
DriverManager.println("Copied "+tl+" bytes");
DriverManager.println("Copied " + tl + " bytes");
// Close the object
System.out.println("Closing object");
......@@ -131,9 +132,9 @@ public class blobtest
System.out.println("Test 2 Reading a large object and save as a file\n");
// Now open the large object
System.out.println("Opening large object "+oid);
LargeObject obj = lobj.open(oid,LargeObjectManager.READ);
DriverManager.println("got obj="+obj);
System.out.println("Opening large object " + oid);
LargeObject obj = lobj.open(oid, LargeObjectManager.READ);
DriverManager.println("got obj=" + obj);
// Now open a test file - this class will do
System.out.println("Opening test destination object");
......@@ -142,17 +143,19 @@ public class blobtest
// copy the data
System.out.println("Copying large object to file");
byte buf[] = new byte[512];
int s=obj.size();
int tl=0;
while(s>0) {
int s = obj.size();
int tl = 0;
while (s > 0)
{
int rs = buf.length;
if(s<rs) rs=s;
obj.read(buf,0,rs);
fos.write(buf,0,rs);
tl+=rs;
s-=rs;
if (s < rs)
rs = s;
obj.read(buf, 0, rs);
fos.write(buf, 0, rs);
tl += rs;
s -= rs;
}
DriverManager.println("Copied "+tl+"/"+obj.size()+" bytes");
DriverManager.println("Copied " + tl + "/" + obj.size() + " bytes");
// Close the object
System.out.println("Closing object");
......@@ -164,7 +167,7 @@ public class blobtest
System.out.println("Test 3 Deleting a large object\n");
// Now open the large object
System.out.println("Deleting large object "+oid);
System.out.println("Deleting large object " + oid);
lobj.unlink(oid);
}
......@@ -175,21 +178,23 @@ public class blobtest
System.out.println("Testing JDBC2 Blob interface:");
jdbc2api_cleanup();
System.out.println("Creating Blob on large object "+oid);
System.out.println("Creating Blob on large object " + oid);
s.executeUpdate("create table basic (a oid)");
System.out.println("Inserting row");
s.executeUpdate("insert into basic values ("+oid+")");
s.executeUpdate("insert into basic values (" + oid + ")");
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());
System.out.println("Blob.length() = " + b.length());
System.out.println("Characters 400-500:");
System.out.write(b.getBytes(400l,100));
System.out.write(b.getBytes(400l, 100));
System.out.println();
}
rs.close();
......@@ -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,21 +234,25 @@ 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);
}
// This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line
if(args.length>3)
if (args.length > 3)
DriverManager.setLogStream(System.err);
// Now run the tests
try {
try
{
blobtest test = new blobtest(args);
} catch(Exception ex) {
System.err.println("Exception caught.\n"+ex);
}
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace();
}
}
......
......@@ -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,55 +20,67 @@ 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));
// Initialize the orb
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args,null);
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
// Get a reference to the Naming Service
org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService");
if(nameServiceObj==null) {
if (nameServiceObj == null)
{
System.err.println("nameServiceObj == null");
return;
return ;
}
nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj);
if(nameService==null) {
if (nameService == null)
{
System.err.println("nameService == null");
return;
return ;
}
// Resolve the dispenser
NameComponent[] dispName = {
new NameComponent("StockDispenser","Stock")
new NameComponent("StockDispenser", "Stock")
};
dispenser = stock.StockDispenserHelper.narrow(nameService.resolve(dispName));
if(dispenser==null) {
if (dispenser == null)
{
System.err.println("dispenser == null");
return;
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() {
boolean run=true;
while(run) {
private void mainMenu()
{
boolean run = true;
while (run)
{
System.out.println("\nCORBA Stock System\n");
System.out.println(" 1 Display stock item");
System.out.println(" 2 Remove item from stock");
......@@ -96,11 +113,11 @@ public class StockClient
System.out.println(" 4 Order item");
System.out.println(" 5 Display all items");
System.out.println(" 0 Exit");
int i = getMenu("Main",5);
switch(i)
int i = getMenu("Main", 5);
switch (i)
{
case 0:
run=false;
run = false;
break;
case 1:
......@@ -126,159 +143,202 @@ public class StockClient
}
}
private void displayItem() {
try {
int id = getMenu("\nStockID to display",item.getLastID());
if(id>0) {
private void displayItem()
{
try
{
int id = getMenu("\nStockID to display", item.getLastID());
if (id > 0)
{
item.fetchItem(id);
System.out.println("========================================");
String status = "";
if(!item.isItemValid())
status=" ** Superceded **";
if (!item.isItemValid())
status = " ** Superceded **";
int av = item.getAvailable();
System.out.println(" Stock ID: "+id+status+
"\nItems Available: "+av+
"\nItems on order: "+item.getOrdered()+
"\n Description: "+item.getDescription());
System.out.println(" Stock ID: " + id + status +
"\nItems Available: " + av +
"\nItems on order: " + item.getOrdered() +
"\n Description: " + item.getDescription());
System.out.println("========================================");
if(av>0)
if(yn("Take this item out of stock?")) {
int rem=1;
if(av>1)
rem=getMenu("How many?",av);
if(rem>0)
if (av > 0)
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);
}
}
} catch(Exception e) {
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
private void bookOut() {
try {
int id = getMenu("\nStockID to take out",item.getLastID());
if(id>0) {
private void bookOut()
{
try
{
int id = getMenu("\nStockID to take out", item.getLastID());
if (id > 0)
{
item.fetchItem(id);
int av = item.getAvailable();
if(av>0)
if(yn("Take this item out of stock?")) {
int rem=1;
if(av>1)
rem=getMenu("How many?",av);
if(rem>0)
if (av > 0)
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()) {
System.out.println("You will need to order some more "+item.getDescription());
if (order > 0)
System.out.println("There are " + item.getOrdered() + " items on order.");
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
System.out.println(item.getDescription()+"\nThis item is out of stock");
} catch(Exception e) {
}
else
System.out.println(item.getDescription() + "\nThis item is out of stock");
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
// book an item into stock
private void bookIn() {
try {
int id = getMenu("\nStockID to book in",item.getLastID());
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) {
int am = getMenu("How many do you want to book in",item.getOrdered());
if(am>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 {
if(id==0)
id = getMenu("\nStockID to order",item.getLastID());
private void order(int id)
{
try
{
if (id == 0)
id = getMenu("\nStockID to order", item.getLastID());
item.fetchItem(id);
System.out.println(item.getDescription());
int am = getMenu("How many do you want to order",999);
if(am>0)
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 {
boolean cont=true;
int nr=item.getLastID();
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((cont=yn("Continue?")))
System.out.println("" + i + "\t" + item.getAvailable() + "\t" + item.getOrdered() + "\t" + item.getDescription());
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) {
int v=-1;
while(v<0 || v>max) {
private int getMenu(String title, int max)
{
int v = -1;
while (v < 0 || v > max)
{
System.out.print(title);
System.out.print(" [0-"+max+"]: ");
System.out.print(" [0-" + max + "]: ");
System.out.flush();
try {
try
{
v = Integer.parseInt(in.readLine());
} catch(Exception nfe) {
v=-1;
}
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();
if(s.startsWith("y") || s.startsWith("Y"))
if (s.startsWith("y") || s.startsWith("Y"))
return true;
if(s.startsWith("n") || s.startsWith("N"))
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);
......
......@@ -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);
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 {
ResultSet rs = st.executeQuery("select description from stock where id="+id);
if(rs!=null) {
public String getDescription() throws SQLException
{
ResultSet rs = st.executeQuery("select description from stock where id=" + id);
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 {
ResultSet rs = st.executeQuery("select avail from stock where id="+id);
if(rs!=null) {
public int getAvailable() throws SQLException
{
ResultSet rs = st.executeQuery("select avail from stock where id=" + id);
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 {
ResultSet rs = st.executeQuery("select ordered from stock where id="+id);
if(rs!=null) {
public int getOrdered() throws SQLException
{
ResultSet rs = st.executeQuery("select ordered from stock where id=" + id);
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 {
ResultSet rs = st.executeQuery("select valid from stock where id="+id);
if(rs!=null) {
public boolean isItemValid() throws SQLException
{
ResultSet rs = st.executeQuery("select valid from stock where id=" + id);
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 {
st.executeUpdate("update stock set avail=avail+"+amount+
", ordered=ordered-"+amount+
" where id="+id+" and ordered>="+amount);
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 {
st.executeUpdate("update stock set avail=avail-"+amount+
" where id="+id);
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 {
st.executeUpdate("update stock set ordered=ordered+"+amount+
" where id="+id);
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();
......
......@@ -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
{
......@@ -13,24 +13,28 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
private int numObjects = 0;
private StockItemStatus[] stock = new StockItemStatus[maxObjects];
public StockDispenserImpl(String[] args,String name,int num)
public StockDispenserImpl(String[] args, String name, int num)
{
super();
try {
try
{
// get reference to orb
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args,null);
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
// prestart num objects
if(num>=maxObjects)
num=maxObjects;
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));
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,10 +44,12 @@ 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);
System.out.println("Reserving slot " + i);
return stock[i].ref;
}
}
......@@ -55,15 +61,17 @@ 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;
System.out.println("Releasing slot " + i);
return ;
}
}
System.out.println("Reserved object not a member of this dispenser");
return;
return ;
}
/**
......@@ -74,7 +82,8 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
StockItemImpl ref;
boolean inUse;
StockItemStatus() {
StockItemStatus()
{
ref = null;
inUse = false;
}
......
......@@ -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 {
db =new StockDB();
db.connect(args[1],args[2],args[3]);
System.out.println("StockDB object "+iname+" created");
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;
}
}
......
......@@ -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,38 +13,43 @@ public class StockServer
{
int numInstances = 3;
try {
try
{
// Initialise the ORB
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args,null);
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
// Create the StockDispenser object
StockDispenserImpl dispenser = new StockDispenserImpl(args,"Stock Dispenser",numInstances);
StockDispenserImpl dispenser = new StockDispenserImpl(args, "Stock Dispenser", numInstances);
// Export the new object
orb.connect(dispenser);
// 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;
return ;
}
org.omg.CosNaming.NamingContext nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj);
if(nameService == null) {
if (nameService == null)
{
System.err.println("nameService = null");
return;
return ;
}
// bind the dispenser into the naming service
NameComponent[] dispenserName = {
new NameComponent("StockDispenser","Stock")
new NameComponent("StockDispenser", "Stock")
};
nameService.rebind(dispenserName,dispenser);
nameService.rebind(dispenserName, dispenser);
// Now wait forever for the current thread to die
Thread.currentThread().join();
} catch(Exception e) {
}
catch (Exception e)
{
e.printStackTrace();
}
}
......
......@@ -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
}
}
......@@ -91,7 +94,7 @@ public class datestyle
//
// NB: January = 0 here
//
standard = new java.sql.Date(98,0,8);
standard = new java.sql.Date(98, 0, 8);
// Now store the result.
//
......@@ -99,7 +102,7 @@ public class datestyle
// The only way of doing this is by using a PreparedStatement.
//
PreparedStatement ps = db.prepareStatement("insert into datestyle values (?)");
ps.setDate(1,standard);
ps.setDate(1, standard);
ps.executeUpdate();
ps.close();
......@@ -112,12 +115,13 @@ public class datestyle
{
System.out.println("\nRunning tests:");
for(int i=0;i<styles.length;i++) {
System.out.print("Test "+i+" - "+styles[i]);
for (int i = 0;i < styles.length;i++)
{
System.out.print("Test " + i + " - " + styles[i]);
System.out.flush();
// set the style
st.executeUpdate("set datestyle='"+styles[i]+"'");
st.executeUpdate("set datestyle='" + styles[i] + "'");
// Now because the driver needs to know what the current style is,
// we have to run the following:
......@@ -129,17 +133,18 @@ public class datestyle
// Throw an exception if there is no result (if the table is empty
// there should still be a result).
if(rs==null)
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.
if(standard.equals(rs.getDate(1)))
System.out.println(" passed, returned "+rs.getString(1));
if (standard.equals(rs.getDate(1)))
System.out.println(" passed, returned " + rs.getString(1));
else
System.out.println(" failed, returned "+rs.getString(1));
System.out.println(" failed, returned " + rs.getString(1));
}
rs.close();
}
......@@ -162,19 +167,22 @@ public class datestyle
{
System.out.println("PostgreSQL datestyle test v6.3 rev 1\n");
if(args.length<3)
if (args.length < 3)
instructions();
// This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line
if(args.length>3)
if (args.length > 3)
DriverManager.setLogStream(System.err);
// Now run the tests
try {
try
{
datestyle test = new datestyle(args);
} catch(Exception ex) {
System.err.println("Exception caught.\n"+ex);
}
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace();
}
}
......
......@@ -22,32 +22,33 @@ public class metadata
/**
* These are the available tests on DatabaseMetaData
*/
public void doDatabaseMetaData() throws SQLException {
if(doTest("getProcedures() - should show all available procedures"))
displayResult(dbmd.getProcedures(null,null,null));
public void doDatabaseMetaData() throws SQLException
{
if (doTest("getProcedures() - should show all available procedures"))
displayResult(dbmd.getProcedures(null, null, null));
if(doTest("getProcedures() with pattern - should show all circle procedures"))
displayResult(dbmd.getProcedures(null,null,"circle%"));
if (doTest("getProcedures() with pattern - should show all circle procedures"))
displayResult(dbmd.getProcedures(null, null, "circle%"));
if(doTest("getProcedureColumns() on circle procedures"))
displayResult(dbmd.getProcedureColumns(null,null,"circle%",null));
if (doTest("getProcedureColumns() on circle procedures"))
displayResult(dbmd.getProcedureColumns(null, null, "circle%", null));
if(doTest("getTables()"))
displayResult(dbmd.getTables(null,null,null,null));
if (doTest("getTables()"))
displayResult(dbmd.getTables(null, null, null, null));
if(doTest("getColumns() - should show all tables, can take a while to run"))
displayResult(dbmd.getColumns(null,null,null,null));
if (doTest("getColumns() - should show all tables, can take a while to run"))
displayResult(dbmd.getColumns(null, null, null, null));
if(doTest("getColumns() - should show the test_b table"))
displayResult(dbmd.getColumns(null,null,"test_b",null));
if (doTest("getColumns() - should show the test_b table"))
displayResult(dbmd.getColumns(null, null, "test_b", null));
if(doTest("getColumnPrivileges() - should show all tables"))
displayResult(dbmd.getColumnPrivileges(null,null,null,null));
if (doTest("getColumnPrivileges() - should show all tables"))
displayResult(dbmd.getColumnPrivileges(null, null, null, null));
if(doTest("getPrimaryKeys()"))
displayResult(dbmd.getPrimaryKeys(null,null,null));
if (doTest("getPrimaryKeys()"))
displayResult(dbmd.getPrimaryKeys(null, null, null));
if(doTest("getTypeInfo()"))
if (doTest("getTypeInfo()"))
displayResult(dbmd.getTypeInfo());
}
......@@ -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";
......@@ -63,24 +65,27 @@ public class metadata
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
if(doTest("isCurrency()"))
System.out.println("isCurrency on col 1 = "+rsmd.isCurrency(1)+" should be false\nisCurrency on col 4 = "+rsmd.isCurrency(4)+" should be true");
if (doTest("isCurrency()"))
System.out.println("isCurrency on col 1 = " + rsmd.isCurrency(1) + " should be false\nisCurrency on col 4 = " + rsmd.isCurrency(4) + " should be true");
// Finally close the query. Now give the user a chance to display the
// ResultSet.
//
// NB: displayResult() actually closes the ResultSet.
if(doTest("Display query result")) {
System.out.println("Query: "+sql);
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
}
}
......@@ -123,17 +132,17 @@ public class metadata
st = db.createStatement();
// This prints the backend's version
System.out.println("Connected to "+dbmd.getDatabaseProductName()+" "+dbmd.getDatabaseProductVersion());
System.out.println("Connected to " + dbmd.getDatabaseProductName() + " " + dbmd.getDatabaseProductVersion());
init();
System.out.println();
// Now the tests
if(doTest("Test DatabaseMetaData"))
if (doTest("Test DatabaseMetaData"))
doDatabaseMetaData();
if(doTest("Test ResultSetMetaData"))
if (doTest("Test ResultSetMetaData"))
doResultSetMetaData();
System.out.println("\nNow closing the connection");
......@@ -146,21 +155,26 @@ 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')) {
c=(char)System.in.read();
try
{
while (!(c == 'n' || c == 'y' || c == 'N' || c == 'Y'))
{
c = (char)System.in.read();
}
}
} catch(IOException ioe) {
catch (IOException ioe)
{
return false;
}
return c=='y' || c=='Y';
return c == 'y' || c == 'Y';
}
/**
......@@ -170,26 +184,28 @@ public class metadata
public void displayResult(ResultSet rs) throws SQLException
{
ResultSetMetaData rsmd = rs.getMetaData();
int count=0;
int count = 0;
// Print the result column names
int cols = rsmd.getColumnCount();
for(int i=1;i<=cols;i++)
System.out.print(rsmd.getColumnLabel(i)+(i<cols?"\t":"\n"));
for (int i = 1;i <= cols;i++)
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"));
if (rs.wasNull())
System.out.print("{null}" + (i < cols ? "\t" : "\n"));
else
System.out.print(o.toString()+(i<cols?"\t":"\n"));
System.out.print(o.toString() + (i < cols ? "\t" : "\n"));
}
}
System.out.println("Result returned "+count+" rows.");
System.out.println("Result returned " + count + " rows.");
// finally close the result set
rs.close();
......@@ -200,43 +216,48 @@ 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 {
String table = line.substring(3);
displayResult(dbmd.getColumns(null, null, table, "%"));
}
else
{
String types[] = null;
if(line.equals("\\d"))
types=allUserTables;
else if(line.equals("\\di"))
types=usrIndices;
else if(line.equals("\\dt"))
types=usrTables;
else if(line.equals("\\ds"))
types=usrSequences;
else if(line.equals("\\dS"))
types=sysTables;
if (line.equals("\\d"))
types = allUserTables;
else if (line.equals("\\di"))
types = usrIndices;
else if (line.equals("\\dt"))
types = usrTables;
else if (line.equals("\\ds"))
types = usrSequences;
else if (line.equals("\\dS"))
types = sysTables;
else
throw new SQLException("Unsupported \\d command: "+line);
throw new SQLException("Unsupported \\d command: " + line);
// Display details about all system tables
//
// Note: the first two arguments are ignored. To keep to the spec,
// you must put null here
//
displayResult(dbmd.getTables(null,null,"%",types));
displayResult(dbmd.getTables(null, null, "%", types));
}
}
} else
throw new SQLException("Unsupported \\ command: "+line);
else
throw new SQLException("Unsupported \\ command: " + line);
}
private static final String allUserTables[] = {"TABLE","INDEX","SEQUENCE"};
private static final String allUserTables[] = {"TABLE", "INDEX", "SEQUENCE"};
private static final String usrIndices[] = {"INDEX"};
private static final String usrTables[] = {"TABLE"};
private static final String usrSequences[] = {"SEQUENCE"};
private static final String sysTables[] = {"SYSTEM TABLE","SYSTEM INDEX"};
private static final String sysTables[] = {"SYSTEM TABLE", "SYSTEM INDEX"};
/**
* Display some instructions on how to run the example
......@@ -255,19 +276,22 @@ public class metadata
{
System.out.println("PostgreSQL metdata tester v6.4 rev 1\n");
if(args.length<3)
if (args.length < 3)
instructions();
// This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line
if(args.length>3)
if (args.length > 3)
DriverManager.setLogStream(System.err);
// Now run the tests
try {
try
{
metadata test = new metadata(args);
} catch(Exception ex) {
System.err.println("Exception caught.\n"+ex);
}
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace();
}
}
......
......@@ -34,7 +34,7 @@ public class psql
st = db.createStatement();
// This prints the backend's version
System.out.println("Connected to "+dbmd.getDatabaseProductName()+" "+dbmd.getDatabaseProductVersion());
System.out.println("Connected to " + dbmd.getDatabaseProductName() + " " + dbmd.getDatabaseProductVersion());
System.out.println();
......@@ -43,23 +43,28 @@ public class psql
input.resetSyntax();
input.slashSlashComments(true); // allow // as a comment delimiter
input.eolIsSignificant(false); // treat eol's as spaces
input.wordChars(32,126);
input.whitespaceChars(59,59);
input.wordChars(32, 126);
input.whitespaceChars(59, 59);
// input.quoteChar(39); *** CWJ: messes up literals in query string ***
// Now the main loop.
int tt=0,lineno=1;
while(tt!=StreamTokenizer.TT_EOF && ! done) { // done added by CWJ to permit \q command
System.out.print("["+lineno+"] ");
int tt = 0, lineno = 1;
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,31 +80,39 @@ public class psql
*/
public void processLine(String line) throws SQLException
{
if(line.startsWith("\\")) {
if (line.startsWith("\\"))
{
processSlashCommand(line);
return;
return ;
}
boolean type = st.execute(line);
boolean loop=true;
while(loop) {
if(type) {
boolean loop = true;
while (loop)
{
if (type)
{
// A ResultSet was returned
ResultSet rs=st.getResultSet();
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 {
loop = false;
}
else
{
// An update count was returned
System.out.println("Updated "+st.getUpdateCount()+" rows");
System.out.println("Updated " + st.getUpdateCount() + " rows");
}
}
if(loop)
if (loop)
type = st.getMoreResults();
}
}
......@@ -114,17 +127,19 @@ public class psql
// Print the result column names
int cols = rsmd.getColumnCount();
for(int i=1;i<=cols;i++)
System.out.print(rsmd.getColumnLabel(i)+(i<cols?"\t":"\n"));
for (int i = 1;i <= cols;i++)
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"));
if (rs.wasNull())
System.out.print("{null}" + (i < cols ? "\t" : "\n"));
else
System.out.print(o.toString()+(i<cols?"\t":"\n"));
System.out.print(o.toString() + (i < cols ? "\t" : "\n"));
}
}
......@@ -137,45 +152,50 @@ public class psql
*/
public void processSlashCommand(String line) throws SQLException
{
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 {
String table = line.substring(3);
displayResult(dbmd.getColumns(null, null, table, "%"));
}
else
{
String types[] = null;
if(line.equals("\\d"))
types=allUserTables;
else if(line.equals("\\di"))
types=usrIndices;
else if(line.equals("\\dt"))
types=usrTables;
else if(line.equals("\\ds"))
types=usrSequences;
else if(line.equals("\\dS"))
types=sysTables;
if (line.equals("\\d"))
types = allUserTables;
else if (line.equals("\\di"))
types = usrIndices;
else if (line.equals("\\dt"))
types = usrTables;
else if (line.equals("\\ds"))
types = usrSequences;
else if (line.equals("\\dS"))
types = sysTables;
else
throw new SQLException("Unsupported \\d command: "+line);
throw new SQLException("Unsupported \\d command: " + line);
// Display details about all system tables
//
// Note: the first two arguments are ignored. To keep to the spec,
// you must put null here
//
displayResult(dbmd.getTables(null,null,"%",types));
displayResult(dbmd.getTables(null, null, "%", types));
}
}
} else if(line.equals("\\q")) // Added by CWJ to permit \q command
else if (line.equals("\\q")) // Added by CWJ to permit \q command
done = true;
else
throw new SQLException("Unsupported \\ command: "+line);
throw new SQLException("Unsupported \\ command: " + line);
}
private static final String allUserTables[] = {"TABLE","INDEX","SEQUENCE"};
private static final String allUserTables[] = {"TABLE", "INDEX", "SEQUENCE"};
private static final String usrIndices[] = {"INDEX"};
private static final String usrTables[] = {"TABLE"};
private static final String usrSequences[] = {"SEQUENCE"};
private static final String sysTables[] = {"SYSTEM TABLE","SYSTEM INDEX"};
private static final String sysTables[] = {"SYSTEM TABLE", "SYSTEM INDEX"};
/**
* Display some instructions on how to run the example
......@@ -194,19 +214,22 @@ public class psql
{
System.out.println("PostgreSQL psql example v6.3 rev 1\n");
if(args.length<3)
if (args.length < 3)
instructions();
// This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line
if(args.length>3)
if (args.length > 3)
DriverManager.setLogStream(System.err);
// Now run the tests
try {
try
{
psql test = new psql(args);
} catch(Exception ex) {
System.err.println("Exception caught.\n"+ex);
}
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace();
}
}
......
This diff is collapsed.
......@@ -28,7 +28,7 @@ public class Field
* @param oid the OID of the field
* @param len the length of the field
*/
public Field(Connection conn, String name, int oid, int length,int mod)
public Field(Connection conn, String name, int oid, int length, int mod)
{
this.conn = conn;
this.name = name;
......@@ -47,7 +47,7 @@ public class Field
*/
public Field(Connection conn, String name, int oid, int length)
{
this(conn,name,oid,length,0);
this(conn, name, oid, length, 0);
}
/**
......
......@@ -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.
......@@ -100,7 +100,7 @@ public class PG_Stream
*/
public void Send(byte buf[], int siz) throws IOException
{
Send(buf,0,siz);
Send(buf, 0, siz);
}
/**
......@@ -116,10 +116,10 @@ public class PG_Stream
{
int i;
pg_output.write(buf, off, ((buf.length-off) < siz ? (buf.length-off) : siz));
if((buf.length-off) < siz)
pg_output.write(buf, off, ((buf.length - off) < siz ? (buf.length - off) : siz));
if ((buf.length - off) < siz)
{
for (i = buf.length-off ; i < siz ; ++i)
for (i = buf.length - off ; i < siz ; ++i)
{
pg_output.write(0);
}
......@@ -139,9 +139,12 @@ public class PG_Stream
try
{
c = pg_input.read();
if (c < 0) throw new PSQLException("postgresql.stream.eof");
} catch (IOException e) {
throw new PSQLException("postgresql.stream.ioerror",e);
if (c < 0)
throw new PSQLException("postgresql.stream.eof");
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
}
return c;
}
......@@ -167,8 +170,10 @@ public class PG_Stream
throw new PSQLException("postgresql.stream.eof");
n = n | (b << (8 * i)) ;
}
} catch (IOException e) {
throw new PSQLException("postgresql.stream.ioerror",e);
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
}
return n;
}
......@@ -194,8 +199,10 @@ public class PG_Stream
throw new PSQLException("postgresql.stream.eof");
n = b | (n << 8);
}
} catch (IOException e) {
throw new PSQLException("postgresql.stream.ioerror",e);
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
}
return n;
}
......@@ -213,31 +220,40 @@ 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
buflen = (int)(buflen*2); // 100% bigger
if (s >= buflen)
{ // Grow the buffer
buflen = (int)(buflen * 2); // 100% bigger
byte[] newrst = new byte[buflen];
System.arraycopy(rst, 0, newrst, 0, s);
rst = newrst;
}
}
}
} catch (IOException e) {
throw new PSQLException("postgresql.stream.ioerror",e);
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
}
return encoding.decode(rst, 0, s);
}
......@@ -254,7 +270,7 @@ public class PG_Stream
*/
public byte[][] ReceiveTuple(int nf, boolean bin) throws SQLException
{
int i, bim = (nf + 7)/8;
int i, bim = (nf + 7) / 8;
byte[] bitmask = Receive(bim);
byte[][] answer = bytePoolDim2.allocByte(nf);
......@@ -295,7 +311,7 @@ public class PG_Stream
private byte[] Receive(int siz) throws SQLException
{
byte[] answer = bytePoolDim1.allocByte(siz);
Receive(answer,0,siz);
Receive(answer, 0, siz);
return answer;
}
......@@ -307,7 +323,7 @@ public class PG_Stream
* @param siz number of bytes to read
* @exception SQLException if a data I/O error occurs
*/
public void Receive(byte[] b,int off,int siz) throws SQLException
public void Receive(byte[] b, int off, int siz) throws SQLException
{
int s = 0;
......@@ -315,13 +331,15 @@ public class PG_Stream
{
while (s < siz)
{
int w = pg_input.read(b, off+s, siz - s);
int w = pg_input.read(b, off + s, siz - s);
if (w < 0)
throw new PSQLException("postgresql.stream.eof");
s += w;
}
} catch (IOException e) {
throw new PSQLException("postgresql.stream.ioerror",e);
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
}
}
......@@ -332,10 +350,13 @@ public class PG_Stream
*/
public void flush() throws SQLException
{
try {
try
{
pg_output.flush();
} catch (IOException e) {
throw new PSQLException("postgresql.stream.flush",e);
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.flush", e);
}
}
......
/**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Exoffice Technologies. For written permission,
* please contact info@exolab.org.
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Exoffice Technologies. Exolab is a registered
* trademark of Exoffice Technologies.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.exolab.org/).
*
* THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved.
*
* $Id: PostgresqlDataSource.java,v 1.2 2000/11/10 22:06:26 momjian Exp $
*/
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Exoffice Technologies. For written permission,
* please contact info@exolab.org.
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Exoffice Technologies. Exolab is a registered
* trademark of Exoffice Technologies.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.exolab.org/).
*
* THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved.
*
* $Id: PostgresqlDataSource.java,v 1.3 2001/10/25 05:59:59 momjian Exp $
*/
package org.postgresql;
......@@ -194,10 +194,10 @@ public class PostgresqlDataSource
* Each datasource maintains it's own driver, in case of
* driver-specific setup (e.g. pools, log writer).
*/
// FIXME
// private transient postgresql.Driver _driver;
private transient org.postgresql.Driver _driver;
//---------
// FIXME
// private transient postgresql.Driver _driver;
private transient org.postgresql.Driver _driver;
//---------
......@@ -223,21 +223,25 @@ 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.
// FIXME
// _driver = new postgresql.Driver();
_driver = new org.postgresql.Driver();
//-----------
//FIXME
// _driver.setLogWriter( _logWriter );
// Method seems to be unavailable. Just commented it out.
//----------
} catch ( SQLException except ) {
// FIXME
// _driver = new postgresql.Driver();
_driver = new org.postgresql.Driver();
//-----------
//FIXME
// _driver.setLogWriter( _logWriter );
// Method seems to be unavailable. Just commented it out.
//----------
}
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 ) ) {
//--------
// FIXME
// if ( ! ( conn instanceof 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,12 +311,13 @@ 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 );
// Method seems to be unavailable. Commented it out.
//----------
// FIXME
// _driver.setLogWriter( writer );
// Method seems to be unavailable. Commented it out.
//----------
_logWriter = 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;
......
......@@ -42,7 +42,7 @@ public abstract class ResultSet
* @param updateCount the number of rows affected by the operation
* @param cursor the positioned update/delete cursor name
*/
public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount,int insertOID, boolean binaryCursor)
public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount, int insertOID, boolean binaryCursor)
{
this.connection = conn;
this.fields = fields;
......@@ -69,7 +69,7 @@ public abstract class ResultSet
*/
public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount)
{
this(conn,fields,tuples,status,updateCount,0,false);
this(conn, fields, tuples, status, updateCount, 0, false);
}
/**
......@@ -166,7 +166,7 @@ public abstract class ResultSet
*/
public int getColumnOID(int field)
{
return fields[field-1].getOID();
return fields[field -1].getOID();
}
/**
......@@ -190,20 +190,23 @@ 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
wasNullFlag = (this_row[col - 1] == null);
if(wasNullFlag)
if (wasNullFlag)
return null;
// Handle Money
if(s.charAt(0)=='(') {
s="-"+org.postgresql.util.PGtokenizer.removePara(s).substring(1);
if (s.charAt(0) == '(')
{
s = "-" + org.postgresql.util.PGtokenizer.removePara(s).substring(1);
}
if(s.charAt(0)=='$') {
s=s.substring(1);
if (s.charAt(0) == '$')
{
s = s.substring(1);
}
return s;
......
......@@ -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;
......@@ -42,11 +43,11 @@ public abstract class Statement {
// Static variables for parsing SQL when escapeProcessing is true.
private static final short IN_SQLCODE = 0;
private static final short IN_STRING = 1;
private static final short BACKSLASH =2;
private static final short BACKSLASH = 2;
private static final short ESC_TIMEDATE = 3;
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,10 +234,11 @@ 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)
if (rs != null)
rs.close();
// Disasociate it from us (For Garbage Collection)
......@@ -249,28 +264,28 @@ public abstract class Statement {
int i = -1;
int len = sql.length();
while(++i < len)
while (++i < len)
{
char c = sql.charAt(i);
switch(state)
switch (state)
{
case IN_SQLCODE:
if(c == '\'') // start of a string?
if (c == '\'') // start of a string?
state = IN_STRING;
else if(c == '{') // start of an escape code?
if(i+1 < len)
else if (c == '{') // start of an escape code?
if (i + 1 < len)
{
char next = sql.charAt(i+1);
if(next == 'd')
char next = sql.charAt(i + 1);
if (next == 'd')
{
state = ESC_TIMEDATE;
i++;
break;
}
else if(next == 't')
else if (next == 't')
{
state = ESC_TIMEDATE;
i += (i+2 < len && sql.charAt(i+2) == 's') ? 2 : 1;
i += (i + 2 < len && sql.charAt(i + 2) == 's') ? 2 : 1;
break;
}
}
......@@ -278,9 +293,9 @@ public abstract class Statement {
break;
case IN_STRING:
if(c == '\'') // end of string?
if (c == '\'') // end of string?
state = IN_SQLCODE;
else if(c == '\\') // a backslash?
else if (c == '\\') // a backslash?
state = BACKSLASH;
newsql.append(c);
......@@ -293,7 +308,7 @@ public abstract class Statement {
break;
case ESC_TIMEDATE:
if(c == '}')
if (c == '}')
state = IN_SQLCODE; // end of escape code.
else
newsql.append(c);
......
......@@ -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.
......@@ -13,21 +14,23 @@ public class BytePoolDim1 {
/**
* The pools not currently in use
*/
ObjectPool notusemap[] = new ObjectPool[maxsize+1];
ObjectPool notusemap[] = new ObjectPool[maxsize + 1];
/**
* The pools currently in use
*/
ObjectPool inusemap[] = new ObjectPool[maxsize+1];
ObjectPool inusemap[] = new ObjectPool[maxsize + 1];
/**
*
*/
byte binit[][] = new byte[maxsize+1][0];
byte binit[][] = new byte[maxsize + 1][0];
/**
* Construct a new pool
*/
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,10 +73,11 @@ 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;
if (b.length > maxsize)
return ;
ObjectPool not_usel = notusemap[b.length];
ObjectPool in_usel = inusemap[b.length];
......@@ -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();
......
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];
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,9 +38,11 @@ public class BytePoolDim2 {
*/
}
public void release(byte[][] b){
if(b.length > maxsize){
return;
public void release(byte[][] b)
{
if (b.length > maxsize)
{
return ;
}
ObjectPool not_usel = notusemap[b.length];
ObjectPool in_usel = inusemap[b.length];
......@@ -52,7 +58,8 @@ public class BytePoolDim2 {
* code to use some form of Statement context, so the buffers are per
* 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();
......
......@@ -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;
}
}
......
......@@ -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
......
......@@ -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
......
......@@ -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);
......
......@@ -21,8 +21,9 @@ public class SimpleObjectPool implements ObjectPool
*/
public void add(Object o)
{
if(cursize >= maxsize){
Object newarr[] = new Object[maxsize*2];
if (cursize >= maxsize)
{
Object newarr[] = new Object[maxsize * 2];
System.arraycopy(arr, 0, newarr, 0, maxsize);
maxsize = maxsize * 2;
arr = newarr;
......@@ -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,13 +44,15 @@ public class SimpleObjectPool implements ObjectPool
* Removes the given object from the pool
* @param o Object to remove
*/
public void remove(Object o) {
int p=0;
while(p<cursize && !arr[p].equals(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);
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,15 +77,17 @@ 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;
if (srcsize == 0)
return ;
int totalsize = srcsize + cursize;
if(totalsize > maxsize){
Object newarr[] = new Object[totalsize*2];
if (totalsize > maxsize)
{
Object newarr[] = new Object[totalsize * 2];
System.arraycopy(arr, 0, newarr, 0, cursize);
maxsize = maxsize = totalsize * 2;
arr = newarr;
......@@ -91,7 +99,8 @@ public class SimpleObjectPool implements ObjectPool
/**
* Clears the pool of all objects
*/
public void clear(){
public void clear()
{
cursize = 0;
}
}
......@@ -40,10 +40,10 @@ public class Fastpath
* @param conn org.postgresql.Connection to attach to
* @param stream The network stream to the backend
*/
public Fastpath(org.postgresql.Connection conn,org.postgresql.PG_Stream stream)
public Fastpath(org.postgresql.Connection conn, org.postgresql.PG_Stream stream)
{
this.conn=conn;
this.stream=stream;
this.conn = conn;
this.stream = stream;
//DriverManager.println("Fastpath initialised");
}
......@@ -56,29 +56,33 @@ public class Fastpath
* @return null if no data, Integer if an integer result, or byte[] otherwise
* @exception SQLException if a database-access error occurs.
*/
public Object fastpath(int fnid,boolean resulttype,FastpathArg[] args) throws SQLException
public Object fastpath(int fnid, boolean resulttype, FastpathArg[] args) throws SQLException
{
// added Oct 7 1998 to give us thread safety
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);
stream.SendInteger(0,1);
stream.SendInteger(70, 1);
stream.SendInteger(0, 1);
stream.SendInteger(fnid,4);
stream.SendInteger(args.length,4);
stream.SendInteger(fnid, 4);
stream.SendInteger(args.length, 4);
for(int i=0;i<args.length;i++)
for (int i = 0;i < args.length;i++)
args[i].send(stream);
// This is needed, otherwise data can be lost
stream.flush();
} catch(IOException ioe) {
throw new PSQLException("postgresql.fp.send",new Integer(fnid),ioe);
}
catch (IOException ioe)
{
throw new PSQLException("postgresql.fp.send", new Integer(fnid), ioe);
}
// Now handle the result
......@@ -95,10 +99,11 @@ 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)
switch (in)
{
case 'V':
break;
......@@ -111,11 +116,12 @@ public class Fastpath
//DriverManager.println("G: size="+sz); //debug
// Return an Integer if
if(resulttype)
if (resulttype)
result = new Integer(stream.ReceiveIntegerR(sz));
else {
else
{
byte buf[] = new byte[sz];
stream.Receive(buf,0,sz);
stream.Receive(buf, 0, sz);
result = buf;
}
break;
......@@ -123,7 +129,7 @@ public class Fastpath
//------------------------------
// Error message returned
case 'E':
throw new PSQLException("postgresql.fp.error",stream.ReceiveString(conn.getEncoding()));
throw new PSQLException("postgresql.fp.error", stream.ReceiveString(conn.getEncoding()));
//------------------------------
// Notice from backend
......@@ -144,7 +150,7 @@ public class Fastpath
break;
default:
throw new PSQLException("postgresql.fp.protocol",new Character((char)in));
throw new PSQLException("postgresql.fp.protocol", new Character((char)in));
}
}
}
......@@ -170,10 +176,10 @@ public class Fastpath
* occurs.
* @see org.postgresql.LargeObject
*/
public Object fastpath(String name,boolean resulttype,FastpathArg[] args) throws SQLException
public Object fastpath(String name, boolean resulttype, FastpathArg[] args) throws SQLException
{
//DriverManager.println("Fastpath: calling "+name);
return fastpath(getID(name),resulttype,args);
return fastpath(getID(name), resulttype, args);
}
/**
......@@ -183,11 +189,11 @@ public class Fastpath
* @return integer result
* @exception SQLException if a database-access error occurs or no result
*/
public int getInteger(String name,FastpathArg[] args) throws SQLException
public int getInteger(String name, FastpathArg[] args) throws SQLException
{
Integer i = (Integer)fastpath(name,true,args);
if(i==null)
throw new PSQLException("postgresql.fp.expint",name);
Integer i = (Integer)fastpath(name, true, args);
if (i == null)
throw new PSQLException("postgresql.fp.expint", name);
return i.intValue();
}
......@@ -198,9 +204,9 @@ public class Fastpath
* @return byte[] array containing result
* @exception SQLException if a database-access error occurs or no result
*/
public byte[] getData(String name,FastpathArg[] args) throws SQLException
public byte[] getData(String name, FastpathArg[] args) throws SQLException
{
return (byte[])fastpath(name,false,args);
return (byte[])fastpath(name, false, args);
}
/**
......@@ -214,9 +220,9 @@ public class Fastpath
* @param name Function name
* @param fnid Function id
*/
public void addFunction(String name,int fnid)
public void addFunction(String name, int fnid)
{
func.put(name,new Integer(fnid));
func.put(name, new Integer(fnid));
}
/**
......@@ -253,8 +259,9 @@ public class Fastpath
*/
public void addFunctions(ResultSet rs) throws SQLException
{
while(rs.next()) {
func.put(rs.getString(1),new Integer(rs.getInt(2)));
while (rs.next())
{
func.put(rs.getString(1), new Integer(rs.getInt(2)));
}
}
......@@ -279,8 +286,8 @@ public class Fastpath
//
// so, until we know we can do this (needs testing, on the TODO list)
// for now, we throw the exception and do no lookups.
if(id==null)
throw new PSQLException("postgresql.fp.unknown",name);
if (id == null)
throw new PSQLException("postgresql.fp.unknown", name);
return id.intValue();
}
......
......@@ -43,8 +43,8 @@ public class FastpathArg
*/
public FastpathArg(int value)
{
type=true;
this.value=value;
type = true;
this.value = value;
}
/**
......@@ -53,8 +53,8 @@ public class FastpathArg
*/
public FastpathArg(byte bytes[])
{
type=false;
this.bytes=bytes;
type = false;
this.bytes = bytes;
}
/**
......@@ -63,11 +63,11 @@ public class FastpathArg
* @param off offset within array
* @param len length of data to include
*/
public FastpathArg(byte buf[],int off,int len)
public FastpathArg(byte buf[], int off, int len)
{
type=false;
type = false;
bytes = new byte[len];
System.arraycopy(buf,off,bytes,0,len);
System.arraycopy(buf, off, bytes, 0, len);
}
/**
......@@ -92,13 +92,16 @@ public class FastpathArg
*/
protected void send(org.postgresql.PG_Stream s) throws IOException
{
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 {
s.SendInteger(4, 4); // size of an integer
s.SendInteger(value, 4); // integer value of argument
}
else
{
// argument is a byte array
s.SendInteger(bytes.length,4); // size of array
s.SendInteger(bytes.length, 4); // size of array
s.Send(bytes);
}
}
......
......@@ -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();
}
......
......@@ -7,23 +7,26 @@ 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);
Object[] argv = new Object[2];
argv[0] = arg1;
argv[1] = arg2;
translate(error,argv);
translate(error, argv);
}
private void translate(String error, Object[] args) {
message = MessageTranslator.translate(error,args);
private void translate(String error, Object[] args)
{
message = MessageTranslator.translate(error, args);
}
// Overides Throwable
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment