Revision 20029

View differences:

trunk/libraries/libDataSourceDBBaseDrivers/.classpath
7 7
	<classpathentry kind="lib" path="/libDataSource/lib/org.gvsig.exceptions.jar"/>
8 8
	<classpathentry kind="lib" path="/_fwAndami/lib/iver-utiles.jar" sourcepath="/libIverUtiles"/>
9 9
	<classpathentry kind="lib" path="/libFMap/lib/jts-1.8.jar" sourcepath="C:/JTS1.8/src"/>
10
	<classpathentry kind="lib" path="lib/postgis-jdbc-driver.jar"/>
11
	<classpathentry kind="lib" path="lib/postgresql-74.213.jar"/>
10
	<classpathentry kind="lib" path="lib/postgis_1.3.2.jar"/>
11
	<classpathentry kind="lib" path="lib/postgresql-8.3-603.jdbc3.jar"/>
12 12
	<classpathentry kind="src" output="bin-test" path="src-test"/>
13 13
	<classpathentry kind="var" path="JUNIT_HOME/junit.jar"/>
14 14
	<classpathentry combineaccessrules="false" kind="src" path="/libDataSourceBaseDrivers"/>
trunk/libraries/libDataSourceDBBaseDrivers/src-test/org/gvsig/data/datastores/vectorial/db/jdbc/postgresql/postgresqlTest.java
1 1
package org.gvsig.data.datastores.vectorial.db.jdbc.postgresql;
2 2

  
3
import java.sql.Connection;
4
import java.sql.DriverManager;
5
import java.sql.SQLException;
6
import java.sql.Statement;
3 7
import java.util.Iterator;
4 8
import java.util.NoSuchElementException;
5 9

  
6 10
import org.gvsig.data.DataManager;
7 11
import org.gvsig.data.datastores.vectorial.db.jdbc.JDBCTest;
12
import org.gvsig.data.datastores.vectorial.db.jdbc.exception.JDBCDriverNotFoundException;
8 13
import org.gvsig.data.exception.CloseException;
9 14
import org.gvsig.data.exception.InitializeException;
10 15
import org.gvsig.data.exception.OpenException;
......
28 33

  
29 34
	private static String DS_NAME = PostgresqlStore.DATASTORE_NAME;
30 35

  
36
	private void preparar_prueba_table() throws Exception{
37
		String url;
38
		url = "jdbc:postgresql://"+SERVER_IP+":" + SERVER_PORT +"/"+SERVER_DBNAME;
31 39

  
40
		Connection conn = null;
41

  
42
		Class.forName("org.postgresql.Driver");
43
		conn = DriverManager.getConnection(url, SERVER_USER, SERVER_PASWD);
44
		conn.setAutoCommit(false);
45
		Statement st = conn.createStatement();
46
		st.execute("delete from "+SERVER_SCHEMA+".prueba");
47
		st.execute("Insert into "+SERVER_SCHEMA+".prueba select * from "+SERVER_SCHEMA+".prueba_backup");
48
		st.close();
49
		conn.commit();
50
		conn.close();
51

  
52

  
53

  
54

  
55
	}
56

  
32 57
	public void test1(){
33 58
		Register.selfRegister();
59

  
60
		try {
61
			preparar_prueba_table();
62
		} catch (Exception e) {
63
			e.printStackTrace();
64
			fail("Inicializando tabla prueba");
65
		}
34 66
		DataManager manager = DataManager.getManager();
35 67

  
36 68

  
......
186 218

  
187 219
		exc=null;
188 220
		try {
189
			fc = (IFeatureCollection)fs.getDataCollection(null,"NOMBRE like 'B%'",null);
221
			fc = (IFeatureCollection)fs.getDataCollection(null,"nombre like 'B%'",null);
190 222
		} catch (ReadException e1) {
191 223
			exc=e1;
192 224
		}
......
194 226

  
195 227
		exc=null;
196 228
		try {
197
			fc = (IFeatureCollection)fs.getDataCollection(null,null,"NOMBRE");
229
			fc = (IFeatureCollection)fs.getDataCollection(null,null,"nombre");
198 230
		} catch (ReadException e1) {
199 231
			exc=e1;
200 232
		}
......
211 243
	}
