Esempio n. 1
0
        public IRemoteCommand[] GenerateCommand(DatabaseTableSolutionItem item)
        {
            var definition = tableDefinitionProvider.GetDefinition(item.DefinitionId);

            if (definition == null)
            {
                return(Array.Empty <IRemoteCommand>());
            }
            if (definition.ReloadCommand == null)
            {
                if (definition.Condition != null)
                {
                    return new IRemoteCommand[] { new ReloadRemoteCommand("reload conditions") }
                }
                ;

                return(Array.Empty <IRemoteCommand>());
            }
            if (definition.Condition == null)
            {
                return new IRemoteCommand[] { new ReloadRemoteCommand(definition.ReloadCommand) }
            }
            ;
            return(new IRemoteCommand[] { new ReloadRemoteCommand(definition.ReloadCommand), new ReloadRemoteCommand("reload conditions") });
        }
    }
}
Esempio n. 2
0
        public async Task <long> GetCount(string definitionId, string?customWhere, IEnumerable <DatabaseKey>?keys)
        {
            var definition = tableDefinitionProvider.GetDefinition(definitionId);

            if (definition == null)
            {
                return(0);
            }

            if (keys != null)
            {
                var whereKeys = BuildWhereFromKeys(definition, keys.ToArray());
                if (string.IsNullOrEmpty(customWhere))
                {
                    customWhere = whereKeys;
                }
                else
                {
                    customWhere = "(" + customWhere + ") AND " + whereKeys;
                }
            }

            var where = string.IsNullOrEmpty(customWhere) ? "" : $"WHERE ({customWhere})";
            var sql = $"SELECT COUNT(*) AS num FROM {definition.TableName} {where}";

            try
            {
                var result = await sqlExecutor.ExecuteSelectSql(sql);

                if (result.Count == 0)
                {
                    return(0);
                }
                return(Convert.ToInt64(result[0]["num"].Item2));
            }
            catch (IMySqlExecutor.CannotConnectToDatabaseException)
            {
                return(0);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(0);
            }
        }
        protected ViewModelBase(IHistoryManager history,
                                DatabaseTableSolutionItem solutionItem,
                                ISolutionItemNameRegistry solutionItemName,
                                ISolutionManager solutionManager,
                                ISolutionTasksService solutionTasksService,
                                IEventAggregator eventAggregator,
                                IQueryGenerator queryGenerator,
                                IDatabaseTableDataProvider databaseTableDataProvider,
                                IMessageBoxService messageBoxService,
                                ITaskRunner taskRunner,
                                IParameterFactory parameterFactory,
                                ITableDefinitionProvider tableDefinitionProvider,
                                IItemFromListProvider itemFromListProvider,
                                ISolutionItemIconRegistry iconRegistry,
                                ISessionService sessionService,
                                IDatabaseTableCommandService commandService,
                                IParameterPickerService parameterPickerService,
                                IStatusBar statusBar,
                                IMySqlExecutor mySqlExecutor)
        {
            this.solutionItemName          = solutionItemName;
            this.solutionManager           = solutionManager;
            this.solutionTasksService      = solutionTasksService;
            this.queryGenerator            = queryGenerator;
            this.databaseTableDataProvider = databaseTableDataProvider;
            this.messageBoxService         = messageBoxService;
            this.taskRunner              = taskRunner;
            this.parameterFactory        = parameterFactory;
            this.tableDefinitionProvider = tableDefinitionProvider;
            this.itemFromListProvider    = itemFromListProvider;
            this.sessionService          = sessionService;
            this.commandService          = commandService;
            this.parameterPickerService  = parameterPickerService;
            this.statusBar     = statusBar;
            this.mySqlExecutor = mySqlExecutor;
            this.solutionItem  = solutionItem;
            History            = history;

            undoCommand            = new DelegateCommand(History.Undo, CanUndo);
            redoCommand            = new DelegateCommand(History.Redo, CanRedo);
            Save                   = new AsyncAutoCommand(SaveSolutionItem);
            title                  = solutionItemName.GetName(solutionItem);
            Icon                   = iconRegistry.GetIcon(solutionItem);
            nameGeneratorParameter = parameterFactory.Factory("Parameter");

            History.PropertyChanged += (_, _) =>
            {
                undoCommand.RaiseCanExecuteChanged();
                redoCommand.RaiseCanExecuteChanged();
                RaisePropertyChanged(nameof(IsModified));
            };

            tableDefinition = tableDefinitionProvider.GetDefinition(solutionItem.DefinitionId) !;
            LoadAndCreateCommands();
            nameGeneratorParameter = parameterFactory.Factory(tableDefinition.Picker);
        }
