예제 #1
0
        public static InsertInto <TEntity> InsertInto <TEntity>(string table = null, string identity = null)
        {
            var query = new InsertInto <TEntity>();

            var type = typeof(TEntity);

            query.Table = string.IsNullOrEmpty(table) ? type.Name : table;

            var properties = type.GetProperties().ToList();

            if (properties.Any(item => item.Name == identity))
            {
                query.Identity = identity;
            }

            foreach (var property in properties)
            {
                if (!string.IsNullOrEmpty(identity) && identity == property.Name)
                {
                    continue;
                }

                query.Columns.Add(property.Name);
            }

            if (!string.IsNullOrEmpty(query.Identity))
            {
                query.Footer = identity;
            }

            return(query);
        }
예제 #2
0
        /// <summary>
        /// 値をテーブルへ挿入する
        /// </summary>
        /// <typeparam name="TColumns">プロパティを列として扱う<see cref="TableDef{TColumns}"/>のTColumnsに該当するクラス</typeparam>
        /// <param name="table">挿入先テーブル</param>
        /// <param name="columnsExpression">列と設定値を指定する t => new[] { t.A == a, t.B == b } の様な式</param>
        /// <returns>INSERT INTO句ノード</returns>
        public InsertInto <TColumns> InsertIntoWithValue <TColumns>(TableDef <TColumns> table, Expression <Func <TColumns, bool[]> > columnsExpression)
        {
            var node = new InsertInto <TColumns>(this, table, columnsExpression);

            this.Children.Add(node);
            return(node);
        }
예제 #3
0
        public async Task VerifyHasTableWorks()
        {
            DropTable.For <Player>().TryExecute(Connection);

            await Table.Ensure <Player>(Connection);

            await InsertInto.Row(Create("Willem")).ExecuteAsync(Connection);

            await InsertInto.Row(Create("Willemse")).ExecuteAsync(Connection);

            await InsertInto.Row(Create("Bastiaan")).ExecuteAsync(Connection);

            await InsertInto.Row(Create("Harry")).ExecuteAsync(Connection);

            Console.WriteLine(Select <Player> .All().WhereContains(x => x.Name, "illem").Format(SqlFormat.MySql));
            var result = Select <Player> .All().WhereContains(x => x.Name, "illem").ExecuteRead(Connection).ToList();

            Assert.That(result, Has.Count.EqualTo(2));

            result = Select <Player> .All().WhereStartsWith(x => x.Name, "bas").ExecuteRead(Connection).ToList();

            Assert.That(result, Has.Count.EqualTo(1));
            Assert.That(result[0].Name, Is.EqualTo("Bastiaan"));

            result = Select <Player> .All().WhereEndsWith(x => x.Name, "ry").ExecuteRead(Connection).ToList();

            Assert.That(result, Has.Count.EqualTo(1));
            Assert.That(result[0].Name, Is.EqualTo("Harry"));
        }
        public static InsertInto <TEntity> InsertInto <TEntity>(TEntity entity, string table = null, string identity = null, IDatabaseNamingConvention dbNamingConvention = null)
        {
            var type = typeof(TEntity);

            var query = new InsertInto <TEntity>
            {
                NamingConvention = dbNamingConvention ?? DatabaseNamingConvention,
                Table            = string.IsNullOrEmpty(table) ? type.Name : table
            };

            var properties = type.GetProperties().ToList();

            if (properties.Any(item => item.Name == identity))
            {
                query.Identity = identity;
            }

            foreach (var property in properties)
            {
                if (!string.IsNullOrEmpty(identity) && identity == property.Name)
                {
                    continue;
                }

                var value = property.GetValue(entity);

                query.Columns.Add(new InsertIntoColumn(property.Name, value));
            }

            return(query);
        }
예제 #5
0
파일: Sql.cs 프로젝트: nQuantums/tips
        public InsertInto <TColumns, TColumnsOrder> InsertInto <TColumns, TColumnsOrder>(TableDef <TColumns> table, ISelect <TColumnsOrder> select) where TColumnsOrder : TColumns
        {
            var node = new InsertInto <TColumns, TColumnsOrder>(this, table, select);

            this.AddChild(node);
            return(node);
        }
