-
Notifications
You must be signed in to change notification settings - Fork 5
/
gll_routines.r
5016 lines (4668 loc) · 181 KB
/
gll_routines.r
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
rebol [
Title: "Rebol routines called by geolllibre gll_* programs"
IDEA: "TODO make an automatic system of imports, where a program named abc_ghea_jh_lkk.r would automatically include any file named abc_ghea_jh_*.r and any file named abc_ghea_jh_routines.r. Doing this recursively would make an easy to maintain tree of dependencies"
Name: gll_routines.r
Version: 2.0.0
Date: 7-Oct-2019/21:40:34+2:00
Author: "Pierre Chevalier"
License: {
This file is part of GeolLLibre software suite: FLOSS dedicated to Earth Sciences.
###########################################################################
## ____ ___/_ ____ __ __ __ _()____ ____ _____ ##
## / ___\/ ___// _ |/ / / / / / / _/ _ \ / __ \/ ___/ ##
## / /___/ /_ / / | / / / / / / / // /_/_/ /_/ / /_ ##
## / /_/ / /___| \/ / /__/ /__/ /___/ // /_/ / _, _/ /___ ##
## \____/_____/ \___/_____/___/_____/__/_____/_/ |_/_____/ ##
## ##
###########################################################################
Copyright (C) 2019 Pierre Chevalier <pierrechevaliergeol@free.fr>
GeolLLibre is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
or write to the Free Software Foundation, Inc., 51 Franklin Street,
Fifth Floor, Boston, MA 02110-1301, USA.
See LICENSE file.
}
History: [
1.0.2 [27-Apr-2019/18:29:32+2:00 {Marre de faire des numéros de versions. Git s'occupe de tout ça à merveille, ce header foutra vite le camp.}]
1.0.1 [21-Aug-2013/16:25:11+2:00 {Ajout d'utilitaires, de fonctions communes, etc.}]
1.0.2 [22-Sep-2013/10:31:32+2:00 {Mise au point de la comparaison de structures de bases}]
1.0.3 [26-Jan-2014/18:27:07+1:00 {Inclusion d'objets et fonction en liaison avec des structures}]
1.0.4 [8-Mar-2014/0:08:07+1:00 {Calculs de structures à partir des mesures d'orientations du GeolPDA semblent corrects}]
1.0.5 [23-Apr-2014/14:44:58+1:00 {Functions concerning GeolPDA moved here, from gll_geolpda_fetch_data.r and gll_geolpda_report_generator.r}]
2.0 [21-Sep-2018/19:39:10+2:00 {Bof, no more history here: see git log, rather}]
] ]
;;;TODO FONCTION POUR RÉCUPÉRER UNE VARIABLE D'ENVIRONNEMENT, OU UN PARAMÈTRE DE .GLL_PREFERENCES => postponed; strange beheviour from scripts, sometimes not reading environment variables, for unknown reason.
;get_env_or_gll_preferences: func ["Function to retreive environment variables or a value from .gll_preferences var] [ ; {{{ } } }
;
;gll_varenv: [ GLL_BD_HOST POSTGEOL GLL_BD_NAME GLL_BD_PORT GLL_BD_USER ]
;foreach v gll_varenv [
; v: to-string v
;; v: to-string gll_varenv/1
;; v: to-string gll_varenv/2
;; v: to-string gll_varenv/3
;; v: to-string gll_varenv/4
;; v: to-string gll_varenv/4
;; v: to-string gll_varenv/5
;??? v
;; code: [
; a: rejoin [ "if (not error? try [varenv_" lowercase v {: get-env "} v {"]) [ } lowercase v ": " (v) ": varenv_" (v) "]"]
;print to-string a
;do a
;]
;
;?? varenv_gll_bd_host
;?? varenv_postgeol
;?? varenv_gll_bd_name
;?? varenv_gll_bd_port
;?? varenv_gll_bd_user
;
;; return sql_result
;;] ; }}}
; Get preferences (dbname dbhost dbuser passw opid tmp_schema) from .gll_preferences file. Récupération des préférences (dbname dbhost dbuser passw opid tmp_schema) à partir du fichier .gll_preferences: {{{ } } }
; .gll_preferences is a plain text file, simply containing variables definition, it is a plain rebol script, intended to be LOADed.
print catch [
; TODO very inelegant code style. Replace with a loop, a bit like (but better than) in log_send function.
; TODO even better: with a ANY block, simply.
if error? try [ do load to-file system/options/home/.gll_preferences
throw ".gll_preferences loaded from ~"]
[print "-"]
if error? try [ do load to-file %/etc/gll_preferences
throw "gll_preferences loaded from /etc/gll_preferences"]
[print "-"]
if error? try [ do load to-file %/usr/bin/.gll_preferences
throw ".gll_preferences loaded from /usr/bin/" ]
[print "-"]
if error? try [ do load to-file rejoin [ system/options/path ".gll_preferences"]
throw ".gll_preferences loaded from current directory" ]
[print "-"]
if error? try [ do load to-file system/options/home/.gll_preferences] [
do load to-file %.gll_preferences ; modif chez Corentin sur windows 7
throw {.gll_preferences loaded from "system/options/home/"} ]
[print "- No .gll_preferences file found."
;TODO set some default values
dbname: postgeol: "postgeol"
dbhost: "localhost"
dbport: 5432
dbuser: "geononymous"
passw: "chut"
geologist: "Anonymous Geologo"
opid: 0
tmp_schema: "tmp_imports"
working_directory: %~/geolllibre/
dir_geolpda_local: %~/geolpda/android_cp/geolpda/
dir_dcim_local: %~/photos/
dir_oruxmaps_local: %~/gps/oruxmaps/
]
]
;}}}
; Get more preferences from environment variables. Récupération d'autres préférences à partir de variables d'environnement:{{{ } } }
; List "interesting" environment variables:
vars: [
BROWSER
DISPLAY
CONNINFO
EDITOR
HOSTNAME
LANG
HOSTTYPE
LC_NUMERIC
LOGNAME
OSTYPE
GDM_LANG
GROUPS
SHELL
GTK_MODULES
HOME
SHELLOPTS
SHLVL
SSH_AGENT_PID
SSH_AUTH_SOCK
TERM
UID
USER
WINDOWID
XAUTHORITY
XDG_CURRENT_DESKTOP
XDG_GREETER_DATA_DIR
XDG_RUNTIME_DIR
XDG_SEAT
XDG_SEAT_PATH
XDG_SESSION_CLASS
XDG_SESSION_DESKTOP
XDG_SESSION_ID
XDG_SESSION_PATH
XDG_SESSION_TYPE
XDG_VTNR
XTERM_LOCALE
XTERM_SHELL
]
; For each of these variables, get its value:
foreach v vars [
v: to-string v
do rejoin [v {: get-env "} uppercase v {"}]
]
; Just to check:
;foreach v vars [ print get v ]
;}}}
; Include Nenad's postgeol driver. Inclusion du pilote postgresql de Nenad: {{{ } } }
do [
REBOL [
Title: "PostgresQL Protocol"
Author: "SOFTINNOV"
Email: pgsql@softinnov.com
Web: http://rebol.softinnov.org/pgsql/
Date: 09/02/2003
File: %pgsql-protocol.r
Version: 0.9.0
Purpose: "PostgresQL client protocol implementation for /Core"
]
make root-protocol [
scheme: 'pgSQL
port-id: 5432
port-flags: system/standard/port-flags/pass-thru or 32 ; /binary
fast-query: none
sys-copy: get in system/words 'copy
sys-insert: get in system/words 'insert
sys-pick: get in system/words 'pick
sys-close: get in system/words 'close
net-log: get in net-utils 'net-log
throws: [closed "closed"]
;------ Internals --------
defs: [
types [
16 bool [to logic! find ["t" "true" "y" "yes" "1"]]
17 bytea [to-rebol-binary]
18 char [to char!]
19 name none
20 int8 [to decimal!]
21 int2 [to integer!]
23 int4 [to integer!]
24 regproc none
25 text none
26 oid [to integer!]
27 tid none
28 xid none
29 cid none
32 SET none
210 smgr none
600 point none
601 lseg none
602 path none
603 box none
604 polygon none
628 line none
650 cidr none
700 float4 [to decimal!]
701 float8 [to decimal!]
702 abstime none
703 reltime none
704 tinterval none
705 unknown none
718 circle none
790 money [to money!]
829 macaddr none
869 inet [to-rebol-inet]
1033 aclitem none
1042 bpchar none
1043 varchar none
1082 date [try-to-date]
1083 time none
1114 timestamp none
1184 timestamptz none
1186 interval none
1266 timetz none
1560 bit none
1562 varbit none
1700 numeric none
1790 refcursor none
]
]
locals-class: context [
;--- Internals (do not touch!)---
buf-size: 64 * 1024
state:
last-status:
stream-end?:
buffer:
cancel-key: none
;-------
auto-commit: on ; not used, just reserved for /Command compatibility.
rows: 10 ; not used, just reserved for /Command compatibility.
auto-conv?: on
auto-ping?: off ; not yet supported
matched-rows:
cursor:
columns:
;protocol:
;version:
process-id:
last-notice:
error-code:
error-msg:
conv-list: none
]
column-class: context [name: length: type: flags: none]
conv-model: make block! length? defs/types
;------ Type Conversion ------
extract-conv-list: does [
blk: defs/types
forskip blk 3 [append conv-model sys-copy/deep reduce [blk/2 blk/3]]
]
set 'change-type-handler func [p [port!] type [word!] blk [block!]][
head change/only next find p/locals/conv-list type blk
]
try-to-date: func [val][error? try [val: to-date val] val]
to-rebol-inet: func [val][
set [a b] parse val "/"
either b [reduce [to tuple! a to integer! b]][to tuple! a]
]
special: charset [#"'" #"\"]
digit: charset [#"0" - #"9"]
to-rebol-binary: func [val /local out a b c][
out: make binary! length? val
parse/all val [
some [
#"\" [
a: special (sys-insert tail out first a)
| a: digit b: digit c: digit (
sys-insert tail out to char! (a/1 - 48 * 8 + b/1 - 48 * 8 + c/1 - 48)
)
] | a: skip (sys-insert tail out first a)
] | end
]
out
]
convert-types: func [p [port!] rows [block!] /local row i
convert-body action cols col conv-func tmp
][
cols: p/locals/columns
convert-body: make block! 1
action: [if tmp: sys-pick row (i)]
foreach col cols [
i: index? find cols col
if 'none <> conv-func: select p/locals/conv-list col/type [
append convert-body append/only compose action head
sys-insert at compose [change/only at row (i) :tmp] 5 conv-func
]
]
if not empty? convert-body [foreach row rows :convert-body]
]
decode: func [int [integer!]][any [select defs/types int 'unknown]]
printable: exclude charset [#" " - #"~"] charset [#"\" #"'"]
to-octal: func [val][
head sys-insert tail sys-copy "\\" reduce [
first to string! to integer! val / 64
first to string! to integer! (remainder val 64) / 8
to string! remainder val 8
]
]
sql-escape: func [value [string!] /local out mark][
out: make string! 3 * length? value
parse/all value [
some [
mark: [
printable (sys-insert tail out first mark)
| skip (sys-insert tail out to-octal to integer! first mark)
]
] | end
]
out
]
to-sql: func [value /local res][
switch/default type?/word value [
none! ["NULL"]
date! [
rejoin ["'" value/year "-" value/month "-" value/day
either value: value/time [
rejoin [" " value/hour ":" value/minute ":" value/second]
][""] "'"
]
]
time! [join "'" [value/hour ":" value/minute ":" value/second "'"]]
money! [to-sql form value]
string! [join "'" [sql-escape value "'"]]
binary! [to-sql to string! value]
tuple! [to-sql to string! value]
pair! [rejoin ["(" value/x "," value/y ")"]]
][form value]
]
map-rebol-values: func [data [block!] /local args sql mark][
args: reduce next data
sql: sys-copy sys-pick data 1
mark: sql
while [found? mark: find mark #"?"][
mark: sys-insert remove mark either tail? args ["NULL"][to-sql args/1]
if not tail? args [args: next args]
]
net-log sql
sql
]
;------ Data reading ------
int: int32: string: field: fields: len: col: msg: byte: bitmap: bytes: pos: sz: none
read-byte: [copy byte skip (byte: to integer! to char! :byte)]
read-int: [copy bytes 2 skip (int: to integer! to binary! bytes)]
read-int32: [copy bytes 4 skip (int32: to integer! to binary! bytes)]
read-bytes: [read-int32 (int32: int32 - sz) copy bytes [int32 skip]]
read: func [[throw] port [port!] /local len][
pl: port/locals
if -1 = len: read-io port/sub-port pl/buffer pl/buf-size - length? pl/buffer [
sys-close port/sub-port
throw throws/closed
]
if positive? len [net-log ["low level read of " len "bytes"]]
if negative? len [throw "IO error"]
len
]
read-stream: func [port [port!] /wait f-state [word!] /records rows /part count
/local final complete msg pl pos utopped row stop error test-error test-exit a-data
][
pl: port/locals
bind protocol-rules 'final
final: f-state
error: none
test-error: [if error [pl/stream-end?: true make error! error]]
test-exit: [
all [wait pl/state = final]
all [records part count = length? rows]
]
if empty? pl/buffer [read port]
forever [
complete: parse/all/case pl/buffer protocol-rules
either all [complete not wait all [not error tail? pos]][
clear pl/buffer
do test-error
break
][
remove/part pl/buffer (index? pos) - 1
if any test-exit [do test-error break]
]
read port
]
if pl/state = 'ready [pl/stream-end?: true]
]
protocol-rules: [
some [
pos: (stop: either any test-exit [length? pos tail pos][pos]) :stop ; exit from parser when needed
[ ; in a Core2.5 compatible way.
#"A" [
read-int32 (net-log join "from " int32)
copy msg to #"^@" (net-log pl/last-notice: msg) skip
]
| #"C" [
copy msg to #"^@" skip (
pos: find/reverse tail pl/last-status: msg #" "
pl/matched-rows: either pos [to integer! trim pos][0]
pl/state: 'completed
final: 'ready
)
]
| [#"D" (sz: 4) | #"B" (sz: 0)] [
(if decimal? fields: divide length? pl/columns 8 [fields: 1 + to integer! fields])
copy bitmap [fields skip]
(
row: make block! length? pl/columns
fields: length? trim/with sys-copy bitmap: enbase/base bitmap 2 "0"
)
fields [read-bytes (append row any [bytes ""])]
(
fields: length? pl/columns
foreach field bitmap [
row: either field = #"0" [sys-insert row none][next row]
if zero? fields: fields - 1 [break]
]
sys-insert/only tail rows head row
pl/state: 'fetching-rows
)
]
| #"E" [
copy error to #"^@" skip (
if newline = last error [remove back tail error]
if find [auth pass-required auth-ok] pl/state [
sys-close port/sub-port
make error! error
]
final: 'ready
)
]
| #"G" [
]
| #"H" [
]
| #"I" [
skip (pl/state: 'empty final: 'ready)
]
| #"K" [
read-int32 (pl/process-id: int32)
read-int32 (pl/cancel-key: int32)
]
| #"N" [
copy msg to #"^@" (net-log pl/last-notice: msg) skip
]
| #"P" [
copy msg to #"^@" (pl/cursor: msg) skip
]
| #"R" [
read-int32 a-data: (
unsupported: func [msg][
sys-close port/sub-port
make error! join msg ": unsupported auth method"
]
switch int32 [
0 [pl/state: 'auth-ok]
1 [unsupported "Kerberos V4"]
2 [unsupported "Kerberos V5"]
3 [
reply-password port none
pl/state: 'pass-required
]
4 [unsupported "Crypt"]
5 [
reply-password port sys-copy/part a-data 4
a-data: skip a-data 4
pl/state: 'pass-required
]
6 [unsupported "SCM Credential"]
]
) :a-data
]
| #"T" [
read-int (pl/columns: make block! max int 1)
int [
(col: make column-class [])
copy string to #"^@" (col/name: string) skip
read-int32 (col/type: decode int32)
read-int (col/length: int)
read-int32 (col/flags: int32)
(append pl/columns :col)
] (pl/state: 'fields-fetched)
]
| #"V" [
]
| #"Z" (pl/state: 'ready)
]
] | end
]
flush-pending-data: func [port [port!] /local pl len][
pl: port/locals
if not pl/stream-end? [
net-log "flushing unread data..."
read-stream/records/wait port [] 'ready
net-log "flush end."
pl/stream-end?: true
pl/state: 'ready
]
]
;------ Data sending ------
write-int32: func [value [integer!]][to string! debase/base to-hex value 16]
write-string: func [value [string!]][head sys-insert tail sys-copy value #"^@"]
write-lim-string: func [len [integer!] value [string!]][
head sys-insert/dup tail sys-copy value #"^@" (len - length? value)
]
send-packet: func [port [port!] data [string!]][
write-io port/sub-port to binary! data length? data
port/locals/stream-end?: false
]
insert-query: func [port [port!] data [string! block!]][
send-packet port rejoin ["Q" data #"^@"]
port/locals/state: 'query-sent
read-stream/wait port 'fields-fetched
none
]
try-reconnect: func [port [port!]][
net-log "Connection closed by server! Reconnecting..."
if throws/closed = catch [open port][net-error "Server down!"]
]
reply-password: func [port data /local tmp][
data: either data [
tmp: lowercase enbase/base checksum/method join port/pass port/user 'md5 16
join "md5" lowercase enbase/base checksum/method join tmp data 'md5 16
][port/pass]
send-packet port rejoin [
write-int32 5 + length? data ; 4 + 1 for '\0'
write-string data
]
]
do-handshake: func [port [port!] /local pl client-param][
pl: port/locals: make locals-class []
pl/state: 'auth
pl/buffer: make binary! pl/buf-size
pl/conv-list: sys-copy/deep conv-model
send-packet port rejoin [
write-int32 296
write-int32 131072 ; v2.0
write-lim-string 64 port/target
write-lim-string 32 port/user
write-lim-string 64 ""
write-lim-string 64 ""
write-lim-string 64 ""
]
read-stream/wait port 'ready
net-log "Connected to server. Handshake OK"
]
;------ Public interface ------
init: func [port [port!] spec /local scheme args][
if url? spec [net-utils/url-parser/parse-url port spec]
fast-query: either args: find port/target #"?" [
port/target: sys-copy/part port/target args
dehex sys-copy next args
][none]
scheme: port/scheme
port/url: spec
if none? port/host [
net-error reform ["No network server for" scheme "is specified"]
]
if none? port/port-id [
net-error reform ["No port address for" scheme "is specified"]
]
if none? port/target [
net-error reform ["No database name for" scheme "is specified"]
]
if none? port/user [port/user: make string! 0]
if none? port/pass [port/pass: make string! 0]
if port/pass = "?" [port/pass: ask/hide "Password: "]
]
open: func [port [port!]][
open-proto port
port/sub-port/state/flags: 524835 ; force /direct/binary mode
do-handshake port
port/locals/stream-end?: true ; force stream-end, so 'copy won't timeout !
if fast-query [
insert port fast-query
fast-query: none
]
port/state/tail: 10 ; for 'pick to work properly
]
close: func [port [port!]][
port/sub-port/timeout: 4
either error? try [
send-packet port "X"
][net-log "Error on closing port!"][net-log "Close ok."]
sys-close port/sub-port
]
insert: func [[throw] port [port!] data [string! block!] /local res][
flush-pending-data port
port/locals/columns: none
if all [port/locals/auto-ping? data <> [ping]][
net-log "sending ping..."
res: catch [insert-cmd port [ping]]
if any [res = throws/closed not res][try-reconnect port]
]
if throws/closed = catch [
if all [string? data data/1 = #"["][data: load data]
res: either block? data [
if empty? data [net-error "No data!"]
either string? data/1 [
insert-query port map-rebol-values data
][
net-error "command dialect not yet supported"
;insert-cmd port data
]
][
insert-query port data
]
][net-error "Connection lost - Port closed!"]
res
]
pick: func [port [port!] data][
either any [none? data data = 1][
either port/locals/stream-end? [sys-copy []][copy/part port 1]
][none]
]
copy: func [port /part n [integer!] /local rows][
either not port/locals/stream-end? [
either all [value? 'part part][
rows: make block! n
read-stream/records/part port rows n
][
rows: make block! port/locals/rows
read-stream/records/wait port rows 'ready
port/locals/stream-end?: true
]
if port/locals/auto-conv? [convert-types port rows]
recycle
rows
][none]
]
; init 'conv-model
extract-conv-list
;--- Register ourselves.
net-utils/net-install pgSQL self 5432
]
] ;}}}
; Include Nenad's mysql driver. Inclusion du pilote mysql de Nenad: {{{ } } }
do [
; :r /home/pierre/.rebol/view/public/rebol.softinnov.org/old/mysql/mysql-r099/mysql-protocol.r
REBOL [
Title: "mySQL Protocol"
Author: "Nenad Rakocevic"
Email: dockimbel@free.fr
Web: http://rebol.dhs.org/mysql/
Date: 25/07/2001
File: %mysql-protocol.r
Version: 0.9.9
Purpose: "mySQL client protocol support"
Comment: "v1.0 Candidate 1"
]
make root-protocol [
scheme: 'mySQL
port-id: 3306
port-flags: system/standard/port-flags/pass-thru or 32 ; /binary
fast-query: none
sys-copy: get in system/words 'copy
sys-insert: get in system/words 'insert
sys-pick: get in system/words 'pick
sys-close: get in system/words 'close
net-log: get in net-utils 'net-log
std-header-length: 4
std-comp-header-length: 3
throws: [closed "closed"]
;------ Internals --------
defs: [
cmd [
;sleep 0
quit 1
init-db 2
query 3
;field-list 4
create-db 5
drop-db 6
reload 7
shutdown 8
statistics 9
;process-info 10
;connect 11
process-kill 12
debug 13
ping 14
;time 15
;delayed-insert 16
change-user 17
]
refresh [
grant 1 ; Refresh grant tables
log 2 ; Start on new log file
tables 4 ; Close all tables
hosts 8 ; Flush host cache
status 16 ; Flush status variables
threads 32 ; Flush status variables
slave 64 ; Reset master info and restart slave thread
master 128 ; Remove all bin logs in the index
] ; and truncate the index
types [
0 decimal
1 tiny
2 short
3 long
4 float
5 double
6 null
7 timestamp
8 longlong
9 int24
10 date
11 time
12 datetime
13 year
14 newdate
247 enum
248 set
249 tiny-blob
250 medium-blob
251 long-blob
252 blob
253 var-string
254 string
]
flag [
not-null 1 ; field can't be NULL
primary-key 2 ; field is part of a primary key
unique-key 4 ; field is part of a unique key
multiple-key 8 ; field is part of a key
blob 16
unsigned 32
zero-fill 64
binary 128
enum 256 ; field is an enum
auto-increment 512 ; field is a autoincrement field
timestamp 1024 ; field is a timestamp
set 2048 ; field is a set
num 32768 ; field is num (for clients)
]
client [
long-password 1 ; new more secure passwords
found-rows 2 ; Found instead of affected rows
long-flag 4 ; Get all column flags
connect-with-db 8 ; One can specify db on connect
no-schema 16 ; Don't allow db.table.column
compress 32 ; Can use compression protcol
odbc 64 ; Odbc client
local-files 128 ; Can use LOAD DATA LOCAL
ignore-space 256 ; Ignore spaces before '('
change-user 512 ; Support the mysql_change_user()
interactive 1024 ; This is an interactive client
ssl 2048 ; Switch to SSL after handshake
ignore-sigpipe 4096 ; IGNORE sigpipes
transactions 8196 ; Client knows about transactions
]
]
locals-class: make object! [
;--- Internals (do not touch!)---
seq-num: 0
buf-size: 10000
last-status:
stream-end?:
buffer: none
;-------
cache: none
auto-commit: on ; not used, just reserved for /Command compatibility.
rows: 10 ; not used, just reserved for /Command compatibility.
auto-conv?: on
auto-ping?: on
matched-rows:
columns:
protocol:
version:
thread-id:
crypt-seed:
capabilities:
error-code:
error-msg:
conv-list: none
]
column-class: make object! [
table: name: length: type: flags: decimals: none
]
conv-model: [
decimal [to decimal!]
tiny [to integer!]
short [to integer!]
long [to integer!]
float [to decimal!]
double none
null none
timestamp none
longlong none
int24 [to integer!]
date [to date!]
time [to time!]
datetime [to date!]
year [to integer!]
newdate none
enum none
set none
tiny-blob none
medium-blob none
long-blob none
blob none
var-string none
string none
]
set 'change-type-handler func [p [port!] type [word!] blk [block!]][
head change/only next find p/locals/conv-list type blk
]
convert-types: func [p [port!] rows [block!] /local row i
convert-body action cols col conv-func tmp
][
cols: p/locals/columns
convert-body: make block! 1
action: [if tmp: sys-pick row (i)]
foreach col cols [
i: index? find cols col
if 'none <> conv-func: select p/locals/conv-list col/type [
append convert-body append/only compose action head
sys-insert at compose [change at row (i) :tmp] 5 conv-func
]
]
if not empty? convert-body [foreach row rows :convert-body]
]
decode: func [int [integer!] /features /flags /type /local list name value][
either type [
any [select defs/types int 'unknown]
][
list: make block! 10
foreach [name value] either flags [defs/flag][defs/client][
if value = (int and value) [append list :name]
]
list
]
]
encode-refresh: func [blk [block!] /local total name value][
total: 0
foreach name blk [
either value: select defs/refresh :name [
total: total + value
][
net-error reform ["Unknown argument:" :name]
]
]
total
]
sql-escape: func [value [string!] /local chars no-chars want escaped
escape mark
][
chars: charset want: {^(00)^/^-^M^(08)'"\}
no-chars: complement chars
escaped: ["\0" "\n" "\t" "\r" "\b" "\'" {\"} "\\"]
escape: func [value][
mark: sys-insert remove mark sys-pick escaped index? find want value
]
parse/all value [any [mark: chars (escape mark/1) :mark | no-chars]]
value
]
to-sql: func [value /local res][
switch/default mold type? value [
"none!" ["NULL"]
"date!" [
rejoin ["'" value/year "-" value/month "-" value/day
either value: value/time [
rejoin [" " value/hour ":" value/minute ":" value/second]
][""] "'"
]
]
"time!" [join "'" [value/hour ":" value/minute ":" value/second "'"]]
"money!" [head remove find mold value "$"]
"string!" [join "'" [sql-escape sys-copy value "'"]]
"binary!" [to-sql to string! value]
"block!" [
if empty? value: reduce value [return "(NULL)"]
res: append make string! 100 #"("
forall value [repend res [to-sql value/1 #","]]
head change back tail res #")"
]
][form value]
]
map-rebol-values: func [data [block!] /local args sql mark][
args: reduce next data
sql: sys-copy sys-pick data 1
mark: sql
while [found? mark: find mark #"?"][
mark: sys-insert remove mark either tail? args ["NULL"][to-sql args/1]
if not tail? args [args: next args]
]
sql
]
show-server: func [obj [object!]][
net-log reform [ newline
"----- Server ------" newline
"Version:" obj/version newline
"Protocol version:" obj/protocol newline
"Thread ID:" obj/thread-id newline
"Crypt Seed:" obj/crypt-seed newline
"Capabilities:" mold obj/capabilities newline
"-------------------"
]
]
;------ Encryption functions ------
scrambler: make object! [
to-pair: func [value [integer!]][system/words/to-pair reduce [value 1]]
xor-pair: func [p1 p2][to-pair p1/x xor p2/x]
or-pair: func [p1 p2][to-pair p1/x or p2/x]
and-pair: func [p1 p2][to-pair p1/x and p2/x]
remainder-pair: func [val1 val2 /local new][
val1: either negative? val1/x [abs val1/x + 2147483647.0][val1/x]
val2: either negative? val2/x [abs val2/x + 2147483647.0][val2/x]
to-pair to-integer val1 // val2