Esempio n. 4
0
        public bool TryCreate(string definitionId, string[] columns, uint[] keys, object[][] data)
        {
            var definition = tableDefinitionProvider.GetDefinition(definitionId);

            if (definition == null)
            {
                return(false);
            }

            foreach (var column in columns)
            {
                if (!definition.TableColumns.ContainsKey(column))
                {
                    throw new Exception("Definition " + definitionId + " doesn't have column " + column);
                }
            }

            DatabaseTableSolutionItem item = new DatabaseTableSolutionItem(definitionId);

            item.Entries.AddRange(keys.Select(k => new SolutionItemDatabaseEntity(k, true)));

            var doc = documentProvider.GetEditor(item);

            if (doc is not MultiRowDbTableEditorViewModel document)
            {
                throw new Exception("Template not expected here, not yet impemented");
            }

            foreach (var dataRow in data)
            {
                var row = document.AddRow((uint)dataRow[0]);
                for (int i = 1; i < columns.Length; ++i)
                {
                    if (row.GetCell(columns[i]) is DatabaseField <long> lField)
                    {
                        lField.Current.Value = (long)dataRow[i];
                    }
                    else if (row.GetCell(columns[i]) is DatabaseField <float> fField)
                    {
                        fField.Current.Value = (float)dataRow[i];
                    }
                    else if (row.GetCell(columns[i]) is DatabaseField <string> sField)
                    {
                        sField.Current.Value = (string)dataRow[i];
                    }
                }
            }
            documentManager.OpenDocument(document);

            return(true);
        }
Esempio n. 5
0
        protected ViewModelBase(IHistoryManager history,
                                DatabaseTableSolutionItem solutionItem,
                                ISolutionItemNameRegistry solutionItemName,
                                ISolutionManager solutionManager,
                                ISolutionTasksService solutionTasksService,
                                IEventAggregator eventAggregator,
                                IQueryGenerator queryGenerator,
                                IDatabaseTableDataProvider databaseTableDataProvider,
                                IMessageBoxService messageBoxService,
                                ITaskRunner taskRunner,
                                IParameterFactory parameterFactory,
                                ITableDefinitionProvider tableDefinitionProvider,
                                IItemFromListProvider itemFromListProvider,
                                ISolutionItemIconRegistry iconRegistry)
        {
            this.solutionItemName          = solutionItemName;
            this.solutionManager           = solutionManager;
            this.solutionTasksService      = solutionTasksService;
            this.queryGenerator            = queryGenerator;
            this.databaseTableDataProvider = databaseTableDataProvider;
            this.messageBoxService         = messageBoxService;
            this.taskRunner           = taskRunner;
            this.parameterFactory     = parameterFactory;
            this.itemFromListProvider = itemFromListProvider;
            this.solutionItem         = solutionItem;
            History = history;

            undoCommand            = new DelegateCommand(History.Undo, CanUndo);
            redoCommand            = new DelegateCommand(History.Redo, CanRedo);
            Save                   = new DelegateCommand(SaveSolutionItem);
            title                  = solutionItemName.GetName(solutionItem);
            Icon                   = iconRegistry.GetIcon(solutionItem);
            nameGeneratorParameter = parameterFactory.Factory("Parameter");

            History.PropertyChanged += (_, _) =>
            {
                undoCommand.RaiseCanExecuteChanged();
                redoCommand.RaiseCanExecuteChanged();
                RaisePropertyChanged(nameof(IsModified));
            };

            tableDefinition        = tableDefinitionProvider.GetDefinition(solutionItem.DefinitionId) !;
            nameGeneratorParameter = parameterFactory.Factory(tableDefinition.Picker);

            AutoDispose(eventAggregator.GetEvent <EventRequestGenerateSql>()
                        .Subscribe(ExecuteSql));
        }
Esempio n. 6
0
        public IRemoteCommand[] GenerateCommand(DatabaseTableSolutionItem item)
        {
            var definition = tableDefinitionProvider.GetDefinition(item.DefinitionId);

            if (definition == null)
            {
                return(Array.Empty <IRemoteCommand>());
            }
            if (definition.ReloadCommand == null)
            {
                if (definition.Condition != null)
                {
                    return new IRemoteCommand[] { new ReloadRemoteCommand("reload conditions", RemoteCommandPriority.Middle) }
                }
                ;

                return(Array.Empty <IRemoteCommand>());
            }

            List <IRemoteCommand> commands = new();
            var split = definition.ReloadCommand.Split(',');

            var priority = 0;

            foreach (var cmd in split)
            {
                if (cmd.Contains("{}"))
                {
                    var newCmd = cmd.Replace("{}", string.Join(" ", item.Entries.Select(x => x.Key[0])));

                    commands.Add(new ReloadRemoteCommand(newCmd, (RemoteCommandPriority)priority));
                }
                else
                {
                    commands.Add(new ReloadRemoteCommand(cmd, (RemoteCommandPriority)priority));
                }
                priority++;
            }

            if (definition.Condition != null)
            {
                commands.Add(new ReloadRemoteCommand("reload conditions", (RemoteCommandPriority)priority));
            }
            return(commands.ToArray());
        }
    }