예제 #6
0
        public void WhenRecordInsertedWithAutoIncrementIdentityGetsUpdated()
        {
            DropTable.For <TableWithIncrement>().TryExecute(Connection);
            CreateTable.For <TableWithIncrement>().Execute(Connection);

            var first = new TableWithIncrement
            {
                Value = "Foo"
            };

            var second = new TableWithIncrement
            {
                Value = "Bar"
            };

            var numberFirst  = InsertInto.Row(first).GetLastInsertIdentity <ulong>().ExecuteRead(Connection).Single();
            var numberSecond = InsertInto.Row(second).GetLastInsertIdentity <ulong>().ExecuteRead(Connection).Single();

            Assert.That(numberFirst, Is.EqualTo(1));
            Assert.That(numberSecond, Is.EqualTo(2));

            var firstSelected = Select.From <TableWithIncrement>().WhereEqual(x => x.Identifier, 1UL)
                                .ExecuteRead(Connection)
                                .SingleOrDefault();

            Assert.IsNotNull(firstSelected);
            Assert.That(firstSelected.Identifier, Is.EqualTo(1UL));
            Assert.That(firstSelected.Value, Is.EqualTo("Foo"));
        }
예제 #7
0
        public void WhenRecordsInsertedTheyCanGetUpdated()
        {
            DropTable.For <Player>().TryExecute(Connection);
            CreateTable.For <Player>().Execute(Connection);

            var player = new Player
            {
                Age        = 10,
                Birthday   = DateTime.Now,
                Identifier = Guid.NewGuid(),
                Name       = "Jim"
            };

            Assert.That(InsertInto.Row(player).TryExecute(Connection));
            var records = Select.From <Player>().ExecuteRead(Connection).ToImmutableList();

            Assert.That(records, Has.Count.EqualTo(1));
            Assert.That(records[0].Name, Is.EqualTo("Jim"));

            player.Name = "John";
            Assert.That(InsertInto.Row(player).TryExecute(Connection), Is.False);

            records = Select.From <Player>().ExecuteRead(Connection).ToImmutableList();
            Assert.That(records, Has.Count.EqualTo(1));
            Assert.That(records[0].Name, Is.EqualTo("Jim"));

            Assert.That(InsertInto.Row(player).UpdateOnDuplicateKey.TryExecute(Connection));

            records = Select.From <Player>().ExecuteRead(Connection).ToImmutableList();
            Assert.That(records, Has.Count.EqualTo(1));
            Assert.That(records[0].Name, Is.EqualTo("John"));
        }
예제 #8
0
        public void SupportForBasicTypes()
        {
            var value = new ExtendedTable
            {
                Age        = 10,
                Identifier = Guid.NewGuid(),
                Name       = "Foo",
                Payload    = new SomeOtherClass
                {
                    Content = 255
                }
            };

            string expected = @"INSERT INTO Extended (Identifier, Name, Age, Payload) VALUES ('" +
                              value.Identifier.ToString("N") + "', 'Foo', 10, x'FF000000')";


            string command = InsertInto.Row(value).Format(SqlFormat.MySql);

            Assert.That(command, Is.EqualTo(expected));

            command = InsertInto.Row(value).UpdateOnDuplicateKey.Format(SqlFormat.MySql);

            string fullExpected = expected + "\r\nON DUPLICATE KEY UPDATE Identifier='" +
                                  value.Identifier.ToString("N") +
                                  "', Name='Foo', Age=10, Payload=x'FF000000'";

            Assert.That(command, Is.EqualTo(fullExpected));
        }
예제 #9
0
        /// <summary>
        /// 同一値が無い場合のみ値をテーブルへ挿入する
        /// </summary>
        /// <typeparam name="TColumns">プロパティを列として扱う<see cref="TableDef{TColumns}"/>のTColumnsに該当するクラス</typeparam>
        /// <param name="table">挿入先テーブル</param>
        /// <param name="columnsExpression">列と設定値を指定する t => new[] { t.A == a, t.B == b } の様な式</param>
        /// <param name="columnCountToWhere">NOT EXISTS (SELECT * FROM t WHERE t.Name = "test") の部分で判定に使用する列数、0が指定されたら全て使用する</param>
        /// <returns>INSERT INTO句ノード</returns>
        public InsertInto <TColumns> InsertIntoWithValueIfNotExists <TColumns>(TableDef <TColumns> table, Expression <Func <TColumns, bool[]> > columnsExpression, int columnCountToWhere = 0)
        {
            var node = new InsertInto <TColumns>(this, table, columnsExpression);

            node.IfNotExists(columnCountToWhere);
            this.Children.Add(node);
            return(node);
        }