212 244

  
213 245
	public void test2(){
246

  
247
		try {
248
			preparar_prueba_table();
249
		} catch (Exception e) {
250
			e.printStackTrace();
251
			fail("Inicializando tabla prueba");
252
		}
253

  
214 254
		Register.selfRegister();
215 255
		DataManager manager = DataManager.getManager();
216 256

  
......
338 378

  
339 379

  
340 380
		try {
341
			fc = (IFeatureCollection)fs.getDataCollection(null,"lower(nombre) like 'b%'","NOMBRE");
381
			fc = (IFeatureCollection)fs.getDataCollection(null,"lower(nombre) like 'b%'","nombre");
342 382
		} catch (ReadException e1) {
343 383
			e1.printStackTrace();
344 384
			fail();
......
393 433

  
394 434

  
395 435
		/// CON  EDICION
396
//		try {
397
//			fs.startEditing();
398
//		} catch (ReadException e1) {
399
//			e1.printStackTrace();
400
//			fail();
401
//		}
402
//
403
//
404
//		IFeature newFeature = fs.createFeature(fs.getDefaultFeatureType());
405
//		newFeature.set("nombre","BuRjaSOT");
406
//		newFeature.set("TIPO","MUNICIPIO");
407
//		fs.insert(newFeature);
408
//
409
//
410
//		try {
411
//			fc = (IFeatureCollection)fs.getDataCollection();
412
//		} catch (ReadException e1) {
413
//			e1.printStackTrace();
414
//			fail();
415
//		}
416
//
417
//		assertEquals(10, fc.size());
418
//		fc.dispose();
419
//
420
//		try {
421
//			fc = (IFeatureCollection)fs.getDataCollection(null,"lower(nombre) like 'b%'",null);
422
//		} catch (ReadException e1) {
423
//			e1.printStackTrace();
424
//			fail();
425
//		}
426
//
427
//		assertEquals(3, fc.size());
428
//
429
//		it = fc.iterator();
430
//		count=0;
431
//		while (it.hasNext()){
432
//			feature = (IFeature)it.next();
433
//			assertTrue("Filter error",feature.getString("nombre").toLowerCase().startsWith("b"));
434
//			count++;
435
//		}
436
//		assertEquals("Iteration error",3,count);
437
//		fc.dispose();
438
//
439
//
440
//		try {
441
//			fc = (IFeatureCollection)fs.getDataCollection(null,null,"nombre ASC");
442
//		} catch (ReadException e1) {
443
//			e1.printStackTrace();
444
//			fail();
445
//		}
446
//		assertEquals(10, fc.size());
447
//		it = fc.iterator();
448
//		count=0;
449
//		pfeature = (IFeature)it.next();
450
//		count++;
451
//		while (it.hasNext()){
452
//			feature = (IFeature)it.next();
453
//			v1 = (Comparable)pfeature.get("nombre");
454
//			v2 = (Comparable)feature.get("nombre");
455
//			pfeature=feature;
456
//			assertTrue("Short error", (v1.compareTo(v1) <= 0));
457
//			count++;
458
//		}
459
//		assertEquals("Iteration error",10,count);
460
//		fc.dispose();
461
//
462
//
463
//		try {
464
//			fc = (IFeatureCollection)fs.getDataCollection(null,null,"nombre DESC");
465
//		} catch (ReadException e1) {
466
//			e1.printStackTrace();
467
//			fail();
468
//		}
469
//		assertEquals(10, fc.size());
470
//		it = fc.iterator();
471
//
472
//		count=0;
473
//		pfeature = (IFeature)it.next();
474
//		count++;
475
//		while (it.hasNext()){
476
//			feature = (IFeature)it.next();
477
//			v1 = (Comparable)pfeature.get("nombre");
478
//			v2 = (Comparable)feature.get("nombre");
479
//			pfeature=feature;
480
//			assertTrue("Short error", (v1.compareTo(v1) >= 0));
481
//			count++;
482
//		}
483
//		assertEquals("Iteration error",10,count);
484
//		fc.dispose();
485
//
486
//
487
//		try {
488
//			fc = (IFeatureCollection)fs.getDataCollection(null,"lower(nombre) like 'b%'","NOMBRE");
489
//		} catch (ReadException e1) {
490
//			e1.printStackTrace();
491
//			fail();
492
//		}
493
//
494
//		assertEquals(3, fc.size());
495
//
496
//		it = fc.iterator();
497
//
498
//		count=0;
499
//		pfeature = (IFeature)it.next();
500
//		assertTrue(pfeature.getString("nombre").toLowerCase().startsWith("b"));
501
//		count++;
502
//		while (it.hasNext()){
503
//			feature = (IFeature)it.next();
504
//			assertTrue("Filter error",feature.getString("nombre").toLowerCase().startsWith("b"));
505
//			v1 = (Comparable)pfeature.get("nombre");
506
//			v2 = (Comparable)feature.get("nombre");
507
//			pfeature=feature;
508
//			assertTrue("Short error", (v1.compareTo(v1) <= 0));
509
//			count++;
510
//		}
511
//		assertEquals("Iteration error",3,count);
512
//		fc.dispose();
513
//
514
//
515
//
516
//		try {
517
//			fc = (IFeatureCollection)fs.getDataCollection(null,null,"Tipo,lower(NOMBRE) Desc");
518
//		} catch (ReadException e1) {
519
//			e1.printStackTrace();
520
//			fail();
521
//		}
522
//		assertEquals(10, fc.size());
523
//		it = fc.iterator();
524
//		count=0;
525
//		pfeature = (IFeature)it.next();
526
//		System.out.println(pfeature.getString("nombre"));
527
//		count++;
528
//		while (it.hasNext()){
529
//			feature = (IFeature)it.next();
530
//			v1 = (Comparable)((String)pfeature.get("nombre")).toLowerCase();
531
//			v2 = (Comparable)((String)feature.get("nombre")).toLowerCase();
532
//			pfeature=feature;
533
//			assertTrue("Short error", (v1.compareTo(v2) >= 0));
534
//			System.out.println(pfeature.getString("nombre"));
535
//			count++;
536
//		}
537
//		assertEquals("Iteration error",10,count);
538
//		fc.dispose();
539
//
540
//
541
//		fs.cancelEditing();
542
//
543
//
544
//		//Insertar un elemento
545
//		try{
546
//			fs.startEditing();
547
//		} catch (ReadException e1) {
548
//			e1.printStackTrace();
549
//			fail();
550
//		}
551
//
552
//		feature = fs.createDefaultFeature(true);
436
		try {
437
			fs.startEditing();
438
		} catch (ReadException e1) {
439
			e1.printStackTrace();
440
			fail();
441
		}
442

  
443

  
444
		IFeature newFeature = fs.createFeature(fs.getDefaultFeatureType());
445
		newFeature.set("nombre","BuRjaSOT");
446
		newFeature.set("tipo","MUNICIPIO");
447
		fs.insert(newFeature);
448

  
449

  
450
		try {
451
			fc = (IFeatureCollection)fs.getDataCollection();
452
		} catch (ReadException e1) {
453
			e1.printStackTrace();
454
			fail();
455
		}
456

  
457
		assertEquals(10, fc.size());
458
		fc.dispose();
459

  
460
		try {
461
			fc = (IFeatureCollection)fs.getDataCollection(null,"lower(nombre) like 'b%'",null);
462
		} catch (ReadException e1) {
463
			e1.printStackTrace();
464
			fail();
465
		}
466

  
467
		assertEquals(3, fc.size());
468

  
469
		it = fc.iterator();
470
		count=0;
471
		while (it.hasNext()){
472
			feature = (IFeature)it.next();
473
			assertTrue("Filter error",feature.getString("nombre").toLowerCase().startsWith("b"));
474
			count++;
475
		}
476
		assertEquals("Iteration error",3,count);
477
		fc.dispose();
478

  
479

  
480
		try {
481
			fc = (IFeatureCollection)fs.getDataCollection(null,null,"nombre ASC");
482
		} catch (ReadException e1) {
483
			e1.printStackTrace();
484
			fail();
485
		}
486
		assertEquals(10, fc.size());
487
		it = fc.iterator();
488
		count=0;
489
		pfeature = (IFeature)it.next();
490
		count++;
491
		while (it.hasNext()){
492
			feature = (IFeature)it.next();
493
			v1 = (Comparable)pfeature.get("nombre");
494
			v2 = (Comparable)feature.get("nombre");
495
			pfeature=feature;
496
			assertTrue("Short error", (v1.compareTo(v1) <= 0));
497
			count++;
498
		}
499
		assertEquals("Iteration error",10,count);
500
		fc.dispose();
501

  
502

  
503
		try {
504
			fc = (IFeatureCollection)fs.getDataCollection(null,null,"nombre DESC");
505
		} catch (ReadException e1) {
506
			e1.printStackTrace();
507
			fail();
508
		}
509
		assertEquals(10, fc.size());
510
		it = fc.iterator();
511

  
512
		count=0;
513
		pfeature = (IFeature)it.next();
514
		count++;
515
		while (it.hasNext()){
516
			feature = (IFeature)it.next();
517
			v1 = (Comparable)pfeature.get("nombre");
518
			v2 = (Comparable)feature.get("nombre");
519
			pfeature=feature;
520
			assertTrue("Short error", (v1.compareTo(v1) >= 0));
521
			count++;
522
		}
523
		assertEquals("Iteration error",10,count);
524
		fc.dispose();
525

  
526

  
527
		try {
528
			fc = (IFeatureCollection)fs.getDataCollection(null,"lower(nombre) like 'b%'","nombre");
529
		} catch (ReadException e1) {
530
			e1.printStackTrace();
531
			fail();
532
		}
533

  
534
		assertEquals(3, fc.size());
535

  
536
		it = fc.iterator();
537

  
538
		count=0;
539
		pfeature = (IFeature)it.next();
540
		assertTrue(pfeature.getString("nombre").toLowerCase().startsWith("b"));
541
		count++;
542
		while (it.hasNext()){
543
			feature = (IFeature)it.next();
544
			assertTrue("Filter error",feature.getString("nombre").toLowerCase().startsWith("b"));
545
			v1 = (Comparable)pfeature.get("nombre");
546
			v2 = (Comparable)feature.get("nombre");
547
			pfeature=feature;
548
			assertTrue("Short error", (v1.compareTo(v1) <= 0));
549
			count++;
550
		}
551
		assertEquals("Iteration error",3,count);
552
		fc.dispose();
553

  
554

  
555

  
556
		try {
557
			fc = (IFeatureCollection)fs.getDataCollection(null,null,"Tipo,lower(nombre) Desc");
558
		} catch (ReadException e1) {
559
			e1.printStackTrace();
560
			fail();
561
		}
562
		assertEquals(10, fc.size());
563
		it = fc.iterator();
564
		count=0;
565
		pfeature = (IFeature)it.next();
566
		System.out.println(pfeature.getString("nombre"));
567
		count++;
568
		while (it.hasNext()){
569
			feature = (IFeature)it.next();
570
			v1 = (Comparable)((String)pfeature.get("nombre")).toLowerCase();
571
			v2 = (Comparable)((String)feature.get("nombre")).toLowerCase();
572
			pfeature=feature;
573
			assertTrue("Short error", (v1.compareTo(v2) >= 0));
574
			System.out.println(pfeature.getString("nombre"));
575
			count++;
576
		}
577
		assertEquals("Iteration error",10,count);
578
		fc.dispose();
579

  
580

  
581
		fs.cancelEditing();
582

  
583

  
584
		//Insertar un elemento
585
		try{
586
			fs.startEditing();
587
		} catch (ReadException e1) {
588
			e1.printStackTrace();
589
			fail();
590
		}
591

  
592
		feature = fs.createDefaultFeature(true);
553 593
//		feature.set("id", 90000);
554
//		feature.set("nombre","BurJASOT");
555
//		feature.set("tipo", "OTRO");
556
//		fs.insert(feature);
557
//
558
//		try {
559
//			fs.finishEditing();
560
//		} catch (WriteException e) {
561
//			e.printStackTrace();
562
//			fail("Exception: "+e);
563
//		} catch (ReadException e) {
564
//			e.printStackTrace();
565
//			fail("Exception: "+e);
566
//		}
567
//
568
//
569
//		try {
570
//			fc = (IFeatureCollection)fs.getDataCollection(null,null,"lower(nombre) Desc");
571
//		} catch (ReadException e1) {
572
//			e1.printStackTrace();
573
//			fail();
574
//		}
575
//		assertEquals(10, fc.size());
576
//		it = fc.iterator();
577
//		count=0;
578
//		pfeature = (IFeature)it.next();
579
//		System.out.println(pfeature.getString("nombre"));
580
//		count++;
581
//		while (it.hasNext()){
582
//			feature = (IFeature)it.next();
583
//			v1 = (Comparable)((String)pfeature.get("nombre")).toLowerCase();
584
//			v2 = (Comparable)((String)feature.get("nombre")).toLowerCase();
585
//			pfeature=feature;
586
//			assertTrue("Short error: "+ v1.toString() + " >= " +v2.toString(), (v1.compareTo(v2) >= 0));
587
//			System.out.println(pfeature.getString("nombre"));
588
//			count++;
589
//		}
590
//		assertEquals("Iteration error",10,count);
591
//		fc.dispose();
592
//
593
//
594
//
595
//		//Actualizacion
596
//		try{
597
//			fs.startEditing();
598
//		} catch (ReadException e1) {
599
//			e1.printStackTrace();
600
//			fail();
601
//		}
602
//
603
//
604
//		try {
605
//			fc = (IFeatureCollection)fs.getDataCollection(null,"lower(nombre) = 'burjasot'",null);
606
//		} catch (ReadException e1) {
607
//			e1.printStackTrace();
608
//			fail();
609
//		}
610
//		assertEquals(1, fc.size());
611
//		Feature old =(Feature)fc.iterator().next();
612
//		feature = fs.createDefaultFeature(false);
613
//		it = fs.getDefaultFeatureType().iterator();
614
//		IFeatureAttributeDescriptor attr;
615
//		while(it.hasNext()){
616
//			 attr = (IFeatureAttributeDescriptor)it.next();
617
////			 if (attr.getDataType() == IFeatureAttributeDescriptor.TYPE_GEOMETRY){
618
////				 feature.set(attr.getName(), old.get(attr.getName()));
619
////			 } else {
594
		feature.set("nombre","BurJASOT");
595
		feature.set("tipo", "OTRO");
596
		fs.insert(feature);
597

  
598
		try {
599
			fs.finishEditing();
600
		} catch (WriteException e) {
601
			e.printStackTrace();
602
			fail("Exception: "+e);
603
		} catch (ReadException e) {
604
			e.printStackTrace();
605
			fail("Exception: "+e);
606
		}
607

  
608

  
609
		try {
610
			fc = (IFeatureCollection)fs.getDataCollection(null,null,"lower(nombre) Desc");
611
		} catch (ReadException e1) {
612
			e1.printStackTrace();
613
			fail();
614
		}
615
		assertEquals(10, fc.size());
616
		it = fc.iterator();
617
		count=0;
618
		pfeature = (IFeature)it.next();
619
		System.out.println(pfeature.getString("nombre"));
620
		count++;
621
		while (it.hasNext()){
622
			feature = (IFeature)it.next();
623
			v1 = (Comparable)((String)pfeature.get("nombre")).toLowerCase();
624
			v2 = (Comparable)((String)feature.get("nombre")).toLowerCase();
625
			pfeature=feature;
626
			assertTrue("Short error: "+ v1.toString() + " >= " +v2.toString(), (v1.compareTo(v2) >= 0));
627
			System.out.println(pfeature.getString("nombre"));
628
			count++;
629
		}
630
		assertEquals("Iteration error",10,count);
631
		fc.dispose();
632

  
633

  
634

  
635
		//Actualizacion
636
		try{
637
			fs.startEditing();
638
		} catch (ReadException e1) {
639
			e1.printStackTrace();
640
			fail();
641
		}
642

  
643

  
644
		try {
645
			fc = (IFeatureCollection)fs.getDataCollection(null,"lower(nombre) = 'burjasot'",null);
646
		} catch (ReadException e1) {
647
			e1.printStackTrace();
648
			fail();
649
		}
650
		assertEquals(1, fc.size());
651
		Feature old =(Feature)fc.iterator().next();
652
		feature = fs.createDefaultFeature(false);
653
		it = fs.getDefaultFeatureType().iterator();
654
		IFeatureAttributeDescriptor attr;
655
		while(it.hasNext()){
656
			 attr = (IFeatureAttributeDescriptor)it.next();
657
//			 if (attr.getDataType() == IFeatureAttributeDescriptor.TYPE_GEOMETRY){
620 658
//				 feature.set(attr.getName(), old.get(attr.getName()));
621
////			 }
622
//		}
623
//		feature.set("NOMBRE", feature.getString("nombre")+"__KK__");
624
//
625
//		fs.update(feature, old);
626
//		try {
627
//			fs.finishEditing();
628
//		} catch (WriteException e) {
629
//			e.printStackTrace();
630
//			fail("Exception: "+e);
631
//		} catch (ReadException e) {
632
//			e.printStackTrace();
633
//			fail("Exception: "+e);
634
//		}
635
//
636
//		try {
637
//			fc = (IFeatureCollection)fs.getDataCollection(null,"nombre like '%__KK__'",null);
638
//		} catch (ReadException e1) {
639
//			e1.printStackTrace();
640
//			fail();
641
//		}
642
//		assertEquals(1, fc.size());
643
//		fc.dispose();
644
//
645
//
646
//		//Eliminacion
647
//		try{
648
//			fs.startEditing();
649
//		} catch (ReadException e1) {
650
//			e1.printStackTrace();
651
//			fail();
652
//		}
653
//
654
//
655
//		try {
656
//			fc = (IFeatureCollection)fs.getDataCollection(null,"nombre like '%__KK__'",null);
657
//		} catch (ReadException e1) {
658
//			e1.printStackTrace();
659
//			fail();
660
//		}
661
//		assertEquals(1, fc.size());
662
//		fs.delete((IFeature)fc.iterator().next());
663
//		fc.dispose();
664
//		try {
665
//			fs.finishEditing();
666
//		} catch (WriteException e) {
667
//			e.printStackTrace();
668
//			fail("Exception: "+e);
669
//		} catch (ReadException e) {
670
//			e.printStackTrace();
671
//			fail("Exception: "+e);
672
//		}
673
//
674
//		try {
675
//			fc = (IFeatureCollection)fs.getDataCollection();
676
//		} catch (ReadException e1) {
677
//			e1.printStackTrace();
678
//			fail();
679
//		}
680
//		assertEquals(9, fc.size());
681
//		fc.dispose();
659
//			 } else {
660
				 feature.set(attr.getName(), old.get(attr.getName()));
661
//			 }
662
		}
663
		feature.set("nombre", feature.getString("nombre")+"__KK__");
682 664

  
665
		fs.update(feature, old);
666
		try {
667
			fs.finishEditing();
668
		} catch (WriteException e) {
669
			e.printStackTrace();
670
			fail("Exception: "+e);
671
		} catch (ReadException e) {
672
			e.printStackTrace();
673
			fail("Exception: "+e);
674
		}
683 675

  
676
		try {
677
			fc = (IFeatureCollection)fs.getDataCollection(null,"nombre like '%__KK__'",null);
678
		} catch (ReadException e1) {
679
			e1.printStackTrace();
680
			fail();
681
		}
682
		assertEquals(1, fc.size());
683
		fc.dispose();
684 684

  
685

  
686
		//Eliminacion
687
		try{
688
			fs.startEditing();
689
		} catch (ReadException e1) {
690
			e1.printStackTrace();
691
			fail();
692
		}
693

  
694

  
685 695
		try {
696
			fc = (IFeatureCollection)fs.getDataCollection(null,"nombre like '%__KK__'",null);
697
		} catch (ReadException e1) {
698
			e1.printStackTrace();
699
			fail();
700
		}
701
		assertEquals(1, fc.size());
702
		fs.delete((IFeature)fc.iterator().next());
703
		fc.dispose();
704
		try {
705
			fs.finishEditing();
706
		} catch (WriteException e) {
707
			e.printStackTrace();
708
			fail("Exception: "+e);
709
		} catch (ReadException e) {
710
			e.printStackTrace();
711
			fail("Exception: "+e);
712
		}
713

  
714
		try {
715
			fc = (IFeatureCollection)fs.getDataCollection();
716
		} catch (ReadException e1) {
717
			e1.printStackTrace();
718
			fail();
719
		}
720
		assertEquals(9, fc.size());
721
		fc.dispose();
722

  
723

  
724

  
725
		try {
686 726
			fs.close();
687 727
		} catch (CloseException e) {
688 728
			e.printStackTrace();
trunk/libraries/libDataSourceDBBaseDrivers/src/org/gvsig/data/datastores/vectorial/db/jdbc/h2/H2FeaturesWriter.java
38 38
import com.iver.cit.gvsig.fmap.core.IGeometry;
39 39
import com.iver.cit.gvsig.fmap.core.IGeometry3D;
40 40
import com.iver.cit.gvsig.fmap.core.ShapeFactory;
41
import com.vividsolutions.jts.io.WKBWriter;
41 42

  
42 43
class H2FeaturesWriter extends JDBCFeaturesWriter implements ISelectiveWriter {
43 44
	DBFeatureType featureType;
......
49 50
	private PreparedStatement insertSt;
50 51
	private PreparedStatement updateSt;
51 52

  
53
	private static WKBWriter wkbWriter = new WKBWriter();
52 54

  
55
	H2FeaturesWriter(){
56

  
57
	}
58

  
53 59
	public void init(IFeatureStore store) {
54
		Statement st;
55 60
		this.store = (H2Store)store;
56 61
		this.parameters=(H2StoreParameters)store.getParameters();
57 62

  
58 63
		this.featureType = (DBFeatureType)this.store.getDefaultFeatureType();
59 64
		conex = this.store.getConnection();
65
	}
66

  
67
	public void postProcess() throws OpenException, WriteException {
60 68
		try {
69
			conex.commit();
70
		} catch (SQLException e) {
71
			throw new WriteException(this.store.getName(),e);
72
		}
73
	}
74

  
75
	public void cancelActions() throws WriteException{
76
		try {
77
			conex.rollback();
78
		} catch (SQLException e) {
79
			throw new WriteException(this.store.getName(),e);
80
		}
81
	}
82

  
83
	public void preProcess() throws OpenException, InitializeWriterException {
84
		Statement st;
85

  
86

  
87
		try {
88
			conex.setAutoCommit(false);
61 89
			st = conex.createStatement();
62 90

  
63 91
			if (bCreateTable) {
......
67 95
				System.out.println("sqlCreate =" + sqlCreate);
68 96
				st.execute(sqlCreate);
69 97

  
70
				conex.commit();
98
//				conex.commit();
71 99
			}
72
			conex.setAutoCommit(false);
100

  
73 101
//			fieldManager = new JdbcFieldManager(((ConnectionJDBC)conex).getConnection(), lyrDef.getTableName());
74 102

  
75 103
		} catch (SQLException e) {
......
77 105
//			throw new InitializeWriterException(getName(),e);
78 106
		}
79 107

  
108
//        ResultSet rsAux;
109
//		try {
110
////				conex.setAutoCommit(false);
111
////			alterTable();
112
//
113
////			rsAux = st.executeQuery("SHOW server_encoding;");
114
////	        rsAux.next();
115
////	        String serverEncoding = rsAux.getString(1);
116
////	        System.out.println("Server encoding = " + serverEncoding);
117
//	        // st.execute("SET CLIENT_ENCODING TO 'UNICODE';");
118
//	        // Intentamos convertir nuestras cadenas a ese encode.
119
////	        setEncoding(serverEncoding);
120
//		} catch (SQLException e) {
121
//			throw new InitializeWriterException("H2",e);
122
//		}
80 123
	}
81 124

  
82
	public void postProcess() throws OpenException, WriteException {
83
		try {
84
			conex.setAutoCommit(true);
85
		} catch (SQLException e) {
86
			throw new WriteException("H2",e);
87
		}
88
	}
89

  
90
	public void preProcess() throws OpenException, InitializeWriterException {
91
		// ATENTION: We will transform (in PostGIS class; doubleQuote())
92
        // to UTF-8 strings. Then, we tell the PostgreSQL server
93
        // that we will use UTF-8, and it can translate
94
        // to its charset
95
        // Note: we have to translate to UTF-8 because
96
        // the server cannot manage UTF-16
97

  
98
        ResultSet rsAux;
99
		try {
100
				conex.rollback();
101
//			alterTable();
102

  
103
//			rsAux = st.executeQuery("SHOW server_encoding;");
104
//	        rsAux.next();
105
//	        String serverEncoding = rsAux.getString(1);
106
//	        System.out.println("Server encoding = " + serverEncoding);
107
	        // st.execute("SET CLIENT_ENCODING TO 'UNICODE';");
108
	        // Intentamos convertir nuestras cadenas a ese encode.
109
//	        setEncoding(serverEncoding);
110
		} catch (SQLException e) {
111
			throw new InitializeWriterException("H2",e);
112
		}
113
	}
114

  
115 125
	public void deleteFeature(IFeature feature) throws WriteException {
116 126
		Statement st;
117 127
		String sqlDelete = getSqlDeleteFeature(featureType, feature);
......
120 130
			st = this.conex.createStatement();
121 131
			st.execute(sqlDelete);
122 132
		} catch (SQLException e) {
123
			throw new WriteException("H2",e);
133
			throw new WriteException(this.store.getName(),e);
124 134
		}
125 135

  
126 136
	}
......
140 150
					continue;
141 151

  
142 152

  
143
				H2Utils.loadValueInPreparedStatement(ps, index, fad, feature);
153
				loadValueInPreparedStatement(ps, index, fad, feature);
144 154
				index++;
145 155
			}
146 156
//			ps.setObject(index, feature.get(ftype.getFieldIdIndex()));
......
148 158
			ps.execute();
149 159

  
150 160
		} catch (SQLException e) {
151
			throw new WriteException("H2",e);
161
			throw new WriteException(this.store.getName(),e);
152 162
		}
153 163
	}
