On the value of foreign key constraints

Here is something I would like to demo regarding foreign key constraints.

This regards what type of errors foreign key constraints can (and can’t!) save you from.

Occasionally you hear developers say how important foreign key constraints are and how foreign key constraints saved them from some bug. That might all seem well and good but when you think it through if a foreign key constraint saved you from a bug it also might very well just have been luck that saved you and the thing that went wrong might have gone wrong another way and have gone undetected as database corruption and potential accidental data disclosure to an incorrect entity.

To set the scene let’s use some schema/data from what we were talking about earlier:

create table t_skinny_customer (
  customer_id bigint not null primary key,
  customer_name varchar(255) not null,
  customer_record_created_on timestamp default current_timestamp,
  customer_record_updated_on timestamp default current_timestamp on update current_timestamp
);

create table t_skinny_customer_phone (
  customer_phone_id bigint not null primary key,
  customer_id bigint not null references t_skinny_customer( customer_id ) on delete cascade,
  phone_number varchar(255) not null,
  phone_type enum( 'phone', 'tollfree', 'mobile' ) not null default 'phone',
  phone_type_order tinyint unsigned not null default 0,
  phone_record_created_on timestamp default current_timestamp,
  phone_record_updated_on timestamp default current_timestamp on update current_timestamp
);

insert into t_skinny_customer (
  customer_id,
  customer_name
)
values (
  1,
  'John Doe'
), (
  2,
  'Jane Doe'
);

insert into t_skinny_customer_phone (
  customer_phone_id,
  customer_id,
  phone_number,
  phone_type,
  phone_type_order
)
values (
  11,
  1,
  '123-456-7890',
  'phone',
  1
), (
  21,
  2,
  '123-456-7894',
  'phone',
  1
);