예제 #10
0
        public void SupportForAutoIncrement()
        {
            var value = new TableWithIncrement
            {
                Value = "Foo"
            };

            string expected =
                $"INSERT INTO with_autoincrement (Value) VALUES ('Foo');{Environment.NewLine}SELECT LAST_INSERT_ID();";
            string command = InsertInto.Row(value).GetLastInsertIdentity <long>().Format(SqlFormat.MySql);

            Assert.That(command, Is.EqualTo(expected));
        }
예제 #11
0
        public void VerifyEnumWriteAndRead()
        {
            DropTable.For <EnumTable>().TryExecute(Connection);
            CreateTable.For <EnumTable>().Execute(Connection);

            var value = new EnumTable
            {
                Name      = "Foo",
                Something = Something.Second
            };

            InsertInto.Row(value).Execute(Connection);

            var values = Select.From <EnumTable>().WhereEqual(x => x.Name, "Foo").ExecuteRead(Connection).ToList();

            Assert.That(values, Has.Count.EqualTo(1));
            Assert.That(values[0].Something, Is.EqualTo(Something.Second));
            Assert.That(values[0].Name, Is.EqualTo("Foo"));
        }
        public static IDbCommand CreateCommand <TEntity>(this InsertInto <TEntity> query, IDbConnection connection)
        {
            var command = connection.CreateCommand();

            command.CommandText = query.ToString();

            foreach (var column in query.Columns)
            {
                var parameter = command.CreateParameter();

                parameter.ParameterName = query.NamingConvention.GetParameterName(column.Name);
                parameter.Value         = column.Value;

                command.Parameters.Add(parameter);
            }

            if (!string.IsNullOrEmpty(query.Identity))
            {
                var parameter = command.CreateParameter();

                var type     = typeof(TEntity);
                var property = type.GetProperties().First(item => item.Name == query.Identity);

                if (property.PropertyType == typeof(int) || property.PropertyType == typeof(int?))
                {
                    parameter.DbType = DbType.Int32;
                }

                parameter.Direction     = ParameterDirection.Output;
                parameter.ParameterName = query.NamingConvention.GetParameterName(query.Identity);

                command.Parameters.Add(parameter);
            }

            return(command);
        }
예제 #13
0
        public void InsertAndSelectProtoBuffer()
        {
            DropTable.For <IdentifiedBlob>().TryExecute(Connection);
            CreateTable.For <IdentifiedBlob>().Execute(Connection);

            var value = new IdentifiedBlob
            {
                Identifier = Guid.NewGuid(),
                Value      = new Payload
                {
                    ValueA = 42,
                    ValueB = -44
                }
            };

            InsertInto.Row(value).Execute(Connection);

            var result = Select.From <IdentifiedBlob>().ExecuteRead(Connection).ToImmutableList();

            Assert.That(result, Has.Count.EqualTo(1));
            Assert.That(result[0].Identifier, Is.EqualTo(value.Identifier));
            Assert.That(result[0].Value.ValueA, Is.EqualTo(value.Value.ValueA));
            Assert.That(result[0].Value.ValueB, Is.EqualTo(value.Value.ValueB));
        }
