-
Notifications
You must be signed in to change notification settings - Fork 11
/
mod.rs
2684 lines (2461 loc) · 91 KB
/
mod.rs
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
/*******************************************************************************
* ___ _ ____ ____
* / _ \ _ _ ___ ___| |_| _ \| __ )
* | | | | | | |/ _ \/ __| __| | | | _ \
* | |_| | |_| | __/\__ \ |_| |_| | |_) |
* \__\_\\__,_|\___||___/\__|____/|____/
*
* Copyright (c) 2014-2019 Appsicle
* Copyright (c) 2019-2024 QuestDB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#![doc = include_str!("mod.md")]
pub use self::timestamp::*;
use crate::error::{self, Error, Result};
use crate::gai;
use crate::ingress::conf::ConfigSetting;
use core::time::Duration;
use std::collections::HashMap;
use std::convert::Infallible;
use std::fmt::{Debug, Display, Formatter, Write};
use std::io::{self, BufRead, BufReader, ErrorKind, Write as IoWrite};
use std::ops::Deref;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use base64ct::{Base64, Base64UrlUnpadded, Encoding};
use ring::rand::SystemRandom;
use ring::signature::{EcdsaKeyPair, ECDSA_P256_SHA256_FIXED_SIGNING};
use rustls::{ClientConnection, RootCertStore, StreamOwned};
use rustls_pki_types::ServerName;
use socket2::{Domain, Protocol as SockProtocol, SockAddr, Socket, Type};
#[derive(Debug, Copy, Clone)]
enum Op {
Table = 1,
Symbol = 1 << 1,
Column = 1 << 2,
At = 1 << 3,
Flush = 1 << 4,
}
impl Op {
fn descr(self) -> &'static str {
match self {
Op::Table => "table",
Op::Symbol => "symbol",
Op::Column => "column",
Op::At => "at",
Op::Flush => "flush",
}
}
}
fn map_io_to_socket_err(prefix: &str, io_err: io::Error) -> Error {
error::fmt!(SocketError, "{}{}", prefix, io_err)
}
/// A validated table name.
///
/// This type simply wraps a `&str`.
///
/// When you pass a `TableName` instead of a plain string to a [`Buffer`] method,
/// it doesn't have to validate it again. This saves CPU cycles.
#[derive(Clone, Copy)]
pub struct TableName<'a> {
name: &'a str,
}
impl<'a> TableName<'a> {
/// Construct a validated table name.
pub fn new(name: &'a str) -> Result<Self> {
if name.is_empty() {
return Err(error::fmt!(
InvalidName,
"Table names must have a non-zero length."
));
}
let mut prev = '\0';
for (index, c) in name.chars().enumerate() {
match c {
'.' => {
if index == 0 || index == name.len() - 1 || prev == '.' {
return Err(error::fmt!(
InvalidName,
concat!("Bad string {:?}: ", "Found invalid dot `.` at position {}."),
name,
index
));
}
}
'?' | ',' | '\'' | '\"' | '\\' | '/' | ':' | ')' | '(' | '+' | '*' | '%' | '~'
| '\r' | '\n' | '\0' | '\u{0001}' | '\u{0002}' | '\u{0003}' | '\u{0004}'
| '\u{0005}' | '\u{0006}' | '\u{0007}' | '\u{0008}' | '\u{0009}' | '\u{000b}'
| '\u{000c}' | '\u{000e}' | '\u{000f}' | '\u{007f}' => {
return Err(error::fmt!(
InvalidName,
concat!(
"Bad string {:?}: ",
"Table names can't contain ",
"a {:?} character, which was found at ",
"byte position {}."
),
name,
c,
index
));
}
'\u{feff}' => {
// Reject unicode char 'ZERO WIDTH NO-BREAK SPACE',
// aka UTF-8 BOM if it appears anywhere in the string.
return Err(error::fmt!(
InvalidName,
concat!(
"Bad string {:?}: ",
"Table names can't contain ",
"a UTF-8 BOM character, which was found at ",
"byte position {}."
),
name,
index
));
}
_ => (),
}
prev = c;
}
Ok(Self { name })
}
/// Construct a table name without validating it.
///
/// This breaks API encapsulation and is only intended for use
/// when the the string was already previously validated.
///
/// The QuestDB server will reject an invalid table name.
pub fn new_unchecked(name: &'a str) -> Self {
Self { name }
}
}
/// A validated column name.
///
/// This type simply wraps a `&str`.
///
/// When you pass a `ColumnName` instead of a plain string to a [`Buffer`] method,
/// it doesn't have to validate it again. This saves CPU cycles.
#[derive(Clone, Copy)]
pub struct ColumnName<'a> {
name: &'a str,
}
impl<'a> ColumnName<'a> {
/// Construct a validated table name.
pub fn new(name: &'a str) -> Result<Self> {
if name.is_empty() {
return Err(error::fmt!(
InvalidName,
"Column names must have a non-zero length."
));
}
for (index, c) in name.chars().enumerate() {
match c {
'?' | '.' | ',' | '\'' | '\"' | '\\' | '/' | ':' | ')' | '(' | '+' | '-' | '*'
| '%' | '~' | '\r' | '\n' | '\0' | '\u{0001}' | '\u{0002}' | '\u{0003}'
| '\u{0004}' | '\u{0005}' | '\u{0006}' | '\u{0007}' | '\u{0008}' | '\u{0009}'
| '\u{000b}' | '\u{000c}' | '\u{000e}' | '\u{000f}' | '\u{007f}' => {
return Err(error::fmt!(
InvalidName,
concat!(
"Bad string {:?}: ",
"Column names can't contain ",
"a {:?} character, which was found at ",
"byte position {}."
),
name,
c,
index
));
}
'\u{FEFF}' => {
// Reject unicode char 'ZERO WIDTH NO-BREAK SPACE',
// aka UTF-8 BOM if it appears anywhere in the string.
return Err(error::fmt!(
InvalidName,
concat!(
"Bad string {:?}: ",
"Column names can't contain ",
"a UTF-8 BOM character, which was found at ",
"byte position {}."
),
name,
index
));
}
_ => (),
}
}
Ok(Self { name })
}
/// Construct a column name without validating it.
///
/// This breaks API encapsulation and is only intended for use
/// when the the string was already previously validated.
///
/// The QuestDB server will reject an invalid column name.
pub fn new_unchecked(name: &'a str) -> Self {
Self { name }
}
}
impl<'a> TryFrom<&'a str> for TableName<'a> {
type Error = self::Error;
fn try_from(name: &'a str) -> Result<Self> {
Self::new(name)
}
}
impl<'a> TryFrom<&'a str> for ColumnName<'a> {
type Error = self::Error;
fn try_from(name: &'a str) -> Result<Self> {
Self::new(name)
}
}
impl From<Infallible> for Error {
fn from(_: Infallible) -> Self {
unreachable!()
}
}
fn write_escaped_impl<Q, C>(check_escape_fn: C, quoting_fn: Q, output: &mut String, s: &str)
where
C: Fn(u8) -> bool,
Q: Fn(&mut Vec<u8>),
{
let output_vec = unsafe { output.as_mut_vec() };
let mut to_escape = 0usize;
for b in s.bytes() {
if check_escape_fn(b) {
to_escape += 1;
}
}
quoting_fn(output_vec);
if to_escape == 0 {
// output.push_str(s);
output_vec.extend_from_slice(s.as_bytes());
} else {
let additional = s.len() + to_escape;
output_vec.reserve(additional);
let mut index = output_vec.len();
unsafe { output_vec.set_len(index + additional) };
for b in s.bytes() {
if check_escape_fn(b) {
unsafe {
*output_vec.get_unchecked_mut(index) = b'\\';
}
index += 1;
}
unsafe {
*output_vec.get_unchecked_mut(index) = b;
}
index += 1;
}
}
quoting_fn(output_vec);
}
fn must_escape_unquoted(c: u8) -> bool {
matches!(c, b' ' | b',' | b'=' | b'\n' | b'\r' | b'\\')
}
fn must_escape_quoted(c: u8) -> bool {
matches!(c, b'\n' | b'\r' | b'"' | b'\\')
}
fn write_escaped_unquoted(output: &mut String, s: &str) {
write_escaped_impl(must_escape_unquoted, |_output| (), output, s);
}
fn write_escaped_quoted(output: &mut String, s: &str) {
write_escaped_impl(must_escape_quoted, |output| output.push(b'"'), output, s)
}
enum Connection {
Direct(Socket),
Tls(Box<StreamOwned<ClientConnection, Socket>>),
}
impl Connection {
fn send_key_id(&mut self, key_id: &str) -> Result<()> {
writeln!(self, "{}", key_id)
.map_err(|io_err| map_io_to_socket_err("Failed to send key_id: ", io_err))?;
Ok(())
}
fn read_challenge(&mut self) -> Result<Vec<u8>> {
let mut buf = Vec::new();
let mut reader = BufReader::new(self);
reader.read_until(b'\n', &mut buf).map_err(|io_err| {
map_io_to_socket_err(
"Failed to read authentication challenge (timed out?): ",
io_err,
)
})?;
if buf.last().copied().unwrap_or(b'\0') != b'\n' {
return Err(if buf.is_empty() {
error::fmt!(
AuthError,
concat!(
"Did not receive auth challenge. ",
"Is the database configured to require ",
"authentication?"
)
)
} else {
error::fmt!(AuthError, "Received incomplete auth challenge: {:?}", buf)
});
}
buf.pop(); // b'\n'
Ok(buf)
}
fn authenticate(&mut self, auth: &EcdsaAuthParams) -> Result<()> {
if auth.key_id.contains('\n') {
return Err(error::fmt!(
AuthError,
"Bad key id {:?}: Should not contain new-line char.",
auth.key_id
));
}
let key_pair = parse_key_pair(auth)?;
self.send_key_id(auth.key_id.as_str())?;
let challenge = self.read_challenge()?;
let rng = SystemRandom::new();
let signature = key_pair
.sign(&rng, &challenge[..])
.map_err(|unspecified_err| {
error::fmt!(AuthError, "Failed to sign challenge: {}", unspecified_err)
})?;
let mut encoded_sig = Base64::encode_string(signature.as_ref());
encoded_sig.push('\n');
let buf = encoded_sig.as_bytes();
if let Err(io_err) = self.write_all(buf) {
return Err(map_io_to_socket_err(
"Could not send signed challenge: ",
io_err,
));
}
Ok(())
}
}
enum ProtocolHandler {
Socket(Connection),
#[cfg(feature = "ilp-over-http")]
Http(HttpHandlerState),
}
impl io::Read for Connection {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match self {
Self::Direct(sock) => sock.read(buf),
Self::Tls(stream) => stream.read(buf),
}
}
}
impl io::Write for Connection {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match self {
Self::Direct(sock) => sock.write(buf),
Self::Tls(stream) => stream.write(buf),
}
}
fn flush(&mut self) -> io::Result<()> {
match self {
Self::Direct(sock) => sock.flush(),
Self::Tls(stream) => stream.flush(),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
enum OpCase {
Init = Op::Table as isize,
TableWritten = Op::Symbol as isize | Op::Column as isize,
SymbolWritten = Op::Symbol as isize | Op::Column as isize | Op::At as isize,
ColumnWritten = Op::Column as isize | Op::At as isize,
MayFlushOrTable = Op::Flush as isize | Op::Table as isize,
}
impl OpCase {
fn next_op_descr(self) -> &'static str {
match self {
OpCase::Init => "should have called `table` instead",
OpCase::TableWritten => "should have called `symbol` or `column` instead",
OpCase::SymbolWritten => "should have called `symbol`, `column` or `at` instead",
OpCase::ColumnWritten => "should have called `column` or `at` instead",
OpCase::MayFlushOrTable => "should have called `flush` or `table` instead",
}
}
}
#[derive(Debug, Clone)]
struct BufferState {
op_case: OpCase,
row_count: usize,
first_table: Option<String>,
transactional: bool,
}
impl BufferState {
fn new() -> Self {
Self {
op_case: OpCase::Init,
row_count: 0,
first_table: None,
transactional: true,
}
}
fn clear(&mut self) {
self.op_case = OpCase::Init;
self.row_count = 0;
self.first_table = None;
self.transactional = true;
}
}
/// A reusable buffer to prepare a batch of ILP messages.
///
/// # Example
///
/// ```
/// # use questdb::Result;
/// use questdb::ingress::{Buffer, TimestampMicros, TimestampNanos};
///
/// # fn main() -> Result<()> {
/// let mut buffer = Buffer::new();
///
/// // first row
/// buffer
/// .table("table1")?
/// .symbol("bar", "baz")?
/// .column_bool("a", false)?
/// .column_i64("b", 42)?
/// .column_f64("c", 3.14)?
/// .column_str("d", "hello")?
/// .column_ts("e", TimestampMicros::now())?
/// .at(TimestampNanos::now())?;
///
/// // second row
/// buffer
/// .table("table2")?
/// .symbol("foo", "bar")?
/// .at(TimestampNanos::now())?;
/// # Ok(())
/// # }
/// ```
///
/// Send the buffer to QuestDB using [`sender.flush(&mut buffer)`](Sender::flush).
///
/// # Sequential Coupling
/// The Buffer API is sequentially coupled:
/// * A row always starts with [`table`](Buffer::table).
/// * A row must contain at least one [`symbol`](Buffer::symbol) or
/// column (
/// [`column_bool`](Buffer::column_bool),
/// [`column_i64`](Buffer::column_i64),
/// [`column_f64`](Buffer::column_f64),
/// [`column_str`](Buffer::column_str),
/// [`column_ts`](Buffer::column_ts)).
/// * Symbols must appear before columns.
/// * A row must be terminated with either [`at`](Buffer::at) or
/// [`at_now`](Buffer::at_now).
///
/// This diagram visualizes the sequence:
///
/// <img src="https://raw.githubusercontent.com/questdb/c-questdb-client/main/api_seq/seq.svg">
///
/// # Buffer method calls, Serialized ILP types and QuestDB types
///
/// | Buffer Method | Serialized as ILP type (Click on link to see possible casts) |
/// |---------------|--------------------------------------------------------------|
/// | [`symbol`](Buffer::symbol) | [`SYMBOL`](https://questdb.io/docs/concept/symbol/) |
/// | [`column_bool`](Buffer::column_bool) | [`BOOLEAN`](https://questdb.io/docs/reference/api/ilp/columnset-types#boolean) |
/// | [`column_i64`](Buffer::column_i64) | [`INTEGER`](https://questdb.io/docs/reference/api/ilp/columnset-types#integer) |
/// | [`column_f64`](Buffer::column_f64) | [`FLOAT`](https://questdb.io/docs/reference/api/ilp/columnset-types#float) |
/// | [`column_str`](Buffer::column_str) | [`STRING`](https://questdb.io/docs/reference/api/ilp/columnset-types#string) |
/// | [`column_ts`](Buffer::column_ts) | [`TIMESTAMP`](https://questdb.io/docs/reference/api/ilp/columnset-types#timestamp) |
///
/// QuestDB supports both `STRING` and `SYMBOL` column types.
///
/// To understand the difference, refer to the
/// [QuestDB documentation](https://questdb.io/docs/concept/symbol/). In a nutshell,
/// symbols are interned strings, most suitable for identifiers that are repeated many
/// times throughout the column. They offer an advantage in storage space and query
/// performance.
///
/// # Inserting NULL values
///
/// To insert a NULL value, skip the symbol or column for that row.
///
/// # Recovering from validation errors
///
/// If you want to recover from potential validation errors, call
/// [`buffer.set_marker()`](Buffer::set_marker) to track the last known good state,
/// append as many rows or parts of rows as you like, and then call
/// [`buffer.clear_marker()`](Buffer::clear_marker) on success.
///
/// If there was an error in one of the rows, use
/// [`buffer.rewind_to_marker()`](Buffer::rewind_to_marker) to go back to the
/// marked last known good state.
///
#[derive(Debug, Clone)]
pub struct Buffer {
output: String,
state: BufferState,
marker: Option<(usize, BufferState)>,
max_name_len: usize,
}
impl Buffer {
/// Construct a `Buffer` with a `max_name_len` of `127`, which is the same as the
/// QuestDB server default.
pub fn new() -> Self {
Self {
output: String::new(),
state: BufferState::new(),
marker: None,
max_name_len: 127,
}
}
/// Construct a `Buffer` with a custom maximum length for table and column names.
///
/// This should match the `cairo.max.file.name.length` setting of the
/// QuestDB instance you're connecting to.
///
/// If the server does not configure it, the default is `127` and you can simply
/// call [`new`](Buffer::new).
pub fn with_max_name_len(max_name_len: usize) -> Self {
let mut buf = Self::new();
buf.max_name_len = max_name_len;
buf
}
/// Pre-allocate to ensure the buffer has enough capacity for at least the
/// specified additional byte count. This may be rounded up.
/// This does not allocate if such additional capacity is already satisfied.
/// See: `capacity`.
pub fn reserve(&mut self, additional: usize) {
self.output.reserve(additional);
}
/// The number of bytes accumulated in the buffer.
pub fn len(&self) -> usize {
self.output.len()
}
/// The number of rows accumulated in the buffer.
pub fn row_count(&self) -> usize {
self.state.row_count
}
/// Tells whether the buffer is transactional. It is transactional iff it contains
/// data for at most one table. Additionally, you must send the buffer over HTTP to
/// get transactional behavior.
pub fn transactional(&self) -> bool {
self.state.transactional
}
pub fn is_empty(&self) -> bool {
self.output.is_empty()
}
/// The total number of bytes the buffer can hold before it needs to resize.
pub fn capacity(&self) -> usize {
self.output.capacity()
}
/// A string representation of the buffer's contents. Useful for debugging.
pub fn as_str(&self) -> &str {
&self.output
}
/// Mark a rewind point.
/// This allows undoing accumulated changes to the buffer for one or more
/// rows by calling [`rewind_to_marker`](Buffer::rewind_to_marker).
/// Any previous marker will be discarded.
/// Once the marker is no longer needed, call
/// [`clear_marker`](Buffer::clear_marker).
pub fn set_marker(&mut self) -> Result<()> {
if (self.state.op_case as isize & Op::Table as isize) == 0 {
return Err(error::fmt!(
InvalidApiCall,
concat!(
"Can't set the marker whilst constructing a line. ",
"A marker may only be set on an empty buffer or after ",
"`at` or `at_now` is called."
)
));
}
self.marker = Some((self.output.len(), self.state.clone()));
Ok(())
}
/// Undo all changes since the last [`set_marker`](Buffer::set_marker)
/// call.
///
/// As a side-effect, this also clears the marker.
pub fn rewind_to_marker(&mut self) -> Result<()> {
if let Some((position, state)) = self.marker.take() {
self.output.truncate(position);
self.state = state;
Ok(())
} else {
Err(error::fmt!(
InvalidApiCall,
"Can't rewind to the marker: No marker set."
))
}
}
/// Discard any marker as may have been set by
/// [`set_marker`](Buffer::set_marker).
///
/// Idempotent.
pub fn clear_marker(&mut self) {
self.marker = None;
}
/// Reset the buffer and clear contents whilst retaining
/// [`capacity`](Buffer::capacity).
pub fn clear(&mut self) {
self.output.clear();
self.state.clear();
self.marker = None;
}
/// Check if the next API operation is allowed as per the OP case state machine.
#[inline(always)]
fn check_op(&self, op: Op) -> Result<()> {
if (self.state.op_case as isize & op as isize) > 0 {
Ok(())
} else {
Err(error::fmt!(
InvalidApiCall,
"State error: Bad call to `{}`, {}.",
op.descr(),
self.state.op_case.next_op_descr()
))
}
}
#[inline(always)]
fn validate_max_name_len(&self, name: &str) -> Result<()> {
if name.len() > self.max_name_len {
return Err(error::fmt!(
InvalidName,
"Bad name: {:?}: Too long (max {} characters)",
name,
self.max_name_len
));
}
Ok(())
}
/// Begin recording a new row for the given table.
///
/// ```
/// # use questdb::Result;
/// # use questdb::ingress::Buffer;
/// # fn main() -> Result<()> {
/// # let mut buffer = Buffer::new();
/// buffer.table("table_name")?;
/// # Ok(())
/// # }
/// ```
///
/// or
///
/// ```
/// # use questdb::Result;
/// # use questdb::ingress::Buffer;
/// use questdb::ingress::TableName;
///
/// # fn main() -> Result<()> {
/// # let mut buffer = Buffer::new();
/// let table_name = TableName::new("table_name")?;
/// buffer.table(table_name)?;
/// # Ok(())
/// # }
/// ```
pub fn table<'a, N>(&mut self, name: N) -> Result<&mut Self>
where
N: TryInto<TableName<'a>>,
Error: From<N::Error>,
{
let name: TableName<'a> = name.try_into()?;
self.validate_max_name_len(name.name)?;
self.check_op(Op::Table)?;
write_escaped_unquoted(&mut self.output, name.name);
self.state.op_case = OpCase::TableWritten;
// A buffer stops being transactional if it targets multiple tables.
if let Some(first_table) = &self.state.first_table {
if first_table != name.name {
self.state.transactional = false;
}
} else {
self.state.first_table = Some(name.name.to_owned());
}
Ok(self)
}
/// Record a symbol for the given column.
/// Make sure you record all symbol columns before any other column type.
///
/// ```
/// # use questdb::Result;
/// # use questdb::ingress::Buffer;
/// # fn main() -> Result<()> {
/// # let mut buffer = Buffer::new();
/// # buffer.table("x")?;
/// buffer.symbol("col_name", "value")?;
/// # Ok(())
/// # }
/// ```
///
/// or
///
/// ```
/// # use questdb::Result;
/// # use questdb::ingress::Buffer;
/// # fn main() -> Result<()> {
/// # let mut buffer = Buffer::new();
/// # buffer.table("x")?;
/// let value: String = "value".to_owned();
/// buffer.symbol("col_name", value)?;
/// # Ok(())
/// # }
/// ```
///
/// or
///
/// ```
/// # use questdb::Result;
/// # use questdb::ingress::Buffer;
/// use questdb::ingress::ColumnName;
///
/// # fn main() -> Result<()> {
/// # let mut buffer = Buffer::new();
/// # buffer.table("x")?;
/// let col_name = ColumnName::new("col_name")?;
/// buffer.symbol(col_name, "value")?;
/// # Ok(())
/// # }
/// ```
///
pub fn symbol<'a, N, S>(&mut self, name: N, value: S) -> Result<&mut Self>
where
N: TryInto<ColumnName<'a>>,
S: AsRef<str>,
Error: From<N::Error>,
{
let name: ColumnName<'a> = name.try_into()?;
self.validate_max_name_len(name.name)?;
self.check_op(Op::Symbol)?;
self.output.push(',');
write_escaped_unquoted(&mut self.output, name.name);
self.output.push('=');
write_escaped_unquoted(&mut self.output, value.as_ref());
self.state.op_case = OpCase::SymbolWritten;
Ok(self)
}
fn write_column_key<'a, N>(&mut self, name: N) -> Result<&mut Self>
where
N: TryInto<ColumnName<'a>>,
Error: From<N::Error>,
{
let name: ColumnName<'a> = name.try_into()?;
self.validate_max_name_len(name.name)?;
self.check_op(Op::Column)?;
self.output
.push(if (self.state.op_case as isize & Op::Symbol as isize) > 0 {
' '
} else {
','
});
write_escaped_unquoted(&mut self.output, name.name);
self.output.push('=');
self.state.op_case = OpCase::ColumnWritten;
Ok(self)
}
/// Record a boolean value for the given column.
///
/// ```
/// # use questdb::Result;
/// # use questdb::ingress::Buffer;
/// # fn main() -> Result<()> {
/// # let mut buffer = Buffer::new();
/// # buffer.table("x")?;
/// buffer.column_bool("col_name", true)?;
/// # Ok(())
/// # }
/// ```
///
/// or
///
/// ```
/// # use questdb::Result;
/// # use questdb::ingress::Buffer;
/// use questdb::ingress::ColumnName;
///
/// # fn main() -> Result<()> {
/// # let mut buffer = Buffer::new();
/// # buffer.table("x")?;
/// let col_name = ColumnName::new("col_name")?;
/// buffer.column_bool(col_name, true)?;
/// # Ok(())
/// # }
/// ```
pub fn column_bool<'a, N>(&mut self, name: N, value: bool) -> Result<&mut Self>
where
N: TryInto<ColumnName<'a>>,
Error: From<N::Error>,
{
self.write_column_key(name)?;
self.output.push(if value { 't' } else { 'f' });
Ok(self)
}
/// Record an integer value for the given column.
///
/// ```
/// # use questdb::Result;
/// # use questdb::ingress::Buffer;
/// # fn main() -> Result<()> {
/// # let mut buffer = Buffer::new();
/// # buffer.table("x")?;
/// buffer.column_i64("col_name", 42)?;
/// # Ok(())
/// # }
/// ```
///
/// or
///
/// ```
/// # use questdb::Result;
/// # use questdb::ingress::Buffer;
/// use questdb::ingress::ColumnName;
///
/// # fn main() -> Result<()> {
/// # let mut buffer = Buffer::new();
/// # buffer.table("x")?;
/// let col_name = ColumnName::new("col_name")?;
/// buffer.column_i64(col_name, 42);
/// # Ok(())
/// # }
/// ```
pub fn column_i64<'a, N>(&mut self, name: N, value: i64) -> Result<&mut Self>
where
N: TryInto<ColumnName<'a>>,
Error: From<N::Error>,
{
self.write_column_key(name)?;
let mut buf = itoa::Buffer::new();
let printed = buf.format(value);
self.output.push_str(printed);
self.output.push('i');
Ok(self)
}
/// Record a floating point value for the given column.
///
/// ```
/// # use questdb::Result;
/// # use questdb::ingress::Buffer;
/// # fn main() -> Result<()> {
/// # let mut buffer = Buffer::new();
/// # buffer.table("x")?;
/// buffer.column_f64("col_name", 3.14)?;
/// # Ok(())
/// # }
/// ```
///
/// or
///
/// ```
/// # use questdb::Result;
/// # use questdb::ingress::Buffer;
/// use questdb::ingress::ColumnName;
///
/// # fn main() -> Result<()> {
/// # let mut buffer = Buffer::new();
/// # buffer.table("x")?;
/// let col_name = ColumnName::new("col_name")?;
/// buffer.column_f64(col_name, 3.14)?;
/// # Ok(())
/// # }
/// ```
pub fn column_f64<'a, N>(&mut self, name: N, value: f64) -> Result<&mut Self>
where
N: TryInto<ColumnName<'a>>,
Error: From<N::Error>,
{
self.write_column_key(name)?;
let mut ser = F64Serializer::new(value);
self.output.push_str(ser.as_str());
Ok(self)
}
/// Record a string value for the given column.
///
/// ```
/// # use questdb::Result;
/// # use questdb::ingress::Buffer;
/// # fn main() -> Result<()> {
/// # let mut buffer = Buffer::new();
/// # buffer.table("x")?;
/// buffer.column_str("col_name", "value")?;
/// # Ok(())
/// # }
/// ```
///
/// or
///
/// ```
/// # use questdb::Result;
/// # use questdb::ingress::Buffer;
/// # fn main() -> Result<()> {
/// # let mut buffer = Buffer::new();
/// # buffer.table("x")?;
/// let value: String = "value".to_owned();
/// buffer.column_str("col_name", value)?;
/// # Ok(())
/// # }
/// ```
///
/// or
///
/// ```
/// # use questdb::Result;
/// # use questdb::ingress::Buffer;
/// use questdb::ingress::ColumnName;
///
/// # fn main() -> Result<()> {
/// # let mut buffer = Buffer::new();
/// # buffer.table("x")?;
/// let col_name = ColumnName::new("col_name")?;
/// buffer.column_str(col_name, "value")?;
/// # Ok(())
/// # }
/// ```
pub fn column_str<'a, N, S>(&mut self, name: N, value: S) -> Result<&mut Self>
where
N: TryInto<ColumnName<'a>>,
S: AsRef<str>,
Error: From<N::Error>,
{
self.write_column_key(name)?;
write_escaped_quoted(&mut self.output, value.as_ref());
Ok(self)
}
/// Record a timestamp value for the given column.
///
/// ```