Then let’s run this code:

    $stmt = $pdo->prepare("
      update
        t_skinny_customer_phone
      set
        customer_id = :customer_id
      where
        customer_phone_id = :phone_id
    ");

    try {

      $stmt->execute([
        'customer_id' => 3,
        'phone_id' => 11,
      ]);

      assert( false );

    }
    catch ( PDOException $ex ) {

      // 2024-02-13 jj5 - foreign key constraint saved the day!

      assert(
        0 === strpos(
          $ex->getMessage(),
          'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails'
        )
      );

    }

    $stmt->execute([
      'customer_id' => 2,
      'phone_id' => 11,
    ]);

    // 2024-02-13 jj5 - ... whoops! what we've done here is switch
    // one of John Doe's phone numbers to be one of Jane Doe's
    // phone numbers. The foreign key constraint is of no value in
    // detecting this type of data corruption.

Now I’m not saying that you shouldn’t have foreign key constraints. I’m just pointing out that if you do have foreign key constraints and you’re relying on them for “referential integrity” your door may be open for all manner of bugs (and exploits).

That your foreign key points to an actual record doesn’t necessarily imply that your foreign key points to a correct record.

PHP shutdown handlers and exit codes

I was in bed trying to get to sleep but my brain wanted to know the answer to this question. So I was forced out of bed to write this experiment:

function main( $argv ) {

  register_shutdown_function( 'shutdown_1' );
  register_shutdown_function( 'shutdown_2' );

  exit( 0 );

}

function shutdown_1() {

  exit( 1 );

}

function shutdown_2() {

  exit( 2 );

}

main( $argv );

With this PHP code, what do you expect is the resultant error level?

The answer is ‘1’. After main() calls exit( 0 ) the shutdown function shutdown_1() is invoked. When shutdown_1() calls exit( 1 ) the process exists and shutdown_2() is never called.

I’m glad we cleared that up. Back to bed.

Context object versus global variables

I’m reading A Philosophy of Software Design by John Ousterhout and he says:

The context object unifies the handling of all system-global information and eliminates the need for pass-through variables. If a new variable needs to be added, it can be added to the context object; no existing code is affected except for the constructor and destructor for the context. The context makes it easy to identify and manage the global state of the system, since it is all stored in one place. The context is also convenient for testing: test code can change the global configuration of the application by modifying fields in the context. It would be much more difficult to implement such changes if the system used pass-through variables.

Contexts are far from an ideal solution. The variables stored in a context have most of the disadvantages of global variables; for example, it may not be obvious why a particular variable is present, or where it is used. Without discipline, a context can turn into a huge grab-bag of data that creates nonobvious dependencies throughout the system. Contexts may also create thread-safety issues; the best way to avoid problems is for variables in a context to be immutable. Unfortunately, I haven’t found a better solution than contexts.

Okay, so I’m just gonna step way out of line over here and suggest something heretical… but shouldn’t you just use global variables? You only introduced the context object so you could tweak it in unit tests, and you could just change your tests so that each one ran in a new process. Just sayin’.

…I suppose for the sake of completeness I should add a little more from Ousterhout which he said prior to the above:

Another approach is to store the information in a global variable, as in Figure 7.2(c). This avoids the need to pass the information from method to method, but global variables almost always create other problems. For example, global variables make it impossible to create two independent instances of the same system in the same process, since accesses to the global variables will conflict. It may seem unlikely that you would need multiple instances in production, but they are often useful in testing.

…so he is bending over backward to support multiple tests in one process, but he could just run each test in its own process and his problem evaporates.

Oh cringe

Man. So. Today, this happened. I was watching a new video from Adrian Black and his EEVBlog multimeter failed:

It's disappointing that it's already failed

I have been saving my pennies and planning to buy an EEVBlog 121GW Multimeter because a lot of the makers around the interwebs have one as a nod to Dave Jones over on the EEVBlog, but that’s just so embarrassing that it’s failing. Of all the equipment you have you need to trust your test equipment the most and this is… well, just sad I guess.

Logic Analyzer with 1GHz Sampling Rate

Today I was pleased to discover this: DreamSourceLab DSLogic U3Pro32 USB-Based Logic Analyzer with 1GHz Sampling Rate, 2Gbits Memory, USB 3.0 Interface, 32 Channels.

There are some notes from the manufacturer over here: DSLogic Series USB-based Logic Analyzer.

It’s a logic analyzer which can operate at 1GHz that’s within my price range. I’m not rushing off to buy this thing, but it is certainly on my list.

The only other thing I have seen that compares to this logic analyzer is this RIGOL DS70304/DS70504– Digital Oscilloscope 3GHz/5GHz 4 Channel 20GSa/s 2Gpts 1000000 wfms/s which is roughly two orders of magnitude more expensive.

Diode Experiment | Project 3/10 | Maxitronix 10in1 | In The Lab With Jay Jay

This post is part of my video blog: In The Lab With Jay Jay.

In this video I do the third Maxitronix 10in1 Electronic Project Lab project: Diode Experiment.

When I looked at the resistor on the bottom I thought it was red – brown – black – gold which would have been 21Ω but I think I misread brown and that was actually purple which would be 27Ω which stacks better with the two measurements I made both of which said 27Ω.

In the video we examine the forward voltage of our germanium diode and get various readings. Typically a germanium diode should be around 0.3V versus silicon diodes which are usually around 0.7V.

The component testers we use are these:

On the FNIRSI component tester the Ir is the “reverse current”, also known as the “leakage current”. This is the small amount of current which flows through the diode when it is reverse biased (that is, basically, connected the wrong way around).

I asked ChatGPT a few questions about diodes and their specifications which you can read here: Germanium Diode Forward Voltage if you’re at all interested in such things. Of course you should be doubly suspicious of anything you read on the internet. :)

The really amazing learning for me in this experiment was how hot the germanium diode got versus the lamp, which was so surprising. Just goes to show how good an idea it is to actually do experiments and measure things! The thermal imager we used was the UNI-T UTi260B.

Also I think I’m coming around to the view that an oscilloscope is a pretty poor voltmeter. My oscilloscope is an MSO5074 70MHz 4 Channel MIXED SIGNAL OSCILLOSCOPE and I love it but I think in future I will limit my use of the oscilloscope to situations where I’m actually dealing with some sort of oscillator. I think simple digital multimeters would have been better test equipment to use for the kinds of readings I was trying to take in this experiment.

I hope you enjoy the video. Stay tuned for the upcoming projects. If you’re interested in seeing them don’t forget to subscribe!

Also, if you’re interested in getting any of these Maxitronix kits yourself the best place I know to look is on eBay. Let me know if you find them somewhere else!