154 164

  
......
187 197
		this.featureType=(DBFeatureType)featureType;
188 198
	}
189 199

  
190
	protected WritableByteChannel getWriteChannel(String path) throws IOException {
191
		WritableByteChannel channel;
192

  
193
		File f = new File(path);
194

  
195
		if (!f.exists()) {
196
//			System.out.println("Creando fichero " + f.getAbsolutePath());
197

  
198
			if (!f.createNewFile()) {
199
				System.err.print("Error al crear el fichero "
200
						+ f.getAbsolutePath());
201
				throw new IOException("Cannot create file " + f);
202
			}
203
		}
204

  
205
		RandomAccessFile raf = new RandomAccessFile(f, "rw");
206
		channel = raf.getChannel();
207

  
208
		return channel;
209
	}
210

  
211 200
	/**
212 201
	 * @param createTable
213 202
	 *            The bCreateTable to set.
......
215 204
	public void setCreateTable(boolean createTable) {
216 205
		bCreateTable = createTable;
217 206
	}
207

  
218 208
	boolean dropTableIfExist() throws SQLException{
219 209
		if (!this.existTable(parameters.getSchema(), parameters.getTableName())){
220 210
			return false;
......
249 239
				JDBCAttributeDescriptor fad=(JDBCAttributeDescriptor)it.next();
250 240
				if (fad.isPrimaryKey())
251 241
					continue;
252
				H2Utils.loadValueInPreparedStatement(ps, index, fad, feature);
242
				loadValueInPreparedStatement(ps, index, fad, feature);
253 243
				index++;
254 244
			}
255 245

  
256
			H2Utils.loadPkInPreparedStatement(ps, index, ftype, feature);
246
			loadPkInPreparedStatement(ps, index, ftype, feature);
257 247

  
258 248
			ps.execute();
259 249

  
260 250
		} catch (SQLException e) {
261
			throw new WriteException("H2",e);
251
			throw new WriteException(this.store.getName(),e);
262 252
		}
263 253
	}
264 254

  
......
269 259
				+ attribute.getName() + ";";
270 260
			st.execute(sql);
271 261
		} catch (SQLException e) {
272
			throw new WriteException("H2",e);
262
			throw new WriteException(this.store.getName(),e);
273 263
		}
274 264
	}
275 265

  
......
280 270
			+ oldAttribute.getName() + " TO " + attribute.getName() + ";";
281 271
			st.execute(sql);
282 272
		} catch (SQLException e) {
283
			throw new WriteException("H2",e);
273
			throw new WriteException(this.store.getName(),e);
284 274
		}
285 275
	}
286 276

  
......
299 289
				+ ";";
300 290
			st.execute(sql);
301 291
		} catch (SQLException e) {
302
			throw new WriteException("H2",e);
292
			throw new WriteException(this.store.getName(),e);
303 293
		}
304 294
	}
305 295

  
......
337 327
		return resul;
338 328
	}
339 329

  
340
	public void setEncoding(String toEncode){
341
		if (toEncode.compareToIgnoreCase("SQL_ASCII") == 0){
342
		   this.toEncode = "ASCII";
343
		  } else {
344
			  this.toEncode = toEncode;
345
		  }
346
	}
347
	public String getEncoding() {
348
		return toEncode;
349
	}
350 330
	public boolean canWriteGeometry(int gvSIGgeometryType) {
351 331
		switch (gvSIGgeometryType) {
352 332
		case FShape.POINT:
......
367 347
		return false;
368 348
	}
369 349

  
370
	public boolean canWriteAttribute(int sqlType) {
371
		switch (sqlType) {
372
		case Types.DOUBLE:
373
		case Types.FLOAT:
374
		case Types.INTEGER:
375
		case Types.BIGINT:
376
			return true;
377
		case Types.DATE:
378
			return true;
379
		case Types.BIT:
380
		case Types.BOOLEAN:
381
			return true;
382
		case Types.VARCHAR:
383
		case Types.CHAR:
384
		case Types.LONGVARCHAR:
385
			return true;
386 350

  
387
		}
388

  
389
		return false;
390
	}
391
	public String getSqlInsertFeature(DBFeatureType dbFeatureType,
392
			IFeature feat) {
393
		StringBuffer sqlBuf = new StringBuffer("INSERT INTO "
394
				+ this.parameters.tableID() + " (");
395
		String sql = null;
396
		int numAlphanumericFields = dbFeatureType.size();
397

  
398
		for (int i = 0; i < numAlphanumericFields; i++) {
399
			IFeatureAttributeDescriptor fad=(IFeatureAttributeDescriptor)dbFeatureType.get(i);
400
			String name = fad.getName();
401
			// if (cols.contains(name) && (!name.equals(uniqueCol) ||
402
			// existsUnique)) {
403
			if (name.equals(dbFeatureType.getFieldId()))
404
				continue;
405
			sqlBuf.append(" " + name + ",");
406
			// }
407
		}
408
		sqlBuf.append(" " + dbFeatureType.getDefaultGeometry());
409
		// sqlBuf.deleteCharAt(sqlBuf.lastIndexOf(","));
410
		sqlBuf.append(" ) VALUES (");
411
		String insertQueryHead = sqlBuf.toString();
412
		sqlBuf = new StringBuffer(insertQueryHead);
413
		for (int j = 0; j < numAlphanumericFields; j++) {
414
			IFeatureAttributeDescriptor fad=(IFeatureAttributeDescriptor)dbFeatureType.get(j);
415

  
416
			String name = fad.getName();
417
			if (name.equals(dbFeatureType.getFieldId()))
418
				continue;
419

  
420
			if (isNumeric(feat.get(j)))
421
				sqlBuf.append(feat.get(j).toString() + ", ");
422
			else
423
				sqlBuf.append(addQuotes(feat.get(j)) + ", ");
424
		}
425
		IGeometry geometry=(IGeometry)feat.getDefaultGeometry();
426
		int type=dbFeatureType.getGeometryTypes()[0];
427
		if (geometry.getGeometryType()!=type){
428
			if (type==FShape.POLYGON){
429
				geometry=ShapeFactory.createPolygon2D(new GeneralPathX(geometry.getInternalShape()));
430
			}else if (type==FShape.LINE){
431
				geometry=ShapeFactory.createPolyline2D(new GeneralPathX(geometry.getInternalShape()));
432
			}else if (type==(FShape.POLYGON|FShape.Z)){
433
				geometry=ShapeFactory.createPolygon3D(new GeneralPathX(geometry.getInternalShape()),((IGeometry3D)geometry).getZs());
434
			}else if (type==(FShape.LINE|FShape.Z)){
435
				geometry=ShapeFactory.createPolyline3D(new GeneralPathX(geometry.getInternalShape()),((IGeometry3D)geometry).getZs());
436
			}
437
		}
438
		sqlBuf.append(" GeometryFromText( '"
439
				+ geometry.toJTSGeometry().toText() + "', "
440
				+ removePrefix(dbFeatureType.getDefaultSRS()) + ")");
441

  
442
		// sqlBuf.deleteCharAt(sqlBuf.lastIndexOf(","));
443
		sqlBuf.append(" ) ");
444
		sql = sqlBuf.toString();
445
		return sql;
446
	}
447
	public boolean isNumeric(Object obj) {
448

  
449
		if (obj instanceof Number){
450
			return true;
451
		}
452
		return false;
453
	}
454
	protected String addQuotes(Object value) {
455
		String retString;
456

  
457
		if (value != null) {
458
			retString = "'" + doubleQuote(value) + "'";
459

  
460
		} else {
461
			retString = "null";
462
		}
463

  
464
		return retString;
465
	}
466
	private String doubleQuote(Object obj) {
467
		String aux = obj.toString().replaceAll("'", "''");
468
		StringBuffer strBuf = new StringBuffer(aux);
469
		ByteArrayOutputStream out = new ByteArrayOutputStream(strBuf.length());
470
		PrintStream printStream = new PrintStream(out);
471
		printStream.print(aux);
472
		String aux2 = "ERROR";
473
		try {
474
			aux2 = out.toString(toEncode);
475
			System.out.println(aux + " " + aux2);
476
		} catch (UnsupportedEncodingException e) {
477
			// TODO Auto-generated catch block
478
			e.printStackTrace();
479
		}
480

  
481
		return aux2;
482
	}
483
	public static String removePrefix(String str) {
484

  
485
		int colon_ind = str.indexOf(":");
486
		if (colon_ind != -1) {
487
			return str.substring(colon_ind + 1);
488
		} else {
489
			return str;
490
		}
491
	}
492

  
493 351
	private PreparedStatement getUpdateFeatureStatement(DBFeatureType dbFeatureType) throws SQLException{
494 352
		if (this.updateSt == null){
495 353
			StringBuffer sqlBuf = new StringBuffer("UPDATE "
......
508 366
			}
509 367
			sqlBuf.deleteCharAt(sqlBuf.lastIndexOf(","));
510 368
			sqlBuf.append(" WHERE ");
511
			sqlBuf.append(H2Utils.getFliterForIDForPStatement(dbFeatureType));
369
			sqlBuf.append(getFliterForIDForPStatement(dbFeatureType));
512 370
			sql = sqlBuf.toString();
513 371

  
514 372

  
......
524 382
		StringBuffer sqlBuf = new StringBuffer("DELETE FROM "
525 383
				+ this.parameters.tableID() + " WHERE ");
526 384
		String sql = null;
527
		sqlBuf.append(H2Utils.getFliterForID(dbFeatureType, feature));
385
		sqlBuf.append(H2Utils.getFilterForID(dbFeatureType, feature));
528 386
		sql = sqlBuf.toString();
529 387

  
530 388
		return sql;
......
583 441
			st.close();
584 442
		}
585 443
		catch(SQLException except){
586
			throw new InitializeWriterException("H2 Feature Writer",except);
444
			throw new InitializeWriterException(parameters.getDataStoreName(),except);
587 445

  
588 446
		}
589 447
	}
448

  
449
	protected void loadPkInPreparedStatement(PreparedStatement ps,int paramIndex,DBFeatureType fType,IFeature feature) throws java.sql.SQLException{
450
		if (fType.getFieldsId().length != 1)
451
			throw new UnsupportedOperationException("ID fields > 1");
452
		String id =fType.getFieldsId()[0];
453
		loadValueInPreparedStatement(ps, paramIndex, (JDBCAttributeDescriptor)fType.get(fType.getFieldIndex(id)), feature);
454
	}
455

  
456
	protected void loadValueInPreparedStatement(PreparedStatement ps,int paramIndex,JDBCAttributeDescriptor attr,IFeature feature) throws java.sql.SQLException{
457
		Object value = feature.get(attr.ordinal());
458
		if (value == null){
459
			ps.setNull(paramIndex, attr.getSqlType());
460
			return;
461
		}
462

  
463
		if (attr.getDataType() == IFeatureAttributeDescriptor.TYPE_GEOMETRY){
464
			IGeometry geom =(IGeometry)feature.get(attr.ordinal());
465
			ps.setBytes(
466
				paramIndex,	wkbWriter.write(geom.toJTSGeometry())
467
			);
468
			return;
469
		}
470
		ps.setObject(paramIndex, feature.get(attr.ordinal()));
471
	}
472

  
473
	protected static String getFliterForIDForPStatement(DBFeatureType fType) {
474
		if (fType.getFieldsId().length != 1)
475
			throw new UnsupportedOperationException("ID fields > 1");
476
		String id =fType.getFieldsId()[0];
477
		return id + " = ?";
478
	}
590 479
}
trunk/libraries/libDataSourceDBBaseDrivers/src/org/gvsig/data/datastores/vectorial/db/jdbc/h2/H2Store.java
152 152
		try{
153 153
			this.open();
154 154
			Statement st=this.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
155
			String sql = this.getSqlSelectPart() + " WHERE "+ H2Utils.getFliterForID(this.featureType, featureKey);
155
			String sql = this.getSqlSelectPart() + " WHERE "+ H2Utils.getFilterForID(this.featureType, featureKey);
156 156
			rs=st.executeQuery(sql);
157 157
			if (rs.isLast()) {
158 158

  
trunk/libraries/libDataSourceDBBaseDrivers/src/org/gvsig/data/datastores/vectorial/db/jdbc/h2/H2Utils.java
28 28

  
29 29
public class H2Utils {
30 30
	private static WKBParser2 wkbParser = new WKBParser2();
31
	private static WKBWriter wkbWriter = new WKBWriter();
32 31

  
33
	static String getFliterForID(DBFeatureType fType, IFeature feature){
34
		return getFliterForID(fType, getPkFromFeature(feature,fType));
32
	static String getFilterForID(DBFeatureType fType, IFeature feature){
33
		return getFilterForID(fType, getPkFromFeature(feature,fType));
35 34
	}
36 35

  
37
	static String getFliterForID(DBFeatureType fType, Object[] featureKey){
36
	static String getFilterForID(DBFeatureType fType, Object[] featureKey){
38 37
		//TODO: Ojo para los multiples
39 38
		if (fType.getFieldsId().length != 1)
40 39
			throw new UnsupportedOperationException("ID fields > 1");
......
473 472
		return str.replace("'", "''");
474 473
	}
475 474

  
476
	static void loadPkInPreparedStatement(PreparedStatement ps,int paramIndex,DBFeatureType fType,IFeature feature) throws java.sql.SQLException{
477
		if (fType.getFieldsId().length != 1)
478
			throw new UnsupportedOperationException("ID fields > 1");
479
		String id =fType.getFieldsId()[0];
480
		loadValueInPreparedStatement(ps, paramIndex, (JDBCAttributeDescriptor)fType.get(fType.getFieldIndex(id)), feature);
481
	}
482

  
483
	static void loadValueInPreparedStatement(PreparedStatement ps,int paramIndex,JDBCAttributeDescriptor attr,IFeature feature) throws java.sql.SQLException{
484
		Object value = feature.get(attr.ordinal());
485
		if (value == null){
486
			ps.setNull(paramIndex, attr.getSqlType());
487
			return;
488
		}
489

  
490
		if (attr.getDataType() == IFeatureAttributeDescriptor.TYPE_GEOMETRY){
491
			IGeometry geom =(IGeometry)feature.get(attr.ordinal());
492
			ps.setBytes(
493
				paramIndex,	wkbWriter.write(geom.toJTSGeometry())
494
			);
495
			return;
496
		}
497
		ps.setObject(paramIndex, feature.get(attr.ordinal()));
498
	}
499

  
500
	public static String getFliterForIDForPStatement(DBFeatureType fType) {
501
		if (fType.getFieldsId().length != 1)
502
			throw new UnsupportedOperationException("ID fields > 1");
503
		String id =fType.getFieldsId()[0];
504
		return id + " = ?";
505
	}
506 475
}
trunk/libraries/libDataSourceDBBaseDrivers/src/org/gvsig/data/datastores/vectorial/db/jdbc/postgresqlbin/PostgresqlBinStore.java
175 175
		return null;
176 176
	}
177 177

  
178
	public boolean isEditable() {
179
		return false;
180

  
181
//		return super.isEditable();
182
	}
183

  
184

  
178 185
}
trunk/libraries/libDataSourceDBBaseDrivers/src/org/gvsig/data/datastores/vectorial/db/jdbc/postgresql/PostgresqlStore.java
145 145
		try{
146 146
			this.open();
147 147
			Statement st=this.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
148
			String sql = this.getSqlSelectPart() + " WHERE "+ PostgresqlStoreUtils.getFliterForID(this.featureType, featureKey);
148
			String sql = this.getSqlSelectPart() + " WHERE "+ PostgresqlStoreUtils.getFilterForID(this.featureType, featureKey);
149 149
			rs=st.executeQuery(sql);
150 150
			if (rs.isLast()) {
151 151

  
......
242 242
	}
243 243

  
244 244

  
245
	public JDBCFeaturesWriter getFeaturesWriter() {
246
//		IFeaturesWriter writer = new H2FeaturesWriter();
247
//		writer.init(this);
248
//		return writer;
249
		return null;
245
	protected JDBCFeaturesWriter getFeaturesWriter() {
246
		PostgresqlFeaturesWriter writer = new PostgresqlFeaturesWriter();
247
		writer.init(this);
248
		return writer;
250 249
	}
251 250

  
252 251
	public IMetadata getMetadata() {
trunk/libraries/libDataSourceDBBaseDrivers/src/org/gvsig/data/datastores/vectorial/db/jdbc/postgresql/PostgresqlStoreUtils.java
1 1
package org.gvsig.data.datastores.vectorial.db.jdbc.postgresql;
2 2

  
3
import java.math.BigDecimal;
4
import java.nio.ByteBuffer;
5 3
import java.sql.Connection;
6
import java.sql.Date;
7 4
import java.sql.DriverManager;
8 5
import java.sql.ResultSet;
9 6
import java.sql.ResultSetMetaData;
10 7
import java.sql.Statement;
11
import java.sql.Timestamp;
12
import java.sql.Types;
8
import java.util.ArrayList;
13 9
import java.util.Iterator;
14 10

  
15 11
import org.gvsig.data.datastores.vectorial.db.DBFeatureType;
......
18 14
import org.gvsig.data.datastores.vectorial.db.jdbc.JDBCStore;
19 15
import org.gvsig.data.datastores.vectorial.db.jdbc.exception.JDBCDriverNotFoundException;
20 16
import org.gvsig.data.datastores.vectorial.db.jdbc.exception.SQLException;
21
import org.gvsig.data.datastores.vectorial.db.jdbc.h2.H2Store;
22 17
import org.gvsig.data.exception.InitializeException;
23 18
import org.gvsig.data.exception.ReadException;
24 19
import org.gvsig.data.vectorial.DefaultAttributeDescriptor;
25 20
import org.gvsig.data.vectorial.IFeature;
26 21
import org.gvsig.data.vectorial.IFeatureAttributeDescriptor;
22
import org.postgis.PGgeometry;
27 23

  
28 24
import com.iver.cit.gvsig.fmap.core.IGeometry;
25
import com.iver.cit.gvsig.fmap.core.ShapeFactory;
29 26
import com.iver.cit.gvsig.fmap.drivers.WKBParser2;
30
import com.iver.cit.gvsig.fmap.drivers.XTypes;
31
import com.vividsolutions.jts.io.WKBWriter;
32 27

  
33 28
public class PostgresqlStoreUtils {
34 29

  
35
	private static WKBParser2 wkbParser = new WKBParser2();
36
	private static WKBWriter wkbWriter = new WKBWriter();
37

  
38

  
39 30
	static String getJDBCUrl(String host, String db, String port) {
40 31
		String url;
41 32
		url = "jdbc:postgresql://"+host+":" + port +"/"+db;
......
43 34
		return url;
44 35
	}
45 36

  
37
	private static void addConditionForSerialField(JDBCAttributeDescriptor attr,StringBuffer sqlSeq){
38
		sqlSeq.append(" (");
39
		sqlSeq.append(" column_name = '" + attr.getName() +"'");
40
		sqlSeq.append("  and table_name = '" + attr.getTableName()+ "'");
41
		if (attr.getSchemaName() != null && attr.getSchemaName().length() > 0){
42
			sqlSeq.append("  and table_schema = '" + attr.getSchemaName() +"'");
43
		}
44

  
45
		sqlSeq.append("  and table_catalog = '" + attr.getCatalogName()+ "'");
46
		sqlSeq.append(")");
47

  
48
	}
49

  
50
	private static void initializeSerialFields(Connection connection,DBFeatureType featureType) throws java.sql.SQLException{
51
		JDBCAttributeDescriptor attr;
52

  
53
		ArrayList serialCandidates= new ArrayList();
54
		Iterator iter = featureType.iterator();
55
		while(iter.hasNext()){
56
			attr = (JDBCAttributeDescriptor)iter.next();
57
			if (attr.getSqlTypeName().equals("int4") &&
58
					attr.getTableName() != null	&&
59
					attr.getTableName().length() > 0){
60
				serialCandidates.add(attr);
61
			}
62
		}
63
		if (serialCandidates.size() == 0){
64
			return;
65
		}
66
		Statement st = connection.createStatement();
67
		StringBuffer sqlSeq= new StringBuffer("select table_catalog,table_schema,table_name,column_name from information_schema.columns where column_default like 'nextval(%'  and ( ");
68
		iter = serialCandidates.iterator();
69
		String sql;
70
		int i;
71
		for (i=0;i<serialCandidates.size()-1;i++){
72
			attr = (JDBCAttributeDescriptor)serialCandidates.get(i);
73
			addConditionForSerialField(attr,sqlSeq);
74
			sqlSeq.append(" or ");
75
		}
76
		attr = (JDBCAttributeDescriptor)serialCandidates.get(i);
77
		addConditionForSerialField(attr,sqlSeq);
78

  
79

  
80
		sqlSeq.append(")");
81
		sql=sqlSeq.toString();
82
		ResultSet rs = st.executeQuery(sql);
83
		while (rs.next()){
84
			iter = serialCandidates.iterator();
85
			while (iter.hasNext()){
86
				attr = (JDBCAttributeDescriptor)iter.next();
87
				if (rs.getString("column_name").equals(attr.getName())){
88
					attr.setAutoIncrement(true);
89
					serialCandidates.remove(attr);
90
					break;
91
				}
92
			}
93

  
94
		}
95

  
96

  
97
	}
98

  
99

  
46 100
	static DBFeatureType getFeatureType(Connection connection, PostgresqlStoreParameters params) throws ReadException{
47 101
		DBFeatureType featureType = new DBFeatureType();
102
		String[] ids =params.getFieldsId();
103
		int i;
48 104

  
49 105

  
50 106
		loadFieldsToFeatureType(connection, params, featureType);
51 107

  
52 108

  
53
		featureType.setFieldsId(params.getFieldsId());
109
		//Inicializamos los IDs
110
		JDBCAttributeDescriptor attr;
111
		for (i=0;i<ids.length;i++){
112
			try {
113
				attr = (JDBCAttributeDescriptor)featureType.get(ids[i]);
114
			} catch (IndexOutOfBoundsException e){
115
				throw new InitializeException(
116
						PostgresqlStore.DATASTORE_NAME,
117
						new Exception("Id Field '"+ ids[i] +"' not Found"));
54 118

  
119
			}
120
			attr.setPrimaryKey(true);
121
		}
122
		featureType.setFieldsId(ids);
123

  
124
		//Inicializamos los 'serial' ya que en postgres el
125
		//'isAutonumeric' devuelve false
126
//		try{
127
//			initializeSerialFields(connection,featureType);
128
//		} catch (java.sql.SQLException e) {
129
//			throw new InitializeException(PostgresqlStore.DATASTORE_NAME,e);
130
//
131
//		}
132
//
133

  
134

  
135

  
136

  
137
		//Inicializar campos geometricos si los hubiese
138
		//TODO Datos geometricos
139

  
140

  
141
		//Inicializar la geometria por defecto
55 142
		if (params.getDefaultGeometryField() != null && params.getDefaultGeometryField() != ""){
56 143
			if (featureType.getFieldIndex(params.getDefaultGeometryField())< 0){
57
				// FIXME: crear una nueva excepcion??
58 144
				throw new InitializeException(
59 145
						PostgresqlStore.DATASTORE_NAME,
60 146
						new Exception("Geometry Field '"+ params.getDefaultGeometryField() +"' not Found"));
61 147

  
62 148
			}
149
			attr = (JDBCAttributeDescriptor)featureType.get(params.getDefaultGeometryField());
150
			if (attr.getDataType() != IFeatureAttributeDescriptor.TYPE_GEOMETRY){
151
				throw new InitializeException(
152
						PostgresqlStore.DATASTORE_NAME,
153
						new Exception("Field '"+ params.getDefaultGeometryField() +"' isn't a geometry"));
63 154

  
155
			}
156

  
64 157
			featureType.setDefaultGeometry(params.getDefaultGeometryField());
65 158
		}
66 159

  
160

  
67 161
		return featureType;
68 162

  
69 163
	}
......
71 165
	private static void loadFieldsToFeatureType(Connection conn,PostgresqlStoreParameters params,DBFeatureType featureType) throws ReadException{
72 166
		String sql="";
73 167
		String columns=params.getFieldsString();
168
		boolean fillTableData;
74 169

  
75 170
		if (params.getSqlSoure() != null){
76 171
			sql = params.getSqlSoure();
172
			fillTableData = false;
77 173
		} else {
78
			sql = "Select "+columns+" from " + params.tableID() + " limit 1;";
174
			sql = "Select "+columns+" from " + params.tableID();
175
			fillTableData = true;
79 176
		}
80 177

  
81 178
		try {
82 179

  
83 180
			Statement stAux = conn.createStatement();
181
			stAux.setFetchSize(1);
84 182
			ResultSet rs = stAux.executeQuery(sql);
85 183
			ResultSetMetaData rsMetadata = rs.getMetaData();
86 184

  
87 185
			int i;
88 186

  
89 187
			featureType.setTableID(params.tableID());
90
			DefaultAttributeDescriptor attr;
188
			JDBCAttributeDescriptor attr;
91 189
			for (i=1;i<=rsMetadata.getColumnCount();i++){
92 190
				attr = getAttributeFromJDBC(conn,rsMetadata,i);
93 191
				featureType.add(attr);
94 192
				attr.setOrdinal(i-1);
193
				attr.setCatalogName(params.getDb());
194
				if (fillTableData){
195
					attr.setSchemaName(params.getSchema());
196
					attr.setTableName(params.getTableName());
197

  
198
				}
95 199
			}
96 200
			rs.close();
201
			stAux.close();
202

  
203

  
204

  
97 205
		} catch (java.sql.SQLException e) {
98
			// TODO Auto-generated catch block
99 206
			throw new SQLException(sql,"getFeatureType",e);
100 207
		}
101 208

  
102 209
	}
103 210

  
104
	private static DefaultAttributeDescriptor getAttributeFromJDBC(Connection conn,ResultSetMetaData rsMetadata,int colIndex) throws SQLException{
211
	private static JDBCAttributeDescriptor getAttributeFromJDBC(Connection conn,ResultSetMetaData rsMetadata,int colIndex) throws SQLException{
105 212
		JDBCAttributeDescriptor column= new JDBCAttributeDescriptor();
106 213
		try {
107 214
			column.setName(rsMetadata.getColumnName(colIndex));
215
			column.setCaseSensitive(rsMetadata.isCaseSensitive(colIndex));
108 216
			column.setSqlType(rsMetadata.getColumnType(colIndex));
109 217
			column.setAllowNull(rsMetadata.isNullable(colIndex) == ResultSetMetaData.columnNullable);
110 218
			column.setAutoIncrement(rsMetadata.isAutoIncrement(colIndex));
111 219
			column.setReadOnly(rsMetadata.isReadOnly(colIndex));
220
			column.setWritable(rsMetadata.isWritable(colIndex));
221
			column.setClassName(rsMetadata.getColumnClassName(colIndex));
222
			column.setCatalogName(rsMetadata.getCatalogName(colIndex));
223
			column.setDefinitelyWritable(rsMetadata.isDefinitelyWritable(colIndex));
224
			column.setLabel(rsMetadata.getColumnLabel(colIndex));
225
			column.setSchemaName(rsMetadata.getSchemaName(colIndex));
226
			column.setTableName(rsMetadata.getTableName(colIndex));
227
			column.setCatalogName(rsMetadata.getCatalogName(colIndex));
228
			column.setSqlTypeName(rsMetadata.getColumnTypeName(colIndex));
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff