private void tsbOk_Click(object sender, EventArgs e) { if (dt.Rows.Count == 0) { DataRow row = dt.Rows.Add("table_credprogr", "table_clients", tbWhereClause.Text); } else { dt.Rows[0]["Clause"] = tbWhereClause.Text; }; TableStruct ts = new TableStruct(); ts.TableName = "where_clauses"; string[] p_keys = { "TableDBName_Left", "TableDBName_Right" }; ts.p_keys = p_keys; string[] columns = { "Clause" }; ts.columns = columns; DBFunctions.WriteToDB(dt, ts); try { DBStructure.UpdateSelectorScript(); } catch (Exception ex) { MessageBox.Show(ex.Message); } Close(); }
private void tsbEdit_Click(object sender, EventArgs e) { DataRow current_row = GreenLight.Tools.FindCurrentRow(dgTableData); if (current_row == null) { return; } var tre = new Forms.TableRecordEditorNew(cbTables.Text, current_row, HaveWriteRights()); if (tre.ShowDialog() == DialogResult.OK) { bool row_added = false; if (current_row.RowState == DataRowState.Added) { row_added = true; } DBFunctions.WriteToDB(dt_table_data, ts); if (row_added) { current_row["ID"] = Convert.ToInt32(DBFunctions.ReadScalarFromDB("SELECT LAST_INSERT_ID()")); } } else { dt_table_data.RejectChanges(); } }
private void dgQuestions_CurrentCellChanged(object sender, EventArgs e) { DataRow row = GreenLight.Tools.FindCurrentRow(dgQuestions); if (splitContainer.Panel2Collapsed == false) { //Значит есть ветвление, значит надо сохранить TableStruct ts = new TableStruct(); ts.TableName = "questionary_answers"; string[] p_keys = { "question_id", "answer" }; ts.p_keys = p_keys; string[] columns = { "answer_next_question_id" }; ts.columns = columns; DBFunctions.WriteToDB(dt_answers, ts); } if ((bool)row["question_variation"] == false) { splitContainer.Panel2Collapsed = true; } else { splitContainer.Panel2Collapsed = false; LoadAnswers((int)row["question_id"]); } }
void SaveElement() { if (tvReference.SelectedNode == null) { return; } foreach (DataColumn dc in dt_elem.Columns) { try { if (dc.DataType.Name == "String") { dt_elem.Rows[0][dc] = edit_controls[dc.ColumnName].Text; } else if (dc.DataType.Name == "Int32") { dt_elem.Rows[0][dc] = Convert.ToInt32(edit_controls[dc.ColumnName].Text); } else if (dc.DataType.Name == "Single") { dt_elem.Rows[0][dc] = Convert.ToSingle(edit_controls[dc.ColumnName].Text); } } catch (Exception) { }; } DBFunctions.WriteToDB(dt_elem, ref_table_struct); if (tvReference.SelectedNode.Tag == null) { tvReference.SelectedNode.Tag = Convert.ToInt32(DBFunctions.ReadScalarFromDB("SELECT LAST_INSERT_ID()")); //Добавим этот элемент во все мультирефы, в которых выбран его родитель Dictionary <string, object> parameters = new Dictionary <string, object>(); parameters.Add("ref_db_name", reference_db_name); DataTable dtMultirefFields = DBFunctions.ReadFromDB("SELECT tabledbname,columndbname FROM tableconfig WHERE referencemultiselect=1 and columnreference=@ref_db_name", parameters); foreach (DataRow multirefFieldRow in dtMultirefFields.Rows) { parameters.Clear(); parameters.Add("id_string", "{" + Convert.ToString(tvReference.SelectedNode.Tag) + "}"); parameters.Add("id", dt_elem.Rows[0]["ParentID"]); string query = @"UPDATE table_" + ((string)multirefFieldRow["tabledbname"]) + @" SET " + ((string)multirefFieldRow["columndbname"]) + @" = CONCAT(" + ((string)multirefFieldRow["columndbname"]) + @",@id_string) WHERE POSITION(CONCAT('{',(SELECT parentid FROM ref_data_" + reference_db_name + @" WHERE id=@id),'}') IN " + ((string)multirefFieldRow["columndbname"]) + ") > 0"; DBFunctions.ExecuteCommand(query, parameters); } } tvReference.SelectedNode.Text = (string)dt_elem.Rows[0]["RefName"]; new_node = null; }
private void tbDelete_Click(object sender, EventArgs e) { if (System.Windows.Forms.MessageBox.Show("Строка таблицы будет удалена безвозвратно. Продолжить?", "Вопрос", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) { return; } DataRow current_row = GreenLight.Tools.FindCurrentRow(dgTableData); current_row.Delete(); DBFunctions.WriteToDB(dt_table_data, ts); }
private void SaveData() { TableStruct ts = new TableStruct(); ts.TableName = "tableconfig"; string[] p_keys = { "TableConfigID" }; ts.p_keys = p_keys; string[] columns = { "TableName", "TableDBName", "ColumnName", "ColumnDBName", "ColumnType", "ColumnReference", "ReferenceMultiSelect", "ShowInOffer", "ShowInOfferShort", "ShowInEditor", "WebOrder", "UseInWhereClause", "ShowFullName" }; ts.columns = columns; DBFunctions.WriteToDB(dt_tableconfig, ts); DBStructure.UpdateDBStructure(); }
private void SaveData() { if (!Auth.AuthModule.rights.reference_struct.write) { return; } TableStruct ts = new TableStruct(); ts.TableName = "referencesconfig"; string[] p_keys = { "ReferenceConfigID" }; ts.p_keys = p_keys; string[] columns = { "ReferenceName", "ReferenceDBName", "Hierarchycal", "ColumnName", "ColumnDBName", "ColumnType" }; ts.columns = columns; DBFunctions.WriteToDB(dt_ref_config, ts); DBStructure.UpdateDBStructure(); }
private void SaveData() { if (!Auth.AuthModule.rights.questionary_editor.write) { return; } TableStruct ts = new TableStruct(); ts.TableName = "questionary_questions"; string[] p_keys = { "question_id" }; ts.p_keys = p_keys; string[] columns = { "questionary_id", "question_text", "question_variation", "question_reference", "question_type", "question_next", "question_dest_column_db_name", "question_hint", "question_input_type", "question_web_position" }; ts.columns = columns; DBFunctions.WriteToDB(dt_questions, ts); DBStructure.UpdateDBStructure(); }
private void btnNext_Click(object sender, EventArgs e) { bool is_variation = (bool)row_question["question_variation"]; object next_question = DBNull.Value; //Если анкета с фильтром, то щелкаем вопросы, пока не найдем подходящий if (!questionary_use_filter) { if (is_variation && tbAnswer.Tag != null) { next_question = DBFunctions.ReadScalarFromDB("SELECT answer_next_question_id FROM questionary_answers WHERE question_id = " + current_question_id + " AND answer = " + tbAnswer.Tag); } ; if (next_question == DBNull.Value) { next_question = row_question["question_next"]; } } else { object answerTag = tbAnswer.Tag; if (is_variation && tbAnswer.Tag != null) { next_question = DBFunctions.ReadScalarFromDB("SELECT answer_next_question_id FROM questionary_answers WHERE question_id = " + current_question_id + " AND answer = " + tbAnswer.Tag); } ; if (next_question == DBNull.Value || next_question == null) { next_question = row_question["question_next"]; } Dictionary <string, object> parameters; while (next_question != DBNull.Value) { if (dt_filter_allowed_questions.Select("question_id = " + Convert.ToString(next_question)).Length > 0) { break; } parameters = new Dictionary <string, object>(); parameters.Add("questionary_id", questionary_id); parameters.Add("q_id", next_question); next_question = DBFunctions.ReadScalarFromDB("SELECT question_next FROM questionary_questions WHERE questionary_id=@questionary_id AND question_id = @q_id", parameters); } } QuestionInfo qi = new QuestionInfo(); qi.question_id = current_question_id; qi.answer_text = tbAnswer.Text; qi.question_text = lbQuestionText.Text; try { qi.answer_id = (int)tbAnswer.Tag; } catch (Exception) { }; if ((string)row_question["question_type"] == "Справочник") { row_table_record[(string)row_question["question_dest_column_db_name"]] = qi.answer_id; } else { row_table_record[(string)row_question["question_dest_column_db_name"]] = qi.answer_text; } question_history.Add(qi); UpdateQuestionHistory(); if (next_question == DBNull.Value) { //Завершаем анкетирование, пишем в базу DBFunctions.WriteToDB(dt_table_data, ts); Close(); return; } current_question_id = (int)next_question; LoadQuestion(); }
static void UpdateMainTableStructure(string TableDBName) { //Получим требуемую структуру DataTable neededStructure = DBFunctions.ReadFromDB("SELECT TableConfigID,ColumnDBName,ColumnDBName_Old,ColumnType,ReferenceMultiSelect FROM tableconfig WHERE TableDBName = '" + TableDBName + "'"); //Получим текущую структуру DataTable CurrentStrurture = new DataTable(); bool new_table = false; try { CurrentStrurture = DBFunctions.ReadFromDB("SHOW COLUMNS FROM table_" + TableDBName); } catch (Exception) { //Таблицы не существует, будем создавать new_table = true; } if (new_table) { string CommandText = "CREATE TABLE `table_" + TableDBName + "` ("; //ПК CommandText += "`ID` int(11) NOT NULL AUTO_INCREMENT"; foreach (DataRow row in neededStructure.Rows) { if ((string)row["ColumnType"] == "Справочник" && (bool)row["ReferenceMultiSelect"] == true) { CommandText += ",`" + row["ColumnDBName"] + "` MEDIUMTEXT DEFAULT NULL"; //CreateMultiRefTable(TableDBName, (string)row["ColumnDBName"]); } { string field_type = ConvertTypeToSQL((string)row["ColumnType"]); if (field_type != null) { CommandText += ",`" + row["ColumnDBName"] + "` " + field_type + " DEFAULT NULL"; } } } CommandText += ", PRIMARY KEY (`ID`)) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8"; DBFunctions.ExecuteCommand(CommandText); } else { //Создаем и меняем строки foreach (DataRow row in neededStructure.Rows) { string col_type; if ((string)row["ColumnType"] == "Справочник" && (bool)row["ReferenceMultiSelect"] == true) { //CreateMultiRefTable(TableDBName, (string)row["ColumnDBName"]); col_type = "MEDIUMTEXT"; } else { col_type = ConvertTypeToSQL((string)row["ColumnType"]); } { //Ищем колонку DataRow[] foundRows = CurrentStrurture.Select("Field = '" + row["ColumnDBName_Old"] + "'"); if (foundRows.Length == 0) { //Добавляем колонку DBFunctions.ExecuteCommand("ALTER TABLE table_" + TableDBName + " ADD `" + row["ColumnDBName"] + "` " + col_type); } else { //Проверяем соответствие имени if ((string)foundRows[0]["Field"] != (string)row["ColumnDBName"]) { //Переименовываем колонку try { DBFunctions.ExecuteCommand("ALTER TABLE `table_" + TableDBName + "` CHANGE `" + row["ColumnDBName_Old"] + "` `" + row["ColumnDBName"] + "` " + col_type); row["ColumnDBName_Old"] = row["ColumnDBName"]; } catch (Exception) { System.Windows.Forms.MessageBox.Show("Невозможно изменить тип столбца.", "Ошибка", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } } else if ((string)foundRows[0]["Type"] != col_type) { //Меняем тип try { DBFunctions.ExecuteCommand("ALTER TABLE `table_" + TableDBName + "` MODIFY `" + row["ColumnDBName"] + "` " + col_type); } catch (Exception) { System.Windows.Forms.MessageBox.Show("Невозможно изменить тип столбца.", "Ошибка", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } } } } } //Внесем изменения конфигурационную таблицу if (neededStructure.GetChanges() != null) { TableStruct ts = new TableStruct(); ts.TableName = "tableconfig"; string[] p_keys = { "TableConfigID" }; ts.p_keys = p_keys; string[] columns = { "ColumnDBName_Old" }; ts.columns = columns; DBFunctions.WriteToDB(neededStructure, ts); } //Удалим лишние колонки foreach (DataRow row in CurrentStrurture.Rows) { if ((string)row["Field"] == "ID") { continue; } DataRow[] foundRows = neededStructure.Select("ColumnDBName = '" + row["Field"] + "'"); if (foundRows.Length == 0) { //Удаляем колонку DBFunctions.ExecuteCommand("ALTER TABLE table_" + TableDBName + " DROP `" + row["Field"] + "`"); } } //Удалим лишние таблицы с множественным выбором //DataTable multi_ref_tables = DBFunctions.ReadFromDB("SHOW TABLES WHERE tables_in_" + DBFunctions.db_name + " LIKE 'MultiRef_" + TableDBName + "_%'"); //foreach(DataRow row in multi_ref_tables.Rows) //{ // DataRow[] foundRows = neededStructure.Select("'MultiRef_" + TableDBName + "_' + ColumnDBName = '" + row["tables_in_" + DBFunctions.db_name] + "' AND ReferenceMultiSelect = 1"); /* if (foundRows.Length == 0) * { * //Удаляем таблицу * DBFunctions.ExecuteCommand("DROP TABLE `" + row["tables_in_" + DBFunctions.db_name] + "`"); * * } * }*/ } }
static void UpdateReferenceStructure(string ref_db_name) { //Получим требуемую структуру DataTable neededStructure = DBFunctions.ReadFromDB("SELECT * FROM referencesconfig WHERE ReferenceDBName = '" + ref_db_name + "'"); if (neededStructure.Rows.Count == 0) { System.Windows.Forms.MessageBox.Show("Неверное наименование справочника.", "Ошибка", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); return; } bool hierarchical = Convert.ToBoolean(neededStructure.Rows[0]["Hierarchycal"]); //Проверим есть ли такая таблица в БД bool ref_data_exists = Convert.ToBoolean(DBFunctions.ReadFromDB("Show tables like 'ref_data_" + ref_db_name + "'").Rows.Count); bool ref_hierarchy_exists = Convert.ToBoolean(DBFunctions.ReadFromDB("Show tables like 'ref_hierarchy_" + ref_db_name + "'").Rows.Count); if ((hierarchical && ref_data_exists && ref_hierarchy_exists) || //Иерархический, есть обе таблицы (!hierarchical && ref_data_exists && !ref_hierarchy_exists) //Не иерархический, есть одна таблица ) { //Всё ок, проверим соответствие состава колонок DataTable CurrentStrurture = DBFunctions.ReadFromDB("SHOW COLUMNS FROM ref_data_" + ref_db_name); //Создаем и меняем строки foreach (DataRow row in neededStructure.Rows) { //Ищем колонку DataRow[] foundRows = CurrentStrurture.Select("Field = '" + row["ColumnDBName_Old"] + "'"); if (foundRows.Length == 0) { //Добавляем колонку DBFunctions.ExecuteCommand("ALTER TABLE ref_data_" + ref_db_name + " ADD `" + row["ColumnDBName"] + "` " + ConvertTypeToSQL((string)row["ColumnType"])); } else { //Проверяем соответствие имени if ((string)foundRows[0]["Field"] != (string)row["ColumnDBName"]) { //Переименовываем колонку try { DBFunctions.ExecuteCommand("ALTER TABLE `ref_data_" + ref_db_name + "` CHANGE `" + row["ColumnDBName_Old"] + "` `" + row["ColumnDBName"] + "` " + ConvertTypeToSQL((string)row["ColumnType"])); row["ColumnDBName_Old"] = row["ColumnDBName"]; } catch (Exception) { System.Windows.Forms.MessageBox.Show("Невозможно изменить тип столбца.", "Ошибка", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } } else if ((string)foundRows[0]["Type"] != ConvertTypeToSQL((string)row["ColumnType"])) { //Меняем тип try { DBFunctions.ExecuteCommand("ALTER TABLE `ref_data_" + ref_db_name + "` MODIFY `" + row["ColumnDBName"] + "` " + ConvertTypeToSQL((string)row["ColumnType"])); } catch (Exception) { System.Windows.Forms.MessageBox.Show("Невозможно изменить тип столбца.", "Ошибка", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } } } } //Внесем изменения конфигурационную таблицу if (neededStructure.GetChanges() != null) { TableStruct ts = new TableStruct(); ts.TableName = "referencesconfig"; string[] p_keys = { "ReferenceConfigID" }; ts.p_keys = p_keys; string[] columns = { "ColumnDBName_Old" }; ts.columns = columns; DBFunctions.WriteToDB(neededStructure, ts); } //Удалим лишние колонки foreach (DataRow row in CurrentStrurture.Rows) { if ((string)row["Field"] == "id" || (string)row["Field"] == "ID") { continue; } if ((string)row["Field"] == "parentid" || (string)row["Field"] == "ParentID") { continue; } DataRow[] foundRows = neededStructure.Select("ColumnDBName = '" + row["Field"] + "'"); if (foundRows.Length == 0) { //Удаляем колонку DBFunctions.ExecuteCommand("ALTER TABLE ref_data_" + ref_db_name + " DROP `" + row["Field"] + "`"); } } //Создадим хранимые процедуры и триггеры string ref_create_script = (string)DBFunctions.ReadScalarFromDB("SELECT script FROM scripts WHERE script_name = 'Reference_Create'"); ref_create_script = ref_create_script.Replace("[RefDBName]", ref_db_name); DBFunctions.ExecuteScript(ref_create_script); return; } if (ref_data_exists || ref_hierarchy_exists) { if (System.Windows.Forms.MessageBox.Show("Сменился тип справочника " + ref_db_name + " данные справочника будут удалены. Продолжить?", "Вопрос", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) { return; } } //Удалим таблицы if (ref_data_exists) { DBFunctions.ExecuteCommand("DROP TABLE `ref_data_" + ref_db_name + "`"); } if (ref_hierarchy_exists) { DBFunctions.ExecuteCommand("DROP TABLE `ref_hierarchy_" + ref_db_name + "`"); } //Создадим новые таблицы //Таблица с данными string CommandText = "CREATE TABLE `ref_data_" + ref_db_name + "` ("; CommandText += "`ID` int(11) NOT NULL AUTO_INCREMENT"; CommandText += ",`ParentID` int(11) DEFAULT 0"; foreach (DataRow row in neededStructure.Rows) { if (row["ColumnType"] == System.DBNull.Value) { continue; } string field_type = ConvertTypeToSQL((string)row["ColumnType"]); if (field_type != null) { CommandText += ",`" + row["ColumnDBName"] + "` " + field_type + " DEFAULT NULL"; } } CommandText += ", PRIMARY KEY (`ID`)) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8"; DBFunctions.ExecuteCommand(CommandText); //Таблица с иерархией if (hierarchical) { CommandText = "CREATE TABLE `ref_hierarchy_" + ref_db_name + "` ("; CommandText += "`ElemID` int(11) NOT NULL"; CommandText += ",`ParentID` int(11) NOT NULL"; CommandText += ",`Level` int(11) NOT NULL"; CommandText += ", PRIMARY KEY (`ElemID`,`ParentID`,`Level`)) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8"; DBFunctions.ExecuteCommand(CommandText); } //Создадим хранимые процедуры и триггеры string ref_create_script_inner = (string)DBFunctions.ReadScalarFromDB("SELECT script FROM scripts WHERE script_name = 'Reference_Create'"); ref_create_script_inner = ref_create_script_inner.Replace("[RefDBName]", ref_db_name); DBFunctions.ExecuteScript(ref_create_script_inner); }