Line data Source code
1 : //
2 : // This file contains common utilities for dealing with PostgreSQL WAL files and
3 : // LSNs.
4 : //
5 : // Many of these functions have been copied from PostgreSQL, and rewritten in
6 : // Rust. That's why they don't follow the usual Rust naming conventions, they
7 : // have been named the same as the corresponding PostgreSQL functions instead.
8 : //
9 :
10 : use crc32c::crc32c_append;
11 :
12 : use super::super::waldecoder::WalStreamDecoder;
13 : use super::bindings::{
14 : CheckPoint, ControlFileData, DBState_DB_SHUTDOWNED, FullTransactionId, TimeLineID, TimestampTz,
15 : XLogLongPageHeaderData, XLogPageHeaderData, XLogRecPtr, XLogRecord, XLogSegNo, XLOG_PAGE_MAGIC,
16 : };
17 : use super::PG_MAJORVERSION;
18 : use crate::pg_constants;
19 : use crate::PG_TLI;
20 : use crate::{uint32, uint64, Oid};
21 : use crate::{WAL_SEGMENT_SIZE, XLOG_BLCKSZ};
22 :
23 : use bytes::BytesMut;
24 : use bytes::{Buf, Bytes};
25 :
26 : use log::*;
27 :
28 : use serde::Serialize;
29 : use std::fs::File;
30 : use std::io::prelude::*;
31 : use std::io::ErrorKind;
32 : use std::io::SeekFrom;
33 : use std::path::{Path, PathBuf};
34 : use std::time::SystemTime;
35 : use utils::bin_ser::DeserializeError;
36 : use utils::bin_ser::SerializeError;
37 :
38 : use utils::lsn::Lsn;
39 :
40 : pub const XLOG_FNAME_LEN: usize = 24;
41 : pub const XLP_FIRST_IS_CONTRECORD: u16 = 0x0001;
42 : pub const XLP_REM_LEN_OFFS: usize = 2 + 2 + 4 + 8;
43 : pub const XLOG_RECORD_CRC_OFFS: usize = 4 + 4 + 8 + 1 + 1 + 2;
44 :
45 : pub const XLOG_SIZE_OF_XLOG_SHORT_PHD: usize = std::mem::size_of::<XLogPageHeaderData>();
46 : pub const XLOG_SIZE_OF_XLOG_LONG_PHD: usize = std::mem::size_of::<XLogLongPageHeaderData>();
47 : pub const XLOG_SIZE_OF_XLOG_RECORD: usize = std::mem::size_of::<XLogRecord>();
48 : #[allow(clippy::identity_op)]
49 : pub const SIZE_OF_XLOG_RECORD_DATA_HEADER_SHORT: usize = 1 * 2;
50 :
51 : /// Interval of checkpointing metadata file. We should store metadata file to enforce
52 : /// predicate that checkpoint.nextXid is larger than any XID in WAL.
53 : /// But flushing checkpoint file for each transaction seems to be too expensive,
54 : /// so XID_CHECKPOINT_INTERVAL is used to forward align nextXid and so perform
55 : /// metadata checkpoint only once per XID_CHECKPOINT_INTERVAL transactions.
56 : /// XID_CHECKPOINT_INTERVAL should not be larger than BLCKSZ*CLOG_XACTS_PER_BYTE
57 : /// in order to let CLOG_TRUNCATE mechanism correctly extend CLOG.
58 : const XID_CHECKPOINT_INTERVAL: u32 = 1024;
59 :
60 12063 : pub fn XLogSegmentsPerXLogId(wal_segsz_bytes: usize) -> XLogSegNo {
61 12063 : (0x100000000u64 / wal_segsz_bytes as u64) as XLogSegNo
62 12063 : }
63 :
64 704 : pub fn XLogSegNoOffsetToRecPtr(
65 704 : segno: XLogSegNo,
66 704 : offset: u32,
67 704 : wal_segsz_bytes: usize,
68 704 : ) -> XLogRecPtr {
69 704 : segno * (wal_segsz_bytes as u64) + (offset as u64)
70 704 : }
71 :
72 5865 : pub fn XLogFileName(tli: TimeLineID, logSegNo: XLogSegNo, wal_segsz_bytes: usize) -> String {
73 5865 : format!(
74 5865 : "{:>08X}{:>08X}{:>08X}",
75 5865 : tli,
76 5865 : logSegNo / XLogSegmentsPerXLogId(wal_segsz_bytes),
77 5865 : logSegNo % XLogSegmentsPerXLogId(wal_segsz_bytes)
78 5865 : )
79 5865 : }
80 :
81 333 : pub fn XLogFromFileName(fname: &str, wal_seg_size: usize) -> (XLogSegNo, TimeLineID) {
82 333 : let tli = u32::from_str_radix(&fname[0..8], 16).unwrap();
83 333 : let log = u32::from_str_radix(&fname[8..16], 16).unwrap() as XLogSegNo;
84 333 : let seg = u32::from_str_radix(&fname[16..24], 16).unwrap() as XLogSegNo;
85 333 : (log * XLogSegmentsPerXLogId(wal_seg_size) + seg, tli)
86 333 : }
87 :
88 1131 : pub fn IsXLogFileName(fname: &str) -> bool {
89 8712 : return fname.len() == XLOG_FNAME_LEN && fname.chars().all(|c| c.is_ascii_hexdigit());
90 1131 : }
91 :
92 708 : pub fn IsPartialXLogFileName(fname: &str) -> bool {
93 708 : fname.ends_with(".partial") && IsXLogFileName(&fname[0..fname.len() - 8])
94 708 : }
95 :
96 : /// If LSN points to the beginning of the page, then shift it to first record,
97 : /// otherwise align on 8-bytes boundary (required for WAL records)
98 1328 : pub fn normalize_lsn(lsn: Lsn, seg_sz: usize) -> Lsn {
99 1328 : if lsn.0 % XLOG_BLCKSZ as u64 == 0 {
100 13 : let hdr_size = if lsn.0 % seg_sz as u64 == 0 {
101 9 : XLOG_SIZE_OF_XLOG_LONG_PHD
102 : } else {
103 4 : XLOG_SIZE_OF_XLOG_SHORT_PHD
104 : };
105 13 : lsn + hdr_size as u64
106 : } else {
107 1315 : lsn.align()
108 : }
109 1328 : }
110 :
111 596 : pub fn generate_pg_control(
112 596 : pg_control_bytes: &[u8],
113 596 : checkpoint_bytes: &[u8],
114 596 : lsn: Lsn,
115 596 : ) -> anyhow::Result<(Bytes, u64)> {
116 596 : let mut pg_control = ControlFileData::decode(pg_control_bytes)?;
117 596 : let mut checkpoint = CheckPoint::decode(checkpoint_bytes)?;
118 :
119 : // Generate new pg_control needed for bootstrap
120 596 : checkpoint.redo = normalize_lsn(lsn, WAL_SEGMENT_SIZE).0;
121 596 :
122 596 : //reset some fields we don't want to preserve
123 596 : //TODO Check this.
124 596 : //We may need to determine the value from twophase data.
125 596 : checkpoint.oldestActiveXid = 0;
126 596 :
127 596 : //save new values in pg_control
128 596 : pg_control.checkPoint = 0;
129 596 : pg_control.checkPointCopy = checkpoint;
130 596 : pg_control.state = DBState_DB_SHUTDOWNED;
131 596 :
132 596 : Ok((pg_control.encode(), pg_control.system_identifier))
133 596 : }
134 :
135 802785 : pub fn get_current_timestamp() -> TimestampTz {
136 802785 : to_pg_timestamp(SystemTime::now())
137 802785 : }
138 :
139 : // Module to reduce the scope of the constants
140 : mod timestamp_conversions {
141 : use std::time::Duration;
142 :
143 : use super::*;
144 :
145 : const UNIX_EPOCH_JDATE: u64 = 2440588; // == date2j(1970, 1, 1)
146 : const POSTGRES_EPOCH_JDATE: u64 = 2451545; // == date2j(2000, 1, 1)
147 : const SECS_PER_DAY: u64 = 86400;
148 : const USECS_PER_SEC: u64 = 1000000;
149 : const SECS_DIFF_UNIX_TO_POSTGRES_EPOCH: u64 =
150 : (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY;
151 :
152 802956 : pub fn to_pg_timestamp(time: SystemTime) -> TimestampTz {
153 802956 : match time.duration_since(SystemTime::UNIX_EPOCH) {
154 802956 : Ok(n) => {
155 802956 : ((n.as_secs() - SECS_DIFF_UNIX_TO_POSTGRES_EPOCH) * USECS_PER_SEC
156 802956 : + n.subsec_micros() as u64) as i64
157 : }
158 0 : Err(_) => panic!("SystemTime before UNIX EPOCH!"),
159 : }
160 802956 : }
161 :
162 22 : pub fn from_pg_timestamp(time: TimestampTz) -> SystemTime {
163 22 : let time: u64 = time
164 22 : .try_into()
165 22 : .expect("timestamp before millenium (postgres epoch)");
166 22 : let since_unix_epoch = time + SECS_DIFF_UNIX_TO_POSTGRES_EPOCH * USECS_PER_SEC;
167 22 : SystemTime::UNIX_EPOCH
168 22 : .checked_add(Duration::from_micros(since_unix_epoch))
169 22 : .expect("SystemTime overflow")
170 22 : }
171 : }
172 :
173 : pub use timestamp_conversions::{from_pg_timestamp, to_pg_timestamp};
174 :
175 : // Returns (aligned) end_lsn of the last record in data_dir with WAL segments.
176 : // start_lsn must point to some previously known record boundary (beginning of
177 : // the next record). If no valid record after is found, start_lsn is returned
178 : // back.
179 227 : pub fn find_end_of_wal(
180 227 : data_dir: &Path,
181 227 : wal_seg_size: usize,
182 227 : start_lsn: Lsn, // start reading WAL at this point; must point at record start_lsn.
183 227 : ) -> anyhow::Result<Lsn> {
184 227 : let mut result = start_lsn;
185 227 : let mut curr_lsn = start_lsn;
186 227 : let mut buf = [0u8; XLOG_BLCKSZ];
187 227 : let pg_version = PG_MAJORVERSION[1..3].parse::<u32>().unwrap();
188 227 : debug!("find_end_of_wal PG_VERSION: {}", pg_version);
189 :
190 227 : let mut decoder = WalStreamDecoder::new(start_lsn, pg_version);
191 :
192 : // loop over segments
193 258 : loop {
194 258 : let segno = curr_lsn.segment_number(wal_seg_size);
195 258 : let seg_file_name = XLogFileName(PG_TLI, segno, wal_seg_size);
196 258 : let seg_file_path = data_dir.join(seg_file_name);
197 258 : match open_wal_segment(&seg_file_path)? {
198 : None => {
199 : // no more segments
200 6 : debug!(
201 0 : "find_end_of_wal reached end at {:?}, segment {:?} doesn't exist",
202 : result, seg_file_path
203 : );
204 6 : return Ok(result);
205 : }
206 252 : Some(mut segment) => {
207 252 : let seg_offs = curr_lsn.segment_offset(wal_seg_size);
208 252 : segment.seek(SeekFrom::Start(seg_offs as u64))?;
209 : // loop inside segment
210 56478 : while curr_lsn.segment_number(wal_seg_size) == segno {
211 56447 : let bytes_read = segment.read(&mut buf)?;
212 56447 : if bytes_read == 0 {
213 0 : debug!(
214 0 : "find_end_of_wal reached end at {:?}, EOF in segment {:?} at offset {}",
215 0 : result,
216 0 : seg_file_path,
217 0 : curr_lsn.segment_offset(wal_seg_size)
218 : );
219 0 : return Ok(result);
220 56447 : }
221 56447 : curr_lsn += bytes_read as u64;
222 56447 : decoder.feed_bytes(&buf[0..bytes_read]);
223 :
224 : // advance result past all completely read records
225 : loop {
226 2906758 : match decoder.poll_decode() {
227 2850311 : Ok(Some(record)) => result = record.0,
228 221 : Err(e) => {
229 221 : debug!(
230 42 : "find_end_of_wal reached end at {:?}, decode error: {:?}",
231 : result, e
232 : );
233 221 : return Ok(result);
234 : }
235 56226 : Ok(None) => break, // need more data
236 : }
237 : }
238 : }
239 : }
240 : }
241 : }
242 227 : }
243 :
244 : // Open .partial or full WAL segment file, if present.
245 258 : fn open_wal_segment(seg_file_path: &Path) -> anyhow::Result<Option<File>> {
246 258 : let mut partial_path = seg_file_path.to_owned();
247 258 : partial_path.set_extension("partial");
248 258 : match File::open(partial_path) {
249 221 : Ok(file) => Ok(Some(file)),
250 37 : Err(e) => match e.kind() {
251 : ErrorKind::NotFound => {
252 : // .partial not found, try full
253 37 : match File::open(seg_file_path) {
254 31 : Ok(file) => Ok(Some(file)),
255 6 : Err(e) => match e.kind() {
256 6 : ErrorKind::NotFound => Ok(None),
257 0 : _ => Err(e.into()),
258 : },
259 : }
260 : }
261 0 : _ => Err(e.into()),
262 : },
263 : }
264 258 : }
265 :
266 0 : pub fn main() {
267 0 : let mut data_dir = PathBuf::new();
268 0 : data_dir.push(".");
269 0 : let wal_end = find_end_of_wal(&data_dir, WAL_SEGMENT_SIZE, Lsn(0)).unwrap();
270 0 : println!("wal_end={:?}", wal_end);
271 0 : }
272 :
273 : impl XLogRecord {
274 158391122 : pub fn from_slice(buf: &[u8]) -> Result<XLogRecord, DeserializeError> {
275 158391122 : use utils::bin_ser::LeSer;
276 158391122 : XLogRecord::des(buf)
277 158391122 : }
278 :
279 73047349 : pub fn from_bytes<B: Buf>(buf: &mut B) -> Result<XLogRecord, DeserializeError> {
280 73047349 : use utils::bin_ser::LeSer;
281 73047349 : XLogRecord::des_from(&mut buf.reader())
282 73047349 : }
283 :
284 18 : pub fn encode(&self) -> Result<Bytes, SerializeError> {
285 18 : use utils::bin_ser::LeSer;
286 18 : Ok(self.ser()?.into())
287 18 : }
288 :
289 : // Is this record an XLOG_SWITCH record? They need some special processing,
290 158391122 : pub fn is_xlog_switch_record(&self) -> bool {
291 158391122 : self.xl_info == pg_constants::XLOG_SWITCH && self.xl_rmid == pg_constants::RM_XLOG_ID
292 158391122 : }
293 : }
294 :
295 : impl XLogPageHeaderData {
296 3274046 : pub fn from_bytes<B: Buf>(buf: &mut B) -> Result<XLogPageHeaderData, DeserializeError> {
297 3274046 : use utils::bin_ser::LeSer;
298 3274046 : XLogPageHeaderData::des_from(&mut buf.reader())
299 3274046 : }
300 :
301 597 : pub fn encode(&self) -> Result<Bytes, SerializeError> {
302 597 : use utils::bin_ser::LeSer;
303 597 : self.ser().map(|b| b.into())
304 597 : }
305 : }
306 :
307 : impl XLogLongPageHeaderData {
308 1573 : pub fn from_bytes<B: Buf>(buf: &mut B) -> Result<XLogLongPageHeaderData, DeserializeError> {
309 1573 : use utils::bin_ser::LeSer;
310 1573 : XLogLongPageHeaderData::des_from(&mut buf.reader())
311 1573 : }
312 :
313 602 : pub fn encode(&self) -> Result<Bytes, SerializeError> {
314 602 : use utils::bin_ser::LeSer;
315 602 : self.ser().map(|b| b.into())
316 602 : }
317 : }
318 :
319 : pub const SIZEOF_CHECKPOINT: usize = std::mem::size_of::<CheckPoint>();
320 :
321 : impl CheckPoint {
322 35015 : pub fn encode(&self) -> Result<Bytes, SerializeError> {
323 35015 : use utils::bin_ser::LeSer;
324 35015 : Ok(self.ser()?.into())
325 35015 : }
326 :
327 2607 : pub fn decode(buf: &[u8]) -> Result<CheckPoint, DeserializeError> {
328 2607 : use utils::bin_ser::LeSer;
329 2607 : CheckPoint::des(buf)
330 2607 : }
331 :
332 : /// Update next XID based on provided new_xid and stored epoch.
333 : /// Next XID should be greater than new_xid. This handles 32-bit
334 : /// XID wraparound correctly.
335 : ///
336 : /// Returns 'true' if the XID was updated.
337 72005823 : pub fn update_next_xid(&mut self, xid: u32) -> bool {
338 72005823 : // nextXid should be greater than any XID in WAL, so increment provided XID and check for wraparround.
339 72005823 : let mut new_xid = std::cmp::max(xid.wrapping_add(1), pg_constants::FIRST_NORMAL_TRANSACTION_ID);
340 72005823 : // To reduce number of metadata checkpoints, we forward align XID on XID_CHECKPOINT_INTERVAL.
341 72005823 : // XID_CHECKPOINT_INTERVAL should not be larger than BLCKSZ*CLOG_XACTS_PER_BYTE
342 72005823 : new_xid =
343 72005823 : new_xid.wrapping_add(XID_CHECKPOINT_INTERVAL - 1) & !(XID_CHECKPOINT_INTERVAL - 1);
344 72005823 : let full_xid = self.nextXid.value;
345 72005823 : let old_xid = full_xid as u32;
346 72005823 : if new_xid.wrapping_sub(old_xid) as i32 > 0 {
347 8496 : let mut epoch = full_xid >> 32;
348 8496 : if new_xid < old_xid {
349 0 : // wrap-around
350 0 : epoch += 1;
351 8496 : }
352 8496 : let nextXid = (epoch << 32) | new_xid as u64;
353 8496 :
354 8496 : if nextXid != self.nextXid.value {
355 8496 : self.nextXid = FullTransactionId { value: nextXid };
356 8496 : return true;
357 0 : }
358 71997327 : }
359 71997327 : false
360 72005823 : }
361 : }
362 :
363 : /// Generate new, empty WAL segment, with correct block headers at the first
364 : /// page of the segment and the page that contains the given LSN.
365 : /// We need this segment to start compute node.
366 602 : pub fn generate_wal_segment(segno: u64, system_id: u64, lsn: Lsn) -> Result<Bytes, SerializeError> {
367 602 : let mut seg_buf = BytesMut::with_capacity(WAL_SEGMENT_SIZE);
368 602 :
369 602 : let pageaddr = XLogSegNoOffsetToRecPtr(segno, 0, WAL_SEGMENT_SIZE);
370 602 :
371 602 : let page_off = lsn.block_offset();
372 602 : let seg_off = lsn.segment_offset(WAL_SEGMENT_SIZE);
373 602 :
374 602 : let first_page_only = seg_off < XLOG_BLCKSZ;
375 602 : let (shdr_rem_len, infoflags) = if first_page_only {
376 5 : (seg_off, pg_constants::XLP_FIRST_IS_CONTRECORD)
377 : } else {
378 597 : (0, 0)
379 : };
380 :
381 602 : let hdr = XLogLongPageHeaderData {
382 602 : std: {
383 602 : XLogPageHeaderData {
384 602 : xlp_magic: XLOG_PAGE_MAGIC as u16,
385 602 : xlp_info: pg_constants::XLP_LONG_HEADER | infoflags,
386 602 : xlp_tli: PG_TLI,
387 602 : xlp_pageaddr: pageaddr,
388 602 : xlp_rem_len: shdr_rem_len as u32,
389 602 : ..Default::default() // Put 0 in padding fields.
390 602 : }
391 602 : },
392 602 : xlp_sysid: system_id,
393 602 : xlp_seg_size: WAL_SEGMENT_SIZE as u32,
394 602 : xlp_xlog_blcksz: XLOG_BLCKSZ as u32,
395 602 : };
396 :
397 602 : let hdr_bytes = hdr.encode()?;
398 602 : seg_buf.extend_from_slice(&hdr_bytes);
399 602 :
400 602 : //zero out the rest of the file
401 602 : seg_buf.resize(WAL_SEGMENT_SIZE, 0);
402 602 :
403 602 : if !first_page_only {
404 597 : let block_offset = lsn.page_offset_in_segment(WAL_SEGMENT_SIZE) as usize;
405 597 : let header = XLogPageHeaderData {
406 597 : xlp_magic: XLOG_PAGE_MAGIC as u16,
407 597 : xlp_info: if page_off >= pg_constants::SIZE_OF_PAGE_HEADER as u64 {
408 595 : pg_constants::XLP_FIRST_IS_CONTRECORD
409 : } else {
410 2 : 0
411 : },
412 : xlp_tli: PG_TLI,
413 597 : xlp_pageaddr: lsn.page_lsn().0,
414 597 : xlp_rem_len: if page_off >= pg_constants::SIZE_OF_PAGE_HEADER as u64 {
415 595 : page_off as u32
416 : } else {
417 2 : 0u32
418 : },
419 597 : ..Default::default() // Put 0 in padding fields.
420 : };
421 597 : let hdr_bytes = header.encode()?;
422 :
423 597 : debug_assert!(seg_buf.len() > block_offset + hdr_bytes.len());
424 597 : debug_assert_ne!(block_offset, 0);
425 :
426 597 : seg_buf[block_offset..block_offset + hdr_bytes.len()].copy_from_slice(&hdr_bytes[..]);
427 5 : }
428 :
429 602 : Ok(seg_buf.freeze())
430 602 : }
431 :
432 : #[repr(C)]
433 18 : #[derive(Serialize)]
434 : struct XlLogicalMessage {
435 : db_id: Oid,
436 : transactional: uint32, // bool, takes 4 bytes due to alignment in C structures
437 : prefix_size: uint64,
438 : message_size: uint64,
439 : }
440 :
441 : impl XlLogicalMessage {
442 9 : pub fn encode(&self) -> Bytes {
443 9 : use utils::bin_ser::LeSer;
444 9 : self.ser().unwrap().into()
445 9 : }
446 : }
447 :
448 : /// Create new WAL record for non-transactional logical message.
449 : /// Used for creating artificial WAL for tests, as LogicalMessage
450 : /// record is basically no-op.
451 : ///
452 : /// NOTE: This leaves the xl_prev field zero. The safekeeper and
453 : /// pageserver tolerate that, but PostgreSQL does not.
454 9 : pub fn encode_logical_message(prefix: &str, message: &str) -> Vec<u8> {
455 9 : let mut prefix_bytes: Vec<u8> = Vec::with_capacity(prefix.len() + 1);
456 9 : prefix_bytes.write_all(prefix.as_bytes()).unwrap();
457 9 : prefix_bytes.push(0);
458 9 :
459 9 : let message_bytes = message.as_bytes();
460 9 :
461 9 : let logical_message = XlLogicalMessage {
462 9 : db_id: 0,
463 9 : transactional: 0,
464 9 : prefix_size: prefix_bytes.len() as u64,
465 9 : message_size: message_bytes.len() as u64,
466 9 : };
467 9 :
468 9 : let mainrdata = logical_message.encode();
469 9 : let mainrdata_len: usize = mainrdata.len() + prefix_bytes.len() + message_bytes.len();
470 9 : // only short mainrdata is supported for now
471 9 : assert!(mainrdata_len <= 255);
472 9 : let mainrdata_len = mainrdata_len as u8;
473 9 :
474 9 : let mut data: Vec<u8> = vec![pg_constants::XLR_BLOCK_ID_DATA_SHORT, mainrdata_len];
475 9 : data.extend_from_slice(&mainrdata);
476 9 : data.extend_from_slice(&prefix_bytes);
477 9 : data.extend_from_slice(message_bytes);
478 9 :
479 9 : let total_len = XLOG_SIZE_OF_XLOG_RECORD + data.len();
480 9 :
481 9 : let mut header = XLogRecord {
482 9 : xl_tot_len: total_len as u32,
483 9 : xl_xid: 0,
484 9 : xl_prev: 0,
485 9 : xl_info: 0,
486 9 : xl_rmid: 21,
487 9 : __bindgen_padding_0: [0u8; 2usize],
488 9 : xl_crc: 0, // crc will be calculated later
489 9 : };
490 9 :
491 9 : let header_bytes = header.encode().expect("failed to encode header");
492 9 : let crc = crc32c_append(0, &data);
493 9 : let crc = crc32c_append(crc, &header_bytes[0..XLOG_RECORD_CRC_OFFS]);
494 9 : header.xl_crc = crc;
495 9 :
496 9 : let mut wal: Vec<u8> = Vec::new();
497 9 : wal.extend_from_slice(&header.encode().expect("failed to encode header"));
498 9 : wal.extend_from_slice(&data);
499 9 :
500 9 : // WAL start position must be aligned at 8 bytes,
501 9 : // this will add padding for the next WAL record.
502 9 : const PADDING: usize = 8;
503 9 : let padding_rem = wal.len() % PADDING;
504 9 : if padding_rem != 0 {
505 0 : wal.resize(wal.len() + PADDING - padding_rem, 0);
506 9 : }
507 :
508 9 : wal
509 9 : }
510 :
511 : #[cfg(test)]
512 : mod tests {
513 : use super::*;
514 :
515 6 : #[test]
516 6 : fn test_ts_conversion() {
517 6 : let now = SystemTime::now();
518 6 : let round_trip = from_pg_timestamp(to_pg_timestamp(now));
519 6 :
520 6 : let now_since = now.duration_since(SystemTime::UNIX_EPOCH).unwrap();
521 6 : let round_trip_since = round_trip.duration_since(SystemTime::UNIX_EPOCH).unwrap();
522 6 : assert_eq!(now_since.as_micros(), round_trip_since.as_micros());
523 :
524 6 : let now_pg = get_current_timestamp();
525 6 : let round_trip_pg = to_pg_timestamp(from_pg_timestamp(now_pg));
526 6 :
527 6 : assert_eq!(now_pg, round_trip_pg);
528 6 : }
529 :
530 : // If you need to craft WAL and write tests for this module, put it at wal_craft crate.
531 : }
|