Here is a table of products I use which may appear in my video with affiliate links to vendors if you would like to buy. The link given here won’t necessarily have the best price so please do shop around to see if you can find a better deal. If you have thoughts or questions please feel free to let me know. Let’s go shopping!

Equipment Affiliate Link Notes

Rigol MSO5074 Mixed Signal Oscilloscope
MSO5074 70MHz 4 Channel MIXED SIGNAL OSCILLOSCOPES notes

FILCO Majestouch 2SS 87-key mechanical keyboard
Tenkeyless 87-key: FILCO Majestouch 2SS Edition Tenkeyless English Layout Cherry MX Speed Silver Axis with 3 Red Key Locks, Black FKBN87MSS/ECSP2B-RKL notes

gku Underdesk Keyboard Drawer
gku™ Underdesk Keyboard Drawer under desk keyboard tray and storage AC1009 notes

UNI-T UTi260B Thermal Imager
UNI-T UTi260B Infrared Thermal Imager 256 x192 Industrial Handheld Testing Thermometer For Repair Floor Heating Thermal Camera notes

Leadstar 12″ LCD TV
Prechen 11.6 Inch Small HDMI Monitor 1366×768 Small PC Monitor TFT LCD Monitor Built-in Speaker with HDMI VGA AV BNC USB Input Mini HD Color Screen Display notes

UPERFECT 15.6″ HDMI LCD
UPERFECT Portable Monitor 15.6″ Computer Display (100% sRGB High Color Gamut) 1920×1080 USB C Monitor FHD Eye Care Gaming Screen IPS Mini HDMI Type C OTG Dual Speaker VESA, Included Smart Cover Stand notes

TOMLOV DM602 Pro Digital Microscope
TOMLOV DM602 Pro 10.1″ HDMI Digital Microscope 2000x, Pro Boom Arm Stand, LCD Soldering Microscope with 3 Lens, Adults Microscope for Electronics Repair, Coin Microscope Ring Light,PC Compatible, 64G notes

Riden RD6006 Bench Power Supply
RD6018 RD6018W USB WiFi Digital Control Power Supply DC to DC Voltage Step Down Module Buck Converter Voltmeter 60V 18A notes

OWON XDM1041 Bench Multimeter
Owon XDM1041/XDM1241 Digital Multimeter 55000 Counts High Accuracy Desktop Multimeters AC/DC Tester True RMS USB Multimeter notes

ANENG AN-999S Bench Multimeter
ANENG AN-999S Desktop Voice Multimeter Digital 19999 Counts Professional Bluetooth Tester True RMS AC/DC Voltmeter Current Tools notes

Hakko CHP 3C-SA Precision Tweezers
Hakko CHP 3C-SA Stainless Steel Non-Magnetic Precision Tweezers with Very Fine Point Tips for Microelectronics Applications, 4-1/4″ Length (5 Pack) notes

Miniware DT71 Digital Tweezers
Miniware DT71 Mini Digital Tweezers Smart SMD LCRDVF Tester Multimeter Signal Generator for Measuring Components notes

FNIRSI DSO-TC3 Component Tester
FNIRSI DSO-TC3 Digital Oscilloscope Transistor Tester 10MS/s Sampling Rate 500kHz Bandwidth Support Diode LCR Detect Signal Generator notes

Brother P-Touch D210 Label Maker
Brother P-Touch D210 Handheld Label Maker TZe 3.5mm 6mm 9mm 12mm with Free Tape notes

UNI-T UT116A Digital Tweezers
UNI-T UT116A Digital Tweezers Smart SMD Tester Electrical Multimeter Resistance Capacitance Continuity Diode Test Meter notes

nmsafety Gloves
24Pieces/12 Pairs Work Gloves For PU Palm Coating Safety Protective Glove Nitrile Professional Safety Suppliers

Color: PU1350NV -DMF

notes

Kaisi Repair Mat
Kaisi Heat Insulation Silicone Repair Mat with Scale Ruler and Screw Position for Soldering Iron, Phone and Computer Repair Size:17.7 x 11.8 Inches notes

Kaisi Repair Mat
Kaisi Heat Insulation Silicone Repair Mat with Scale Ruler and Screw Position for Soldering Iron, Phone and Computer Repair Size: 13.7 x 9.8 Inches notes

