Example #1
0
 public TokenInfo(string _text, TK _token, int _pos, TokenInfo _lastToken, int _line)
 {
     this.text = _text;
     this.token = _token;
     this.pos = _pos;
     this.lastToken = _lastToken;
     this.line = _line;
 }
Example #2
0
 public TypedToken( TK type )
 {
     _Type = type;
 }
Example #3
0
		private bool _IsReserved( string identifier, out TK type )
		{
			return ReservedWordDict.TryGetValue( identifier, out type );
		}
Example #4
0
 private bool _IsReserved(string identifier, out TK type)
 {
     return(ReservedWordDict.TryGetValue(identifier, out type));
 }
Example #5
0
 public bool EqualsToToken(TK other)
 {
     return(TokenType == (int)other);
 }
        /// <summary>
        ///  平台退款详细页面
        /// </summary>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        public ActionResult TKDetail(long orderNo)
        {
            try
            {
                TK tk = ServiceHelper.Create <ITKService>().getTK(orderNo);

                if (tk != null)
                {
                    ViewBag.type          = tk.TKType;
                    ViewBag.ReasonType    = tk.ReasonType;
                    ViewBag.TKAmont       = tk.TKAmont;
                    ViewBag.TKInstruction = tk.TKInstruction;
                }
                else
                {
                    ViewBag.type          = 1;
                    ViewBag.ReasonType    = 0;
                    ViewBag.TKAmont       = 0;
                    ViewBag.TKInstruction = "";
                }

                OrderInfo             order = ServiceHelper.Create <IOrderService>().GetOrder(Convert.ToInt64(orderNo));
                List <TKMessageModel> tkmms = new List <TKMessageModel>();
                List <TKMessage>      tks   = ServiceHelper.Create <ITKService>().getTKMessage(tk.Id);
                if (tks != null)
                {
                    foreach (TKMessage item in tks)
                    {
                        TKMessageModel tkmm = new TKMessageModel()
                        {
                            MessageAttitude = item.MessageAttitude,
                            ReturnName      = item.ReturnName,
                            MessageDate     = item.MessageDate,
                            MessageContent  = item.MessageContent,
                            UserId          = item.UserId,
                            TKId            = item.TKId,
                            Id   = item.Id,
                            tkis = ServiceHelper.Create <ITKService>().getTKImage(item.Id)
                        };
                        tkmms.Add(tkmm);
                        ViewBag.MessageContent += "" + item.MessageContent;
                    }
                    ViewBag.tkmms = tkmms;
                }
                if (order != null)
                {
                    ViewBag.OrderNo  = orderNo;
                    ViewBag.UserName = order.UserName;
                    ViewBag.yunfei   = order.Freight;
                    ViewBag.total    = order.ProductTotalAmount;
                    ViewBag.max      = order.Freight + order.ProductTotalAmount;
                    ViewBag.ShopName = order.ShopName;
                }
                else
                {
                    ViewBag.OrderNo  = "";
                    ViewBag.UserName = "";
                    ViewBag.yunfei   = 0;
                    ViewBag.total    = 0;
                    ViewBag.max      = 0;
                    ViewBag.ShopName = "";
                }
                return(View());
            }
            catch (Exception)
            {
                return(View());
            }
        }
Example #7
0
 private PonyToken Token(TK kind)
 {
     return(new PonyToken(kind, Source, clutter, payload, next));
 }
Example #8
0
 public static void SetK1(MyBO bo, ISession s, TK value)
 {
     switch (value)
     {
         case TK.ValueNull:
             bo.K1 = null;
             break;
         case TK.Zero:
             bo.K1 = 0;
             break;
         case TK.One:
             bo.K1 = 1;
             break;
         default:
             throw new Exception("Value " + value + " not handled in code");
     }
 }
Example #9
0
        public void js_beautify(string js_source_text)
        {
            string str;
            this.sb = new StringBuilder();
            this.lastword = "";
            //this.indent = 0;
            this.lasttok = TK.EOF;
            this._in = IN.BLOCK;
            this.in_push(this._in);
            int pos = 0;

            int lastPos = 0;
            activeFormatedOffset = 0;
            isFindPos = false;

            TK uNKNOWN = TK.UNKNOWN;
            Next_token:
            str = this.get_next_token(ref js_source_text, ref pos, out uNKNOWN);

            if (activeOffset >= lastPos && activeOffset < pos)
            {
                offset = str.Length - (pos - activeOffset - 1);
                if (offset < 0)
                {
                    offset = 0;
                }
                isFindPos = true;
                this.activeFormatedOffset = sb.ToString().Length + offset;
            }
            else
            {
                isFindPos = false;
            }
            lastPos = pos;

            if (this.isDebugEnabled)
            {
                this.proto("[" + uNKNOWN.ToString() + "]>");
            }
            if (uNKNOWN == TK.EOF)
            {
                return;
            }
            if (str == null)
            {
                return;
            }
            switch (uNKNOWN)
            {
                case TK.UNKNOWN:
                    if ((str == "\n") && (this.lasttok == TK.WORD || this.lasttok == TK.START_CASE))
                    {
                        this.write(";", new string[0]);
                    }
                    this.write(str, new string[0]);
                    goto GetLastInfo;
                case TK.START_CASE:
                    if (this.lasttok != TK.START_BLOCK)
                    {
                        this.un_indent();
                    }
                    if (this.lasttok == TK.PUNCT || this.lasttok == TK.END_BLOCK)
                    {
                        this.do_indent();
                    }
                    this.nl();
                    this.write(str + " ", new string[0]);
                    this.case_push(CASE.CASE);
                    goto GetLastInfo;
                case TK.WORD:
                    {
                        if (lasttok == TK.NEW_LINE)
                        {
                            this.nl();
                        }
                        else if (lastword == ":" && _cases == CASE.CASE)
                        {
                            this.do_indent();
                            this.nl();
                        }
                        else if ((this.lasttok == TK.END_COMMAND) || (!(str.ToLower() == "break") && !(str.ToLower() == "else")))
                        {
                            if (this.lasttok == TK.END_BLOCK)
                            {
                                if (str.ToLower() != "else")
                                {
                                    //如果要在每个{}后面加一个空行,则取消掉注释
                                    //this.nl();
                                }
                                else
                                {
                                    this.write(" ", new string[0]);
                                }
                            }
                            if ((this.lasttok == TK.END_COMMAND) && (this._in == IN.BLOCK))
                            {
                                this.nl();
                            }
                            else if ((this.lasttok == TK.END_COMMAND) && (this._in == IN.EXPR))
                            {
                                this.write(" ", new string[0]);
                            }
                            else if (this.lasttok == TK.WORD)
                            {
                                this.write(" ", new string[0]);
                            }
                            else if (this.lasttok == TK.START_BLOCK || this.lasttok == TK.END_BLOCK)
                            {
                                this.nl();
                            }
                            else if (this.lasttok == TK.STRING)
                            {
                                //2008-12-1去掉该段,会影响正则表达式:if (json.match(/^\d+$/g)) {}
                                //this.write(";", new string[0]);
                                //this.nl();

                                //正则表达式
                                if (!lastword.EndsWith("/"))
                                {
                                    this.write(";", new string[0]);
                                    this.nl();
                                }
                            }
                            else if (this.lasttok == TK.END_EXPR && this.lasttok == TK.START_SWITCH)
                            {
                                if (Inners[0] == Inner.Flow)
                                {
                                    this.do_indent();
                                    this.nl();
                                    this.un_indent();
                                }
                                else
                                {
                                    this.nl();
                                }
                            }
                        }
                        else
                        {
                            if (lasttok != TK.EOF)
                            {
                                this.nl();
                            }
                        }

                        //代码着色
                        List<string> list = new List<string>();
                        list.AddRange(new string[] { "function" });
                        if (list.Contains(str))
                        {
                            this.write(str, new string[] { "color:blue;" });
                        }
                        else
                        {
                            this.write(str, new string[0]);
                        }
                        goto GetLastInfo;
                    }
                case TK.START_EXPR:
                    this.in_push(IN.EXPR);
                    if (this.lastword == "switch")
                    {
                        this.case_push(CASE.SWITCH);
                    }
                    else if (cases.Count > 0)
                    {
                        this.case_push(CASE.EXPR);
                    }
                    if (this.keyword.Contains(lastword))
                    {
                        //内部流程操作
                        this.Inners.Add(Inner.Flow);
                    }
                    else
                    {
                        //普通的运算
                        this.Inners.Add(Inner.Exp);
                    }
                    if (this.lasttok != TK.END_EXPR && this.lasttok != TK.START_SWITCH)
                    {
                        if (((this.lasttok != TK.WORD && this.lasttok != TK.START_CASE) && (this.lasttok != TK.START_EXPR)) && (this.lasttok != TK.PUNCT))
                        {
                            this.write(" ", new string[0]);
                        }
                        else if (((this.lastword == "if") || (this.lastword == "for")) || ((this.lastword == "while") || (this.lastword == "switch")))
                        {
                            if (addSpaceAfterCtrlWord)
                            {
                                this.write(" ", new string[0]);
                            }

                        }
                        break;
                    }
                    if ((str != "[") && (str != "("))
                    {
                        this.nl();
                    }
                    break;

                case TK.START_SWITCH:
                case TK.END_EXPR:
                    this.write(str, new string[0]);
                    this.in_pop();
                    if (cases.Count > 0)
                    {
                        case_pop();
                    }
                    goto GetLastInfo;

                case TK.START_BLOCK:
                    this.in_push(IN.BLOCK);
                    if (this.lasttok == TK.START_SWITCH)
                    {
                        case_push(CASE.BLOCK);
                    }
                    else if (_cases != CASE.None)
                    {
                        case_push(CASE.CASE_BLOCK);
                    }
                    //if (this.lasttok != TK.PUNCT)
                    //{
                    //    this.write(" ", new string[0]);
                    //}

                    //jrt,加入代码风格,如果是return {...}这种返回的语句,“{”不可以换到下一行
                    if (this.lastword == "return")
                    {
                        this.write(" ");
                    }
                    else if (this.lasttok == TK.PUNCT || (this.lasttok != TK.COMMENT && this.style == CodeStyle.MS))
                    {
                        this.nl();
                    }

                    this.write("{", new string[0]);
                    this.do_indent();
                    goto GetLastInfo;

                case TK.END_BLOCK:
                    //if (lasttok != TK.EOF)
                    //{
                        if (this.lasttok != TK.END_EXPR && this.lasttok != TK.START_SWITCH)
                        {
                            if (this._cases == CASE.BLOCK)
                            {
                                this.un_indent();
                                if (this.lasttok != TK.END_BLOCK)
                                {
                                    this.un_indent();
                                }
                                this.nl();
                            }
                            else if (this.lasttok == TK.END_BLOCK)
                            {
                                this.un_indent();
                                this.nl();
                            }
                            else if (this.lasttok == TK.START_BLOCK)
                            {
                                this.un_indent();
                            }
                            else
                            {
                                this.un_indent();
                                if (lasttok == TK.COMMENT)
                                {
                                    removeLastNL();
                                }
                                this.nl();
                            }
                        }
                        else
                        {
                            //jrt
                            this.un_indent();

                            this.nl();
                            //this.un_indent();

                        }
                    //}

                    this.write(str, new string[0]);
                    this.in_pop();
                    if (_cases != CASE.None)
                    {
                        case_pop();
                    }
                    goto GetLastInfo;

                case TK.END_COMMAND:
                    this.write(";", new string[0]);
                    goto GetLastInfo;

                case TK.STRING:
                    if (this.lasttok != TK.START_BLOCK)
                    {
                        if (this.lasttok == TK.WORD)
                        {
                            this.write(" ", new string[0]);
                        }
                    }
                    else
                    {
                        this.nl();
                    }
                    this.write(str, new string[] { "color:red;" });
                    goto GetLastInfo;

                case TK.BLOCK_COMMENT:
                    if (this.lasttok != TK.EOF &&
                        this.lasttok != TK.COMMENT &&
                        (this.sb.Length > 0))
                    {
                        if (!(lastword == "," && this._in == IN.BLOCK))
                        {
                            this.nl();
                        }
                    }
                    this.write(str, new string[] { "color:green;" });
                    this.nl();
                    goto GetLastInfo;

                case TK.COMMENT:

                    //if (str.StartsWith(regionPair.Key))
                    //{
                    //    this.nl();
                    //}
                    if (this.lasttok != TK.COMMENT && this.lasttok != TK.EOF)
                    {
                        if (lastword == ":" && _cases == CASE.CASE)
                        {
                            this.do_indent();
                            this.nl();
                        }
                        else if (!(lastword == "," && this._in == IN.BLOCK))
                        {
                            this.nl();
                        }

                    }

                    this.write(str, new string[] { "color:green;" });
                    this.nl();
                    //if (str.StartsWith(regionPair.Value))
                    //{
                    //    this.n();
                    //}
                    goto GetLastInfo;

                case TK.PUNCT:
                    {
                        //是否在左、右添加空格的标记
                        bool leftFlag = true;
                        bool rightFlag = true;
                        if (!(str == ","))
                        {
                            if (str == "?" && cases.Contains(CASE.CASE))
                            {
                                case_push(CASE.EXPR);
                            }

                            //case default:的情况
                            if (str == ":" && this.lasttok == TK.START_CASE)
                            {
                                leftFlag = false;
                            }
                            if (this.lasttok == TK.PUNCT)
                            {
                                leftFlag = false;
                                rightFlag = false;
                            }
                            else if (str == ".")
                            {
                                leftFlag = false;
                                rightFlag = false;
                            }
                            //else
                            //{
                            //    lasttok = this.lasttok;
                            //}

                            if (leftFlag)
                            {
                                this.write(" ", new string[0]);
                            }
                            this.write(str, new string[0]);
                            if (rightFlag)
                            {
                                this.write(" ", new string[0]);
                            }

                        }
                        //08-11-19 增加对json数据的处理
                        else if (this._in == IN.BLOCK)
                        {
                            this.write(",", new string[0]);
                            this.nl();
                        }
                        else if (this._in != IN.EXPR)
                        {
                            this.write(", ", new string[0]);
                        }
                        else
                        {
                            this.write(", ", new string[0]);
                        }

                        goto GetLastInfo;
                    }
                default:
                    goto GetLastInfo;
            }
            this.write(str, new string[0]);
            GetLastInfo:
            if (this.lasttok == TK.END_EXPR && this.lasttok == TK.START_SWITCH)
                Inners.RemoveAt(Inners.Count - 1);

            if (lastword == ":")
            {
                if (_cases == CASE.EXPR)
                {
                    case_pop();
                }
            }
            this.lasttok = uNKNOWN;
            this.lastword = str.ToLower();
            goto Next_token;
        }
