-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cr
More file actions
2087 lines (1911 loc) · 69.9 KB
/
Copy pathmain.cr
File metadata and controls
2087 lines (1911 loc) · 69.9 KB
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-FileCopyrightText: Yoran Heling <projects@yorhel.nl>
# SPDX-License-Identifier: AGPL-3.0-only
require "option_parser"
require "ini"
require "db"
require "pg"
require "csv"
require "json"
require "sqlite3"
require "http/server"
require "compress/gzip"
require "digest/sha256"
CSS_BODY = {{ `gzip -nc style.css`.stringify }}
CSS_PATH = {{ "/" + `sha1sum style.css | head -c 16`.stringify + ".css" }}
FAVICON = {{ read_file "favicon.ico" }}
JS_BODY = {{ `gzip -nc lib/script.js`.stringify }}
JS_PATH = {{ "/" + `sha1sum lib/script.js | head -c 16`.stringify + ".js" }}
config_path = "config.ini"
OptionParser.parse do |parser|
parser.banner = "Usage: sqlbin [arguments]"
parser.on("-c PATH", "--config=PATH", "Path to the configation file") {|p| config_path = p}
parser.on("-h", "--help", "Show this help") do
puts parser
exit
end
end
class PG::Connection
def conn
connection
end
end
class Conf
getter db : String, storage : String, bind, gnuplot_path : String?, broken_check_interval : UInt32
getter id_anon, name_anon, role_anon
getter id_header : String?, name_header : String?, role_header : String?
getter min_query_time : Float32, check_interval : UInt32, max_age : UInt32
getter max_table_rows : UInt32, max_plot_rows : UInt32, max_export_rows : UInt32, queries_per_page : UInt32, about : String?
def initialize(path)
conf = INI.parse File.open path
server = conf["server"]? || raise "Missing [server] configuration block"
@db = server["db"]? || raise "Missing 'db' setting"
@storage = server["storage"]? || raise "Missing 'storage' setting"
@bind = server["bind"]? || "tcp://127.0.0.1:8000/"
@gnuplot_path = server["gnuplot_path"]?
@broken_check_interval = (server["broken_check_interval"]? || "86400").to_u32? || raise "Invalid value for broken_check_interval"
user = conf["user"]? || {} of String => String
@id_anon = user["id_anon"]? || "anonymous"
@name_anon = user["name_anon"]? || "Anonymous"
@role_anon = user["role_anon"]? || "editor"
@id_header = user["id_header"]?
@name_header = user["name_header"]?
@role_header = user["role_header"]?
cache = conf["cache"]? || {} of String => String
@min_query_time = (cache["min_query_time"]? || "0.05").to_f32? || raise "Invalid value for cache.min_query_time"
@check_interval = (cache["check_interval"]? || "1800").to_u32? || raise "Invalid value for cache.check_interval"
@max_age = (cache["max_age"]? || "3600").to_u32? || raise "Invalid value for cache.max_age"
ui = conf["ui"]? || {} of String => String
@max_table_rows = (ui["max_table_rows"]? || "10000").to_u32? || raise "Invalid value for ui.max_table_rows"
@max_plot_rows = (ui["max_plot_rows"]? || "10000").to_u32? || raise "Invalid value for ui.max_plot_rows"
@max_export_rows = (ui["max_export_rows"]? || "100000").to_u32? || raise "Invalid value for ui.max_export_rows"
@queries_per_page = (ui["queries_per_page"]? || "100").to_u32? || raise "Invalid value for ui.queries_per_page"
@about = ui["about"]?
end
end
class Storage
@db : DB::Database
getter xsrf_secret : Bytes
def initialize(@path : String)
Dir.mkdir_p @path, 0o700
Dir.mkdir "#{@path}/db" if !Dir.exists? "#{@path}/db"
Dir.mkdir "#{@path}/cache" if !Dir.exists? "#{@path}/cache"
File.write "#{@path}/cache/CACHEDIR.TAG", "Signature: 8a477f597d28d172789f06886806bc55\n" if !File.exists? "#{@path}/cache/CACHEDIR.TAG"
@db = DB.open "sqlite3://#{@path}/db/db.sqlite3?foreign_keys=ON"
init_schema
@xsrf_secret = @db.scalar("SELECT value FROM globals WHERE key = 'xsrf_secret'").as(Bytes)
end
private def init_schema
ver = @db.scalar("PRAGMA user_version").as(Int64)
if ver == 0
puts "[storage] Initializing new database at #{@path}"
@db.exec <<-SQL
CREATE TABLE users (
id text PRIMARY KEY,
name text
) STRICT
SQL
@db.exec <<-SQL
CREATE TABLE queries (
id int PRIMARY KEY,
visibility int NOT NULL,
created int NOT NULL DEFAULT (unixepoch('now')),
updated int NOT NULL DEFAULT (unixepoch('now')),
user text NOT NULL REFERENCES users(id),
title text NOT NULL,
sql text NOT NULL,
params text NOT NULL
) STRICT
SQL
ver += 1
end
if ver == 1
@db.exec <<-SQL
CREATE TABLE globals (
key text NOT NULL PRIMARY KEY,
value text
)
SQL
@db.exec "INSERT INTO globals VALUES (?, ?)", "xsrf_secret", Random::Secure.random_bytes
ver += 1
end
if ver == 2
@db.exec "ALTER TABLE queries ADD COLUMN graph int NOT NULL DEFAULT 0"
ver += 1
end
if ver == 3
@db.exec "ALTER TABLE queries ADD COLUMN copy int"
ver += 1
end
if ver == 4
@db.exec <<-SQL
CREATE TABLE queries_tags (
query int NOT NULL REFERENCES queries (id) ON DELETE CASCADE ON UPDATE CASCADE,
tag text NOT NULL,
PRIMARY KEY(query, tag)
) STRICT
SQL
@db.exec %{CREATE INDEX queries__user ON queries (user)}
@db.exec %{CREATE INDEX queries_tags__tag ON queries_tags (tag)}
ver += 1
end
if ver == 5
@db.exec "ALTER TABLE queries ADD COLUMN broken_check int"
@db.exec "ALTER TABLE queries ADD COLUMN broken_since int"
@db.exec "CREATE INDEX queres__broken_check ON queries (broken_check)"
ver += 1
end
@db.exec "PRAGMA user_version = #{ver}"
end
def update_user(id, name)
@db.exec "UPDATE users SET name = ?2 WHERE id = ?1 AND name <> ?2", id, name
end
def get_user(id : String)
@db.scalar("SELECT name FROM users WHERE id = ?", id).as(String)
end
def save_query(query, broken, user_id, user_name, is_admin)
@db.transaction do |trans|
db = trans.connection
db.exec "INSERT INTO users (id, name) VALUES (?, ?) ON CONFLICT (id) DO NOTHING", user_id, user_name
id = query.save.try(&.to_i64) || Random::Secure.rand(Int64)
params = query.stored_params
copy = query.copy.try &.to_i64
# XXX: While the WHERE clause below will prevent users from overwriting
# each other's queries, this code still allows someone to save a query
# with a chosen, non-random, ID. Not really a problem, I guess?
id = db.scalar(%{\
INSERT INTO queries (id, visibility, user, title, sql, graph, copy, params, broken_check, broken_since) \
VALUES (?1, ?2, ?3, coalesce(nullif(?4, ''), 'Unnamed query'), ?5, ?6, ?7, ?8, unixepoch('now'), #{ broken ? "unixepoch('now')" : "NULL" }) \
ON CONFLICT (id) DO UPDATE SET \
updated = unixepoch('now'), \
visibility = ?2, \
title = coalesce(nullif(?4, ''), title), \
sql = ?5, \
graph = ?6, \
params = ?8, \
broken_check = unixepoch('now'), \
broken_since = #{ broken ? "COALESCE(broken_since, unixepoch('now'))" : "NULL" } \
#{ is_admin ? "" : "WHERE user = ?3" } \
RETURNING id\
}, id, query.vis.value, user_id, query.title, query.input, params["plot"]? ? 1 : 0, copy == id ? nil : copy, params.to_s).as(Int64)
db.exec "DELETE FROM queries_tags WHERE query = ?1", id
query.tags.each {|t| db.exec "INSERT INTO queries_tags (query, tag) VALUES (?1, ?2)", id, t}
id
end.not_nil!
end
def load_query(id)
@db.query_one %{\
SELECT q.title, q.sql, q.params, q.visibility, q.user, q.created, q.updated, u.name \
, q.copy, cq.visibility, cq.title, cq.user, cu.name \
FROM queries q \
JOIN users u ON u.id = q.user \
LEFT JOIN queries cq ON cq.id = q.copy \
LEFT JOIN users cu ON cu.id = cq.user \
WHERE q.id = ?}, id,
as: {
title: String, sql: String, params: String, visibility: Int32, user_id: String, created: Int64, updated: Int64, user_name: String,
copy: Int64?, copy_visibility: Int32?, copy_title: String?, copy_user_id: String?, copy_user_name: String?
}
end
def delete_query(id)
@db.exec "DELETE FROM queries WHERE id = ?1", id
end
private def internal_queries(sel : String, order : String? = nil, visibility : Int32? = nil, graph : Bool? = nil, tag : String? = nil, user : String? = nil, search : String? = nil, limit : Int64? = nil, offset : Int64? = nil)
@db.query "\
SELECT #{sel} \
FROM queries q \
JOIN users u ON u.id = q.user \
WHERE (1 IN(1,?1,?2,?3,?4,?5,?6))
#{user ? "AND q.user = ?1" : ""} \
#{visibility ? "AND q.visibility = ?2" : ""} \
#{graph == nil ? "" : graph ? "AND graph <> 0" : "AND graph = 0"} \
#{tag && tag != "" ? "AND EXISTS(SELECT 1 FROM queries_tags t WHERE t.query = q.id AND t.tag = ?3)" : ""} \
#{search ? "AND (q.title REGEXP ?4 OR q.sql REGEXP ?4)" : ""} \
#{order ? "ORDER BY #{order}" : ""} \
#{limit ? "LIMIT ?5" : ""} \
#{offset ? "OFFSET ?6" : ""}",
user, visibility, tag, search, limit, offset
end
def queries(**args)
q = internal_queries "COUNT(*)", **args
q.move_next
res = q.read(Int64)
q.close
res
end
def queries(**args, &)
q = internal_queries "q.id, q.visibility, q.title, q.graph, q.created, q.updated, q.broken_since, q.user, u.name", **args
q.each do
yield q.read id: Int64, visibility: Int32, title: String, graph: Int64, created: Int64, updated: Int64, broken_since: Int64?, user_id: String, user_name: String
end
q.close
end
def query_tags(id : Int64)
@db.query_all "SELECT tag FROM queries_tags WHERE query = ?1 ORDER BY tag", id, as: String
end
def tags(user : String? = nil)
@db.query_all "\
SELECT DISTINCT t.tag \
FROM queries_tags t \
WHERE #{ user ? "EXISTS(SELECT 1 FROM queries q WHERE q.id = t.query AND (q.visibility == 2 OR q.user = ?1))" : "?1 IS NULL" } \
ORDER BY tag", user, as: String
end
class Cache < IO
# We're including a buffer here because the Gzip writer is pretty slow on small writes.
# The Gzip reader is already buffered, but we're just bypassing that one.
include IO::Buffered
@wr : Compress::Gzip::Writer?
@rd : Compress::Gzip::Reader?
def initialize(writer : Bool, @fd : File)
if writer
@wr = Compress::Gzip::Writer.new fd, 3
else
@rd = Compress::Gzip::Reader.new fd
end
end
def closed?
@fd.closed?
end
def writer
@wr != nil
end
def unbuffered_write(slice : Bytes) : Nil
@wr.not_nil!.write slice
end
def unbuffered_read(slice : Bytes) : Int32
@rd.not_nil!.unbuffered_read slice
end
def unbuffered_flush
@wr.not_nil!.flush
@fd.flush
end
def unbuffered_rewind
raise "Unable to rewind Cache"
end
def unbuffered_close
(@wr || @rd).not_nil!.close
@fd.close
end
def cancel
return if closed?
(@wr || @rd).not_nil!.close
@fd.truncate 0 if writer
@fd.close
end
end
# Open a cache file and return an IO object.
# If .writer is false, then the cache already exists and the IO can be read
# from, otherwise the cache has just been created and the IO should be
# written to. This approach attempts to avoid the thundering herd problem
# with locks, letting any concurrent readers wait until the write is done.
# Not quite perfect, though:
# - If the writer doesn't complete the write for some reason, without
# cancelling or raising an error, readers will end up with an incomplete
# cache file. This persists until the cache expires.
# - There's a race condition on checking whether this instance is the writer,
# there is a tiny chance that multiple processes will write the same cache.
# Not a problem in terms of correctness, just not great for performance.
# Cache files are transparently compressed. The writer can call .cancel at
# any time to drop this cache file.
def cache(id)
fn = "#{@path}/cache/#{Digest::SHA256.new.update(id).hexfinal[0..31]}"
# Properly fixing the race conditions requires O_EXCL, https://github.com/crystal-lang/crystal/issues/7857
10.times do
# Read attempt.
begin
rd = File.new fn, "r"
rescue
else
rd.flock_shared
# It's possible that we obtain this read lock before the writer got
# their exclusive lock, or that the writer has crashed and didn't write
# anything. In both cases we're reading an empty file, which is not
# useful, so close and continue.
# (Note: a properly written empty cache will still have a gzip header)
if rd.size == 0
rd.close
else
return Cache.new false, rd
end
end
wr = File.open(fn, "w")
# If we can't get an exclusive lock without blocking, something happened:
# - Another writer is active, in which case we can just go back and read the file.
# - Or a reader opened the file and locked for reading before we could write anything.
begin
wr.flock_exclusive blocking: false
rescue
next
end
return Cache.new true, wr
end
raise "Unable to open '#{fn}' after 10 attempts"
end
def cache_cleanup(max_age)
t1 = Time.instant
oldest = Time.utc - max_age
num, size = 0, 0
Dir.glob("#{@path}/cache/????????????????????????????????") do |fn|
begin
nfo = File.info(fn)
if nfo.modification_time < oldest
size += nfo.size
num += 1
File.delete fn
end
rescue ex
puts "Error deleting '#{fn}': #{ex.message}"
end
end
puts "[cache] Cleaned up #{num} files and #{size} bytes in #{(Time.instant-t1).total_seconds} seconds"
end
# Returns an {Int,String} for the next query to check (id,sql).
# Sleeps if there's nothing (yet) to check.
def next_broken(check_interval)
loop do
begin
id, sql, last_check = @db.query_one "SELECT id, sql, broken_check FROM queries ORDER BY broken_check LIMIT 1", as: {Int64, String, Int64?}
rescue
# No rows -> empty database. Newly saved queries are already checked,
# so we won't have to check again for at least check_interval.
sleep check_interval.second
next
end
return {id,sql} unless last_check
now = Time.utc.to_unix
return {id,sql} if last_check + check_interval < now
sleep ((last_check + check_interval) - now).clamp(1, check_interval).second
end
end
def save_broken(id, broken)
@db.exec "\
UPDATE queries \
SET broken_check = unixepoch('now') \
, broken_since = #{ broken ? "COALESCE(broken_since, unixepoch('now'))" : "NULL"} \
WHERE id = ?1", id
end
end
class PGTypes
@type_names = Hash(Int32, String).new
def initialize(@db : DB::Database)
end
def [](oid : Int32) String
@type_names.put_if_absent(oid) do
@db.scalar("SELECT typname FROM pg_catalog.pg_type WHERE oid = $1", oid).as(String)
end
end
end
class Query
getter input, title, vis, tags : Array(String), save : Id?
getter plot, gw, gh
@plot : String = ""
@gw : Int32 = 800
@gh : Int32 = 600
# string when viewing, nil when editing
getter id : Id?, created : Time?, updated : Time?
getter user_id : String?, user_name : String?
# 'copy' can be set from a param, used when saving.
# The other fields are only set when viewing.
getter copy : Id?, copy_vis : Visibility?, copy_title : String?, copy_user_id : String?, copy_user_name : String?
enum Visibility
Private
Unlisted
Public
end
struct Id
def initialize(@id : Int64); end
def initialize(s : String); @id = s.to_u64(16).to_i64!; end
def self.from_s?(s : String?); s =~ /^[0-9a-f]{16}$/ ? new s : nil; end
def to_s(io); io.printf "%016x", @id.to_u64!; end
def to_s; String.build {|b| to_s b}; end
def to_i64; @id; end
end
def initialize(params : URI::Params)
@input = params["sql"]? || ""
@title = params["title"]? || ""
@vis = (params["vis"]? || "").to_i?.try {|v| v >= 0 && v <= 2 ? Visibility.new v : Visibility::Public} || Visibility::Public
@save = params["save"]?.try {|v| Id.from_s? v}
@copy = params["copy"]?.try {|v| Id.from_s? v}
@tags = (params["tags"]?||"").split(/[\s,]+/).map(&.downcase).reject!(/[^a-z0-9\/_-]/).reject ""
load_params params
end
def initialize(storage : Storage, id : String)
id = Id.new id
q = storage.load_query id.to_i64
@id = id
@title = q[:title]
@input = q[:sql]
@vis = Visibility.new q[:visibility]
@tags = storage.query_tags id.to_i64
@user_id = q[:user_id]
@user_name = q[:user_name]
@created = Time.unix q[:created]
@updated = Time.unix q[:updated]
@copy = q[:copy].try {|v| Id.new v}
@copy_vis = q[:copy_visibility].try {|v| Visibility.new v}
@copy_title = q[:copy_title]
@copy_user_id = q[:copy_user_id]
@copy_user_name = q[:copy_user_name]
load_params URI::Params.parse(q[:params])
end
# For query params shared between read-only and editable queries
private def load_params(params)
@plot = params["plot"]? || ""
@gw = ((params["gw"]? || "800").to_i32? || 800).clamp 50, 3000
@gh = ((params["gh"]? || "600").to_i32? || 600).clamp 50, 3000
end
def sql
@input.strip.gsub(/;$/, "") # Not very reliable, won't catch ';-- comment here'
end
# Fields stored in the "params" column
def stored_params
p = URI::Params.new
if self.plot != ""
p["plot"] = self.plot
p["gw"] = self.gw.to_s
p["gh"] = self.gh.to_s
end
p
end
# Fields passed around in our form (excluding "sql")
def form_params
p = stored_params
p["vis"] = vis.value.to_s if vis != Visibility::Public
p["title"] = title if title != ""
save.try {|s| p["save"] = s.to_s}
p["tags"] = tags.join ", " unless tags.empty?
p
end
def save(ctx)
Id.new ctx.storage.save_query self, broken?(ctx.db), ctx.user_id, ctx.user_name, ctx.admin?
end
class Results
getter columns : Array(Column)
getter row : UInt32
record Column, name : String, oid : Int32, typname : String
# Cache format:
# i32 number of columns
# for each column:
# i32 type oid
# i32 name size
# bytes name
# i32 typname size
# bytes typname
# for each row:
# for each column:
# i32 value size (-1 for NULL)
# bytes value
ENDIAN = IO::ByteFormat::LittleEndian
def initialize(sql : String, @max_rows : UInt32, @min_query_time : Float32, @conn : PG::Connection, @cache : Storage::Cache, pgtypes : PGTypes)
@columns = cached? ? cache_query : db_query pgtypes, sql
@row = 0
@numcols = 0_i16
end
def cached?
!@cache.writer
end
# Rest of the code assumes that a PQError is a user error, i.e. bad query.
# These are caught and displayed to the user, whereas other error types
# result in a 500.
private def pqerr(msg)
PQ::PQError.new [
PQ::Frame::ErrorResponse::Field.new :message, msg, 77
]
end
# Based on PG::Statement.perform_query
private def db_query(pgtypes, sql)
@t1 = Time.instant
conn = @conn.conn
conn.send_parse_message sql
conn.send_bind_message [] of PQ::Param, 0 # 0 for text format
conn.send_describe_portal_message
conn.send_execute_message
conn.send_sync_message
conn.expect_frame PQ::Frame::ParseComplete
conn.expect_frame PQ::Frame::BindComplete
frame = conn.read
case frame
when PQ::Frame::RowDescription
fields = frame.fields
when PQ::Frame::NoData
cause = conn.read
case cause
when PQ::Frame::EmptyQueryResponse
conn.expect_frame PQ::Frame::ReadyForQuery
raise pqerr "Empty query"
when PQ::Frame::CommandComplete
@conn.close # We can recover from this, but it could've been a SET and we don't want users to fiddle with connection parameters.
raise pqerr "Not a SELECT, EXPLAIN or SHOW"
when PQ::Frame::Unknown
@conn.close # Can't recover
case cause.type
when 'G', 'H', 'F' # CopyInResponse, CopyOutResponse, CopyFail
raise pqerr "Can't use COPY queries here"
else
raise "unexpected response, got #{cause}"
end
else
raise "unexpected response, got #{cause}"
end
else
raise "expected RowDescription or NoData, got #{frame}"
end
@cache.write_bytes fields.size, ENDIAN
fields.map do |c|
@cache.write_bytes c.type_oid, ENDIAN
@cache.write_bytes c.name.size, ENDIAN
@cache.write c.name.to_slice
typname = pgtypes[c.type_oid]
@cache.write_bytes typname.size, ENDIAN
@cache.write typname.to_slice
Column.new c.name, c.type_oid, typname
end
rescue ex
@cache.cancel
@conn.close unless ex.class == PQ::PQError # Connection is now in an invalid state, don't keep around
raise ex
end
private def cache_query()
size = @cache.read_bytes Int32, ENDIAN
Array.new(size) do
oid = @cache.read_bytes Int32, ENDIAN
nsize = @cache.read_bytes Int32, ENDIAN
name = @cache.read_string nsize
typsize = @cache.read_bytes Int32, ENDIAN
typname = @cache.read_string typsize
Column.new name, oid, typname
end
end
private def db_next_row
t1 = @t1
if t1
@cache.cancel if (Time.instant-t1).total_seconds < @min_query_time
@t1 = nil
end
conn = @conn.conn
if conn.read_next_row_start
conn.read_i32 # frame size
@numcols = conn.read_i16
else
conn.expect_frame PQ::Frame::ReadyForQuery
@numcols = -1
end
rescue ex
@cache.cancel
raise ex
end
def next
return false if @numcols < 0
raise "Not all values have been read" if @numcols > 0
if cached?
@numcols = @cache.peek.size > 0 ? columns.size : -1
else
db_next_row
end
@row += 1 if @numcols >= 0
@numcols >= 0
end
def db_read
size = @conn.conn.read_i32
@cache.write_bytes size, ENDIAN unless @cache.closed?
if size == -1
nil
else
bytes = @conn.conn.read_bytes size
@cache.write bytes unless @cache.closed?
String.new bytes
end
rescue ex
@cache.cancel
raise ex
end
def cache_read
size = @cache.read_bytes Int32, ENDIAN
if size == -1
nil
else
@cache.read_string size
end
end
def read : String?
raise "Nothing to read" if @numcols < 1
@numcols -= 1
if cached?
cache_read
else
db_read
end
end
def close
# Fill the cache till we've reached max_rows
if !cached? && !@cache.closed?
while @numcols != -1 && @row <= @max_rows
while @numcols > 0
read
end
db_next_row
@row += 1
end
end
@cache.close unless @cache.closed?
# If we still haven't read all rows yet, there's a good chance someone
# forgot a LIMIT and we'll be receiving far too many rows. In that case
# it's likely faster to disconnect than to consume all rows.
@conn.close if !cached? && @numcols != -1
end
end
# Execute the query, transparently using a cache. The returned object is
# similar to a DB::ResultSet and must be .close'd after use.
#
# Why all this custom code? The cystal-pg ResultSet API uses the binary
# protocol to transfer query results, which is efficient, but means that we
# are responsible for decoding and formatting every type, which we can't
# really be expected to do. I've also experimented with using COPY, which
# additionally provides a convenient format for caching, but TSV is not as
# efficient or convenient to parse as a simple binary protocol.
def execute(ctx)
cache_rows = {
ctx.config.max_table_rows+1,
ctx.config.max_plot_rows,
ctx.config.max_export_rows
}.reduce {|acc, v| acc > v ? acc : v}
Results.new input, cache_rows, ctx.config.min_query_time, ctx.db, ctx.storage.cache("sql2:#{input}"), ctx.pgtypes
end
def internal_explain(db)
# ANALYZE can time-out, hence the fallback to plain EXPLAIN.
begin
db.query_all("EXPLAIN ANALYZE #{sql}", as: {String}).join("\n")
rescue ex
%{# EXPLAIN ANALYZE failed: #{ex.message}\n\
# Output below is from EXPLAIN without ANALYZE\n\n\
} + db.query_all("EXPLAIN #{sql}", as: {String}).join("\n")
end
end
def explain(ctx)
cache = ctx.storage.cache "explain:#{sql}"
begin
if cache.writer
res = internal_explain ctx.db
cache << res
cache.close
res
else
cache.gets_to_end
end
ensure
cache.cancel
end
end
def self.check_broken(db, sql)
begin
db.exec("EXPLAIN #{sql}")
rescue
return true
end
false
end
def broken?(db)
Query.check_broken db, sql
end
private def plot_val(val, io)
if val == nil
io << %{""}
elsif val && val.index /[\b\v\f\r\n\t "#]/
io << '"'
val.each_byte do |b|
case b
when 34; io << '\'' # ", unclear how to escape
when 8,9,10,11,12,13; io << ' ' # various forms of whitespace and newlines
else io.write_byte b
end
end
io << '"'
else
io << val
end
end
# Write gnuplot commands to io
def plot(ctx, results, io)
io << "set term svg size " << self.gw << "," << self.gh << "\n"
io << "set datafile columnheaders\n"
eod = Random::Secure.hex
io << "$data << EOD" << eod << "\n"
results.columns.each_with_index do |c, i|
io << ' ' if i > 0
plot_val c.name, io
end
io << '\n'
while results.row < ctx.config.max_plot_rows && results.next
results.columns.size.times do |i|
io << ' ' if i > 0
plot_val results.read, io
end
io << '\n'
end
io << "EOD" << eod << "\n"
io << self.plot
end
end
# Embedding HTML as strings is garbage, but at least we get to create useful abstractions this way.
# Might want to look into using a HTML builder shard to clean this up, but I'm never enthusiastic about adding dependencies.
module HTML
# More convenient and efficient alternative to HTML.escape()
struct Escape
def initialize(@s : String, @br : Bool); end
def to_s(io)
@s.each_byte do |b|
case b
when 10; io << (@br ? "<br>" : '\n')
when 34; io << """
when 38; io << "&"
when 60; io << "<"
when 62; io << ">"
else io.write_byte b
end
end
end
end
def self.esc(s, br : Bool = false); Escape.new(s, br); end
# Icons from lucide.dev
enum Icon
ArrowRightCircle
CircleEqual
CircleOff
KeyRound
LineChart
Search
SearchSlash
def to_s(io)
io << %{<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">}
io << case self
in ArrowRightCircle then %{<circle cx="12" cy="12" r="10"/><path d="M8 12h8"/><path d="m12 16 4-4-4-4"/>}
in CircleOff then %{<path d="m2 2 20 20"/><path d="M8.35 2.69A10 10 0 0 1 21.3 15.65"/><path d="M19.08 19.08A10 10 0 1 1 4.92 4.92"/>}
in CircleEqual then %{<path d="M7 10h10"/><path d="M7 14h10"/><circle cx="12" cy="12" r="10"/>}
in KeyRound then %{<path d="M2 18v3c0 .6.4 1 1 1h4v-3h3v-3h2l1.4-1.4a6.5 6.5 0 1 0-4-4Z"/><circle cx="16.5" cy="7.5" r=".5"/>}
in LineChart then %{<path d="M3 3v18h18"/><path d="m19 9-5 5-4-4-3 3"/>}
in Search then %{<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>}
in SearchSlash then %{<path d="m13.5 8.5-5 5"/><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>}
end
io << "</svg>"
end
end
def self.sql_error(io, ex)
io << "<h2>SQL error</h2>"
io << "<p>" << esc(ex.message.as(String)) << "</p>"
end
def self.gnuplot(path, io, embed = true)
proc = Process.new command: path, args: {"-d"},
input: Process::Redirect::Pipe,
output: Process::Redirect::Pipe,
error: Process::Redirect::Pipe
errch = Channel(String).new
spawn do
begin
errch.send proc.error.gets_to_end
rescue ex
errch.send ex.message.as(String)
end
end
outch = Channel(Exception?).new
spawn do
begin
IO.copy proc.output, io
outch.send nil
rescue ex
proc.output.skip_to_end
outch.send ex
end
end
yield proc.input
proc.input.close
err = outch.receive
raise err if err
err = errch.receive
raise err if err != ""
status = proc.wait
raise "gnuplot exited with error: #{status}" if (!err || err == "") && !status.success?
rescue ex
io << "<pre>" << HTML.esc(ex.message.as(String)) << "</pre>" if embed
ensure
if proc && !status
proc.terminate graceful: false
proc.wait
end
end
struct QueryInfo
def initialize(@ctx : Context, @query : Query); end
def self.id; 'q'; end
def self.label; "Info"; end
def to_s(io)
io << %{<h3>SQL</h3><pre><code class="language-sql">} << HTML.esc(@query.input) << %{</code></pre>}
unless @query.plot.empty?
io << %{<h3>Gnuplot commands</h3><pre><code class="language-gnuplot">} << HTML.esc(@query.plot) << %{</code></pre>}
end
end
end
struct QueryTable
def initialize(@ctx : Context, @query : Query); end
def self.id; 't'; end
def self.label; "Table"; end
def column_attr(c, io)
case c.typname
when "int2", "int4", "int8", "oid", "numeric"
# Excluding floats, as their unpredictable precision often renders right-alignment useless.
io << %{ class="int"}
end
end
def write_val(c, v, io)
io << "<td"
column_attr c, io
io << '>'
if !v
io << "<em>null</em>"
elsif c.typname == "vndbid"
io << %{<a href="https://vndb.org/} << HTML.esc(v) << %{">} << HTML.esc(v) << %{</a></td>}
elsif v =~ /^https?:\/\/[^\s]+$/
io << %{<a href="} << HTML.esc(v) << %{">} << HTML.esc(v) << %{</a>}
else
io << HTML.esc v, true
end
io << %{</td>}
end
def to_s(io)
return if @query.sql == ""
t1 = Time.instant
results = @query.execute @ctx
io << %{<table class="stripe results"><thead><tr>}
results.columns.each do |c|
io << "<th"
column_attr c, io
io << '>' << HTML.esc(c.name) << "</th>"
end
io << "</tr></thead><tbody>"
while results.row < @ctx.config.max_table_rows && results.next
io << "\n<tr>"
col = 0
esc = false
results.columns.each {|c| write_val c, results.read, io }
io << "</tr>"
end
num = results.row
io << "\n</tbody></table><p>"
io << "Limited to " if results.next
io << num << " result" << (num == 1 ? "" : 's')
if results.cached?
io << " (cached)"
else
io << " in " << (Time.instant - t1).total_seconds << " seconds."
end
io << "</p>"
rescue ex : PQ::PQError
return HTML.sql_error io, ex
ensure
results.close if results
end
end
struct QueryExplain
def initialize(@ctx : Context, @query : Query); end
def self.id; 'e'; end
def self.label; "Explain"; end
def to_s(io)
return if @query.sql == ""
begin
res = @query.explain @ctx
rescue ex
HTML.sql_error io, ex
end
io << "<pre>" << res << "</pre>"