예제 #14
0
        /// <summary>
        ///     Renders the object model in it's EPL syntax textual representation, using a whitespace-formatter as provided.
        /// </summary>
        /// <param name="formatter">the formatter to use</param>
        /// <param name="writer">writer to use</param>
        /// <throws>IllegalStateException if required clauses do not exist</throws>
        public void ToEPL(
            EPStatementFormatter formatter,
            TextWriter writer)
        {
            AnnotationPart.ToEPL(writer, Annotations, formatter);
            ExpressionDeclaration.ToEPL(writer, ExpressionDeclarations, formatter);
            ScriptExpression.ToEPL(writer, ScriptExpressions, formatter);
            ClassProvidedExpression.ToEPL(writer, ClassProvidedExpressions, formatter);

            if (ContextName != null)
            {
                formatter.BeginContext(writer);
                writer.Write("context ");
                writer.Write(ContextName);
            }

            if (CreateIndex != null)
            {
                formatter.BeginCreateIndex(writer);
                CreateIndex.ToEPL(writer);
                return;
            }

            if (CreateSchema != null)
            {
                formatter.BeginCreateSchema(writer);
                CreateSchema.ToEPL(writer);
                return;
            }

            if (CreateExpression != null)
            {
                formatter.BeginCreateExpression(writer);
                CreateExpression.ToEPL(writer);
                return;
            }

            if (CreateClass != null)
            {
                formatter.BeginCreateExpression(writer);
                CreateClass.ToEPL(writer);
                return;
            }

            if (CreateContext != null)
            {
                formatter.BeginCreateContext(writer);
                CreateContext.ToEPL(writer, formatter);
                return;
            }

            if (CreateWindow != null)
            {
                formatter.BeginCreateWindow(writer);
                CreateWindow.ToEPL(writer);

                writer.Write(" as ");

                if (SelectClause == null || SelectClause.SelectList.IsEmpty() && !CreateWindow.Columns.IsEmpty())
                {
                    CreateWindow.ToEPLCreateTablePart(writer);
                }
                else
                {
                    SelectClause.ToEPL(writer, formatter, false, false);
                    if (CreateWindow.AsEventTypeName != null)
                    {
                        writer.Write(" from ");
                        writer.Write(CreateWindow.AsEventTypeName);
                    }

                    CreateWindow.ToEPLInsertPart(writer);
                }

                return;
            }

            if (CreateVariable != null)
            {
                formatter.BeginCreateVariable(writer);
                CreateVariable.ToEPL(writer);
                return;
            }

            if (CreateTable != null)
            {
                formatter.BeginCreateTable(writer);
                CreateTable.ToEPL(writer);
                return;
            }

            if (CreateDataFlow != null)
            {
                formatter.BeginCreateDataFlow(writer);
                CreateDataFlow.ToEPL(writer, formatter);
                return;
            }

            var displayWhereClause = true;

            if (UpdateClause != null)
            {
                formatter.BeginUpdate(writer);
                UpdateClause.ToEPL(writer);
            }
            else if (OnExpr != null)
            {
                formatter.BeginOnTrigger(writer);
                writer.Write("on ");
                FromClause.Streams[0].ToEPL(writer, formatter);

                if (OnExpr is OnDeleteClause onDeleteClause)
                {
                    formatter.BeginOnDelete(writer);
                    writer.Write("delete from ");
                    onDeleteClause.ToEPL(writer);
                }
                else if (OnExpr is OnUpdateClause onUpdateClause)
                {
                    formatter.BeginOnUpdate(writer);
                    writer.Write("update ");
                    onUpdateClause.ToEPL(writer);
                }
                else if (OnExpr is OnSelectClause onSelectClause)
                {
                    InsertInto?.ToEPL(writer, formatter, true);
                    SelectClause.ToEPL(writer, formatter, true, onSelectClause.IsDeleteAndSelect);
                    writer.Write(" from ");
                    onSelectClause.ToEPL(writer);
                }
                else if (OnExpr is OnSetClause onSetClause)
                {
                    onSetClause.ToEPL(writer, formatter);
                }
                else if (OnExpr is OnMergeClause onMergeClause)
                {
                    onMergeClause.ToEPL(writer, WhereClause, formatter);
                    displayWhereClause = false;
                }
                else
                {
                    var split = (OnInsertSplitStreamClause)OnExpr;
                    InsertInto.ToEPL(writer, formatter, true);
                    SelectClause.ToEPL(writer, formatter, true, false);
                    if (WhereClause != null)
                    {
                        writer.Write(" where ");
                        WhereClause.ToEPL(writer, ExpressionPrecedenceEnum.MINIMUM);
                    }

                    split.ToEPL(writer, formatter);
                    displayWhereClause = false;
                }
            }
            else
            {
                IntoTableClause?.ToEPL(writer);

                if (SelectClause == null)
                {
                    throw new IllegalStateException("Select-clause has not been defined");
                }

                if (FromClause == null)
                {
                    throw new IllegalStateException("From-clause has not been defined");
                }

                if (FireAndForgetClause is FireAndForgetUpdate fireAndForgetUpdate)
                {
                    writer.Write("update ");
                    FromClause.ToEPLOptions(writer, formatter, false);
                    writer.Write(" ");
                    UpdateClause.RenderEPLAssignments(writer, fireAndForgetUpdate.Assignments);
                }
                else if (FireAndForgetClause is FireAndForgetInsert fireAndForgetInsert)
                {
                    InsertInto.ToEPL(writer, formatter, true);
                    if (fireAndForgetInsert.IsUseValuesKeyword)
                    {
                        writer.Write(" values (");
                        var delimiter = "";
                        foreach (var element in SelectClause.SelectList)
                        {
                            writer.Write(delimiter);
                            element.ToEPLElement(writer);
                            delimiter = ", ";
                        }

                        writer.Write(")");
                    }
                    else
                    {
                        SelectClause.ToEPL(writer, formatter, true, false);
                    }
                }
                else if (FireAndForgetClause is FireAndForgetDelete)
                {
                    writer.Write("delete ");
                    FromClause.ToEPLOptions(writer, formatter, true);
                }
                else
                {
                    InsertInto?.ToEPL(writer, formatter, true);
                    SelectClause.ToEPL(writer, formatter, true, false);
                    FromClause.ToEPLOptions(writer, formatter, true);
                }
            }

            MatchRecognizeClause?.ToEPL(writer);

            if (WhereClause != null && displayWhereClause)
            {
                formatter.BeginWhere(writer);
                writer.Write("where ");
                WhereClause.ToEPL(writer, ExpressionPrecedenceEnum.MINIMUM);
            }

            if (GroupByClause != null)
            {
                formatter.BeginGroupBy(writer);
                writer.Write("group by ");
                GroupByClause.ToEPL(writer);
            }

            if (HavingClause != null)
            {
                formatter.BeginHaving(writer);
                writer.Write("having ");
                HavingClause.ToEPL(writer, ExpressionPrecedenceEnum.MINIMUM);
            }

            if (OutputLimitClause != null)
            {
                formatter.BeginOutput(writer);
                writer.Write("output ");
                OutputLimitClause.ToEPL(writer);
            }

            if (OrderByClause != null)
            {
                formatter.BeginOrderBy(writer);
                writer.Write("order by ");
                OrderByClause.ToEPL(writer);
            }

            if (RowLimitClause != null)
            {
                formatter.BeginLimit(writer);
                writer.Write("limit ");
                RowLimitClause.ToEPL(writer);
            }

            if (ForClause != null)
            {
                formatter.BeginFor(writer);
                ForClause.ToEPL(writer);
            }
        }
