`
温柔一刀
  • 浏览: 863387 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Fast Query

SQL 
阅读更多
class System::FastQuery
  def self.sub_join_str(model)
    Util.is_submodel(model) ? " AND #{model.table_name}.#{model.inheritance_column} = '#{model.name.demodulize}'" : ""
  end
  class Conditions
    attr_reader :conditions
    def initialize(model)
      @model = model
      @conditions={}
    end

    def method_missing(method_id)
      name = method_id.id2name
      condition = Condition.new(@model,name.to_sym)
      @conditions[name] = condition
      condition
    end
  end
  
  class Relation
    def initialize(parent_model,child_model,belongs_to=false)
      @parent_model = parent_model
      @child_model = child_model
      @join_model = belongs_to ? parent_model : child_model
      @block_conditions = Conditions.new(@join_model)
      @foreign_key = parent_model.class_name.underscore + '_id'
      @model = Model.new(@join_model)
      @conditions = {}
    end
    
    def model
      @model
    end
    
    def and_conditions(conditions)
      @conditions = conditions
      self
    end
    
    def should()
      yield(@block_conditions)
    end
    
    def through(key)
      @foreign_key = key.to_s
      self
    end
    
    def join_str
      join_type = model.is_nil ? "LEFT JOIN" : "JOIN" 

      join = " #{join_type} #{@join_model.table_name} ON #{@parent_model.table_name}.id = #{@child_model.table_name}.#{@foreign_key} "
      join << System::FastQuery.sub_join_str(@child_model)
      join << System::FastQuery.sub_join_str(@parent_model)
      
      @conditions.each do |k,v|
        join << " AND #{@join_model.table_name}.#{k} = #{Util.get_value(v)}" 
      end
      
      @block_conditions.conditions.each do |k,v|
        join << v.to_s
      end
      join
    end
  end
  
  class Model
    attr_reader :is_nil
    attr_reader :table_name
    attr_reader :relations
    attr_reader :model
    attr_reader :conditions
    def initialize(model)
      @model,@table_name = model, model.table_name
      @relations = {}
      @is_nil = false
      @conditions = []
    end
    
    def have(child_model)
      unless @relations.has_key? child_model
        relation = Relation.new(@model,child_model)
        @relations[child_model] = relation
        instance_eval("def #{child_model.name.demodulize.underscore}\n @relations[#{child_model}].model() \n end")
      end
      @relations[child_model]
    end
    
    def belongs_to(parent_model)
      unless @relations.has_key? parent_model
        relation = Relation.new(parent_model,@model,true)
        @relations[parent_model] = relation
        instance_eval("def #{parent_model.name.demodulize.underscore}\n @relations[#{parent_model}].model() \n end")
      end
      @relations[parent_model]      
    end
    
    def should(attr)
      operator = @conditions.empty? ? :NIL : :AND
      create_condition(attr,operator)
    end
    
    def and(attr)
      raise 1 if @conditions.empty?
      create_condition(attr,:AND)
    end
    
    def or(attr)
      raise 1 if @conditions.empty?
      create_condition(attr,:OR)
    end

    def nil
      @is_nil = true
      self.should(:id).nil
    end
    
    def find_all(query_model = @model,&block)
      self.find({:type=>:all,:model=>query_model},&block)
    end
    
    def find_first(query_model = @model,&block)
      self.find({:type=>:first,:model=>query_model},&block)
    end
    
    def find(options={},&block)
      query_model = options[:model] || @model
      type = options[:type] || :all
      
      sql = generate_sql(query_model,type)
      
      all = query_model.find_by_sql(sql)
      if block
        all.find_all(&block)
      end
      if type == :first
        all.empty? ? nil : all[0]
      else
        all
      end
    end
    
    def order_by(order)
      @order_by = " ORDER BY #{order}"
    end    
    
    def generate_sql(query_model=@model,type=:all)
      table = query_model.table_name
      sql = "SELECT DISTINCT #{table}.* FROM #{@model.table_name}"
      conditions,joins = " WHERE 1=1 ",""
      generate_joins(joins,self)
      generate_conditions(conditions,self)
      sql << joins << conditions
      sql << @order_by if @order_by
      sql << " LIMIT 1 " if type == :first
      sql
    end

    private
    def create_condition(attr,operator)
      condition = Condition.new(self,attr,operator)
      @conditions << condition
      condition      
    end

    def generate_joins(joins,model)
      model.relations.each do |k,v|
        joins << v.join_str
        generate_joins(joins,v.model)
      end
    end   
    
    def generate_conditions(conditions,model)
      conditions << ' AND (' unless model.conditions.empty?
      model.conditions.each_with_index do |c,i|
        conditions << c.to_s
      end
      #      conditions << System::FastQuery.sub_join_str(model.model)
      conditions << ") " unless model.conditions.empty?
      
      model.relations.each do |k,v|
        generate_conditions(conditions,v.model)
      end
    end
  end
  
  class Condition
    def initialize(model,attr,operator=:AND)
      @model = model
      @table_name = model.table_name
      @attr = attr
      @operator = operator
    end
    
    def equal(value)
      internal_compare('=',value)
      @model
    end
    
    def not_equal(value)
      internal_compare('<>',value)
      @model
    end
    
    def between(range)
      @str = " #{@table_name}.#{@attr.to_s} BETWEEN #{Util.get_value(range.begin)} AND #{Util.get_value(range.end)} "
      @model    
    end
    
    def ==(value)
      self.equal(value)
    end
    
    def <(value)
      internal_compare('<',value)
    end    
 
    def <=(value)
      internal_compare('<=',value)
    end
    
    def >(value)
      internal_compare('>',value)
    end
    
    def >=(value)
      internal_compare('>=',value)
    end
    
    def like(value)
      @str = " #{@table_name}.#{@attr.to_s} like '%#{value}%' "
      @model
    end
    
    def in(value)
      internal_in(value,"IN")
    end
    
    def not_in(value)
      internal_in(value,"NOT IN")
    end    
    
    def nil
      @str = " #{@table_name}.#{@attr.to_s} IS NULL "
      @model
    end
    
    def to_s
      operator = (@operator==:NIL) ? ' ' : " #{@operator.to_s} "
      operator + @str
    end   
    
    private
    def internal_in(value,type)
      if value.empty?
        if type == "IN"
          @str = " 1=0 " 
        else
          @str = " 1=1 "
        end
      else
        @str = " #{@table_name}.#{@attr.to_s} #{type} ("
        @str << value.collect{|v| Util.get_value(v)}.join(',') << ') '
      end
      @model
    end
    
    def internal_compare(operator,value)
      @str = " #{@table_name}.#{@attr.to_s} #{operator} #{Util.get_value(value)} "
      @model
    end
  end  
end

 

分享到:
评论

相关推荐

    Lightweight preprocessing and fast query of geodesic distance via proximity graph

    Lightweight preprocessing and fast query of geodesic distance via proximity graph

    Fast and Scalable Range Query Processing

    with the problem of privacy-preserving range query processing on clouds. Prior schemes are weak in privacy protection as they cannot achieve index indistinguishability, and therefore allow the cloud ...

    Fast Report Professional Edition 4.7.9 - 22.10.2008 FS

    在压缩包中,`recompile.exe`可能是用于重新编译FastReport组件的程序,`frx_icon.ico`是FastReport的图标文件,`install_rus.txt`可能是俄文版的安装说明,`FastQB`可能是指Fast Query Builder,一个用于构建查询的...

    Accuracer v17.00.for Delphi 10.4 by [CS].rar (首先在互联网上. 仅在CSDN中.)

    - Accuracer Data Provider for Fast Query Builder - for visual query building; - Accuracer Database Connection for Easy Query - for visual query building; - Accuracer Data Provider for Active Query ...

    SuRF: Practical Range Query Filtering with Fast Succinct Tries原文

    SuRF基于一个名为Fast Succinct Trie(FST)的新型数据结构,能够在保持点查询和范围查询性能的同时,将每个trie节点的存储消耗降低到10比特。 在数据结构中,Bloom Filter是一种使用位数组进行成员测试的数据结构...

    【Anki插件】Word Query插件使用说明.pdf

    【Anki插件】Word Query插件使用说明.pdf

    A Fast and High Throughput SQL Query System for Big Data

    In this paper, we introduce a fast, high throughput and scalable system to perform read-only SQL well with the advantage of NoSQL’s distributed architecture. We adopt HBase as the storage layer and ...

    The Data Warehouse Tookit 3rd.epub

    Design dimensional databases that are easy to understand and provide fast query response with The Data Warehouse Toolkit: The Definitive Guide to Dimensional Modeling, 3rd Edition. Table of Contents ...

    Best Practices for SAP BW on DB2 UDB for z/OS V8

    1. **High Performance**: The combination of SAP BW and DB2 UDB for z/OS delivers exceptional performance, enabling fast query response times and efficient data processing. 2. **Scalability**: z/OS is ...

    faceback数据仓库揭秘

    #### 快速查询处理(Fast query processing) 为了支持实时网站请求和高并发用户的查询需求,底层存储结构必须能够处理大量读负载,保持快速的查询响应时间。RCFile通过优化数据访问路径,确保了即使在查询数量激增...

    FQuery for moss

    FQuery这个名字融合了“Fast Query”和“Frequently Used Query”的概念,意味着它能够快速、便捷地执行常见的查询操作。 **1. 查询优化** FQuery的核心功能在于其强大的查询引擎。它支持自定义SQL语句,允许用户...

    Facebook数据仓库揭秘之RCFile高效存储结构.docx

    2. **快速查询处理(Fast Query Processing)**: - 高并发用户的实时查询需求对数据处理速度提出了极高要求。 - 底层存储结构需能支持随着查询数量增加而维持快速处理能力。 3. **高效存储空间利用(Highly ...

    尚硅谷大数据技术之Druid1

    快速查询(Fast Query)是 Druid 的一个重要设计原则。Druid 通过部分数据的聚合(Partial Aggregate)、内存化(In-Memory)和索引(Index)来实现快速查询。在数据分析场景中,大部分情况下,我们只关心一定粒度...

    FastReport5.4.7 for D10.2.7z

    7. **FastQB(Fast Query Builder)**:这可能是一个快速查询构建器,用于帮助开发者创建和管理SQL查询,可以与FastReport结合使用,方便地从数据库中获取数据填充报表。 8. **Res文件夹**:资源文件,可能包含图标...

    Facebook数据仓库

    #### 快速查询处理(Fast query processing) 为了应对高并发用户的查询请求,RCFile采用了列存储的方式,使得系统能够在查询执行时仅读取所需列的数据,极大地减少了I/O操作,从而显著加快了查询响应时间。这种...

    fast-wp-query:WP_Query通过使用对象缓存进行MySQL优化

    #Fast WP_Query WP_Query通过使用对象缓存进行MySQL优化 ##基准### 1。 选择最后10个帖子(数据库中有7000行) $ query = new WP_Query ( [ 'post_type' => 'post' , 'posts_per_page' => 10 ] ); ####默认SQL: ...

    宿舍管理系统 系统分析

    Proper normalization and indexing techniques ensure data integrity and fast query execution. After the design phase, comes the implementation. Writing code in Visual Basic to create the system's ...

    fastapi-query-expansion:FastAPI查询扩展

    在fastapi-query-expansion/api-config.config ,将deployment_method的值更改为local并创建所需的配置。 从fastapi-query-expansion/ bash ./start_service.sh 创建一个Docker镜像 要求: 的Python> = 3.X 码头...

    Postgres-X2的介绍

    - **快速查询分发 (Fast Query Shipping)**:通过优化查询计划的生成和分发流程,加快查询执行速度。 #### 社区发展历史 - **发展历程**: - **2004~2008 年**:NTT Data 开始构建 Rita-DB 模型。 - **2009 年**...

Global site tag (gtag.js) - Google Analytics