summaryrefslogtreecommitdiff
path: root/web/lib/sql.rb
blob: 030cf37ad2a43bc089c3d327274868bd0878603b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# web/lib/sql.rb
#
# SQL database wrapper with convenience methods for query building.
module SQL

    # Wrapper for a database connection.
    class Database

        # This has to be called once to initialize the context for the database
        def self.init(dir)
            @@dir = dir

            db = SQL::Database.new

            db.select('SELECT * FROM sources ORDER BY no').execute().each do |source|
                Source.new(source['id'], source['name'], source['data_until'], source['update_start'], source['update_end'], source['visible'].to_i == 1)
            end

            data_until = db.select("SELECT min(data_until) FROM sources WHERE id='db'").get_first_value().sub(/:..$/, '')

            db.close

            data_until
        end

        def initialize
            filename = @@dir + '/taginfo-master.db'
            @db = SQLite3::Database.new(filename)
            @db.results_as_hash = true

            @db.execute('SELECT * FROM languages') do |row|
                Language.new(row)
            end
        end

        def attach_sources
            Source.each do |source|
                @db.execute("ATTACH DATABASE ? AS ?", "#{ @@dir }/#{ source.dbname }", source.id.to_s)
            end
            @db.execute("ATTACH DATABASE ? AS search", "#{ @@dir }/taginfo-search.db")
            @db.execute("ATTACH DATABASE ? AS history", "#{ @@dir }/taginfo-history.db")
            self
        end

        def close
            @db.close
            @db = nil
        end

        def wrap_query(query, *params)
            t1 = Time.now
            out = yield
            duration = Time.now - t1

            min_duration = TaginfoConfig.get('logging.min_duration', 0)
            if duration > min_duration
                if params.size > 0
                    p = ' params=[' + params.map{ |p| "'#{p}'" }.join(', ') + ']'
                else
                    p = ''
                end
                ($queries_log||$stdout).puts %Q{SQL duration=#{ duration } query="#{ query };"} + p
            end

            out
        end

        def execute(*args, &block)
            wrap_query(*args) do
                @db.execute(*args, &block)
            end
        end

        def get_first_row(*args)
            wrap_query(*args) do
                @db.get_first_row(*args)
            end
        end

        def get_first_value(*args)
            wrap_query(*args) do
                @db.get_first_value(*args)
            end
        end

        def select(query, *params)
            Select.new(self, query, *params)
        end

        # Build query of the form
        #   SELECT count(*) FROM table;
        def count(table)
            Select.new(self, 'SELECT count(*) FROM ' + table)
        end

        def stats(key)
            get_first_value('SELECT value FROM master_stats WHERE key=?', key).to_i
        end

    end

    # Representation of a SELECT query.
    class Select

        def initialize(db, query, *params)
            @db = db

            @query      = [query]
            @conditions = []

            @params = params
        end

        def condition(expression, *params)
            @conditions << expression
            @params.push(*params)
            self
        end

        def is_null(attribute)
            condition("#{attribute} IS NULL")
            self
        end

        def condition_if(expression, *param)
            unless param.first.to_s.match(/^%?%?$/)
                condition(expression, *param)
            end
            self
        end

        def conditions(cond)
            cond.each do |cond|
                condition(cond)
            end
            self
        end

        def order_by(values, direction, &block)
            if values.is_a?(Array)
                values = values.compact
            else
                values = [values]
            end

            o = Order.new(values, &block)

            if direction != 'ASC' && direction != 'DESC'
                raise ArgumentError, 'direction must be ASC or DESC'
            end

            values.each do |value|
                value = o.default if value.nil?
                unless o._allowed(value)
                    raise ArgumentError, 'order by this attribute not allowed'
                end
            end

            unless values.empty?
                @order_by = "ORDER BY " + values.map{ |value|
                    value = o.default if value.nil?
                    o[value.to_s].map{ |oel| oel.to_s(direction) }.join(',')
                }.join(',')
            end

            self
        end

        def group_by(value)
            @group_by = "GROUP BY #{value}"
            self
        end

        def paging(ap)
            if ap.do_paging?
                limit(ap.results_per_page, ap.first_result)
            end
            self
        end

        def limit(limit, offset=0)
            @limit = "LIMIT #{limit} OFFSET #{offset}"
            self
        end

        def build_query
            unless @conditions.empty?
                @query << 'WHERE'
                @query << @conditions.map{ |c| "(#{c})" }.join(' AND ')
            end
            @query << @group_by
            @query << @order_by
            @query << @limit
            @query.compact.join(' ')
        end

        def execute(&block)
            q = build_query()
            @db.execute(q, *@params, &block)
        end

        def get_first_value
            q = build_query()
            @db.get_first_value(q, *@params)
        end

        def get_first_i
            get_first_value().to_i
        end

        def get_columns(*columns)
            q = build_query()
            row = @db.get_first_row(q, *@params)
            return [nil] * columns.size if row.nil?;
            columns.map{ |column| row[column.to_s] }
        end

    end

    class OrderElement

        @@DIRECTION = { 'ASC' => 'DESC', 'DESC' => 'ASC' }

        def initialize(column, reverse)
            @column  = column
            @reverse = reverse
        end

        def to_s(direction)
            dir = @reverse ? @@DIRECTION[direction.upcase] : direction.upcase
            "#{@column} #{dir}"
        end

    end

    class Order

        attr_reader :default

        def initialize(values, &block)
            @allowed = Hash.new
            if block_given?
                yield self
            else
                values.each do |value|
                    _add(value.to_s)
                end
            end
        end

        def _allowed(field)
            @allowed.has_key?(field.to_s)
        end

        def [](field)
            @allowed[field]
        end

        def _add(field, attribute=nil)
            field = field.to_s
            @default = field unless defined? @default
            if field =~ /^(.*)!$/
                field = $1
                reverse = true
            else
                reverse = false
            end
            attribute = field if attribute.nil?

            @allowed[field] ||= Array.new
            @allowed[field] << OrderElement.new(attribute.to_s, reverse)
        end

        def method_missing(field, attribute=nil)
            _add(field, attribute)
        end

    end

end