public IList <PRelation> getAllRelation() { //"SELECT * FROM SystemRelation", "system_relation") var relations = new List <PRelation>(); DataSet dts = new DataSet(); try { dts.Tables.Add(ConcreteDb.Instance.getDataTable("SELECT * FROM SystemRelation", "system_relation")); foreach (DataRow row in dts.Tables["system_relation"].Rows) { string relationname = row[1].ToString(); PSchema schema = SchemaService.Instance().getSchemeById(Convert.ToInt16(row[2])); var tuple = PTupleService.Instance().getAllTupleByRelationName(relationname, schema.Attributes); if (tuple is null) { tuple = new List <PTuple>(); } PRelation relation = new PRelation(Convert.ToInt16(row[0]), schema, relationname, tuple); relations.Add(relation); } } catch { } return(relations); }
public PRelation Delete(PRelation pRelation) { using (var conn = ConcreteDb.Instance.BeginTransaction()) { try { //delete SystemRelation if (ConcreteDb.Instance.Update("DELETE FROM SystemRelation where ID = " + pRelation.id, false) < 0) { throw new Exception(ConcreteDb.Instance.errorMessage); } //delete data tuple if (!ConcreteDb.Instance.DropTable(pRelation.relationName, false)) { throw new Exception(ConcreteDb.Instance.errorMessage); } conn.Commit(); } catch (Exception ex) { conn.Rollback(); throw new Exception(ex.Message); } ConcreteDb.Instance.closeConnection(); } return(pRelation); }
public SelectCondition(PRelation probRelation, string conditionString) { // TODO: Complete member initialization relations = probRelation; int i = 0; while (i < conditionString.Length - 1) { if (conditionString[i] == '<' && conditionString[i + 1] != '=') { conditionString = conditionString.Insert(i++, "_"); } if (conditionString[i] == '>' && conditionString[i + 1] != '=') { conditionString = conditionString.Insert(i++, "_"); } if (conditionString[i] == '=' && conditionString[i - 1] != '!' && conditionString[i - 1] != '<' && conditionString[i - 1] != '>') { conditionString = conditionString.Insert(i++, "_"); } i++; } this.conditionString = conditionString.Trim(); this.Attributes = probRelation.schema.Attributes; this.MessageError = string.Empty; }
public PTuple GetTuplebyId(ref PRelation rel, string tupId) { var relid = rel.id; PTuple reVal = null; { var relation = RelationService.Instance().getAllRelation().Where(r => r.id.Equals(relid)).First(); tupId = tupId.Replace("{", ""); tupId = tupId.Replace("}", ""); if (!(relation is null)) { var pri = relation.schema.Attributes.Where(a => a.primaryKey).First(); var atr = String.Format("{0}.{1}", relation.relationName, pri.AttributeName); if (!(pri is null)) { try { reVal = relation.tupes.Where(t => SelectCondition.EQUAL(t.valueSet[atr].First(), tupId.Trim(), pri.Type.TypeName)).First(); } catch //ko tim thay (insert khi id is Empty) { if (String.IsNullOrEmpty(tupId)) { reVal = new PTuple(relation); } } } rel = relation; } } return(reVal); }
public PTuple Update(PTuple pTuple, PRelation pRelation, String key) { try { if (key.Substring(key.IndexOf(".") + 1).Equals(ContantCls.emlementProb, StringComparison.CurrentCultureIgnoreCase)) { var priName = pRelation.schema.Attributes.Where(a => a.primaryKey).Select(p => p.AttributeName).Single().Trim().ToLower(); var standard = key.IndexOf(".") == -1 ? key : key.Substring(key.IndexOf(".") + 1).Trim(); var sql = ""; sql += String.Format("UPDATE {0} SET ", pRelation.relationName.ToLower().Trim()); sql += String.Format("{0} = ", standard); //note sql += "' " + pTuple.Ps.ToString() + " '"; priName = String.Format("{0}.{1}", pRelation.relationName, priName); var priVal = pTuple.valueSet[priName].First().Trim(); sql += String.Format(" WHERE {0} = ", priName); //note sql += "'{ " + priVal + " }'"; //in db ConcreteDb.Instance.Update(sql); //in ram var relation = SystemParam.StaticParams.currentDb.Relations.Where(p => p.id == pRelation.id).First(); var tuple = relation.tupes.Where(t => t.valueSet[priName].First().Equals(pTuple.valueSet[priName].First(), StringComparison.CurrentCultureIgnoreCase)).First(); tuple = pTuple; } else { var priName = pRelation.schema.Attributes.Where(a => a.primaryKey).Select(p => p.AttributeName).Single().Trim().ToLower(); var standard = key.IndexOf(".") == -1 ? key : key.Substring(key.IndexOf(".") + 1).Trim(); var sql = ""; sql += String.Format("UPDATE {0} SET ", pRelation.relationName.ToLower().Trim()); var vals = String.Join(" , ", pTuple.valueSet[key].ToArray()); sql += String.Format("{0} = ", standard); //note sql += "'{ " + vals + " }'"; priName = String.Format("{0}.{1}", pRelation.relationName, priName); var priVal = pTuple.valueSet[priName].First().Trim(); sql += String.Format(" WHERE {0} = ", priName); //note sql += "'{ " + priVal + " }'"; //in db ConcreteDb.Instance.Update(sql); //in ram var relation = SystemParam.StaticParams.currentDb.Relations.Where(p => p.id == pRelation.id).First(); var tuple = relation.tupes.Where(t => t.valueSet[priName].First().Equals(pTuple.valueSet[priName].First(), StringComparison.CurrentCultureIgnoreCase)).First(); tuple = pTuple; } } catch (Exception ex) { return(null); } return(pTuple); }
private void dtg_CurrentCellChanged(object sender, EventArgs e) { this.ucEdit.btnClr.IsEnabled = false; this.ucEdit.btnCommitEdit.IsEnabled = false; this.ucEdit.btnApply.IsEnabled = false; this.ucEdit.dtgCellContent.IsEnabled = false; this.ucEdit.rtbxCellContent.IsReadOnly = true; var relation = new PRelation() { id = int.Parse(this.cbx.SelectedValue.ToString()) }; try { var tupID = (this.dtg.CurrentItem as DataRowView).Row.ItemArray[0].ToString().Trim(); var tuple = RawDatabaseService.Instance().GetTuplebyId(ref relation, tupID); var header = this.dtg.CurrentCell.Column.Header.ToString().ToLower(); String attrName = header; attrName = String.Format("{0}.{1}", relation.relationName, header); if (!header.Equals(ContantCls.emlementProb, StringComparison.CurrentCultureIgnoreCase)) { this.ucEdit.txtInfo.Content = attrName.ToUpper(); this.ucEdit.curTuple = tuple; this.ucEdit.setValCell(tuple.valueSet[attrName]); } else { this.ucEdit.txtInfo.Content = attrName.ToUpper(); this.ucEdit.curTuple = tuple; this.ucEdit.setValCell(new List <String> { tuple.Ps.ToString() }); } var att = relation.schema.Attributes.Where(p => p.AttributeName.Equals(header, StringComparison.CurrentCultureIgnoreCase)).First(); this.ucEdit.pAttribute = att; this.ucEdit.txtDataType.Content = att.Type.TypeName; this.ucEdit.chkPri.IsChecked = att.primaryKey; this.ucEdit.pRelation = relation; Parameter.currentColumn = this.dtg.CurrentCell.Column.DisplayIndex; Parameter.currentRow = this.dtg.Items.IndexOf(this.dtg.CurrentItem); } catch { } this.ucEdit.rtbxCellContent.Visibility = Visibility.Visible; this.ucEdit.dtgCellContent.Visibility = Visibility.Collapsed; }
private IList <IDictionary <string, string> > getDataSource(PRelation relations) { var reVal = new List <IDictionary <string, string> >(); foreach (var tuple in relations.tupes) { IDictionary <string, string> dataSource = new Dictionary <string, string>(); foreach (var key in tuple.valueSet.Keys) { dataSource.Add(key, getValCell(tuple.valueSet[key])); } dataSource.Add(ContantCls.emlementProb, tuple.Ps.ToString()); reVal.Add((dataSource)); } return(reVal); }
public string getStrTupleId(PRelation pRelation) { var pri = pRelation.schema.Attributes.Where(p => p.primaryKey).FirstOrDefault(); var sql = String.Empty; int i = 0; //if(pri != null) //{ // while (true) // { // var count = ConcreteDb.Instance.ExecuteScalar($"SELECT * FROM {pRelation.relationName.ToLower()} WHERE {pri.AttributeName.ToLower()} = '{}'")); // if (count == 0d) break; // i++; // } //} return(""); }
public PRelation Insert(PRelation pRelation) { if (pRelation.id == -1) { pRelation.id = RelationService.Instance().getNextIdRel(); } using (var conn = ConcreteDb.Instance.BeginTransaction()) { try { string SQL = ""; SQL = ""; SQL += "INSERT INTO SystemRelation VALUES ( "; SQL += pRelation.id + ","; SQL += "'" + pRelation.relationName + "'" + ","; SQL += pRelation.schema.id; SQL += " );"; if (ConcreteDb.Instance.Update(SQL, false) < 0) { throw new Exception(ConcreteDb.Instance.errorMessage); } //insert Relation Data Table if (!RelationService.Instance().InsertTupleDataTable(pRelation)) { throw new Exception("The schema have no Attribute!"); } conn.Commit(); } catch (Exception ex) { conn.Rollback(); throw new Exception(ex.Message); } ConcreteDb.Instance.closeConnection(); } return(pRelation); }
public PTuple insertEmptyTuple(PRelation pRelation, PAttribute pri, String IdTuple) { var relation = new PRelation() { id = pRelation.id }; var tupID = String.Empty; //insert empty tuple try { var tuple = RawDatabaseService.Instance().GetTuplebyId(ref relation, tupID); tuple.valueSet[$"{relation.relationName.ToLower()}.{pri.AttributeName.ToLower()}"] = new List <String>() { "{ " + IdTuple + " }" }; foreach (var key in tuple.valueSet.Keys.ToList()) { var atr = key.Substring(key.IndexOf(".") + 1); var Pri = $"{relation.relationName.ToLower()}.{pri.AttributeName.ToLower()}"; if (!atr.Equals(ContantCls.emlementProb, StringComparison.CurrentCultureIgnoreCase) && key != Pri) { tuple.valueSet[key] = new List <String>() { "{ Insert Data }" }; } } PTupleService.Instance().Insert(tuple, relation); return(tuple); } catch (Exception Ex) { return(null); } }
private void btnDel_Click(object sender, System.Windows.RoutedEventArgs e) { var rs = MessageBox.Show("Delete this Tuple?", "Notification", MessageBoxButton.YesNo, MessageBoxImage.Question); if (rs == MessageBoxResult.Yes) { var relation = new PRelation() { id = int.Parse(this.cbx.SelectedValue.ToString()) }; var tupID = (this.dtg.SelectedItem as DataRowView).Row.ItemArray[0].ToString().Trim(); var tuple = RawDatabaseService.Instance().GetTuplebyId(ref relation, tupID); try { RawDatabaseService.Instance().DeleteTupleById(relation, tuple); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
public bool DeleteTupleById(PRelation pRelation, PTuple pTuple) { try { var strPriAtt = pRelation.schema.Attributes.Where(att => att.primaryKey).First().ToString().Trim(); var pri = String.Format("{0}.{1}", pRelation.relationName, strPriAtt); var tupID = pTuple.valueSet[pri].FirstOrDefault().Trim(); //del in db var sql = ""; sql += String.Format("DELETE FROM {0} ", pRelation.relationName.ToUpper()); sql += String.Format("WHERE {0} = '{1}'", strPriAtt, "{ " + tupID + " }"); //del in ram SystemParam.StaticParams.currentDb.Relations.Where(p => p.id == pRelation.id).First().tupes.Remove(pTuple); if (ConcreteDb.Instance.Update(sql) < 0) { throw new Exception(ConcreteDb.Instance.errorMessage); } } catch (Exception ex) { return(false); } return(true); }
public bool InsertTupleIntoTableRelation(PRelation pRelation) { if (pRelation.schema.Attributes.Count > 0) { string SQL = ""; SQL += "INSERT INTO " + pRelation.relationName + " VALUES ( "; foreach (var attribute in pRelation.schema.Attributes) { SQL += " " + ", "; } SQL = SQL.Remove(SQL.LastIndexOf(','), 1); SQL += " ); "; if (!ConcreteDb.Instance.CreateTable(SQL, false)) { throw new Exception(ConcreteDb.Instance.errorMessage); } return(true); } else { return(false); } }
public PTuple Insert(PTuple pTuple, PRelation pRelation) { var sql = ""; sql += String.Format("INSERT INTO {0} ", pRelation.relationName.ToLower().Trim()); var atrrs = String.Join(",", pRelation.schema.Attributes.Select(a => a.AttributeName.Trim().ToLower()).ToArray()); sql += String.Format("({0}) VALUES", atrrs); //value list var vallist = new List <String>(); foreach (var key in pTuple.valueSet.Keys) { if (!key.Substring(key.IndexOf(".") + 1).Equals(ContantCls.emlementProb, StringComparison.CurrentCultureIgnoreCase)) { var vals = String.Join(",", pTuple.valueSet[key].ToArray()); vallist.Add("'" + vals + "'"); } } vallist.Add("'" + pTuple.Ps.ToString() + "'"); String strVal = String.Join(",", vallist.ToArray()); sql += $"({strVal})"; try { //in db ConcreteDb.Instance.Update(sql); //in ram SystemParam.StaticParams.currentDb.Relations.Where(p => p.id == pRelation.id).First().tupes.Add(pTuple); } catch (Exception ex) { return(null); } return(pTuple); }
public bool InsertTupleDataTable(PRelation pRelation) { if (pRelation.schema.Attributes.Count > 0) { string SQL = ""; SQL += "CREATE TABLE " + pRelation.relationName + " ( "; foreach (var attribute in pRelation.schema.Attributes) { SQL += attribute.AttributeName + " " + "TEXT" + ", "; } SQL = SQL.Remove(SQL.LastIndexOf(','), 1); SQL += " ); "; if (!ConcreteDb.Instance.CreateTable(SQL, false)) { throw new Exception(ConcreteDb.Instance.errorMessage); } return(true); } else { return(false); } }
public PRelation InsertSystemRelation(PRelation pRelation) { throw new NotImplementedException(); }
public bool InsertTupleIntoTableRelation(PRelation pRelation) { return(RelationService.Instance().InsertTupleIntoTableRelation(pRelation)); }
public PRelation Delete(PRelation pRelation) { return(RelationService.Instance().Delete(pRelation)); }
public bool DropTableByTableName(PRelation pRelation) { throw new NotImplementedException(); }
public bool InsertTupleData(PRelation pRelation) { throw new NotImplementedException(); }
public PTuple insertEmptyTuple(PRelation pRelation, PAttribute pri, String idTuple) { return(PTupleService.Instance().insertEmptyTuple(pRelation, pri, idTuple)); }
public PTuple Update(PTuple pTuple, PRelation pRelation, String key) { return(PTupleService.Instance().Update(pTuple, pRelation, key)); }
public PRelation UpdateSystemRelation(PRelation pRelation) { throw new NotImplementedException(); }
public bool DeleteTupleById(PRelation pRelation, PTuple pTuple) { return(PTupleService.Instance().DeleteTupleById(pRelation, pTuple)); }
private void executeQuery(object sender, EventArgs e) { this.txtMessage.Visibility = Visibility.Collapsed; try { this.dtgDataResult.ItemsSource = null; this.dtgDataResult.Columns.Clear(); var strQry = String.Empty; foreach (TabItem tab in TbQry.Items) { if (tab.IsSelected) { strQry = new TextRange(this.rbxQry.Document.ContentStart, this.rbxQry.Document.ContentEnd).Text; strQry = (String.IsNullOrEmpty(this.rbxQry.Selection.Text) ? strQry : this.rbxQry.Selection.Text); } } if (String.IsNullOrEmpty(strQry)) { MessageBox.Show("Query does not exist!", "Notification", MessageBoxButton.OK, MessageBoxImage.Error); return; } IList <String> queries = new List <String>(); IList <String> operatorQry = new List <String>(); var relationResult = new PRelation(); multiQueryAnalyze(queries: ref queries, operatorQry: ref operatorQry, queryString: strQry); for (int i = 0; i < queries.Count; i++) { if (String.IsNullOrEmpty(queries[i])) { MessageBox.Show("Query syntax Error"); return; } var query = new QueryExecutor(queries[i], (SystemParam.StaticParams.currentDb)); if (query.ExecuteQuery()) { if (!String.IsNullOrEmpty(queries[i]) && queries.Count > 1 && operatorQry.Count > 0) { switch (operatorQry.First()) { case "_u_": relationResult = QueryExecutor.unionOperator(relationResult, query.relationResult, query.selectedAttributes); break; case "_i_": relationResult = QueryExecutor.intersertOperator(relationResult, query.relationResult, query.selectedAttributes); break; case "_e_": relationResult = QueryExecutor.exceptOperator(relationResult, query.relationResult, query.selectedAttributes); break; default: relationResult = query.relationResult; break; //the first time } } else { relationResult = query.relationResult; } //remove stack if (operatorQry.Count > 0) { operatorQry.Remove(operatorQry.First()); } } else { this.txtMessage.Visibility = Visibility.Visible; txtMessage.Foreground = Brushes.Red; txtMessage.Text += query.MessageError; } #region projecttions try { relationResult = query.getRelationBySelectAttribute(relationResult, query.selectedAttributes); } catch (Exception ex) { MessageBox.Show("Selected Attributes must be same in each Query"); return; } #endregion } if (relationResult.tupes.Count <= 0) { txtMessage.Foreground = Brushes.IndianRed; if (String.IsNullOrEmpty(txtMessage.Text)) { this.txtMessage.Visibility = Visibility.Visible; txtMessage.Text = "There is no tuple satisfies the condition"; } } else { var data = dynamicGenDataTable(getDataSource(relationResult)).DefaultView; this.dtgDataResult.ItemsSource = data; if (this.dtgDataResult.Columns.Count == 1) { this.txtMessage.Visibility = Visibility.Visible; txtMessage.Foreground = Brushes.Red; this.txtMessage.Text = "Something when wrong with the query!"; this.dtgDataResult.Items.Clear(); this.dtgDataResult.Items.Refresh(); } this.txtMessage.Text = String.Empty; txtMessage.Foreground = Brushes.Black; txtMessage.Text += String.Format("\nProjection Strategy: {0}", Parameter.curStrategy.ToString()); txtMessage.Text += String.Format("\nResult Tuple Count: {0}\n", dtgDataResult.Items.Count); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { ClearAll(); // đưa csdl về trạng thái ban đầu } }
public PTuple Insert(PTuple pTuple, PRelation pRelation) { return(PTupleService.Instance().Insert(pTuple, pRelation)); }
private void btnExecCur_Click(object sender, RoutedEventArgs e) { this.txtMessage.Visibility = Visibility.Collapsed; var currentLine = String.Empty; foreach (TabItem tab in this.TbQry.Items) { if (tab.IsSelected) { currentLine = new TextRange(this.rbxQry.CaretPosition.GetLineStartPosition(0), this.rbxQry.CaretPosition.GetLineStartPosition(1) ?? this.rbxQry.CaretPosition.DocumentEnd).Text.Trim(); } } try { IList <String> queries = new List <String>(); IList <String> operatorQry = new List <String>(); var relationResult = new PRelation(); multiQueryAnalyze(queries: ref queries, operatorQry: ref operatorQry, queryString: currentLine); for (int i = 0; i < queries.Count; i++) { var query = new QueryExecutor(queries[i], (SystemParam.StaticParams.currentDb)); if (query.ExecuteQuery()) { if (queries.Count > 1 && operatorQry.Count > 0) { switch (operatorQry.First()) { case "_u_": relationResult = QueryExecutor.unionOperator(relationResult, query.relationResult, query.selectedAttributes); break; case "_i_": relationResult = QueryExecutor.intersertOperator(relationResult, query.relationResult, query.selectedAttributes); break; case "_e_": relationResult = QueryExecutor.exceptOperator(relationResult, query.relationResult, query.selectedAttributes); break; default: relationResult = query.relationResult; break; //the first time } } else { relationResult = query.relationResult; } //remove stack if (operatorQry.Count > 0) { operatorQry.Remove(operatorQry.First()); } } else { this.txtMessage.Visibility = Visibility.Visible; txtMessage.Foreground = Brushes.Red; txtMessage.Text += query.MessageError; } #region projecttions try { relationResult = query.getRelationBySelectAttribute(relationResult, query.selectedAttributes); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } #endregion } if (relationResult.tupes.Count <= 0) { txtMessage.Foreground = Brushes.IndianRed; if (this.dtgDataResult.Columns.Count == 1) { this.txtMessage.Visibility = Visibility.Visible; txtMessage.Foreground = Brushes.Red; this.txtMessage.Text = "Something when wrong with the query!"; this.dtgDataResult.Items.Clear(); this.dtgDataResult.Items.Refresh(); } } else { this.dtgDataResult.ItemsSource = dynamicGenDataTable(getDataSource(relationResult)).DefaultView; if (!String.IsNullOrEmpty(this.txtMessage.Text)) { txtMessage.Foreground = Brushes.Black; txtMessage.Text += String.Format("\nProjection Strategy: {0}", Parameter.curStrategy.ToString()); txtMessage.Text += String.Format("\nResult Tuple Count: {0}\n", dtgDataResult.Items.Count); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { ClearAll(); // đưa csdl về trạng thái ban đầu } }
private void btnSave_Click(object sender, RoutedEventArgs e) { if (this.cbxSch.SelectedItem is null) { MessageBox.Show("Please choose any item of Combobox", "Notification", MessageBoxButton.OK, MessageBoxImage.Information); return; } try { if (this.txtRelName.Text.Trim().Length <= 0) { MessageBox.Show("You must enter a relation name, please try again !", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (this.txtRelName.Text.ToLower() == "select" || this.txtRelName.Text.ToLower() == "from" || this.txtRelName.Text.ToLower() == "where") { MessageBox.Show("Relation name is not valid ( not match with keyword 'select', 'from', 'where')", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } foreach (var item in StaticParams.currentDb.Relations.ToList()) { if (item.relationName.Equals(this.txtRelName.Text.ToLower(), StringComparison.OrdinalIgnoreCase)) { MessageBox.Show("This relation name has already existed in the database, please try again !", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } } PSchema schema = StaticParams.currentDb.Schemas.SingleOrDefault(c => c == this.cbxSch.SelectedItem); var relation = new PRelation(); relation.relationName = this.txtRelName.Text.ToLower(); relation.id = RawDatabaseService.Instance().getNextIdRl(); relation.schema = schema; try { //in db RawDatabaseService.Instance().Insert(relation); //in ram StaticParams.currentDb.Relations.Add(relation); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } if (MessageBox.Show("Add successfully.Do you want add a new relation name ?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { this.txtRelName.Focus(); this.txtRelName.Text = null; this.Window_Loaded(sender, e); } else { this.Close(); } } catch (Exception EX) { MessageBox.Show(EX.Message); } }