MMOBIEL Helping Hands
LED Light Helping Hand Magnifier Station for Soldering, Assembly, Repair,Modeling, Hobbies and Crafts – 2.5X /4X LED Light – Hands-Free Magnifying Glass Stand – Incl. Clamp and Alligator Clips notes

QWORK Helping Hands
QWORK Glass Stand notes

Legion Tools Mini Screwdriver Set
Precision Mini Screwdriver Set 11pc Jeweller Laptop Phone Watch Repair Tool notes

Kaisi Soldering Tools w/ Desoldering Pump
Kaisi Professional Solder Auxiliary Tool 6 piece double-sided repair tool with Desoldering Wick & Desoldering Pump notes

Craft Knife Set
Precision Craft Knife Set 52pcs Professional Razor Sharp Knives for Art, Hobby notes

Sudake SDK07 test clips
10X Universal Chip clamp micro IC clamp SOP SOIC TSOP MSOP SSOP SMD IC Test Clip pin Socket Adpter Programmer for logic analyzer notes

Sudake SDK08 test clips
10pcs x Universal Chip IC clamp SOP SOIC TSOP MSOP SSOP SMD IC Test Clip Socket Adpter Programmer for logic analyzer notes

Magnetic/Claw Pickup Tool
Magnetic Pick Up Tool LED Light Magnet 4 Claw Flexible Telescopic Grabber 62cm notes

‎SWANLAKE Telescopic Magnetic Pick Up Tool
Telescopic Magnetic Pick Up & Swivel Inspection Mirror Set Round, Round Mirror Pen Style Magnet Auto Hand Tools notes

‎SWANLAKE Telescopic Swivel Inspection Mirror
Telescopic Magnetic Pick Up & Swivel Inspection Mirror Set Round, Round Mirror Pen Style Magnet Auto Hand Tools notes

Digital meter
Digital Voltmeter Ammeter DC 100V 10A Amp Voltage Current Meter Tester 0.28 Inch Dual LED Display Panel with Connect Wires

Telescopic magnet
1pc 8lb Orange Red Handle Magnetic Pickup Stainless Steel Antenna Retractable Suction Iron Rod Strong Magnetic Suction Rod Tools

Dismantling tools
22 In 1 Multifunctional Disassembly Tool Mobile Phone iPad Laptop Screwdriver Maintenance Kit Repair Tools Opening Set For Hand

Telescopic Magnetic Pickup w/ Light
Telescopic Pickup Magnetic Iron Rod Household Automotive Repair And Inspection Tool Strong Magnetic Metal Screw Suction Rod

Knife blades
100/50pcs Knife DIY Wood Carving Fruit Food Scalpel Craft Sculpture Cutting Tool Metal Engraving Blades Knifes Wood Carving Disc

Multifunction Hooks
4Pcs 160mm Car Auto Vehicle Oil Seal Screwdrivers Set O Ring Gasket Puller Remover Pick Hooks Multifunction Tools

Spudger set
5PCs Car Audio Trim Removal Tool Kit Anti-Scratch Pry Applicable Car Door Panel and Audio Dashboard

IC Chip Pickup Tool
IC Chip Pickup Tools Pen Extractor Electronic Parts Gripper Electronic Repair Tools

Metal spudgers
6PCS Metal Crowbar with Two Ends Universal Mobile Phone Digital Home Appliance Product Dismantling Stick Shell Opening Tool

Victorinox Swiss Champ Red Swiss Army Knife
VICTORINOX SWISS CHAMP RED – SWISS ARMY POCKET KNIFE – LENGTH: 91 MM – 33 TOOLS notes

Scotch Titanium Scissors
3M Scotch Precision Ultra Edge Titanium 8″ Scissors Stay Sharp Smooth Cutting notes

DT830B Digital Multimeter
DT830B AC/DC LCD Digital Multimeter 750/1000V Voltmeter Ammeter Ohm Tester High Safety Handheld Meter Digital Multimeter notes

Propagation of electricity

Thanks to Craig for referring me to Brian Haidet’s AlphaPhoenix channel.

I found the following four videos on the AlphaPhoenix channel explaining various aspects of the propagation of electricity, which goes some way to explaining how the high impedance headphone might work in my 10in1 2/10 project.

While watching the videos I discovered that Brian’s oscilloscope is a Siglent SDS1104X-E (100 MHz) Oscilloscope, a pretty nice looking bit of kit!