Esempio n. 7
0
        public string GetName(DatabaseTableSolutionItem item)
        {
            var definition = tableDefinitionProvider.GetDefinition(item.DefinitionId);

            if (definition == null)
            {
                return($"Unknown item (" + item.DefinitionId + ")");
            }

            var parameter = parameterFactory.Factory(definition.Picker);

            if (item.Entries.Count == 1)
            {
                var name = parameter.ToString(item.Entries[0].Key);
                return(definition.SingleSolutionName.Replace("{name}", name).Replace("{key}", item.Entries[0].Key.ToString()));
            }

            return(definition.MultiSolutionName);
        }
        public Task Invoke(ICommandArguments arguments)
        {
            if (!arguments.TryGetString(out var tableName))
            {
                return(Task.CompletedTask);
            }

            var definition = tableDefinitionProvider.GetDefinition(tableName);

            if (definition == null)
            {
                return(Task.CompletedTask);
            }

            if (definition.RecordMode == RecordMode.SingleRow)
            {
                eventAggregator.GetEvent <EventRequestOpenItem>().Publish(new DatabaseTableSolutionItem(definition.Id, definition.IgnoreEquality));

                if (!arguments.TryGetUint(out var entry_))
                {
                    return(Task.CompletedTask);
                }

                foreach (var doc in documentManager.Value.OpenedDocuments)
                {
                    if (doc is SingleRowDbTableEditorViewModel singleRow && singleRow.TableDefinition.Id == definition.Id)
                    {
                        var rest = arguments.TakeRestArguments;
                        return(singleRow.TryFind(new DatabaseKey(entry_), rest));
                    }
                }
                return(Task.CompletedTask);
            }

            if (!arguments.TryGetUint(out var entry))
            {
                return(Task.CompletedTask);
            }

            eventAggregator.GetEvent <EventRequestOpenItem>().Publish(new DatabaseTableSolutionItem(new DatabaseKey(entry), true, tableName, definition.IgnoreEquality));
            return(Task.CompletedTask);
        }
        public IDocument GetEditor(DatabaseTableSolutionItem item)
        {
            var definition = tableDefinitionProvider.GetDefinition(item.DefinitionId);

            if (definition == null)
            {
                if (tableDefinitionProvider.CoreCompatibility(item.DefinitionId) is { } compatibility)
                {
                    throw new Exception("This item was created with different core compatibility mode and cannot be opened now. If you want to open the item, switch to any of those core compatibility modes: " + string.Join(", ", compatibility));
                }

                throw new Exception("Cannot find table editor for definition " + item.DefinitionId + ". If you think this is a bug, please report it via Help -> Report a bug");
            }

            if (definition.IsMultiRecord)
            {
                return(containerRegistry.Resolve <MultiRowDbTableEditorViewModel>((typeof(DatabaseTableSolutionItem), item)));
            }
            return(containerRegistry.Resolve <TemplateDbTableEditorViewModel>((typeof(DatabaseTableSolutionItem), item)));
        }