예제 #15
0
        public static IQuery Parse(string miniSqlSentence)
        {
            const string selectAllPattern             = @"SELECT \* FROM ([a-zA-Z0-9]+);";
            const string deletePattern                = @"DELETE FROM ([a-zA-Z0-9]+) WHERE ([a-zA-Z]+)([=><])('{0,1})([a-zA-Z0-9-\.\s]+)\4;";
            const string updatePattern                = @"UPDATE ([a-zA-Z0-9]+) SET ([a-zA-Z0-9]+=('{0,1})[a-zA-Z0-9\.\s-]+\3(,[a-zA-Z0-9]+=('{0,1})[a-zA-Z0-9\.\s-]+\5)*) WHERE ([a-zA-Z]+)([=><])('{0,1})([a-zA-Z0-9-\.\s]+)\8;";
            const string selectAllWherePattern        = @"SELECT \* FROM ([a-zA-Z0-9]+) WHERE ([a-zA-Z]+)([=><])('{0,1})([a-zA-Z0-9-\.\s]+)\4;";
            const string selectColumnsPattern         = @"SELECT ([a-zA-Z0-9]+(,[a-zA-Z0-9]+)*) FROM ([a-zA-Z0-9]+);";
            const string selectColumnsWherePattern    = @"SELECT ([a-zA-Z0-9]+(,[a-zA-Z0-9]+)*) FROM ([a-zA-Z0-9]+) WHERE ([a-zA-Z0-9]+)([=><])('{0,1})([a-zA-Z0-9-\.\s]+)\6;";
            const string insertIntoPattern            = @"INSERT INTO ([a-zA-Z0-9]+) VALUES \(((('{0,1})[a-zA-Z0-9\.\s-]+\4)+(,('{0,1})[a-zA-Z0-9\.\s-]+\6)*)\);";
            const string dropTablePattern             = @"DROP TABLE ([a-zA-Z0-9]+);";
            const string createTablePattern           = @"CREATE TABLE ([a-zA-Z0-9]+) \(((([a-zA-Z0-9]+) (INT|DOUBLE|TEXT))+((,([a-zA-Z0-9]+) (INT|DOUBLE|TEXT))*))\);";
            const string grantPrivelegePattern        = @"GRANT (INSERT|DELETE|SELECT|UPDATE) ON ([a-zA-Z0-9]+) TO ([a-zA-Z0-9-_\.\s]+);";
            const string revokePrivelegePattern       = @"REVOKE (INSERT|DELETE|SELECT|UPDATE) ON ([a-zA-Z0-9]+) TO ([a-zA-Z0-9-_\.\s]+);";
            const string addUserPattern               = @"ADD USER \('([a-zA-Z0-9]+)','([a-zA-Z0-9]+)',([a-zA-Z0-9]+)\);";
            const string createSecurityProfilePattern = @"CREATE SECURITY PROFILE ([a-zA-Z0-9-_\.\s]+);";
            const string deleteSecurityProfilePattern = @"DROP SECURITY PROFILE ([a-zA-Z0-9-_\.\s]+);";
            const string deleteUserPattern            = @"DELETE USER ([a-zA-Z0-9-_\.\s]+);";

            Match match = Regex.Match(miniSqlSentence, selectAllWherePattern);

            if (match.Success)
            {
                CompareWhere   cW             = new CompareWhere(match.Groups[2].Value, match.Groups[5].Value, match.Groups[3].Value);
                SelectAllWhere selectAllWhere = new SelectAllWhere(match.Groups[1].Value, cW);
                return(selectAllWhere);
            }
            match = Regex.Match(miniSqlSentence, selectAllPattern);
            if (match.Success)
            {
                SelectAll selectAll = new SelectAll(match.Groups[1].Value);
                return(selectAll);
            }
            match = Regex.Match(miniSqlSentence, selectColumnsWherePattern);
            if (match.Success)
            {
                string[]          columnNames       = match.Groups[1].Value.Split(',');
                CompareWhere      cW                = new CompareWhere(match.Groups[4].Value, match.Groups[7].Value, match.Groups[5].Value);
                SelectColumnWhere selectColumnWhere = new SelectColumnWhere(match.Groups[3].Value, cW, columnNames);
                return(selectColumnWhere);
            }
            match = Regex.Match(miniSqlSentence, selectColumnsPattern);
            if (match.Success)
            {
                string[]      columnNames   = match.Groups[1].Value.Split(',');
                SelectColumns selectColumns = new SelectColumns(match.Groups[3].Value, columnNames);
                return(selectColumns);
            }
            match = Regex.Match(miniSqlSentence, deletePattern);
            if (match.Success)
            {
                CompareWhere cW     = new CompareWhere(match.Groups[2].Value, match.Groups[5].Value, match.Groups[3].Value);
                Delete       delete = new Delete(match.Groups[1].Value, cW);
                return(delete);
            }
            match = Regex.Match(miniSqlSentence, updatePattern);
            if (match.Success)
            {
                CompareWhere cW = new CompareWhere(match.Groups[6].Value, match.Groups[9].Value, match.Groups[7].Value);

                List <string> setColumns = new List <string>();
                List <string> setValues  = new List <string>();

                string   set         = match.Groups[2].Value.Replace("'", "");
                string[] setElements = set.Split(',');
                for (int i = 0; i < setElements.Length; i++)
                {
                    string[] columnAndValue = setElements[i].Split('=');
                    string   column         = columnAndValue[0];
                    string   value          = columnAndValue[1];

                    setColumns.Add(column);
                    setValues.Add(value);
                }
                Update update = new Update(match.Groups[1].Value, cW, setColumns, setValues);
                return(update);
            }
            match = Regex.Match(miniSqlSentence, insertIntoPattern);
            if (match.Success)
            {
                string     temp        = match.Groups[2].Value.Replace("'", "");
                string[]   columnNames = temp.Split(',');
                InsertInto insertInto  = new InsertInto(match.Groups[1].Value, null, columnNames);
                return(insertInto);
            }
            match = Regex.Match(miniSqlSentence, createTablePattern);
            if (match.Success)
            {
                List <TableColumn> columns = new List <TableColumn>();

                string   tableName = match.Groups[1].Value;
                string[] temp      = match.Groups[2].Value.Split(',');

                for (int i = 0; i < temp.Length; i++)
                {
                    string[] columnAndValue = temp[i].Split(' ');
                    string   column         = columnAndValue[0];
                    string   value          = columnAndValue[1];

                    TableColumn tc = new TableColumn(column, value);
                    columns.Add(tc);
                }

                CreateTable createTable = new CreateTable(tableName, columns);
                return(createTable);
            }
            match = Regex.Match(miniSqlSentence, dropTablePattern);
            if (match.Success)
            {
                DropTable dropTable = new DropTable(match.Groups[1].Value);
                return(dropTable);
            }
            match = Regex.Match(miniSqlSentence, grantPrivelegePattern);
            if (match.Success)
            {
                GrantPrivilege grantPrivilege = new GrantPrivilege(StringToPrivilegeType(match.Groups[1].Value), match.Groups[2].Value, match.Groups[3].Value);
                return(grantPrivilege);
            }
            match = Regex.Match(miniSqlSentence, revokePrivelegePattern);
            if (match.Success)
            {
                RevokePrivilege revokePrivilege = new RevokePrivilege(StringToPrivilegeType(match.Groups[1].Value), match.Groups[2].Value, match.Groups[3].Value);
                return(revokePrivilege);
            }
            match = Regex.Match(miniSqlSentence, addUserPattern);
            if (match.Success)
            {
                AddUser addUser = new AddUser(match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value);
                return(addUser);
            }
            match = Regex.Match(miniSqlSentence, createSecurityProfilePattern);
            if (match.Success)
            {
                CreateSecurityProfile createProfile = new CreateSecurityProfile(match.Groups[1].Value);
                return(createProfile);
            }
            match = Regex.Match(miniSqlSentence, deleteSecurityProfilePattern);
            if (match.Success)
            {
                DeleteSecurityProfile deleteProfile = new DeleteSecurityProfile(match.Groups[1].Value);
                return(deleteProfile);
            }
            match = Regex.Match(miniSqlSentence, deleteUserPattern);
            if (match.Success)
            {
                DeleteUser deleteUser = new DeleteUser(match.Groups[1].Value);
                return(deleteUser);
            }


            return(null);
        }