Example #10
0
        public VSBlockInfo GetBLOCK(string js)
        {
            Stack<TokenInfo> stack = new Stack<TokenInfo>();
            VSBlockInfo block = new VSBlockInfo();
            TokenInfo beforToken = null;
            string str;
            this.sb = new StringBuilder();
            this.lastword = "";
            this.lasttok = TK.EOF;
            this._in = IN.BLOCK;
            this.in_push(this._in);
            int pos = 0;
            TK token = TK.UNKNOWN;
            curreTokenLine = 1;
            while (true)
            {
                str = this.get_next_token(ref js, ref pos, out token);

                switch (token)
                {
                    case TK.START_BLOCK:
                        stack.Push(new TokenInfo(str, token, pos, beforToken, curreTokenLine));
                        break;
                    case TK.END_BLOCK:
                        if (pos == js.Length)
                        {
                            if (stack.Count > 0)
                            {
                                TokenInfo startBlockToken = stack.Peek();
                                block.startBlock = startBlockToken;
                                TokenInfo startToken = startBlockToken.lastToken;

                                bool isJson = false;
                                if (startBlockToken.lastToken.token == TK.PUNCT && startBlockToken.lastToken.text == "," )
                                {
                                    if (startBlockToken.lastToken.lastToken != null && startBlockToken.lastToken.lastToken.token == TK.END_BLOCK)
                                    {
                                        isJson = true;
                                    }
                                }

                                if (startToken.token == TK.NEW_LINE)
                                {
                                    startToken = startToken.lastToken;
                                }
                                int stratLine = startToken.line;
                                block.line = stratLine;
                                startToken = startToken.lastToken;
                                while (startToken.line == stratLine)
                                {
                                    block.line = startToken.line;
                                    if (startToken.line == 0)
                                    {
                                        break;
                                    }
                                    if (startToken.lastToken == null)
                                    {
                                        break;
                                    }
                                    startToken = startToken.lastToken;
                                    block.line = startToken.line+1;
                                }

                                int lastIndex = 0;
                                int postion = startToken.pos;
                                for (int i = startToken.pos; i >= 0; i--)
                                {
                                    postion = i;
                                    if (whitespace.Contains(js[i]))
                                    {
                                        lastIndex++;
                                        if (js[i] == '\n')
                                        {
                                            break;
                                        }
                                        if (js[i] == '\r')
                                        {
                                            if (js[i + 1] == '\n')
                                            {
                                                postion = i + 1;
                                            }

                                            break;
                                        }
                                    }

                                }

                                //上一行语句的最后一个字符
                                string prevStatementLastWord = "";

                                int prevStatementPostion = postion;

                                if (postion > 0)
                                {
                                    int prevForStart = postion - 1;
                                    if (js[prevForStart] == '\r')
                                    {
                                        prevForStart = prevForStart - 1;
                                    }
                                    for (int i = prevForStart; i >= 0; i--)
                                    {
                                        prevStatementPostion = i;
                                        if (whitespace.Contains(js[i]))
                                        {
                                            lastIndex++;
                                            if (js[i] == '\n')
                                            {
                                                break;
                                            }
                                            if (js[i] == '\r')
                                            {
                                                if (js[i + 1] == '\n')
                                                {
                                                    prevStatementPostion = i + 1;
                                                }
                                                break;
                                            }
                                        }

                                    }

                                    block.prevStatementLastWord = prevStatementLastWord;
                                    for (int i = postion; i >= 0; i--)
                                    {
                                        if (!whitespace.Contains(js[i]))
                                        {
                                            if (js[i] != '\n' && js[i] != '\r')
                                            {
                                                prevStatementLastWord = js[i].ToString();
                                                block.prevStatementLastWord = prevStatementLastWord;
                                                break;
                                            }
                                        }
                                    }
                                }

                                if (postion == 0)
                                {
                                    postion = -1;
                                }
                                string result = js.Substring(postion + 1, js.Length - postion - 1);

                                int spaceCount = 0;
                                if (prevStatementPostion > 0)
                                {
                                    for (int i = prevStatementPostion + 1; i >= 0; i++)
                                    {
                                        if (js[i] == '\t')
                                        {
                                            spaceCount += 4;
                                        }
                                        else if (js[i] == ' ')
                                        {
                                            spaceCount += 1;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }
                                int indent = spaceCount / 4;

                                string endChars = "{[";

                                if (prevStatementLastWord!=""&&endChars.IndexOf(prevStatementLastWord) >= 0)
                                {
                                    indent++;
                                }
                                //if (isJson)
                                //{
                                //    indent++;
                                //}

                                block.indent = indent;

                                block.column = lastIndex;
                                block.text = result;
                                if (startBlockToken.lastToken != null)
                                {
                                    block.befor = startToken.token.ToString();
                                }
                                return block;
                            }
                            else
                            {
                                return block;
                            }
                        }
                        else
                        {
                            if (stack.Count > 0)
                            {
                                stack.Pop();
                            }
                        }
                        break;
                }
                if (pos >= js.Length)
                {
                    break;
                }
                beforToken = new TokenInfo(str, token, pos, beforToken, curreTokenLine);
                this.lasttok = token;
                this.lastword = str.ToLower();
            }
            return block;
        }
Example #11
0
        public ActionResult Step2(long orderNo)
        {
            TK tk = ServiceHelper.Create <ITKService>().getTK(orderNo);

            if (tk == null)
            {
                ViewBag.TKResion = 0;
                ViewBag.TKAmont  = "";
                ViewBag.type     = 0;
            }
            else
            {
                ViewBag.TKResion = tk.TKResion;
                ViewBag.TKAmont  = tk.TKAmont;
                ViewBag.type     = 1;
            }
            OrderInfo             order = ServiceHelper.Create <IOrderService>().GetOrder(Convert.ToInt64(orderNo));
            List <TKMessageModel> tkmms = new List <TKMessageModel>();
            List <TKMessage>      tks   = ServiceHelper.Create <ITKService>().getTKMessage(tk.Id);

            if (tks != null)
            {
                foreach (TKMessage item in tks)
                {
                    TKMessageModel tkmm = new TKMessageModel()
                    {
                        MessageAttitude = item.MessageAttitude,
                        ReturnName      = item.ReturnName,
                        MessageDate     = item.MessageDate,
                        MessageContent  = item.MessageContent,
                        UserId          = item.UserId,
                        TKId            = item.TKId,
                        Id   = item.Id,
                        tkis = ServiceHelper.Create <ITKService>().getTKImage(item.Id)
                    };
                    tkmms.Add(tkmm);
                    ViewBag.MessageContent += "" + item.MessageContent;
                }
                ViewBag.tkmms = tkmms;
            }
            if (order != null && order.ShopId == base.CurrentSellerManager.ShopId)
            {
                ViewBag.OrderNo  = orderNo;
                ViewBag.ShopName = order.ShopName;
                ViewBag.yunfei   = order.Freight;
                ViewBag.total    = order.ProductTotalAmount;
                ViewBag.max      = order.Freight + order.ProductTotalAmount;
                ViewBag.ShopId   = order.ShopId;
            }
            else
            {
                ViewBag.OrderNo  = "";
                ViewBag.ShopName = "";
                ViewBag.yunfei   = "";
                ViewBag.total    = "";
                ViewBag.max      = "";
                ViewBag.ShopId   = "";
            }

            return(View());
        }
Example #12
0
 private bool Iss(TK kind)
 {
     return(next < limit && Tokens[next].Kind == kind);
 }
Example #13
0
 public GroupingWrapper(TK key)
 {
     Key = key;
 }
Example #14
0
        static WRC LookupName(Parse parse, string dbName, string tableName, string colName, NameContext nc, Expr expr)
        {
            int     cnt       = 0;            // Number of matching column names
            int     cntTab    = 0;            // Number of matching table names
            int     subquerys = 0;            // How many levels of subquery
            Context ctx       = parse.Ctx;    // The database connection

            SrcList.SrcListItem item;         // Use for looping over pSrcList items
            SrcList.SrcListItem match = null; // The matching pSrcList item
            NameContext         topNC = nc;   // First namecontext in the list
            Schema schema = null;             // Schema of the expression
            bool   isTrigger = false;
            int    i, j;

            Debug.Assert(nc != null);      // the name context cannot be NULL.
            Debug.Assert(colName != null); // The Z in X.Y.Z cannot be NULL
            Debug.Assert(!E.ExprHasAnyProperty(expr, EP.TokenOnly | EP.Reduced));

            // Initialize the node to no-match
            expr.TableId = -1;
            expr.Table   = null;
            E.ExprSetIrreducible(expr);

            // Translate the schema name in zDb into a pointer to the corresponding schema.  If not found, pSchema will remain NULL and nothing will match
            // resulting in an appropriate error message toward the end of this routine
            if (dbName != null)
            {
                for (i = 0; i < ctx.DBs.length; i++)
                {
                    Debug.Assert(ctx.DBs[i].Name != null);
                    if (string.Compare(ctx.DBs[i].Name, dbName) == 0)
                    {
                        schema = ctx.DBs[i].Schema;
                        break;
                    }
                }
            }

            // Start at the inner-most context and move outward until a match is found
            while (nc != null && cnt == 0)
            {
                ExprList list;
                SrcList  srcList = nc.SrcList;
                if (srcList != null)
                {
                    for (i = 0; i < srcList.Srcs; i++)
                    {
                        item = srcList.Ids[i];
                        Table table = item.Table;
                        Debug.Assert(table != null && table.Name != null);
                        Debug.Assert(table.Cols.length > 0);
                        if (item.Select != null && (item.Select.SelFlags & SF.NestedFrom) != 0)
                        {
                            bool hit = false;
                            list = item.Select.EList;
                            for (j = 0; j < list.Exprs; j++)
                            {
                                if (Walker.MatchSpanName(list.Ids[j].Span, colName, tableName, dbName))
                                {
                                    cnt++;
                                    cntTab        = 2;
                                    match         = item;
                                    expr.ColumnId = j;
                                    hit           = true;
                                }
                            }
                            if (hit || table == null)
                            {
                                continue;
                            }
                        }
                        if (dbName != null && table.Schema != schema)
                        {
                            continue;
                        }
                        if (tableName != null)
                        {
                            string tableName2 = (item.Alias != null ? item.Alias : table.Name);
                            Debug.Assert(tableName2 != null);
                            if (!string.Equals(tableName2, tableName, StringComparison.OrdinalIgnoreCase))
                            {
                                continue;
                            }
                        }
                        if (cntTab++ == 0)
                        {
                            match = item;
                        }
                        Column col;
                        for (j = 0; j < table.Cols.length; j++)
                        {
                            col = table.Cols[j];
                            if (string.Equals(col.Name, colName, StringComparison.InvariantCultureIgnoreCase))
                            {
                                // If there has been exactly one prior match and this match is for the right-hand table of a NATURAL JOIN or is in a
                                // USING clause, then skip this match.
                                if (cnt == 1)
                                {
                                    if ((item.Jointype & JT.NATURAL) != 0)
                                    {
                                        continue;
                                    }
                                    if (NameInUsingClause(item.Using, colName))
                                    {
                                        continue;
                                    }
                                }
                                cnt++;
                                match = item;
                                // Substitute the rowid (column -1) for the INTEGER PRIMARY KEY
                                expr.ColumnId = (j == table.PKey ? -1 : (short)j);
                                break;
                            }
                        }
                    }
                    if (match != null)
                    {
                        expr.TableId = match.Cursor;
                        expr.Table   = match.Table;
                        schema       = expr.Table.Schema;
                    }
                }

#if !OMIT_TRIGGER
                // If we have not already resolved the name, then maybe it is a new.* or old.* trigger argument reference
                if (dbName == null && tableName != null && cnt == 0 && parse.TriggerTab != null)
                {
                    TK    op    = parse.TriggerOp;
                    Table table = null;
                    Debug.Assert(op == TK.DELETE || op == TK.UPDATE || op == TK.INSERT);
                    if (op != TK.DELETE && string.Equals("new", tableName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        expr.TableId = 1;
                        table        = parse.TriggerTab;
                    }
                    else if (op != TK.INSERT && string.Equals("old", tableName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        expr.TableId = 0;
                        table        = parse.TriggerTab;
                    }
                    if (table != null)
                    {
                        int colId;
                        schema = table.Schema;
                        cntTab++;
                        for (colId = 0; colId < table.Cols.length; colId++)
                        {
                            Column col = table.Cols[colId];
                            if (string.Equals(col.Name, colName, StringComparison.InvariantCultureIgnoreCase))
                            {
                                if (colId == table.PKey)
                                {
                                    colId = -1;
                                }
                                break;
                            }
                        }
                        if (colId >= table.Cols.length && Expr.IsRowid(colName))
                        {
                            colId = -1; // IMP: R-44911-55124
                        }
                        if (colId < table.Cols.length)
                        {
                            cnt++;
                            if (colId < 0)
                            {
                                expr.Aff = AFF.INTEGER;
                            }
                            else if (expr.TableId == 0)
                            {
                                C.ASSERTCOVERAGE(colId == 31);
                                C.ASSERTCOVERAGE(colId == 32);
                                parse.Oldmask |= (colId >= 32 ? 0xffffffff : (((uint)1) << colId));
                            }
                            else
                            {
                                C.ASSERTCOVERAGE(colId == 31);
                                C.ASSERTCOVERAGE(colId == 32);
                                parse.Newmask |= (colId >= 32 ? 0xffffffff : (((uint)1) << colId));
                            }
                            expr.ColumnId = (short)colId;
                            expr.Table    = table;
                            isTrigger     = true;
                        }
                    }
                }
#endif

                // Perhaps the name is a reference to the ROWID
                if (cnt == 0 && cntTab == 1 && Expr.IsRowid(colName))
                {
                    cnt           = 1;
                    expr.ColumnId = -1; // IMP: R-44911-55124
                    expr.Aff      = AFF.INTEGER;
                }

                // If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z might refer to an result-set alias.  This happens, for example, when
                // we are resolving names in the WHERE clause of the following command:
                //
                //     SELECT a+b AS x FROM table WHERE x<10;
                //
                // In cases like this, replace pExpr with a copy of the expression that forms the result set entry ("a+b" in the example) and return immediately.
                // Note that the expression in the result set should have already been resolved by the time the WHERE clause is resolved.
                if (cnt == 0 && (list = nc.EList) != null && tableName == null)
                {
                    for (j = 0; j < list.Exprs; j++)
                    {
                        string asName = list.Ids[j].Name;
                        if (asName != null && string.Equals(asName, colName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            Debug.Assert(expr.Left == null && expr.Right == null);
                            Debug.Assert(expr.x.List == null);
                            Debug.Assert(expr.x.Select == null);
                            Expr orig = list.Ids[j].Expr;
                            if ((nc.NCFlags & NC.AllowAgg) == 0 && E.ExprHasProperty(orig, EP.Agg))
                            {
                                parse.ErrorMsg("misuse of aliased aggregate %s", asName);
                                return(WRC.Abort);
                            }
                            ResolveAlias(parse, list, j, expr, "", subquerys);
                            cnt   = 1;
                            match = null;
                            Debug.Assert(tableName == null && dbName == null);
                            goto lookupname_end;
                        }
                    }
                }

                // Advance to the next name context.  The loop will exit when either we have a match (cnt>0) or when we run out of name contexts.
                if (cnt == 0)
                {
                    nc = nc.Next;
                    subquerys++;
                }
            }

            // If X and Y are NULL (in other words if only the column name Z is supplied) and the value of Z is enclosed in double-quotes, then
            // Z is a string literal if it doesn't match any column names.  In that case, we need to return right away and not make any changes to
            // pExpr.
            //
            // Because no reference was made to outer contexts, the pNC->nRef fields are not changed in any context.
            if (cnt == 0 && tableName == null && E.ExprHasProperty(expr, EP.DblQuoted))
            {
                expr.OP    = TK.STRING;
                expr.Table = null;
                return(WRC.Prune);
            }

            // cnt==0 means there was not match.  cnt>1 means there were two or more matches.  Either way, we have an error.
            if (cnt != 1)
            {
                string err = (cnt == 0 ? "no such column" : "ambiguous column name");
                if (dbName != null)
                {
                    parse.ErrorMsg("%s: %s.%s.%s", err, dbName, tableName, colName);
                }
                else if (tableName != null)
                {
                    parse.ErrorMsg("%s: %s.%s", err, tableName, colName);
                }
                else
                {
                    parse.ErrorMsg("%s: %s", err, colName);
                }
                parse.CheckSchema = 1;
                topNC.Errs++;
            }

            // If a column from a table in pSrcList is referenced, then record this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
            // bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the column number is greater than the number of bits in the bitmask
            // then set the high-order bit of the bitmask.
            if (expr.ColumnId >= 0 && match != null)
            {
                int n = expr.ColumnId;
                C.ASSERTCOVERAGE(n == BMS - 1);
                if (n >= BMS)
                {
                    n = BMS - 1;
                }
                Debug.Assert(match.Cursor == expr.TableId);
                match.ColUsed |= ((Bitmask)1) << n;
            }

            // Clean up and return
            Expr.Delete(ctx, ref expr.Left);
            expr.Left = null;
            Expr.Delete(ctx, ref expr.Right);
            expr.Right = null;
            expr.OP    = (isTrigger ? TK.TRIGGER : TK.COLUMN);
lookupname_end:
            if (cnt == 1)
            {
                Debug.Assert(nc != null);
                Auth.Read(parse, expr, schema, nc.SrcList);
                // Increment the nRef value on all name contexts from TopNC up to the point where the name matched.
                for (; ;)
                {
                    Debug.Assert(topNC != null);
                    topNC.Refs++;
                    if (topNC == nc)
                    {
                        break;
                    }
                    topNC = topNC.Next;
                }
                return(WRC.Prune);
            }
            return(WRC.Abort);
        }
Example #15
0
 static TriggerStep TriggerStepAllocate(Context ctx, TK op, Token name)
 {
     TriggerStep triggerStep = new TriggerStep(); //: _tagalloc(ctx, sizeof(TriggerStep) + name->length, true);
     if (triggerStep != null)
     {
         string z = name.data;
         triggerStep.Target.data = z;
         triggerStep.Target.length = name.length;
         triggerStep.OP = op;
     }
     return triggerStep;
 }
Example #16
0
        public static void BeginTrigger(Parse parse, Token name1, Token name2, TK trTm, TK op, IdList columns, SrcList tableName, Expr when, bool isTemp, int noErr)
        {
            Context ctx = parse.Ctx; // The database connection
            Debug.Assert(name1 != null);   // pName1.z might be NULL, but not pName1 itself
            Debug.Assert(name2 != null);
            Debug.Assert(op == TK.INSERT || op == TK.UPDATE || op == TK.DELETE);
            Debug.Assert(op > 0 && op < (TK)0xff);
            Trigger trigger = null; // The new trigger

            int db; // The database to store the trigger in
            Token name = null; // The unqualified db name
            if (isTemp)
            {
                // If TEMP was specified, then the trigger name may not be qualified.
                if (name2.length > 0)
                {
                    parse.ErrorMsg("temporary trigger may not have qualified name");
                    goto trigger_cleanup;
                }
                db = 1;
                name = name1;
            }
            else
            {
                // Figure out the db that the the trigger will be created in
                db = parse.TwoPartName(name1, name2, ref name);
                if (db < 0)
                    goto trigger_cleanup;
            }
            if (tableName == null || ctx.MallocFailed)
                goto trigger_cleanup;

            // A long-standing parser bug is that this syntax was allowed:
            //    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
            //                                                 ^^^^^^^^
            // To maintain backwards compatibility, ignore the database name on pTableName if we are reparsing our of SQLITE_MASTER.
            if (ctx.Init.Busy && db != 1)
            {
                C._tagfree(ctx, ref tableName.Ids[0].Database);
                tableName.Ids[0].Database = null;
            }

            // If the trigger name was unqualified, and the table is a temp table, then set iDb to 1 to create the trigger in the temporary database.
            // If sqlite3SrcListLookup() returns 0, indicating the table does not exist, the error is caught by the block below.
            //? if (tableName == null) goto trigger_cleanup;
            Table table = Delete.SrcListLookup(parse, tableName); // Table that the trigger fires off of
            if (ctx.Init.Busy == null && name2.length == 0 && table != null && table.Schema == ctx.DBs[1].Schema)
                db = 1;

            // Ensure the table name matches database name and that the table exists
            if (ctx.MallocFailed) goto trigger_cleanup;
            Debug.Assert(tableName.Srcs == 1);
            DbFixer sFix = new DbFixer(); // State vector for the DB fixer
            if (sFix.FixInit(parse, db, "trigger", name) && sFix.FixSrcList(tableName))
                goto trigger_cleanup;
            table = Delete.SrcListLookup(parse, tableName);
            if (table == null)
            {
                // The table does not exist.
                if (ctx.Init.DB == 1)
                {
                    // Ticket #3810.
                    // Normally, whenever a table is dropped, all associated triggers are dropped too.  But if a TEMP trigger is created on a non-TEMP table
                    // and the table is dropped by a different database connection, the trigger is not visible to the database connection that does the
                    // drop so the trigger cannot be dropped.  This results in an "orphaned trigger" - a trigger whose associated table is missing.
                    ctx.Init.OrphanTrigger = true;
                }
                goto trigger_cleanup;
            }
            if (E.IsVirtual(table))
            {
                parse.ErrorMsg("cannot create triggers on virtual tables");
                goto trigger_cleanup;
            }

            // Check that the trigger name is not reserved and that no trigger of the specified name exists
            string nameAsString = Parse.NameFromToken(ctx, name);
            if (nameAsString == null || parse.CheckObjectName(nameAsString) != RC.OK)
                goto trigger_cleanup;
            Debug.Assert(Btree.SchemaMutexHeld(ctx, db, null));
            if (ctx.DBs[db].Schema.TriggerHash.Find(nameAsString, nameAsString.Length, (Trigger)null) != null)
            {
                if (noErr == 0)
                    parse.ErrorMsg("trigger %T already exists", name);
                else
                {
                    Debug.Assert(!ctx.Init.Busy);
                    parse.CodeVerifySchema(db);
                }
                goto trigger_cleanup;
            }

            // Do not create a trigger on a system table
            if (table.Name.StartsWith("sqlite_", StringComparison.InvariantCultureIgnoreCase))
            {
                parse.ErrorMsg("cannot create trigger on system table");
                parse.Errs++;
                goto trigger_cleanup;
            }

            // INSTEAD of triggers are only for views and views only support INSTEAD of triggers.
            if (table.Select != null && trTm != TK.INSTEAD)
            {
                parse.ErrorMsg("cannot create %s trigger on view: %S", (trTm == TK.BEFORE ? "BEFORE" : "AFTER"), tableName, 0);
                goto trigger_cleanup;
            }
            if (table.Select == null && trTm == TK.INSTEAD)
            {
                parse.ErrorMsg("cannot create INSTEAD OF trigger on table: %S", tableName, 0);
                goto trigger_cleanup;
            }

#if !OMIT_AUTHORIZATION
            {
                int tabDb = Prepare.SchemaToIndex(ctx, table.Schema); // Index of the database holding pTab
                AUTH code = AUTH.CREATE_TRIGGER;
                string dbName = ctx.DBs[tabDb].Name;
                string dbTrigName = (isTemp ? ctx.DBs[1].Name : dbName);
                if (tabDb == 1 || isTemp) code = AUTH.CREATE_TEMP_TRIGGER;
                if (Auth.Check(parse, code, nameAsString, table.Name, dbTrigName) != 0 || Auth.Check(parse, AUTH.INSERT, E.SCHEMA_TABLE(tabDb), 0, dbName))
                    goto trigger_cleanup;
            }
#endif

            // INSTEAD OF triggers can only appear on views and BEFORE triggers cannot appear on views.  So we might as well translate every
            // INSTEAD OF trigger into a BEFORE trigger.  It simplifies code elsewhere.
            if (trTm == TK.INSTEAD)
                trTm = TK.BEFORE;

            // Build the Trigger object
            trigger = new Trigger(); //: (Trigger *)_tagalloc(db, sizeof(Trigger), true);
            if (trigger == null) goto trigger_cleanup;
            trigger.Name = name;
            trigger.Table = tableName.Ids[0].Name; //: _tagstrdup(ctx, tableName->Ids[0].Name);
            trigger.Schema = ctx.DBs[db].Schema;
            trigger.TabSchema = table.Schema;
            trigger.OP = op;
            trigger.TRtm = (trTm == TK.BEFORE ? TRIGGER.BEFORE : TRIGGER.AFTER);
            trigger.When = Expr.Dup(db, when, E.EXPRDUP_REDUCE);
            trigger.Columns = Expr.IdListDup(ctx, columns);
            Debug.Assert(parse.NewTrigger == null);
            parse.NewTrigger = trigger;

        trigger_cleanup:
            C._tagfree(ctx, ref name);
            Expr.SrcListDelete(ctx, ref tableName);
            Expr.IdListDelete(ctx, ref columns);
            Expr.Delete(ctx, ref when);
            if (parse.NewTrigger == null)
                DeleteTrigger(ctx, ref trigger);
            else
                Debug.Assert(parse.NewTrigger == trigger);
        }
Example #17
0
        private string get_next_token(ref string text, ref int pos, out TK token)
        {
            char ch;
            string str;
            string str2;
            int length = text.Length;
            int num2 = 0;
            token = TK.UNKNOWN;

            do
            {
                if (pos >= length)
                {
                    token = TK.EOF;
                    return null;
                }
                ch = text[pos];
                pos++;
                if (ch == '\n')
                {
                    curreTokenLine++;
                }
                if (ch == '\n')
                {

                    num2++;
                    if (lastword != ";" && (lasttok == TK.WORD || lasttok == TK.END_EXPR))
                    {
                        token = TK.NEW_LINE;
                        return ch.ToString();
                    }
                }
            }
            while (this.in_array(ch, this.whitespace));

            if (num2 > 1)
            {
                if (removeBlankLine != BlankLineOption.None)
                {
                    int max = removeBlankLine == BlankLineOption.RemoveOtiose ? MaxBlankLine : 1;
                    int keepLine = removeBlankLine == BlankLineOption.RemoveOtiose ? KeepBlankLineCount + 1 : 0;
                    //是否去除多余的空行
                    if (num2 >= max)
                    {
                        num2 = keepLine;
                    }
                }
                for (int i = 1; i < num2; i++)
                {
                    this.nl();
                }
            }
            if (!this.in_array(ch, this.wordchar))
            {
                switch (ch)
                {
                    case '(':
                    case '[':
                        token = TK.START_EXPR;
                        return ch.ToString();

                    case ')':
                    case ']':
                        if (ch == ')' && _cases == CASE.SWITCH)
                        {
                            token = TK.START_SWITCH;
                            return ch.ToString();
                        }

                        token = TK.END_EXPR;
                        return ch.ToString();

                    case '{':
                        token = TK.START_BLOCK;
                        return ch.ToString();

                    case '}':
                        if (_cases == CASE.CASE)
                            this.case_pop();
                        token = TK.END_BLOCK;
                        return ch.ToString();

                    case ';':
                        token = TK.END_COMMAND;
                        return ch.ToString();
                    //case ':':
                    //    token = TK.JSON;
                    //    return ch.ToString();
                }
                if (ch != '/')
                {
                    goto CheckPunct;
                }
                if (text[pos] != '*')
                {
                    if (text[pos] == '/')
                    {
                        string str3 = ch.ToString();
                        while ((text[pos] != '\r') && (text[pos] != '\n'))
                        {
                            str3 = str3 + text[pos];
                            pos++;
                            if (pos >= length)
                            {
                                break;
                            }
                        }
                        if (pos > length && text[pos] == '\n')
                        {
                            curreTokenLine++;
                        }
                        pos++;
                        token = TK.COMMENT;
                        return str3;
                    }
                    goto CheckPunct;
                }
                str2 = "";
                pos++;
                if (pos < length)
                {
                    while ((((text[pos] != '*') || ((pos + 1) >= length)) || (text[pos + 1] != '/')) && (pos < length))
                    {
                        if (text[pos] == '\n')
                        {
                            curreTokenLine++;
                        }
                        str2 = str2 + text[pos];
                        pos++;
                        if (pos >= length)
                        {
                            break;
                        }
                    }
                }
            }
            else
            {
                str = ch.ToString();
                if (pos < length)
                {
                    while (this.in_array(text[pos], this.wordchar))
                    {
                        if (text[pos] == '\n')
                        {
                            curreTokenLine++;
                        }
                        str = str + text[pos];
                        pos++;
                        if (pos == length)
                        {
                            break;
                        }
                    }
                }

                if (str == "case" || str == "default")
                {
                    if (_cases == CASE.CASE)
                        this.case_pop();
                    token = TK.START_CASE;
                }
                else
                {
                    token = TK.WORD;
                }
                return str;
            }
            pos += 2;
            token = TK.BLOCK_COMMENT;
            return ("/*" + str2 + "*/");

            CheckPunct:
            if (((ch != '\'') && (ch != '"')) && ((ch != '/') || (((this.lasttok != TK.START_EXPR) && (this.lasttok != TK.PUNCT)) && ((this.lasttok != TK.EOF) && (this.lasttok != TK.END_COMMAND)))))
            {
                if (!this.in_array(ch, this.punct))
                {
                    //除法操作运算的情况
                    if (ch == '/')
                    {
                        token = TK.PUNCT;
                        return ch.ToString();
                    }
                    return ch.ToString();
                }
                str = ch.ToString();
                if (pos < length)
                {
                    //08-12-5 fixed :var s=.1这种情况格式化后的效果应该是var s = .1而不是var s =. 1,
                    //所以后面加了一个判断下一个符号是否为‘.’&& text[pos]!='.'
                    while (this.in_array(text[pos], this.punct) && text[pos] != '.')
                    {
                        str = str + text[pos];
                        pos++;
                        if (pos >= length)
                        {
                            break;
                        }
                    }
                }
            }
            else
            {
                char ch2 = ch;
                ch = '\0';
                str = "";
                bool flag = false;
                if (pos < length)
                {
                    while (flag || (text[pos] != ch2))
                    {
                        str = str + text[pos];
                        if (!flag)
                        {
                            flag = text[pos] == '\\';
                        }
                        else
                        {
                            flag = false;
                        }
                        pos++;
                        if (pos >= length)
                        {
                            break;
                        }
                    }
                }
                pos++;
                if (this.lasttok == TK.END_COMMAND)
                {
                    this.nl();
                }
                token = TK.STRING;
                return (ch2.ToString() + str + ch2.ToString());
            }
            token = TK.PUNCT;
            return str;
        }
Example #18
0
 static string SelectOpName(TK id)
 {
     switch (id)
     {
         case TK.ALL: return "UNION ALL";
         case TK.INTERSECT: return "INTERSECT";
         case TK.EXCEPT: return "EXCEPT";
         default: return "UNION";
     }
 }
Example #19
0
 public Node(TK key, TV value)
 {
     Key   = key;
     Value = value;
 }
Example #20
0
        private List <TK> Tokenizer(string str)
        {
            var tokenized = new List <TK>();

            if (!str.Contains("  "))
            {
                str.Replace(" ", "");
                if (verifyDivBy0(str))
                {
                    if (!(new Regex("0\\s?\\^\\s?0").IsMatch(str)))
                    {
                        for (int i = 0; i < str.Length; i++)
                        {
                            TK token = TK.TK_NULL;
                            str = str.Replace(" ", "");
                            switch (str[i])
                            {
                            case '+':
                                token = TK.TK_PLUS;
                                break;

                            case '-':
                                token = TK.TK_MINUS;
                                break;

                            case '*':
                                token = TK.TK_STAR;
                                break;

                            case '/':
                                token = TK.TK_SLASH;
                                break;

                            case '^':
                                token = TK.TK_POW;
                                break;

                            case '(':
                                token = TK.TK_LP;
                                break;

                            case ')':
                                token = TK.TK_RP;
                                break;

                            default:
                                if ('0' <= str[i] && str[i] <= '9')
                                {
                                    int j = 0;
                                    while (i + j < str.Length && ('0' <= str[i + j] && str[i + j] <= '9'))
                                    {
                                        j++;
                                    }
                                    i    += j - 1;
                                    token = TK.TK_CONST;
                                }
                                else if ('a' <= str[i] && str[i] <= 'z')
                                {
                                    int j = 0;
                                    while (i + j < str.Length && (('a' <= str[i + j] && str[i + j] <= 'z') || ('0' <= str[i + j] && str[i + j] <= '9')))
                                    {
                                        j++;
                                    }
                                    var id = str.Substring(i, j);
                                    i += j - 1;
                                    if (this.ids.Contains(id))
                                    {
                                        token = TK.TK_ID;
                                    }
                                    else
                                    {
                                        Form1.Output($"Error de léxico (linea {line}): ID inválida en la expresión ({id})");
                                        token = TK.TK_NULL;
                                    }
                                }
                                break;
                            }
                            tokenized.Add(token);

                            if (token == TK.TK_NULL)
                            {
                                Form1.Output($"Error de sintaxis (linea {line}): Caracter inválido en la expresión ({str[i]})");
                                Form1.Output($"\tEn caso de ser una variable, verifique que se haya leído o se le haya asignado algo antes y que esté bien escrita.");
                                tokenized.Add(TK.TK_NULL);
                                // Syntax Error
                            }
                        }
                    }
                    else
                    {
                        Form1.Output($"Excepción Matemática (linea {line}): 0 ^ 0 no está definido");
                        tokenized.Add(TK.TK_NULL);
                    }
                }
                else
                {
                    Form1.Output($"Excepción Matemática (linea {line}): División entre 0");
                    tokenized.Add(TK.TK_NULL);
                    // Syntax Error!
                }
            }
            else
            {
                Form1.Output($"Error de sintaxis (linea {line}): Dos espacios en la expresión matemática");

                tokenized.Add(TK.TK_NULL);
                // Syntax Error!
            }

            return(tokenized);
        }
       public DummyDataContext()
       {
           
           Europa = new Continent();
           Europa.ContinentID = 1;
           Europa.Name = "Europa";

           Graad = new Grade(1);
          
           Belgium = new Country("Belgie",Europa);
           England = new Country("England",Europa);
           Belgium.CountryID = 1;
           England.CountryID = 2;
           //Belgium.AboveEquator = true;
           //England.AboveEquator = false; //voor te testen. England ligt obviously boven de Equator
           int[] temp = new int[]{1,5,3,4,5,6,7,8,9,10,40,12};
           int[] sed = new int[] {10, 206, 30, 200, 50, 60, 70, 80, 20, 100, 110, 120};
           int[] temp2 = new int[] { 1, 2, 3, 0, -10, -12, 7, 8, 9, 10, 11, 12 };
           int[] sed2 = new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120 };
           NegTempClimateChart = new ClimateChart("Chelsea",2000,2030,temp2,sed2, -20, 10);
           NegTempClimateChart.Country = England;
           NegTempClimateChart.ClimateChartID = 2;
           England.ClimateCharts = new List<ClimateChart>{NegTempClimateChart};
           Gent = new ClimateChart("gent",1950,1960,temp,sed, 55, 6);
           Gent.Country = Belgium;
           Gent.ClimateChartID = 1;
           ClimateCharts = new List<ClimateChart>{ Gent };
           Belgium.ClimateCharts = ClimateCharts;  
           Countries = new List<Country>{ Belgium,England };
           Europa.Countries = Countries;
           Continenten = new List<Continent>{ Europa };
           Graad.Continents = Continenten;
           Parameter tw = new TW("Wat is de temperatuur van de warmste maand (TW)?");
           Parameter mw = new MW("Wat is de warmste maand?");
           Parameter mk = new MK("Wat is de temperatuur van de koudste maand?");
           Parameter tk = new TK("Wat is de temperatuur van de koudste maand (TK)?");
           Parameter d = new D("Hoeveel droge maanden zijn er?");
           Parameter nz = new NZ("Hoeveelheid neerslag in de zomer?");
           Parameter nw = new NW("Hoeveelheid neerslag in de winter?");
           Parameter tj = new TJ("");
           Parameter nj = new NJ("");
           Parameter tm = new TM("");
           //ClauseComponent tw10 = new Clause("TW <= 10", tw, "<=", 10);
           //ClauseComponent CC2 = new Clause("TW <= 10", tw, "<", 10);
           //ClauseComponent CC3 = new Clause("TW <= 10", tw, ">=", 10);
           //ClauseComponent CC4 = new Clause("TW <= 10", tw, ">", 10);
           //ClauseComponent res1 = new Result("YES", "geen woestijn");
           //ClauseComponent res2 = new Result("NO", "woestijn");
           //tw10.ClauseComponentId = 1;
           //res1.ClauseComponentId = 2;
           //res2.ClauseComponentId = 3;
           //tw10.Add(true, res1);
           //tw10.Add(false, res2);
           //CC2.Add(true, res1);
           //CC2.Add(false, res2);
           //CC3.Add(true, res1);
           //CC3.Add(false, res2);
           //CC4.Add(true, res1);
           //CC4.Add(false, res2);
           //DetTable = new DeterminateTable();
           
           //DetTable2 = new DeterminateTable();
           
           //DetTable3 = new DeterminateTable();
           
           //DetTable4 = new DeterminateTable();
           Graad.DeterminateTableProp = DetTable;

           Country belgië = new Country { Name = "België" };
           temps = new int[] { 10, 12, 12, 14, 15, 20, 28, 32, 28, 16, 6, 2 };
           sed = new[] { 120, 145, 200, 120, 150, 100, 140, 40, 100, 120, 130, 100 };
           chart = new ClimateChart("Gent", 1990, 1991, temps, sed, 55, 6);
           chart.Country = belgië;

           temps2 = new int[] { 14, 15, 17, 21, 25, 27, 28, 27, 26, 23, 19, 15 };
           sed2 = new[] { 7, 4, 4, 2, 0, 0, 0, 0, 0, 1, 3, 5 };
           chart2 = new ClimateChart("Kaïro", 1961, 1990, temps2, sed2, -20, 2);
           Country egypte = new Country { Name = "Egypte" };
           //egypte.AboveEquator = false;
           chart2.Country = egypte;

           temps3 = new int[] { 0, 1, 5, 11, 17, 22, 25, 24, 20, 14, 9, 3 };
           sed3 = new[] { 77, 73, 91, 96, 97, 91, 103, 95, 86, 77, 97, 86 };
           chart3 = new ClimateChart("New York", 1961, 1990, temps3, sed3, 50, -50);
           Country newyork = new Country { Name = "New York" };
           chart3.Country = newyork;

           temps4 = new int[] { 25, 1, 5, 11, 17, 22, 25, 24, 20, 14, 9, 3 };
           sed4 = new[] { 1, 2, 0, 0, 0, 100, 100, 100, 100, 100, 0, 0 };
           chart4 = new ClimateChart("Fictief", 1961, 1990, temps4, sed4, 60, 20);
           Country fictief = new Country { Name = "Fictief" };
           chart4.Country = fictief;
           

           byte[] picture = null;
           ClauseComponent tw10 = new Clause("TW <= 10", tw, "<=", 10);
           ClauseComponent tw0 = new Clause("TW <= 0", tw, "<=", 0);
           ClauseComponent tw0Yes = new Result("Koud klimaat zonder dooiseizoen", "Ijswoestijnklimaat", picture);
           ClauseComponent tw0No = new Result("Koud klimaat met dooiseizoen", "Toendraklimaat", picture);
           tw0.Add(true, tw0Yes);
           tw0.Add(false, tw0No);
           tw10.Add(true, tw0);
           ClauseComponent tj0 = new Clause("TJ <= 0", tj, "<=", 0);
           tw10.Add(false, tj0);


           ClauseComponent tj0Yes = new Result("Koudgematigd klimaat met strenge winter", "Taigaklimaat", picture);
           tj0.Add(true, tj0Yes);
           ClauseComponent nj200 = new Clause("NJ <= 200", nj, "<=", 200);

           ClauseComponent tk15 = new Clause("TK <= 15", tk, "<=", 15);
           ClauseComponent tk15Yes = new Result("Gematigd altijd droog klimaat", "Woestijnklimaat van de middelbreedten", picture);
           ClauseComponent tk15No = new Result("Warm altijd droog klimaat", "Woestijnklimaat van de tropen", picture);
           tk15.Add(true, tk15Yes);
           tk15.Add(false, tk15Yes);
           nj200.Add(true, tk15);
           tj0.Add(false, nj200);

           ClauseComponent tk18 = new Clause("TK <= 18", tk, "<=", 18);
           ClauseComponent nj400 = new Clause("NJ <= 400", nj, "<=", 400);
           ClauseComponent nj400Yes = new Result("Gematigd, droog klimaat", "Steppeklimaat", picture);
           ClauseComponent tk10N = new Clause("TK <= -10", tk, "<=", -10);
           ClauseComponent tk10NYes = new Result("Koudgematigd klimaat met strenge winter", "Taigaklimaat", picture);
           ClauseComponent d1 = new Clause(" D <= 1", d, "<=", 1);
           ClauseComponent tk3N = new Clause("TK <= -3", tk, "<=", -3);
           ClauseComponent tk3NYes = new Result("Koelgematigd klimaat met koude winter", "Gemengd-woudklimaat", picture);
           ClauseComponent tw22 = new Clause(" TW <= 22", tw, "<=", 22);
           ClauseComponent tw22Yes = new Result("Koelgematigd klimaat met zachte winter", "Loofbosklimaat", picture);
           ClauseComponent tw22No = new Result("Warmgematigd altijd nat klimaat", "Subtropisch regenwoudklimaat", picture);
           ClauseComponent nznw = new Clause("NZ <= NW", nz, nw);
           ClauseComponent tw222 = new Clause("TW <= 22", tw, "<=", 22);
           ClauseComponent tw222Yes = new Result("Koelgematigd klimaat met natte winter", "Hardbladige-vegetatieklimaat van de centrale middelbreedten", picture);
           ClauseComponent tw222No = new Result("Warmgematigd klimaat met natte winter", "Hardbladige-vegetatieklimaat van de subtropen", picture);
           ClauseComponent nznwNo = new Result("Warmgematigd klimaat met natte zomer", "Subtropisch savanneklimaat", picture);

           tw222.Add(true, tw222Yes);
           tw222.Add(false, tw222No);
           nznw.Add(true, tw222);
           nznw.Add(false, nznwNo);
           tw22.Add(true, tw22Yes);
           tw22.Add(false, tw22No);
           tk3N.Add(true, tk3NYes);
           tk3N.Add(false, tw22);
           d1.Add(true, tk3N);
           d1.Add(false, nznw);
           tk10N.Add(true, tk10NYes);
           tk10N.Add(false, d1);
           nj400.Add(true, nj400Yes);
           nj400.Add(false, tk10N);
           tk18.Add(true, nj400);
           nj200.Add(false, tk18);

           ClauseComponent d12 = new Clause("D <= 1", d, "<=", 1);
           ClauseComponent d12Yes = new Result("Warm klimaat met nat seizoen", "Tropisch savanneklimaat", picture);
           ClauseComponent d12No = new Result("Warm altijd nat klimaat", "Tropisch regenwoudklimaat", picture);
           d12.Add(true, d12Yes);
           d12.Add(false, d12No);
           tk18.Add(false, d12);
           dTable = new DeterminateTable();

           List<ClauseComponent> results1 = (new ClauseComponent[]
                {
                    tw0, tj0,nj200, tk15,tk18, nj400, tk10N, d1, tk3N, tw22, nznw, tw222, d12,
                    tw0Yes, tw0No, tj0Yes,
                    tk15Yes, tk15No, nj400Yes, tk10NYes, tk3NYes,
                    tw22Yes, tw22No, tw222Yes, tw222No, nznwNo,
                    d12Yes, d12No, tw10
                }).ToList();

           results1.ForEach(r => dTable.AllClauseComponents.Add(r));
       }
        public JsonResult CheckTK(long OrderNo)
        {
            Result res = new Result();

            try
            {
                /*1、更改退款单的状态*/
                ServiceHelper.Create <ITKService>().UpdateTK(OrderNo, 5);

                /*2、更改订单的状态 单状态为已退款*/
                ServiceHelper.Create <IOrderService>().UpdateOrderStatu(OrderNo, 11);

                /*3、转账*/
                TK      tk       = ServiceHelper.Create <ITKService>().getTK(OrderNo);
                long    buyid    = tk.UserId;
                long    sellid   = ServiceHelper.Create <IShopService>().GetMemberInfoByShopid(tk.SellerUserId) == null ? 0 : ServiceHelper.Create <IShopService>().GetMemberInfoByShopid(tk.SellerUserId).Id;
                decimal tkamount = tk.TKAmont;

                /* 获取转账方的用户id和用户类型 供应商2*/
                Finance_Wallet fwinfo = ServiceHelper.Create <IFinance_WalletService>().GetWalletInfo(sellid, 2, int.Parse(ConfigurationManager.AppSettings["CoinType"].ToString()));
                fwinfo.Wallet_UserLeftMoney = fwinfo.Wallet_UserLeftMoney - tkamount;//获取当前用的可用金额

                /* 获取转账接受方的用户id和用户类型 采购商3*/
                Finance_Wallet fwinfoto = ServiceHelper.Create <IFinance_WalletService>().GetWalletInfo(buyid, 3, int.Parse(ConfigurationManager.AppSettings["CoinType"].ToString()));
                fwinfoto.Wallet_UserLeftMoney = fwinfoto.Wallet_UserLeftMoney + tkamount;//获取当前用的可用金额

                /*添加财务转账信息*/

                Finance_Transfer ftinfo = new Finance_Transfer();
                ChemCloud.Service.Order.Business.OrderBO _orderBO = new ChemCloud.Service.Order.Business.OrderBO();
                ftinfo.Trans_Number     = _orderBO.GenerateOrderNumber();/*创建转账单号*/
                ftinfo.Trans_UserId     = sellid;
                ftinfo.Trans_UserType   = 2;
                ftinfo.Trans_Money      = tkamount;
                ftinfo.Trans_SXMoney    = 0;
                ftinfo.Trans_MoneyType  = int.Parse(ConfigurationManager.AppSettings["CoinType"].ToString());
                ftinfo.Trans_Time       = DateTime.Now;
                ftinfo.Trans_Address    = ChemCloud.Core.Common.GetIpAddress();
                ftinfo.Trans_ToUserId   = buyid;
                ftinfo.Trans_ToUserType = 3;
                ftinfo.Trans_Status     = 1;

                //添加财务退款信息
                Finance_Refund frinfo = new Finance_Refund();
                frinfo.Refund_Number     = _orderBO.GenerateOrderNumber();//创建退款单号
                frinfo.Refund_OrderNum   = OrderNo;
                frinfo.Refund_UserId     = sellid;
                frinfo.Refund_UserType   = ServiceHelper.Create <IMemberService>().GetMember(sellid) == null ? 2 : ServiceHelper.Create <IMemberService>().GetMember(sellid).UserType;
                frinfo.Refund_UserName   = ServiceHelper.Create <IMemberService>().GetMember(sellid).UserName == null ? "" : ServiceHelper.Create <IMemberService>().GetMember(sellid).UserName;
                frinfo.Refund_Money      = tkamount;
                frinfo.Refund_MoneyType  = int.Parse(ConfigurationManager.AppSettings["CoinType"].ToString());
                frinfo.Refund_SXMoney    = 0;
                frinfo.Refund_ISChujing  = 0;
                frinfo.Refund_Address    = ChemCloud.Core.Common.GetIpAddress();
                frinfo.Refund_Time       = tk.TKDate;
                frinfo.Refund_Status     = 1;
                frinfo.Refund_ToUserId   = buyid;
                frinfo.Refund_ToUserType = 3;
                frinfo.Refund_ToUserName = ServiceHelper.Create <IMemberService>().GetMember(buyid).UserName == null ? "" : ServiceHelper.Create <IMemberService>().GetMember(buyid).UserName;

                ServiceHelper.Create <IFinance_TransferService>().AddFinance_Transfer(ftinfo);
                ServiceHelper.Create <IFinance_RefundService>().AddFinance_Refund(frinfo);
                ServiceHelper.Create <IFinance_WalletService>().UpdateFinance_Wallet(fwinfo);
                ServiceHelper.Create <IFinance_WalletService>().UpdateFinance_Wallet(fwinfoto);
                res.success = true;
            }
            catch (Exception)
            {
                res.success = false;
            }
            return(Json(res));
        }
Example #23
0
        /// <summary>
        /// 供应商退款方法
        /// </summary>
        /// <param name="OrderNo"></param>
        /// <param name="Reson"></param>
        /// <param name="Amont"></param>
        /// <param name="Introduce"></param>
        /// <param name="ReasonType"></param>
        /// <param name="images"></param>
        /// <param name="Attitude"></param>
        /// <returns></returns>
        public JsonResult InsertTK(long OrderNo, string Reson, string Amont, string Introduce, int ReasonType, string images, string Attitude)
        {
            Result res = new Result();

            try
            {
                OrderInfo order = ServiceHelper.Create <IOrderService>().GetOrder(Convert.ToInt64(OrderNo));
                DateTime  end   = DateTime.Now.AddDays(3);
                TK        tkQ   = ServiceHelper.Create <ITKService>().getTK(OrderNo);
                long      TKid  = 0;
                if (tkQ == null)
                {
                    /*1.添加退款信息*/
                    TK tk = new TK()
                    {
                        TKDate        = DateTime.Now,
                        OrderId       = Convert.ToInt64(OrderNo),
                        TKAmont       = Convert.ToDecimal(Amont),
                        EndDate       = end,
                        TKInstruction = Introduce,
                        TKResion      = Reson,
                        TKType        = 1, /*1退款中*/
                        SellerUserId  = order.ShopId,
                        UserId        = base.CurrentUser.Id,
                        ReasonType    = ReasonType
                    };
                    TKid = ServiceHelper.Create <ITKService>().InsertTK(tk);

                    /*订单状态为 退款中*/
                    ServiceHelper.Create <IOrderService>().UpdateOrderStatu(OrderNo, 10);
                }
                else
                {
                    TKid = tkQ.Id;
                    /*再次提交拒绝退款*/
                    if (tkQ.TKType == 4)
                    {
                        tkQ.TKType = 1;
                        ServiceHelper.Create <ITKService>().UpdateTK(tkQ.OrderId, 1);
                        /*订单状态为 退款中*/
                        ServiceHelper.Create <IOrderService>().UpdateOrderStatu(OrderNo, 10);
                    }
                }


                /*2.添加退款日志*/
                TKMessage tkm = new TKMessage()
                {
                    MessageContent  = Introduce,
                    MessageDate     = DateTime.Now,
                    MessageAttitude = Convert.ToInt32(Attitude),
                    ReturnName      = base.CurrentUser.RealName,
                    UserId          = base.CurrentUser.Id,
                    TKId            = TKid
                };
                long tkmid = ServiceHelper.Create <ITKService>().InsertTKMessage(tkm);

                /*3、退款凭证*/
                string[]           imgs = images.Split(',');
                List <TKImageInfo> tkis = new List <TKImageInfo>();
                foreach (string item in imgs)
                {
                    if (string.IsNullOrWhiteSpace(item))
                    {
                        continue;
                    }
                    TKImageInfo tki = new TKImageInfo()
                    {
                        TKImage     = item,
                        TKMessageId = tkmid
                    };
                    tkis.Add(tki);
                }
                ServiceHelper.Create <ITKService>().InsertTKImage(tkis);

                res.success = true;
                res.msg     = "操作成功!";
            }
            catch (Exception)
            {
                res.success = false;
                res.msg     = "操作失败!";
            }
            return(Json(res));
        }
Example #24
0
 public TypedToken(TK type)
 {
     _Type = type;
 }
Example #25
0
        public ActionResult Step3(long OrderNo)
        {
            TK tk = ServiceHelper.Create <ITKService>().getTK(OrderNo);

            if (tk == null)
            {
                ViewBag.TKResion      = 0;
                ViewBag.TKAmont       = "";
                ViewBag.type          = 0;
                ViewBag.TKInstruction = "";
            }
            else
            {
                ViewBag.TKResion      = tk.TKResion;
                ViewBag.TKAmont       = tk.TKAmont;
                ViewBag.type          = tk.TKType;
                ViewBag.ReasonType    = tk.ReasonType;
                ViewBag.TKInstruction = tk.TKInstruction;

                ViewBag.TK = tk.EndDate.ToString("yyyy-MM-dd hh:mm:ss");
                List <TKMessageModel> tkmms = new List <TKMessageModel>();
                List <TKMessage>      tks   = ServiceHelper.Create <ITKService>().getTKMessage(tk.Id);
                foreach (TKMessage item in tks)
                {
                    TKMessageModel tkmm = new TKMessageModel()
                    {
                        MessageAttitude = item.MessageAttitude,
                        ReturnName      = item.ReturnName,
                        MessageDate     = item.MessageDate,
                        MessageContent  = item.MessageContent,
                        UserId          = item.UserId,
                        TKId            = item.TKId,
                        Id   = item.Id,
                        tkis = ServiceHelper.Create <ITKService>().getTKImage(item.Id)
                    };
                    tkmms.Add(tkmm);
                }
                ViewBag.tkmms = tkmms;
            }
            OrderInfo order = ServiceHelper.Create <IOrderService>().GetOrder(Convert.ToInt64(OrderNo));

            if (order.UserId == base.CurrentUser.Id)
            {
                ViewBag.OrderNo  = OrderNo;
                ViewBag.ShopName = order.ShopName;
                ViewBag.yunfei   = order.Freight;
                ViewBag.total    = order.ProductTotalAmount;
                ViewBag.max      = order.Freight + order.ProductTotalAmount;
                ViewBag.ShopId   = order.ShopId;
                ViewBag.UserName = order.UserName;
            }
            else
            {
                ViewBag.OrderNo  = "";
                ViewBag.ShopName = "";
                ViewBag.yunfei   = "";
                ViewBag.total    = "";
                ViewBag.max      = "";
                ViewBag.ShopId   = "";
            }
            ViewBag.OrderNo = OrderNo;

            return(View());
        }
Example #26
0
 public static void SetK3(MyBO bo, ISession s, TK value)
 {
     bo.K3 = value == TK.One ? 1 : 0;
 }
 public KeyValuePair(TK key, TV value)
 {
     this.key   = key;
     this.value = value;
 }
Example #28
0
 public bool EqualsToToken( TK other ) {
     return TokenType == (int)other;
 }
 public static Node CreateNode(TK key, TV value, int nbLevels)
 {
     return(new Node(nbLevels, key, value));
 }
Example #30
0
        public int RunParser(string sql, ref string errMsg)
        {
            Debug.Assert(errMsg != null);
            Debug.Assert(NewTable == null);
            Debug.Assert(NewTrigger == null);
            Debug.Assert(VarsSeen == 0);
            Debug.Assert(Vars.length == 0);
            Debug.Assert(Vars.data == null);
            Context ctx          = Ctx;                               // The database connection
            int     maxSqlLength = ctx.Limits[(int)LIMIT.SQL_LENGTH]; // Max length of an SQL string

            if (ctx.ActiveVdbeCnt == 0)
            {
                ctx.u1.IsInterrupted = false;
            }
            RC   = RC.OK;
            Tail = new StringBuilder(sql);
            yyParser engine = Parser_Alloc(); // The LEMON-generated LALR(1) parser

            if (engine == null)
            {
                ctx.MallocFailed = true;
                return((int)RC.NOMEM);
            }
            bool enableLookaside = ctx.Lookaside.Enabled; // Saved value of db->lookaside.bEnabled

            if (ctx.Lookaside.Start != 0)
            {
                ctx.Lookaside.Enabled = true;
            }
            int errs            = 0;      // Number of errors encountered
            TK  tokenType       = 0;      // type of the next token
            TK  lastTokenParsed = 0;      // type of the previous token
            int i = 0;

            while (/*  !ctx.MallocFailed && */ i < sql.Length)
            {
                Debug.Assert(i >= 0);
                LastToken.data   = sql.Substring(i);
                LastToken.length = (uint)GetToken(sql, i, ref tokenType);
                i += (int)LastToken.length;
                if (i > maxSqlLength)
                {
                    RC = RC.TOOBIG;
                    break;
                }
                switch (tokenType)
                {
                case TK.SPACE:
                {
                    if (ctx.u1.IsInterrupted)
                    {
                        ErrorMsg("interrupt");
                        RC = RC.INTERRUPT;
                        goto abort_parse;
                    }
                    break;
                }

                case TK.ILLEGAL:
                {
                    C._tagfree(ctx, ref errMsg);
                    errMsg = SysEx.Mprintf(ctx, "unrecognized token: \"%T\"", (object)LastToken);
                    errs++;
                    goto abort_parse;
                }

                case TK.SEMI:
                {
                    //Tail = new StringBuilder(sql.Substring(i, sql.Length - i));
                    goto default;
                }

                default:
                {
                    Parser(engine, tokenType, LastToken, this);
                    lastTokenParsed = tokenType;
                    if (RC != RC.OK)
                    {
                        goto abort_parse;
                    }
                    break;
                }
                }
            }
abort_parse:
            Tail = new StringBuilder(sql.Length <= i ? string.Empty : sql.Substring(i, sql.Length - i));
            if (sql.Length >= i && errs == 0 && RC == RC.OK)
            {
                if (lastTokenParsed != TK.SEMI)
                {
                    Parser(engine, TK.SEMI, LastToken, this);
                }
                Parser(engine, 0, LastToken, this);
            }
#if YYTRACKMAXSTACKDEPTH
            sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK, sqlite3ParserStackPeak(engine));
#endif
            Parser_Free(engine, null);
            ctx.Lookaside.Enabled = enableLookaside;
            //if (ctx.MallocFailed)
            //    RC = RC.NOMEM;
            if (RC != RC.OK && RC != RC.DONE && string.IsNullOrEmpty(ErrMsg))
            {
                SetString(ref ErrMsg, ctx, ErrStr(RC));
            }
            if (ErrMsg != null)
            {
                errMsg = ErrMsg;
                SysEx.LOG(RC, "%s", errMsg);
                ErrMsg = string.Empty;
                errs++;
            }
            if (V != null && Errs > 0 && Nested == 0)
            {
                Vdbe.Delete(ref V);
                V = null;
            }
#if !OMIT_SHARED_CACHE
            if (Nested == 0)
            {
                C._tagfree(ctx, ref TableLocks.data);
                TableLocks.data   = null;
                TableLocks.length = 0;
            }
#endif
#if !OMIT_VIRTUALTABLE
            VTableLocks.data = null;
#endif
            if (!E.INDECLARE_VTABLE(this))
            {
                // If the pParse.declareVtab flag is set, do not delete any table structure built up in pParse.pNewTable. The calling code (see vtab.c)
                // will take responsibility for freeing the Table structure.
                DeleteTable(ctx, ref NewTable);
            }

#if !OMIT_TRIGGER
            DeleteTrigger(ctx, ref NewTrigger);
#endif
            //for (i = Vars.length - 1; i >= 0; i--)
            //    C._tagfree(ctx, ref Vars.data[i]);
            C._tagfree(ctx, ref Vars.data);
            C._tagfree(ctx, ref Alias.data);
            while (Ainc != null)
            {
                AutoincInfo p = Ainc;
                Ainc = p.Next;
                C._tagfree(ctx, ref p);
            }
            while (ZombieTab != null)
            {
                Table p = ZombieTab;
                ZombieTab = p.NextZombie;
                DeleteTable(ctx, ref p);
            }
            if (errs > 0 && RC == RC.OK)
            {
                RC = RC.ERROR;
            }
            return(errs);
        }
Example #31
0
        public static int GetToken(string z, int offset, ref TK tokenType)
        {
            int  i;
            char c = '\0';

            switch (z[offset + 0])
            {
            case ' ':
            case '\t':
            case '\n':
            case '\f':
            case '\r':
            {
                C.ASSERTCOVERAGE(z[offset + 0] == ' ');
                C.ASSERTCOVERAGE(z[offset + 0] == '\t');
                C.ASSERTCOVERAGE(z[offset + 0] == '\n');
                C.ASSERTCOVERAGE(z[offset + 0] == '\f');
                C.ASSERTCOVERAGE(z[offset + 0] == '\r');
                for (i = 1; z.Length > offset + i && char.IsWhiteSpace(z[offset + i]); i++)
                {
                }
                tokenType = TK.SPACE;
                return(i);
            }

            case '-':
            {
                if (z.Length > offset + 1 && z[offset + 1] == '-')
                {
                    // IMP: R-15891-05542 -- syntax diagram for comments
                    for (i = 2; z.Length > offset + i && (c = z[offset + i]) != '\0' && c != '\n'; i++)
                    {
                    }
                    tokenType = TK.SPACE;           // IMP: R-22934-25134
                    return(i);
                }
                tokenType = TK.MINUS;
                return(1);
            }

            case '(':
            {
                tokenType = TK.LP;
                return(1);
            }

            case ')':
            {
                tokenType = TK.RP;
                return(1);
            }

            case ';':
            {
                tokenType = TK.SEMI;
                return(1);
            }

            case '+':
            {
                tokenType = TK.PLUS;
                return(1);
            }

            case '*':
            {
                tokenType = TK.STAR;
                return(1);
            }

            case '/':
            {
                if (offset + 2 >= z.Length || z[offset + 1] != '*')
                {
                    tokenType = TK.SLASH;
                    return(1);
                }
                // IMP: R-15891-05542 -- syntax diagram for comments
                for (i = 3, c = z[offset + 2]; offset + i < z.Length && (c != '*' || (z[offset + i] != '/') && (c != '\0')); i++)
                {
                    c = z[offset + i];
                }
                if (offset + i == z.Length)
                {
                    c = '\0';
                }
                if (c != '\0')
                {
                    i++;
                }
                tokenType = TK.SPACE;         // IMP: R-22934-25134
                return(i);
            }

            case '%':
            {
                tokenType = TK.REM;
                return(1);
            }

            case '=':
            {
                tokenType = TK.EQ;
                return(1 + (z[offset + 1] == '=' ? 1 : 0));
            }

            case '<':
            {
                if ((c = z[offset + 1]) == '=')
                {
                    tokenType = TK.LE;
                    return(2);
                }
                else if (c == '>')
                {
                    tokenType = TK.NE;
                    return(2);
                }
                else if (c == '<')
                {
                    tokenType = TK.LSHIFT;
                    return(2);
                }
                else
                {
                    tokenType = TK.LT;
                    return(1);
                }
            }

            case '>':
            {
                if (z.Length > offset + 1 && (c = z[offset + 1]) == '=')
                {
                    tokenType = TK.GE;
                    return(2);
                }
                else if (c == '>')
                {
                    tokenType = TK.RSHIFT;
                    return(2);
                }
                else
                {
                    tokenType = TK.GT;
                    return(1);
                }
            }

            case '!':
            {
                if (z[offset + 1] != '=')
                {
                    tokenType = TK.ILLEGAL;
                    return(2);
                }
                else
                {
                    tokenType = TK.NE;
                    return(2);
                }
            }

            case '|':
            {
                if (z[offset + 1] != '|')
                {
                    tokenType = TK.BITOR;
                    return(1);
                }
                else
                {
                    tokenType = TK.CONCAT;
                    return(2);
                }
            }

            case ',':
            {
                tokenType = TK.COMMA;
                return(1);
            }

            case '&':
            {
                tokenType = TK.BITAND;
                return(1);
            }

            case '~':
            {
                tokenType = TK.BITNOT;
                return(1);
            }

            case '`':
            case '\'':
            case '"':
            {
                int delim = z[offset + 0];
                C.ASSERTCOVERAGE(delim == '`');
                C.ASSERTCOVERAGE(delim == '\'');
                C.ASSERTCOVERAGE(delim == '"');
                for (i = 1; (offset + i) < z.Length && (c = z[offset + i]) != '\0'; i++)
                {
                    if (c == delim)
                    {
                        if (z.Length > offset + i + 1 && z[offset + i + 1] == delim)
                        {
                            i++;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                if ((offset + i == z.Length && c != delim) || z[offset + i] != delim)
                {
                    tokenType = TK.ILLEGAL;
                    return(i + 1);
                }
                if (c == '\'')
                {
                    tokenType = TK.STRING;
                    return(i + 1);
                }
                else if (c != 0)
                {
                    tokenType = TK.ID;
                    return(i + 1);
                }
                else
                {
                    tokenType = TK.ILLEGAL;
                    return(i);
                }
            }

            case '.':
            {
#if !OMIT_FLOATING_POINT
                if (!char.IsDigit(z[offset + 1]))
#endif
                {
                    tokenType = TK.DOT;
                    return(1);
                }
                // If the next character is a digit, this is a floating point number that begins with ".".  Fall thru into the next case
                goto case '0';
            }

            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            {
                C.ASSERTCOVERAGE(z[offset] == '0');
                C.ASSERTCOVERAGE(z[offset] == '1');
                C.ASSERTCOVERAGE(z[offset] == '2');
                C.ASSERTCOVERAGE(z[offset] == '3');
                C.ASSERTCOVERAGE(z[offset] == '4');
                C.ASSERTCOVERAGE(z[offset] == '5');
                C.ASSERTCOVERAGE(z[offset] == '6');
                C.ASSERTCOVERAGE(z[offset] == '7');
                C.ASSERTCOVERAGE(z[offset] == '8');
                C.ASSERTCOVERAGE(z[offset] == '9');
                tokenType = TK.INTEGER;
                for (i = 0; z.Length > offset + i && char.IsDigit(z[offset + i]); i++)
                {
                }
#if !OMIT_FLOATING_POINT
                if (z.Length > offset + i && z[offset + i] == '.')
                {
                    i++;
                    while (z.Length > offset + i && char.IsDigit(z[offset + i]))
                    {
                        i++;
                    }
                    tokenType = TK.FLOAT;
                }
                if (z.Length > offset + i + 1 && (z[offset + i] == 'e' || z[offset + i] == 'E') && (char.IsDigit(z[offset + i + 1]) || z.Length > offset + i + 2 && ((z[offset + i + 1] == '+' || z[offset + i + 1] == '-') && char.IsDigit(z[offset + i + 2]))))
                {
                    i += 2;
                    while (z.Length > offset + i && char.IsDigit(z[offset + i]))
                    {
                        i++;
                    }
                    tokenType = TK.FLOAT;
                }
#endif
                while (offset + i < z.Length && IsIdChar(z[offset + i]))
                {
                    tokenType = TK.ILLEGAL;
                    i++;
                }
                return(i);
            }

            case '[':
            {
                for (i = 1, c = z[offset + 0]; c != ']' && (offset + i) < z.Length && (c = z[offset + i]) != '\0'; i++)
                {
                }
                tokenType = (c == ']' ? TK.ID : TK.ILLEGAL);
                return(i);
            }

            case '?':
            {
                tokenType = TK.VARIABLE;
                for (i = 1; z.Length > offset + i && char.IsDigit(z[offset + i]); i++)
                {
                }
                return(i);
            }

            case '#':
            {
                for (i = 1; z.Length > offset + i && char.IsDigit(z[offset + i]); i++)
                {
                }
                if (i > 1)
                {
                    // Parameters of the form #NNN (where NNN is a number) are used internally by sqlite3NestedParse.
                    tokenType = TK.REGISTER;
                    return(i);
                }
                // Fall through into the next case if the '#' is not followed by a digit. Try to match #AAAA where AAAA is a parameter name.
                goto case ':';
            }

#if !OMIT_TCL_VARIABLE
            case '$':
#endif
            case '@':      // For compatibility with MS SQL Server
            case ':':
            {
                int n = 0;
                C.ASSERTCOVERAGE(z[offset + 0] == '$');
                C.ASSERTCOVERAGE(z[offset + 0] == '@');
                C.ASSERTCOVERAGE(z[offset + 0] == ':');
                tokenType = TK.VARIABLE;
                for (i = 1; z.Length > offset + i && (c = z[offset + i]) != '\0'; i++)
                {
                    if (IsIdChar(c))
                    {
                        n++;
#if !OMIT_TCL_VARIABLE
                    }
                    else if (c == '(' && n > 0)
                    {
                        do
                        {
                            i++;
                        } while ((offset + i) < z.Length && (c = z[offset + i]) != 0 && !char.IsWhiteSpace(c) && c != ')');
                        if (c == ')')
                        {
                            i++;
                        }
                        else
                        {
                            tokenType = TK.ILLEGAL;
                        }
                        break;
                    }
                    else if (c == ':' && z[offset + i + 1] == ':')
                    {
                        i++;
#endif
                    }
                    else
                    {
                        break;
                    }
                }
                if (n == 0)
                {
                    tokenType = TK.ILLEGAL;
                }
                return(i);
            }

#if !OMIT_BLOB_LITERAL
            case 'x':
            case 'X':
            {
                C.ASSERTCOVERAGE(z[offset + 0] == 'x');
                C.ASSERTCOVERAGE(z[offset + 0] == 'X');
                if (z.Length > offset + 1 && z[offset + 1] == '\'')
                {
                    tokenType = TK.BLOB;
                    for (i = 2; z.Length > offset + i && IsXDigit(z[offset + i]); i++)
                    {
                    }
                    if (offset + i == z.Length || z[offset + i] != '\'' || i % 2 != 0)
                    {
                        tokenType = TK.ILLEGAL;
                        while (z.Length > offset + i && z[offset + i] != '\'')
                        {
                            i++;
                        }
                    }
                    if (z.Length > offset + i)
                    {
                        i++;
                    }
                    return(i);
                }
                goto default;
                // Otherwise fall through to the next case
            }
#endif
            default:
            {
                if (!IsIdChar(z[offset]))
                {
                    break;
                }
                for (i = 1; i < z.Length - offset && IsIdChar(z[offset + i]); i++)
                {
                }
                tokenType = KeywordCode(z, offset, i);
                return(i);
            }
            }
            tokenType = TK.ILLEGAL;
            return(1);
        }
Example #32
0
 public static Trigger TriggersExist(Parse parse, Table table, TK op, ExprList changes, out TRIGGER maskOut)
 {
     TRIGGER mask = 0;
     Trigger list = null;
     if ((parse.Ctx.Flags & Context.FLAG.EnableTrigger) != 0)
         list = List(parse, table);
     Debug.Assert(list == null || !E.IsVirtual(table));
     for (Trigger p = list; p != null; p = p.Next)
         if (p.OP == op && CheckColumnOverlap(p.Columns, changes))
             mask |= p.TRtm;
     maskOut = mask;
     return (mask != 0 ? list : null);
 }
 public fDoiMK(TK tk)
 {
     this.TaiKhoanDangNhap = tk;
     InitializeComponent();
 }
Example #34
0
        public void CodeRowTrigger(Parse parse, TK op, ExprList changes, TRIGGER trtm, Table table, int reg, OE orconf, int ignoreJump)
        {
            Debug.Assert(op == TK.UPDATE || op == TK.INSERT || op == TK.DELETE);
            Debug.Assert(trtm == TRIGGER.BEFORE || trtm == TRIGGER.AFTER);
            Debug.Assert((op == TK.UPDATE) == (changes != null));

            for (Trigger p = this; p != null; p = p.Next)
            {
                // Sanity checking:  The schema for the trigger and for the table are always defined.  The trigger must be in the same schema as the table or else it must be a TEMP trigger.
                Debug.Assert(p.Schema != null);
                Debug.Assert(p.TabSchema != null);
                Debug.Assert(p.Schema == p.TabSchema || p.Schema == parse.Ctx.DBs[1].Schema);

                // Determine whether we should code this trigger
                if (p.OP == op && p.TRtm == trtm && CheckColumnOverlap(p.Columns, changes))
                    p.CodeRowTriggerDirect(parse, table, reg, orconf, ignoreJump);
            }
        }
Example #35
0
 private void Begin(TK kind)
 {
     marks.Push(next);
     Match(kind);
 }
Example #36
0
 public static void SetK3(MyBO bo, ISession s, TK value)
 {
     bo.K3 = value == TK.One ? 1 : 0;
 }
Example #37
0
 private PonyTokenSpan End(TK token)
 {
     Match(token);
     return(End());
 }
Example #38
0
 static void ExplainComposite(Parse parse, TK op, int sub1Id, int sub2Id, bool useTmp)
 {
     Debug.Assert(op == TK.UNION || op == TK.EXCEPT || op == TK.INTERSECT || op == TK.ALL);
     if (parse.Explain == 2)
     {
         Vdbe v = parse.V;
         string msg = C._mtagprintf(parse.Ctx, "COMPOUND SUBQUERIES %d AND %d %s(%s)", sub1Id, sub2Id, (useTmp ? "USING TEMP B-TREE " : ""), SelectOpName(op));
         v.AddOp4(OP.Explain, parse.SelectId, 0, 0, msg, Vdbe.P4T.DYNAMIC);
     }
 }
Example #39
0
        public static void BeginTrigger(Parse parse, Token name1, Token name2, TK trTm, TK op, IdList columns, SrcList tableName, Expr when, bool isTemp, int noErr)
        {
            Context ctx = parse.Ctx;     // The database connection

            Debug.Assert(name1 != null); // pName1.z might be NULL, but not pName1 itself
            Debug.Assert(name2 != null);
            Debug.Assert(op == TK.INSERT || op == TK.UPDATE || op == TK.DELETE);
            Debug.Assert(op > 0 && op < (TK)0xff);
            Trigger trigger = null; // The new trigger

            int   db;               // The database to store the trigger in
            Token name = null;      // The unqualified db name

            if (isTemp)
            {
                // If TEMP was specified, then the trigger name may not be qualified.
                if (name2.length > 0)
                {
                    parse.ErrorMsg("temporary trigger may not have qualified name");
                    goto trigger_cleanup;
                }
                db   = 1;
                name = name1;
            }
            else
            {
                // Figure out the db that the the trigger will be created in
                db = parse.TwoPartName(name1, name2, ref name);
                if (db < 0)
                {
                    goto trigger_cleanup;
                }
            }
            if (tableName == null || ctx.MallocFailed)
            {
                goto trigger_cleanup;
            }

            // A long-standing parser bug is that this syntax was allowed:
            //    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
            //                                                 ^^^^^^^^
            // To maintain backwards compatibility, ignore the database name on pTableName if we are reparsing our of SQLITE_MASTER.
            if (ctx.Init.Busy && db != 1)
            {
                C._tagfree(ctx, ref tableName.Ids[0].Database);
                tableName.Ids[0].Database = null;
            }

            // If the trigger name was unqualified, and the table is a temp table, then set iDb to 1 to create the trigger in the temporary database.
            // If sqlite3SrcListLookup() returns 0, indicating the table does not exist, the error is caught by the block below.
            //? if (tableName == null) goto trigger_cleanup;
            Table table = Delete.SrcListLookup(parse, tableName); // Table that the trigger fires off of

            if (ctx.Init.Busy == null && name2.length == 0 && table != null && table.Schema == ctx.DBs[1].Schema)
            {
                db = 1;
            }

            // Ensure the table name matches database name and that the table exists
            if (ctx.MallocFailed)
            {
                goto trigger_cleanup;
            }
            Debug.Assert(tableName.Srcs == 1);
            DbFixer sFix = new DbFixer(); // State vector for the DB fixer

            if (sFix.FixInit(parse, db, "trigger", name) && sFix.FixSrcList(tableName))
            {
                goto trigger_cleanup;
            }
            table = Delete.SrcListLookup(parse, tableName);
            if (table == null)
            {
                // The table does not exist.
                if (ctx.Init.DB == 1)
                {
                    // Ticket #3810.
                    // Normally, whenever a table is dropped, all associated triggers are dropped too.  But if a TEMP trigger is created on a non-TEMP table
                    // and the table is dropped by a different database connection, the trigger is not visible to the database connection that does the
                    // drop so the trigger cannot be dropped.  This results in an "orphaned trigger" - a trigger whose associated table is missing.
                    ctx.Init.OrphanTrigger = true;
                }
                goto trigger_cleanup;
            }
            if (E.IsVirtual(table))
            {
                parse.ErrorMsg("cannot create triggers on virtual tables");
                goto trigger_cleanup;
            }

            // Check that the trigger name is not reserved and that no trigger of the specified name exists
            string nameAsString = Parse.NameFromToken(ctx, name);

            if (nameAsString == null || parse.CheckObjectName(nameAsString) != RC.OK)
            {
                goto trigger_cleanup;
            }
            Debug.Assert(Btree.SchemaMutexHeld(ctx, db, null));
            if (ctx.DBs[db].Schema.TriggerHash.Find(nameAsString, nameAsString.Length, (Trigger)null) != null)
            {
                if (noErr == 0)
                {
                    parse.ErrorMsg("trigger %T already exists", name);
                }
                else
                {
                    Debug.Assert(!ctx.Init.Busy);
                    parse.CodeVerifySchema(db);
                }
                goto trigger_cleanup;
            }

            // Do not create a trigger on a system table
            if (table.Name.StartsWith("sqlite_", StringComparison.InvariantCultureIgnoreCase))
            {
                parse.ErrorMsg("cannot create trigger on system table");
                parse.Errs++;
                goto trigger_cleanup;
            }

            // INSTEAD of triggers are only for views and views only support INSTEAD of triggers.
            if (table.Select != null && trTm != TK.INSTEAD)
            {
                parse.ErrorMsg("cannot create %s trigger on view: %S", (trTm == TK.BEFORE ? "BEFORE" : "AFTER"), tableName, 0);
                goto trigger_cleanup;
            }
            if (table.Select == null && trTm == TK.INSTEAD)
            {
                parse.ErrorMsg("cannot create INSTEAD OF trigger on table: %S", tableName, 0);
                goto trigger_cleanup;
            }

#if !OMIT_AUTHORIZATION
            {
                int    tabDb      = Prepare.SchemaToIndex(ctx, table.Schema); // Index of the database holding pTab
                AUTH   code       = AUTH.CREATE_TRIGGER;
                string dbName     = ctx.DBs[tabDb].Name;
                string dbTrigName = (isTemp ? ctx.DBs[1].Name : dbName);
                if (tabDb == 1 || isTemp)
                {
                    code = AUTH.CREATE_TEMP_TRIGGER;
                }
                if (Auth.Check(parse, code, nameAsString, table.Name, dbTrigName) != 0 || Auth.Check(parse, AUTH.INSERT, E.SCHEMA_TABLE(tabDb), 0, dbName))
                {
                    goto trigger_cleanup;
                }
            }
#endif

            // INSTEAD OF triggers can only appear on views and BEFORE triggers cannot appear on views.  So we might as well translate every
            // INSTEAD OF trigger into a BEFORE trigger.  It simplifies code elsewhere.
            if (trTm == TK.INSTEAD)
            {
                trTm = TK.BEFORE;
            }

            // Build the Trigger object
            trigger = new Trigger(); //: (Trigger *)_tagalloc(db, sizeof(Trigger), true);
            if (trigger == null)
            {
                goto trigger_cleanup;
            }
            trigger.Name      = name;
            trigger.Table     = tableName.Ids[0].Name; //: _tagstrdup(ctx, tableName->Ids[0].Name);
            trigger.Schema    = ctx.DBs[db].Schema;
            trigger.TabSchema = table.Schema;
            trigger.OP        = op;
            trigger.TRtm      = (trTm == TK.BEFORE ? TRIGGER.BEFORE : TRIGGER.AFTER);
            trigger.When      = Expr.Dup(db, when, E.EXPRDUP_REDUCE);
            trigger.Columns   = Expr.IdListDup(ctx, columns);
            Debug.Assert(parse.NewTrigger == null);
            parse.NewTrigger = trigger;

trigger_cleanup:
            C._tagfree(ctx, ref name);
            Expr.SrcListDelete(ctx, ref tableName);
            Expr.IdListDelete(ctx, ref columns);
            Expr.Delete(ctx, ref when);
            if (parse.NewTrigger == null)
            {
                DeleteTrigger(ctx, ref trigger);
            }
            else
            {
                Debug.Assert(parse.NewTrigger == trigger);
            }
        }