Esempio n. 10
0
    public async Task <long?> PickByColumn(string table, DatabaseKey?key, string column, long?initialValue, string?backupColumn = null)
    {
        var definition = definitionProvider.GetDefinition(table);

        if (definition == null)
        {
            throw new UnsupportedTableException(table);
        }

        if (definition.RecordMode != RecordMode.SingleRow && !key.HasValue)
        {
            throw new Exception("Pick by column is not supported for multi-row tables without key");
        }

        var solutionItem = await tableOpenService.Create(definition, key ?? default);

        if (solutionItem == null)
        {
            throw new UnsupportedTableException(table);
        }

        bool          openInNoSaveMode = IsItemAlreadyOpened((DatabaseTableSolutionItem)solutionItem, out _);
        ViewModelBase tableViewModel;

        if (definition.RecordMode == RecordMode.MultiRecord)
        {
            var multiRow = containerProvider.Resolve <MultiRowDbTableEditorViewModel>((typeof(DatabaseTableSolutionItem), solutionItem));
            tableViewModel             = multiRow;
            multiRow.AllowMultipleKeys = false;
            if (initialValue.HasValue)
            {
                tableViewModel.ToObservable(that => that.IsLoading)
                .Where(@is => !@is)
                .SubscribeOnce(@is =>
                {
                    var group = multiRow.Rows.FirstOrDefault(row => row.Key == key);
                    if (group != null)
                    {
                        var row = group.FirstOrDefault(r =>
                                                       (r.Entity.GetCell(column) is DatabaseField <long> longField &&
                                                        longField.Current.Value == initialValue) ||
                                                       (backupColumn != null && r.Entity.GetCell(backupColumn) is DatabaseField <long> longField2 &&
                                                        longField2.Current.Value == initialValue));
                        if (row != null)
                        {
                            mainThread.Delay(() => multiRow.SelectedRow = row, TimeSpan.FromMilliseconds(1));
                        }
                    }
                });
            }
        }
        else if (definition.RecordMode == RecordMode.SingleRow)
        {
            var singleRow = containerProvider.Resolve <SingleRowDbTableEditorViewModel>((typeof(DatabaseTableSolutionItem), solutionItem));
            tableViewModel = singleRow;
            if (key != null)
            {
                singleRow.FilterViewModel.FilterText = $"`{definition.GroupByKeys[0]}` = {key.Value[0]}";
            }
            if (initialValue.HasValue)
            {
                singleRow.TryFind(key.HasValue ? key.Value.WithAlso(initialValue.Value) : new DatabaseKey(initialValue.Value)).ListenErrors();
            }
            if (key != null)
            {
                singleRow.FilterViewModel.ApplyFilter.Execute(null);
            }
        }
        else
        {
            throw new Exception("TemplateMode not (yet?) supported");
        }

        var viewModel = containerProvider.Resolve <RowPickerViewModel>((typeof(ViewModelBase), tableViewModel), (typeof(bool), openInNoSaveMode));

        if (await windowManager.ShowDialog(viewModel))
        {
            var col = viewModel.SelectedRow?.GetCell(column);
            if (col is DatabaseField <long> longColumn)
            {
                return(longColumn.Current.Value);
            }
            else if (backupColumn != null)
            {
                col = viewModel.SelectedRow?.GetCell(backupColumn);
                if (col is DatabaseField <long> longColumn2)
                {
                    return(longColumn2.Current.Value);
                }
            }
            Console.WriteLine($"Couldn't find column {column} or {backupColumn} in {tableViewModel.TableDefinition.Name}");
        }
        return(null);
    }