예제 #16
0
        public void ConnectWithSimpleObject()
        {
            DropTable.For <Player>().TryExecute(Connection);
            CreateTable.For <Player>().Execute(Connection);

            var peter = new Player
            {
                Identifier = Guid.NewGuid(),
                Name       = "Peter",
                Age        = 22,
                Birthday   = new DateTime(1983, 3, 21).ToUniversalTime()
            };

            var willem = new Player
            {
                Identifier = Guid.NewGuid(),
                Name       = "Willem",
                Age        = 50,
                Birthday   = new DateTime(1983, 3, 22).ToUniversalTime()
            };

            InsertInto.Row(peter).Execute(Connection);
            InsertInto.Row(willem).Execute(Connection);

            var selectResult = Select.From <Player>().ExecuteRead(Connection)
                               .OrderBy(x => x.Name)
                               .ToImmutableList();

            Assert.That(selectResult, Has.Count.EqualTo(2));
            Assert.That(selectResult[0].Name, Is.EqualTo(peter.Name));
            Assert.That(selectResult[0].Identifier, Is.EqualTo(peter.Identifier));
            Assert.That(selectResult[0].Age, Is.EqualTo(peter.Age));
            Assert.That(selectResult[0].Birthday, Is.EqualTo(peter.Birthday));

            Assert.That(selectResult[1].Name, Is.EqualTo(willem.Name));
            Assert.That(selectResult[1].Identifier, Is.EqualTo(willem.Identifier));
            Assert.That(selectResult[1].Age, Is.EqualTo(willem.Age));
            Assert.That(selectResult[1].Birthday, Is.EqualTo(willem.Birthday));

            selectResult = Select.From <Player>().Take(1).ExecuteRead(Connection)
                           .OrderBy(x => x.Name)
                           .ToImmutableList();

            Assert.That(selectResult, Has.Count.EqualTo(1));

            selectResult = Select.From <Player>()
                           .WhereEqual(x => x.Identifier, peter.Identifier)
                           .ExecuteRead(Connection)
                           .OrderBy(x => x.Name).ToImmutableList();

            Assert.That(selectResult, Has.Count.EqualTo(1));
            Assert.That(selectResult[0].Name, Is.EqualTo(peter.Name));

            var maximumAge = Select.From <Player>().Maximum(x => x.Age).ExecuteRead(Connection).ToImmutableList();

            Assert.That(maximumAge, Has.Count.EqualTo(1));
            Assert.That(maximumAge[0], Is.EqualTo(50));

            var minimumAge = Select.From <Player>().Minimum(x => x.Age).ExecuteRead(Connection).ToImmutableList();

            Assert.That(minimumAge, Has.Count.EqualTo(1));
            Assert.That(minimumAge[0], Is.EqualTo(22));
        }