View Javadoc

1   /***
2    * @version $Revision: 1.4 $
3    */
4   package uba.db.sql.interpreter;
5   
6   import java.util.Iterator;
7   import java.util.List;
8   
9   import uba.db.Database;
10  import uba.db.ar.AttributeDef;
11  import uba.db.ar.Tupla;
12  import uba.db.ar.TuplaDef;
13  import uba.db.sql.language.Insert;
14  import uba.db.sql.language.LiteralBehavior;
15  
16  public class InsertQueryPlan implements SentenceQueryPlan {
17  
18  	Insert sentence;
19  
20  	private boolean hasNotifiedResult;
21  
22  	private Database database;
23  
24  	private Object[] values;
25  
26  	private Tupla tuplaToInform;
27  
28  	public InsertQueryPlan(Insert sqlSentence, Database database) {
29  		sentence = sqlSentence;
30  		this.database = database;
31  	}
32  
33  	/*
34  	 * @see uba.db.sql.interpreter.SentenceQueryPlan#startExecution(uba.db.sql.language.Sentence)
35  	 */
36  	public void startExecution() {
37  		hasNotifiedResult = false;
38  		sentence.values().accept(new InsertValuesVisitor(this));
39  		try {
40  			database.tableNamed(sentence.tableName().toString()).insert(values);
41  			tuplaToInform = successTupla();
42  		} catch (Exception e) {
43  			tuplaToInform = errorTupla();
44  		}
45  	}
46  
47  	public boolean hasMoreResults() {
48  		return (!hasNotifiedResult);
49  	}
50  
51  	public Tupla successTupla() {
52  		TuplaDef def = new TuplaDef();
53  		def.addDefinition(new AttributeDef("Resultado del insert"));
54  		Tupla tuple = new Tupla(def);
55  		tuple.set(1, "Execución exitosa.");
56  		return tuple;
57  	}
58  
59  	public Tupla errorTupla() {
60  		TuplaDef def = new TuplaDef();
61  		def.addDefinition(new AttributeDef("Error"));
62  		Tupla errorTuple = new Tupla(def);
63  		errorTuple.set(1, "La ejecución no pudo concretarse.");
64  		return errorTuple;
65  	}
66  
67  	public Tupla nextTuple() {
68  		hasNotifiedResult = true;
69  		return tuplaToInform;
70  	}
71  
72  	public void valuesToInsert(List valuesToInsert) {
73  		values = new Object[valuesToInsert.size()];
74  		Iterator it = valuesToInsert.iterator();
75  		int position = 0;
76  		while (it.hasNext()) {
77  			values[position] = ((LiteralBehavior) it.next()).value();
78  			position++;
79  		}
80  	}
81  
82  	public String planDetail() {
83  		return "Insert " + sentence.tableName() + "\t";
84  	}
85  
86  	/*
87  	 * @see uba.db.sql.interpreter.SentenceQueryPlan#tuplaDefinition()
88  	 */
89  	public TuplaDef tuplaDefinition() {
90  		return tuplaToInform.tuplaDefinition();
91  	}
92  }