Esempio n. 11
0
        public async Task <IDatabaseTableData?> Load(string definitionId, params uint[] keys)
        {
            var definition = tableDefinitionProvider.GetDefinition(definitionId);

            if (definition == null)
            {
                return(null);
            }

            IList <Dictionary <string, (Type, object)> >?result = null;

            IDatabaseProvider.ConditionKeyMask keyMask = IDatabaseProvider.ConditionKeyMask.None;
            if (definition.Condition != null)
            {
                if (definition.Condition.SourceEntryColumn != null)
                {
                    keyMask |= IDatabaseProvider.ConditionKeyMask.SourceEntry;
                }
                if (definition.Condition.SourceGroupColumn != null)
                {
                    keyMask |= IDatabaseProvider.ConditionKeyMask.SourceGroup;
                }
                if (definition.Condition.SourceIdColumn != null)
                {
                    keyMask |= IDatabaseProvider.ConditionKeyMask.SourceId;
                }
            }

            if (keys.Length > 0)
            {
                if (definition.IsOnlyConditionsTable)
                {
                    if (definition.Condition == null)
                    {
                        throw new Exception("only_conditions + no conditions make no sense");
                    }

                    result = new List <Dictionary <string, (Type, object)> >();

                    foreach (var key in keys)
                    {
                        int?sourceGroup = null, sourceEntry = null, sourceId = null;
                        if (definition.Condition.SourceGroupColumn != null &&
                            definition.TablePrimaryKeyColumnName == definition.Condition.SourceGroupColumn)
                        {
                            keyMask     = IDatabaseProvider.ConditionKeyMask.SourceGroup;
                            sourceGroup = (int)key;
                        }

                        if (definition.Condition.SourceEntryColumn != null &&
                            definition.TablePrimaryKeyColumnName == definition.Condition.SourceEntryColumn)
                        {
                            keyMask     = IDatabaseProvider.ConditionKeyMask.SourceEntry;
                            sourceEntry = (int)key;
                        }

                        if (definition.Condition.SourceIdColumn != null &&
                            definition.TablePrimaryKeyColumnName == definition.Condition.SourceIdColumn)
                        {
                            keyMask  = IDatabaseProvider.ConditionKeyMask.SourceId;
                            sourceId = (int)key;
                        }

                        IList <IConditionLine>?conditionList = await databaseProvider.GetConditionsForAsync(keyMask,
                                                                                                            new IDatabaseProvider.ConditionKey(definition.Condition.SourceType, sourceGroup,
                                                                                                                                               sourceEntry, sourceId));

                        if (conditionList != null && conditionList.Count > 0)
                        {
                            foreach (var distinct in conditionList
                                     .Select(line => (line.SourceEntry, line.SourceGroup, line.SourceId)).Distinct())
                            {
                                var row        = new Dictionary <string, (Type, object)>();
                                var conditions = conditionList.Where(l =>
                                                                     l.SourceEntry == distinct.SourceEntry && l.SourceId == distinct.SourceId &&
                                                                     l.SourceGroup == distinct.SourceGroup).ToList();

                                foreach (var column in definition.TableColumns.Values)
                                {
                                    if (column.IsConditionColumn)
                                    {
                                        continue;
                                    }
                                    if (definition.Condition.SourceGroupColumn != null &&
                                        column.DbColumnName == definition.Condition.SourceGroupColumn)
                                    {
                                        row.Add(column.DbColumnName, (typeof(int), distinct.SourceGroup));
                                    }

                                    if (definition.Condition.SourceEntryColumn != null &&
                                        column.DbColumnName == definition.Condition.SourceEntryColumn)
                                    {
                                        row.Add(column.DbColumnName, (typeof(int), distinct.SourceEntry));
                                    }

                                    if (definition.Condition.SourceIdColumn != null &&
                                        column.DbColumnName == definition.Condition.SourceIdColumn)
                                    {
                                        row.Add(column.DbColumnName, (typeof(int), distinct.SourceId));
                                    }
                                }
                                row.Add("conditions", (typeof(IList <IConditionLine>), conditions));
                                result.Add(row);
                            }
                        }
                    }
                }
                else
                {
                    var sqlStatement = BuildSQLQueryFromTableDefinition(definition, keys);
                    try
                    {
                        result = await sqlExecutor.ExecuteSelectSql(sqlStatement);

                        if (definition.Condition != null)
                        {
                            foreach (var row in result)
                            {
                                int?sourceGroup = null, sourceEntry = null, sourceId = null;

                                if (definition.Condition.SourceGroupColumn != null &&
                                    row.TryGetValue(definition.Condition.SourceGroupColumn, out var groupData) &&
                                    int.TryParse(groupData.Item2.ToString(), out var groupInt))
                                {
                                    sourceGroup = groupInt;
                                }

                                if (definition.Condition.SourceEntryColumn != null &&
                                    row.TryGetValue(definition.Condition.SourceEntryColumn, out var entryData) &&
                                    int.TryParse(entryData.Item2.ToString(), out var entryInt))
                                {
                                    sourceEntry = entryInt;
                                }

                                if (definition.Condition.SourceIdColumn != null &&
                                    row.TryGetValue(definition.Condition.SourceIdColumn, out var idData) &&
                                    int.TryParse(idData.Item2.ToString(), out var idInt))
                                {
                                    sourceId = idInt;
                                }

                                IList <IConditionLine>?conditionList = await databaseProvider.GetConditionsForAsync(keyMask,
                                                                                                                    new IDatabaseProvider.ConditionKey(definition.Condition.SourceType, sourceGroup,
                                                                                                                                                       sourceEntry, sourceId));

                                if (conditionList == null || conditionList.Count == 0)
                                {
                                    conditionList = new List <IConditionLine>();
                                }
                                row.Add("conditions", (typeof(IList <IConditionLine>), conditionList !));
                            }
                        }
                    }
                    catch (IMySqlExecutor.CannotConnectToDatabaseException)
                    {
                    }
                    catch (Exception e)
                    {
                        await messageBoxService.ShowDialog(new MessageBoxFactory <bool>()
                                                           .SetTitle("Database error")
                                                           .SetMainInstruction(
                                                               "Unable to execute SQL query. Most likely your database is incompatible with provided database schema, if you think this is a bug, report it via Help -> Report Bug")
                                                           .SetContent(e.ToString())
                                                           .SetIcon(MessageBoxIcon.Error)
                                                           .WithOkButton(false)
                                                           .Build());

                        return(null);
                    }
                }
            }

            if (result == null)
            {
                result = new List <Dictionary <string, (Type, object)> >();
            }

            return(tableModelGenerator.CreateDatabaseTable(definition, keys, result));
        }