Idempotent Seed Insert With NOT EXISTS
Seed reference data idempotently with INSERT SELECT plus a WHERE NOT EXISTS guard, so replaying the script neither duplicates rows nor needs a conflict target.
Page 20 of 50
Seed reference data idempotently with INSERT SELECT plus a WHERE NOT EXISTS guard, so replaying the script neither duplicates rows nor needs a conflict target.
Compute per-event durations by subtracting the current timestamp from LEAD of the next event, then aggregate total durations per endpoint outside.
Sort numeric codes stored as text correctly: LPAD adds leading zeros so lexicographic order matches numeric order, indexable as an expression.
Collect every descendant of a category with a recursive CTE, then delete the whole subtree in one statement that returns the removed rows.
Score customers into quintiles with three NTILE windows over recency, frequency, and spend, then concatenate the ranks into a classic RFM score string.
ROUND ties away from zero, TRUNC cuts toward zero, and FLOOR and CEIL head toward minus and plus infinity.
Close the previous version row and insert the replacement in one data-modifying CTE so slowly changing dimension history keeps a single open row.
FOR SHARE takes a row lock that blocks writers but permits other readers, unlike the plain snapshot read that lets a concurrent UPDATE slip between checks.
Enforce a one-row settings table with a CHECK (id = 1) guard so concurrent writers cannot create a second row, and mutate it with ON CONFLICT.
Build display strings with chained ||, the concat and concat_ws functions, and format() placeholders — each handles NULL and separators differently.
A unique constraint owns a same-named index: DROP INDEX fails with a dependency error, while DROP CONSTRAINT removes both in one step.
Enforce uniqueness for an undirected pair: a unique index on LEAST and GREATEST normalizes both directions to the same key before comparing.
Multi-argument unnest in the FROM clause expands parallel arrays of labels and values, turning one wide row into one row per month without UNION ALL repetition.
Guard upsert replay with DO UPDATE SET plus a WHERE that compares target values against EXCLUDED so unchanged rows are skipped and dead tuples avoided.
Pull only rows past a stored watermark with an incremental sync query, then advance the watermark so repeated runs move forward without reprocessing.
Compute a weighted average as SUM(value * weight) over SUM(weight), because averaging already-averaged group values weights small samples the same as big ones.
Unpack session intervals into enter and leave events, then window-sum the deltas to find the moment with the most simultaneous visitors.
A LEFT JOIN before GROUP BY keeps categories with no matching rows, and COUNT over the joined column reports 0 — filters must move into ON or they vanish.
Type fresh config object literals against an interface so a misspelled key fails compilation, while values from wider variables skip the extra-key check.
Pin generic type arguments to a class reference without calling the constructor, so helper aliases inherit strict item types and wrong members fail compilation.
Restrict a parameter to non-primitive values with the lowercase object type, and see why the older Object and {} annotations still accept strings.
Partial Record over keyof SignupForm types per-field validation messages, keeping the error map in sync with the form interface as fields change.
The typeof type operator turns a runtime constant's full shape into a type, so nested config fields keep literal types without hand-writing an interface.
Feed bytes through hash/adler32 incrementally and compare the running digest with the one-shot Checksum helper to prove both paths agree.
Pack binary bytes into printable Ascii85 text with encoding/ascii85, then decode the result and confirm a byte-exact round trip.
Use atomic.Bool Swap and CompareAndSwap to flip a shared flag across goroutines without a mutex, watching each returned value.
Encode and decode Base32 with padded, unpadded, and custom alphabets for OTP secrets and case-insensitive configuration values.
Measure throughput and allocations with testing.B, ReportAllocs, and sub-benchmarks so optimization claims rest on numbers you can reproduce.
Raise precision with big.Float SetPrec, print a long decimal expansion, and read Acc to learn whether a division was rounded.
Feed events through a buffered channel and drop repeated keys with a seen map, so burst traffic cannot duplicate downstream work.
Wrap file and network IO in bufio so many small reads and writes coalesce into few syscalls instead of one each.
Read a line longer than the buffer with bufio.Reader ReadSlice, handle ErrBufferFull by appending fragments, and compare it with ReadString.
Compare byte slices case-insensitively with bytes.EqualFold, including a Unicode simple-fold pair that plain ASCII lowering would miss.
Cap concurrent work by filling a buffered channel and bound waiting with a timeout case, so slow slots never block callers forever.
Launch goroutines per task and cancel every sibling through a shared context CancelFunc as soon as one fails, ending the whole batch early.
Push, move, and remove nodes in container/list so splice operations stay O(1) once you already hold the element pointer.
Rotate, link, and unlink elements in a circular ring so fixed-size buffers and round-robin schedulers reuse slots without reallocation.
Compute CRC-64/ECMA checksums with hash/crc64, append the value to a wire frame, and prove a flipped bit is detected.
Mint tokens with crypto/rand Text, check the base32 alphabet and length, and collect a thousand identifiers to confirm uniqueness.
Capture the current goroutine stack with runtime/debug.Stack, then pick the calling frame out of it without panicking the process.
Agree on an identical secret with crypto/ecdh P-256 keys, compare both sides, and confirm an eavesdropper derives a different value.
Compress and restore data with compress/flate writers and readers, comparing compressed sizes and verifying a byte-exact round trip.
Hash keys with hash/fnv for deterministic shard assignment, and reuse one hasher via Reset to avoid allocating on every call.
Mount one directory of an fs.FS as its own root with fs.Sub, read files through the narrowed view, and confirm parent paths are refused.
Turn fixed edge cases into a fuzz target with seed inputs, letting the engine mutate strings and search for round-trip violations.
Sum int and float slices through one generic function whose constraint unions numeric types, keeping a single call site per element type.
Derive separate encryption keys from one shared secret with HKDF extract, expand, and label binding instead of reusing raw keys.
Compose request middleware as http.Handler wrappers so logging, recovery, and auth stack in a readable order.
Define integer enums with iota and give them readable names via String() so logs show labels instead of bare numbers.
Exercise error paths with testing/iotest readers that fail on first read, return one byte at a time, and simulate timeouts.
Decode objects holding repeated keys into map and struct targets, showing how encoding/json resolves the collision deterministically.
Unwrap a repeated API envelope once with a generic helper, so every endpoint keeps typed payloads without repeating decode boilerplate.
Decode an RFC 7386 style patch into a map and overlay it on a base document, keeping nested objects merged and null values removed.
Hold nested payloads as json.RawMessage and parse them only when needed, so routing decisions avoid decoding the whole document.
Encode integer-keyed maps as readable JSON keys by implementing encoding.TextMarshaler and TextUnmarshaler on a custom key type.
Compare two maps with maps.EqualFunc and delegate value comparison to slices.Equal, so nested slices match element-wise instead of by identity.
Combine two ascending slices into one ordered result with a two index merge, allocating once and avoiding a resort.
Generate an ML-KEM key pair, encapsulate a shared secret, decapsulate it with the private key, and round-trip the public key.
Compose multipart/form-data bodies with mime/multipart, attach file parts, and parse the encoded payload back to verify fields and contents.
Guard a shared map with sync.RWMutex so concurrent readers proceed together while writers stay exclusive.
Connect two goroutines with net.Pipe, an in-memory synchronous connection that needs no listener, and exchange one framed line before closing.
Parse IPv4 and IPv6 literals with net/netip, then classify private, loopback, and link-local ranges and test CIDR membership.
Resolve the current account and a named user through os/user, reading username, uid, gid, home directory, and group IDs.
Derive a key with crypto/pbkdf2, confirm the same inputs reproduce it, and see how a different salt changes the whole output.
Wrap a PKIX public key into a PEM block, then decode and parse it back into a typed ECDSA key for configuration or transport.
Build a gradient image in memory, encode it with image/png, and decode the bytes back to verify dimensions and pixel values.
Switch a regexp to Longest mode and watch alternation prefer the longest branch instead of the first one that matches at the leftmost position.
Escape user-supplied text with regexp.QuoteMeta before building patterns, so dots and stars in input match themselves instead of rewriting the search.
Drive per-response write deadlines and explicit flushes through ResponseController so streamed output reaches clients before the handler returns.
Encrypt short payloads with RSA-OAEP and a context label, then verify that a mismatched label is rejected at decrypt time.
Walk the call stack with runtime.Callers and runtime.CallersFrames to log function names, files, and line numbers for diagnostics.
List runtime/metrics names, then read heap and goroutine counters into a snapshot and branch on the value kind.
Answer byte-range requests with http.ServeContent on an httptest server and inspect the 206 status and Content-Range header.
Hash data with SHA3-256 in one shot or incrementally, and read variable-length SHAKE output for key derivation and identifiers.
Copy a slice with slices.Clone, then mutate the clone to show that the backing array is independent while nil and capacity keep their own rules.
Intern equal strings with unique.Make so repeated values share one handle, cutting memory when the same keys arrive from many decoders.
Split text on any rune class with strings.FieldsFunc so comma, semicolon, and whitespace delimiters collapse without empty fields.
Iterate over a string with strings.Lines and see how each yielded value keeps its line terminator, including CRLF input and an empty line.
Drive serialization and validation from one struct tag line so the wire format and the rules are declared in the same place.
Index text with index/suffixarray and query it with Lookup and FindAllIndex to collect every occurrence offset of a pattern.
Declare reusable blocks with text/template define and render them through template actions, keeping one row layout across several records.
Enumerate cases in a table and run each as a subtest with t.Run, so one failure names the case instead of failing the suite.
Override environment variables inside a test with t.Setenv and rely on the automatic restore that keeps neighbouring tests isolated.
Give each test its own temporary directory with t.TempDir, write fixtures there, and let the testing package remove everything on cleanup.
Split a small expression language into identifiers, numbers, and operators with text/scanner, printing each token with its position.
Swap time.After for one reusable Ticker inside polling loops so per-iteration timers stop piling up before they fire.
Build dates from out-of-range fields and let time.Date normalize them, turning day 0, month 14, or a negative nanosecond offset into real instants.
Call Time.ZoneBounds around a daylight-saving change to get the exact UTC instants where one zone span ends and the next one starts.
Pin a minimum TLS version, supply an explicit root pool, and set handshake timeouts so clients fail closed instead of negotiating weak protocols.
Read struct size, alignment, and field offsets with unsafe.Sizeof, Alignof, and Offsetof to see exactly where padding bytes come from.
Build request URLs with url.JoinPath, let it clean dot segments, and observe how reserved characters in path elements are escaped.
Resolve per-user config and cache directories through os.UserConfigDir with an explicit fallback when the platform variable is unset.
Encode runes to UTF-16 code units, detect surrogate pairs for characters outside the BMP, and decode units back into a string.
Screen text with utf8.ValidString, then walk runes with DecodeRuneInString to locate the first invalid byte and report its offset.
Rank repeated words from log lines by splitting each line with strings.Fields and accumulating counts in a map keyed by the word.
Cap in-flight work with a semaphore channel so a large batch never opens more connections than the upstream tolerates.
Copy, pad, slice, and fill primitive arrays with Arrays.copyOf, copyOfRange, and fill, keeping ranges half-open and copies independent.
Update volatile long fields without AtomicLong objects through AtomicLongFieldUpdater, using compareAndSet and incrementAndGet.
Track a value and a mark bit together with AtomicMarkableReference, testing compareAndSet and attemptMark transitions.
Test primality with BigInteger.isProbablePrime and walk to the next prime, clarifying what the certainty argument does and does not promise.