Generating Temperature Data with Data Diluvium for Time Series Data with TimeScaleDB

Following up on my previous post about adding humidity data generation to Data Diluvium, I’m now adding temperature data generation. This completes the pair of environmental data generators I needed for my TimeScale DB setup. Temperature data is crucial for time-series analysis and works perfectly alongside the humidity data we just implemented.

Why Temperature Data?

When working with TimeScale DB for time-series data, having realistic environmental data is crucial. I’ve found that temperature is one of the most fundamental environmental parameters we measure. Having realistic temperature data is essential for:

  • Weather simulation systems
  • Climate modeling
  • Building automation systems
  • Agricultural planning
  • Energy consumption analysis

The Implementation

I created a temperature generator that produces realistic values based on typical Earth conditions. Here’s what I considered:

  • Average temperature ranges (typically -10°C to 35°C for most inhabited areas)
  • Daily temp cycles (warmer in afternoon, cooler at night)
  • Seasonal variations
  • Geographic influences

At least, I’m aiming to include all those, hopefully I can get all these criteria in there in one code session!

Here’s how I implemented this in Data Diluvium:

export const temperatureGenerator: GeneratorConfig = {
  name: 'Temperature',
  description: 'Generates realistic temperature values with daily and seasonal variations',
  category: 'number',
  compatibleTypes: [
    'NUMBER', 'DECIMAL', 'NUMERIC', 'FLOAT', 'DOUBLE',
    'NUMBER(5,2)', 'DECIMAL(5,2)', 'NUMERIC(5,2)'
  ],
  defaultOptions: {
    minTemperature: -10,
    maxTemperature: 35,
    includeTimeVariation: true,
    includeSeasonalVariation: true,
    useCelsius: true
  },
  generate: async (count: number, options?: GeneratorOptions) => {
    const finalOptions = { ...temperatureGenerator.defaultOptions, ...options };

    return Array.from({ length: count }, () => {
      let baseTemperature = finalOptions.minTemperature! +
        (Math.random() * (finalOptions.maxTemperature! - finalOptions.minTemperature!));

      if (finalOptions.includeTimeVariation) {
        // Add daily variation (warmer in afternoon, cooler at night)
        const hour = new Date().getHours();
        const timeFactor = Math.sin((hour - 14) * Math.PI / 12); // Peak at 2 PM
        baseTemperature += timeFactor * 8; // 8°C daily variation
      }

      if (finalOptions.includeSeasonalVariation) {
        // Add seasonal variation (warmer in summer, cooler in winter)
        const month = new Date().getMonth();
        const seasonalFactor = Math.sin((month - 6) * Math.PI / 6); // Peak in July
        baseTemperature += seasonalFactor * 15; // 15°C seasonal variation
      }

      // Ensure the value stays within bounds
      baseTemperature = Math.max(finalOptions.minTemperature!, Math.min(finalOptions.maxTemperature!, baseTemperature));

      // Convert to Fahrenheit if needed
      return finalOptions.useCelsius ? baseTemperature : (baseTemperature * 9/5) + 32;
    });
  }
};

Using the Generator with TimeScale DB

I’ve made it easy to use this generator in your Data Diluvium configuration like this:

{
  "generator": "temperature",
  "options": {
    "minTemperature": -5,
    "maxTemperature": 30,
    "includeTimeVariation": true,
    "includeSeasonalVariation": true,
    "useCelsius": true
  }
}

This configuration works perfectly with TimeScale DB’s time-series capabilities, allowing you to generate continuous temperature data that follows natural patterns over time. When used alongside the humidity generator, you can create comprehensive environmental datasets.

What Makes This Implementation Special?

I’ve designed this implementation with several key features that work well with time-series databases:

  1. Realistic Ranges: I set the default range of -10°C to 35°C to cover most inhabited areas on Earth.
  2. Time-Aware: The generator considers daily patterns, producing warmer values in the afternoon and cooler values at night.
  3. Seasonal Awareness: Values naturally vary with the seasons, warmer in summer and cooler in winter.
  4. Unit Flexibility: I’ve added support for both Celsius and Fahrenheit temperature scales.
  5. Type Compatibility: The generator supports various numeric SQL types including NUMBER, DECIMAL, NUMERIC, FLOAT, and DOUBLE.

Testing the Generator

I’ve implemented comprehensive testing to ensure our temperature generator produces realistic values that will work well with TimeScale DB:

describe('Temperature Generator', () => {
  it('should generate values within specified range', () => {
    const value = generateTemperature({
      minTemperature: 15,
      maxTemperature: 25
    });
    expect(value).toBeGreaterThanOrEqual(15);
    expect(value).toBeLessThanOrEqual(25);
  });

  it('should respect time-based variations', () => {
    const morningValue = generateTemperature({ includeTimeVariation: true });
    const afternoonValue = generateTemperature({ includeTimeVariation: true });
    expect(afternoonValue).toBeGreaterThan(morningValue);
  });

  it('should convert between Celsius and Fahrenheit', () => {
    const celsiusValue = generateTemperature({ useCelsius: true });
    const fahrenheitValue = generateTemperature({ useCelsius: false });
    expect(fahrenheitValue).toBeCloseTo((celsiusValue * 9/5) + 32, 1);
  });
});

String-Based Temperature Generators

While the numeric temperature generator is perfect for database storage and calculations, I also needed string-based temperature generators for display and reporting purposes. I’ve added two new generators:

Celsius String Generator

export const celsiusStringGenerator: GeneratorConfig = {
  name: 'Temperature (Celsius String)',
  description: 'Generates temperature values as strings with °C suffix',
  category: 'text',
  compatibleTypes: [
    'CHAR', 'VARCHAR', 'VARCHAR2', 'TEXT', 'STRING',
    'CHARACTER VARYING'
  ],
  defaultOptions: {
    minTemperature: -10,
    maxTemperature: 35,
    includeTimeVariation: true,
    includeSeasonalVariation: true,
    decimalPlaces: 1
  },
  generate: async (count: number, options?: GeneratorOptions) => {
    const finalOptions = { ...celsiusStringGenerator.defaultOptions, ...options };

    return Array.from({ length: count }, () => {
      let baseTemperature = finalOptions.minTemperature! +
        (Math.random() * (finalOptions.maxTemperature! - finalOptions.minTemperature!));

      if (finalOptions.includeTimeVariation) {
        const hour = new Date().getHours();
        const timeFactor = Math.sin((hour - 14) * Math.PI / 12);
        baseTemperature += timeFactor * 8;
      }

      if (finalOptions.includeSeasonalVariation) {
        const month = new Date().getMonth();
        const seasonalFactor = Math.sin((month - 6) * Math.PI / 6);
        baseTemperature += seasonalFactor * 15;
      }

      baseTemperature = Math.max(finalOptions.minTemperature!, Math.min(finalOptions.maxTemperature!, baseTemperature));

      return `${baseTemperature.toFixed(finalOptions.decimalPlaces!)}°C`;
    });
  }
};

Fahrenheit String Generator

export const fahrenheitStringGenerator: GeneratorConfig = {
  name: 'Temperature (Fahrenheit String)',
  description: 'Generates temperature values as strings with °F suffix',
  category: 'text',
  compatibleTypes: [
    'CHAR', 'VARCHAR', 'VARCHAR2', 'TEXT', 'STRING',
    'CHARACTER VARYING'
  ],
  defaultOptions: {
    minTemperature: 14, // 57.2°F
    maxTemperature: 95, // 203°F
    includeTimeVariation: true,
    includeSeasonalVariation: true,
    decimalPlaces: 1
  },
  generate: async (count: number, options?: GeneratorOptions) => {
    const finalOptions = { ...fahrenheitStringGenerator.defaultOptions, ...options };

    return Array.from({ length: count }, () => {
      let baseTemperature = finalOptions.minTemperature! +
        (Math.random() * (finalOptions.maxTemperature! - finalOptions.minTemperature!));

      if (finalOptions.includeTimeVariation) {
        const hour = new Date().getHours();
        const timeFactor = Math.sin((hour - 14) * Math.PI / 12);
        baseTemperature += timeFactor * 14.4; // 8°C = 14.4°F
      }

      if (finalOptions.includeSeasonalVariation) {
        const month = new Date().getMonth();
        const seasonalFactor = Math.sin((month - 6) * Math.PI / 6);
        baseTemperature += seasonalFactor * 27; // 15°C = 27°F
      }

      baseTemperature = Math.max(finalOptions.minTemperature!, Math.min(finalOptions.maxTemperature!, baseTemperature));

      return `${baseTemperature.toFixed(finalOptions.decimalPlaces!)}°F`;
    });
  }
};

These string-based generators are particularly useful for:

  • Displaying temperatures in reports
  • Creating human-readable logs
  • Generating sample data for UI testing
  • Creating documentation examples

You can use them in your Data Diluvium configuration like this:

{
  "generator": "temperature-celsius-string",
  "options": {
    "minTemperature": -5,
    "maxTemperature": 30,
    "includeTimeVariation": true,
    "includeSeasonalVariation": true,
    "decimalPlaces": 1
  }
}

or for fahrenheit:

{
  "generator": "temperature-fahrenheit-string",
  "options": {
    "minTemperature": 23,
    "maxTemperature": 86,
    "includeTimeVariation": true,
    "includeSeasonalVariation": true,
    "decimalPlaces": 1
  }
}

The examples here are of course if you’re running the site code itself. Otherwise navigate over to https://datadiluvium.com and you can just get the data generated on the site, as I’ve pushed this feature to prod and it’s good to go!

The data when generated per my sample schema looks like this.

That should do it!

Happy thrashing coding! 🌡️ Next post coming up will be the next steps in the TimeScaleDB sample I started in this post.

Generating Realistic Humidity Data for TimeScale DB with Data Diluvium

For next steps of why I set up TimeScale DB up for local dev, and being able to just do things, I need two new data generators over on Data Diluvium. One for humidity, which will be this post, and one for temperature, which will be next.

Why Humidity Data?

When working with TimeScale DB for time-series data, having realistic environmental data is crucial. I’ve found that humidity is a particularly important parameter that affects everything from agriculture to HVAC systems. Having realistic humidity data is essential for:

  • Testing environmental monitoring systems
  • Simulating weather conditions
  • Developing IoT applications
  • Training machine learning models for climate prediction

The Implementation

I created a humidity generator that produces realistic values based on typical Earth conditions. Here’s what I considered:

  • Average humidity ranges (typically 30-70% for most inhabited areas)
  • Daily variations (higher in the morning, lower in the afternoon)
  • Seasonal patterns
  • Geographic influences

With the definition of what needs to be generated, I created a table schema for Data Diluvium that would use this (and the temperature) data generators.

CREATE TABLE TestingHumidityAndTemperature (
    Identifier UUID PRIMARY KEY,
    StampInTime DATETIME,
    Temperature DOUBLE,
    Humidity DOUBLE
);

Since both Temperature and Humidity generators will be double values, to test humidity while we implement, I’ll just set temperature to humidity too.

The Data Diluvium App Code

Here’s how I implemented this in Data Diluvium:

export const humidityGenerator: GeneratorConfig = {
  name: 'Humidity',
  description: 'Generates realistic humidity values with daily and seasonal variations',
  category: 'number',
  compatibleTypes: [
    'NUMBER', 'DECIMAL', 'NUMERIC', 'FLOAT', 'DOUBLE',
    'NUMBER(5,2)', 'DECIMAL(5,2)', 'NUMERIC(5,2)'
  ],
  defaultOptions: {
    minHumidity: 30,
    maxHumidity: 70,
    includeTimeVariation: true,
    includeSeasonalVariation: true
  },
  generate: async (count: number, options?: GeneratorOptions) => {
    const finalOptions = { ...humidityGenerator.defaultOptions, ...options };

    return Array.from({ length: count }, () => {
      let baseHumidity = finalOptions.minHumidity! +
        (Math.random() * (finalOptions.maxHumidity! - finalOptions.minHumidity!));

      if (finalOptions.includeTimeVariation) {
        // Add daily variation (higher in morning, lower in afternoon)
        const hour = new Date().getHours();
        const timeFactor = Math.sin((hour - 6) * Math.PI / 12); // Peak at 6 AM
        baseHumidity += timeFactor * 10;
      }

      if (finalOptions.includeSeasonalVariation) {
        // Add seasonal variation (higher in winter, lower in summer)
        const month = new Date().getMonth();
        const seasonalFactor = Math.sin((month - 1) * Math.PI / 6); // Peak in January
        baseHumidity += seasonalFactor * 5;
      }

      // Ensure the value stays within bounds
      return Math.max(finalOptions.minHumidity!, Math.min(finalOptions.maxHumidity!, baseHumidity));
    });
  }
};

Using the Generator with TimeScale DB

I’ve made it easy to use this generator in your Data Diluvium configuration like this:

{
  "generator": "humidity",
  "options": {
    "minHumidity": 25,
    "maxHumidity": 75,
    "includeTimeVariation": true,
    "includeSeasonalVariation": true
  }
}

This configuration works perfectly with TimeScale DB’s time-series capabilities, allowing you to generate continuous humidity data that follows natural patterns over time.

What Makes This Implementation Special?

I’ve designed this implementation with several key features that work well with time-series databases:

  1. Realistic Ranges: I set the default range of 30-70% to cover most inhabited areas on Earth.
  2. Time-Aware: The generator considers daily patterns, producing higher values in the morning and lower values in the afternoon.
  3. Seasonal Awareness: Values naturally vary with the seasons, higher in winter and lower in summer.
  4. Flexible Configuration: I’ve made it easy to customize the ranges and toggle features as needed.
  5. Type Compatibility: The generator supports various numeric SQL types including NUMBER, DECIMAL, NUMERIC, FLOAT, and DOUBLE.

Testing the Generator

I’ve implemented comprehensive testing to ensure our humidity generator produces realistic values that will work well with TimeScale DB:

describe('Humidity Generator', () => {
  it('should generate values within specified range', () => {
    const value = generateHumidity({
      minHumidity: 40,
      maxHumidity: 60
    });
    expect(value).toBeGreaterThanOrEqual(40);
    expect(value).toBeLessThanOrEqual(60);
  });

  it('should respect time-based variations', () => {
    const morningValue = generateHumidity({ includeTimeVariation: true });
    const afternoonValue = generateHumidity({ includeTimeVariation: true });
    expect(morningValue).toBeGreaterThan(afternoonValue);
  });
});

Alright, next up I’m going to test this and see what I get. Clicking over to the generate data tab it looks like the data is generating as expected and what is being generated will work for what I need.

Clicking through again to generate data, the humidity settings look mostly ok. I think I’ll come back to this after a while, and maybe change some parameters. But for now, this is good for what I’ll need for further testing and development.

Next up I’ll add the temperature generator, tweak them until they’re effective, and will get a feature addition up at https://datadiluvium.com and you too can give em’ a try!

With that, until next time happy thrashing coding! 🚀

Setup TimescaleDB with Docker Compose: A Step-by-Step Guide

This tutorial will guide you through setting up and using TimescaleDB using Docker Compose.

Prerequisites

  • Docker installed on your system
  • Docker Compose installed on your system

Getting Started

  1. Start the TimescaleDB Container

    Navigate to the directory containing the docker-compose.yml file and run:

    docker-compose up -d
    

    This will start TimescaleDB in detached mode. The database will be accessible on port 5432.

  2. Connection Details

    • Host: localhost
    • Port: 5432
    • Database: timescale
    • Username: timescale
    • Password: timescale
  3. Verify the Installation

    You can connect to the database using psql or any PostgreSQL client:

    docker exec -it timescale-timescaledb-1 psql -U timescale -d timescale
    

    Once connected, you can verify TimescaleDB is properly installed:

    SELECT default_version, installed_extensions FROM pg_available_extensions WHERE name = 'timescaledb';
    
  4. Create Your First Hypertable

    -- Create a regular table
    CREATE TABLE sensor_data (
        time        TIMESTAMPTZ       NOT NULL,
        sensor_id   TEXT             NOT NULL,
        temperature DOUBLE PRECISION  NULL,
        humidity    DOUBLE PRECISION  NULL
    );
    
    -- Convert it to a hypertable
    SELECT create_hypertable('sensor_data', 'time');
    
    -- Create an index
    CREATE INDEX ON sensor_data (sensor_id, time DESC);
    
  5. Insert Some Test Data

    -- Insert sample data
    INSERT INTO sensor_data (time, sensor_id, temperature, humidity)
    VALUES
        (NOW(), 'sensor_1', 23.5, 45.0),
        (NOW(), 'sensor_2', 24.1, 46.2),
        (NOW(), 'sensor_1', 23.8, 45.5);
    
  6. Query Your Data

    -- Basic query
    SELECT * FROM sensor_data ORDER BY time DESC;
    
    -- Time-bucket query (aggregate data into 1-hour buckets)
    SELECT time_bucket('1 hour', time) AS hour,
           sensor_id,
           avg(temperature) as avg_temp,
           avg(humidity) as avg_humidity
    FROM sensor_data
    GROUP BY hour, sensor_id
    ORDER BY hour DESC;
    

Stopping the Database

To stop the TimescaleDB container:

docker-compose down

To stop the container and remove the volume (this will delete all data):

docker-compose down -v

Additional Resources

A Little Lagniappe: Running Multiple PostgreSQL Instances

Hey, here’s a common scenario you might run into. You’re working on multiple projects (because who isn’t these days?), and you’ve already got a PostgreSQL instance running on the default port 5432. In my case, I’ve got a core platform database running there:

$ docker ps | grep 5432
96e464b414f0   postgres:latest   "docker-entrypoint.s…"   Up 8 days   0.0.0.0:5432->5432/tcp   a-core-platform-db

No problem! PostgreSQL (and by extension, TimescaleDB) is perfectly happy running on different ports. Here’s how we handle this:

  1. Check Your Ports First

    $ lsof -i :5432
    # This will show you what's using the default PostgreSQL port
    
  2. Modify the Port Mapping Instead of the standard port mapping, we’ll shift TimescaleDB to 5433:

    ports:
      - "5433:5432"
    

    Note that we’re mapping port 5433 on the host to 5432 in the container. The container still thinks it’s using 5432 (PostgreSQL’s default), but we access it through 5433 on our machine.

  3. Connection Details Now you’ve got two separate PostgreSQL instances:

    • Core Platform DB: localhost:5432
    • TimescaleDB: localhost:5433
  4. Using Different Ports in Your Tools

    • psql: psql -h localhost -p 5433 -U timescale timescale
    • Connection strings: postgresql://timescale:timescale@localhost:5433/timescale
    • GUI tools: Just remember to use port 5433 for TimescaleDB connections

This setup is perfect for:

  • Running multiple projects simultaneously
  • Testing different PostgreSQL-based databases
  • Keeping your development environments isolated
  • Not breaking existing applications that expect PostgreSQL on 5432

Remember, you can run as many PostgreSQL instances as you want (well, as many as your system resources allow), just make sure each one has its own port. I’ve seen setups with half a dozen different PostgreSQL instances, each serving a different purpose. Just keep track of what’s running where!

Staying in Software Dev? Best be able to just do things!

I sat down recently and started reading through some articles. Of all the articles of the 20 or so I was reading, one that stood out from the bunch was something Geoffrey Huntley wrote. In the article “The future belongs to people who can just do things” he brings up some points that I – and I think a LOT of people out there like Geoffrey and I – have been thinking in the preceding months. Let’s delve into a few of those thoughts, paraphrased, and elaborated on.

  • First and foremost, for those coders that have been making a living writing those artisanal, bespoke, hand crafted, single lines of thought out code – your time is nigh.
  • Second, if you’re one of those coders that churns out code, but you don’t care or don’t think about the bigger picture of the product you’re working on, you’re also in for a rude awakening.
  • Third, if you have your environment or your stack that you build with, and don’t explore much beyond that stack (i.e. you’re specialized in .NET or Java or iOS) and rarely touch anything outside of that singular stack, you’re running straight at a brick wall.
  • Fourth, if you’re pedantic about every line of code, every single feature, in a way that doesn’t further progress product but you love to climb up on that hill to die arguing about the state of the code base, you’re going to be left up on the hill to starve to death.

Beyond the developers. If you’re a technical product manager and can’t implement, or coder and can’t product, if you don’t understand the overlap then I’d bet you’ll run into some very serious issues in the coming years. If you’re a manager get ready to mitigate all of the above, and above all get ready to deal with a lot of upheaval. If you still focus on hiring the above focused and inflexible engineers, you’re likely to be falling on that sword for your team. Needless to say, there are very rough waters ahead.

That paints the picture of where the industry is right now and who is at greatest risk. Cast out and unable to realign and move forward with the industry – nay – the world in the coming weeks, months, and years. I’m not even going to mention why, what for, or how we got here. That’s a whole other article. I’m just going to focus on the now and the future.

It appears, as one common aside points out, that the future is with the redefined purpose and role that a “Product Engineer” would be. I could immediately pick this apart and say it may be too specific. I could also rant about what “product” means and what “engineer” means and that it misleads in context to programming. So I’ll elaborate to help stave off the pedantic soul that can’t think in an elaborative and systemic way.

Product Engineer

What I mean when I write “Product Engineer” is a melding of many levels and scope that we currently have in modern software development. It’s the rolling together in a mutative and advancing way the positions of product, engineering, QA, SRE, design, user experience, architecture, and all sorts of peripheral jobs around creating software into one role. Those that can take this role and run with it will be the ones that are the most successful in the coming years.

As Geoffrey titled his post, “The future belongs to those who can just do things“.

For many, I’d sadly argue a larger majority of folks than most, those on the “not prepared” side of the equation far outweigh those on the side of the “prepared” side. I’m not saying that the “not prepared” folks are going to be out of a job tomorrow, but I am saying that they’re going to be left behind. They’re going to be the ones that are going to be the first to be let go when the next round of layoffs come around. They’re going to be the ones that are going to be the first to be passed over for promotions. They’re going to be the ones that are going to be the first to be left behind when the company they’re working for decides to pivot to a new technology or a new way of doing things.

So what to do? How to prepare? How to get ready for the future?

You need to be able to do things. You need to be able to take a problem, break it down, and solve it. You need to be able to take a project, break it down, and deliver it. You need to be able to take a product, break it down, and improve it. You need to be able to take a team, break it down, and lead it. You need to be able to take a company, break it down, and grow it.

One thing that immediately pops into mind is something that almost all veterans attain, the skills they teach every prospective soldier going through boot camp. You need to be able to adapt and overcome. These are the things you need to do before you even sit down and start studying about that next tool or tech stack to get things done with.

Once you feel like you’ve gotten pretty good at breaking down a problem, a project, product, team, or company, then you need to start learning how to do it most effectively through the tooling that is out there. Working toward getting better and better at its use every day. Understanding what it really is and what it’s doing, all while not falling prey to the marketecture talk of the magic brains in the sky clouds nonsense.

Things don’t end there however. You’ve got to go beyond just breaking down something and implementation, you also need to really dig into why you break things down and how and why you’re delivering it the way you are. Without, and much of the tooling and technologies being created today are going to leave you on the sidewalk with a cup in hand hoping that it’s all quarters being dropped in.

Retro

In retrospect, I’m not saying hustle (not necessary unless that’s your juice, then go on). I’m not saying work yourself to the bone here. What I’m saying is – if you want to stay in tech at this juncture in time and into the future. It is absolutely fundamental to think from a systemic perspective, and understand the larger scale strategic reasoning behind what you’re doing. The reason being, in the coming weeks, months, and years what you will be able to do with tech innovations is so far beyond what we have been doing that you’ll need to be responsible for vastly expanded aspects of the process. You’ll need to understand market, product, fit, design, engineering, and more because working silo’d at this point isn’t going to be an option. Companies that silo the departmental cross functions are going to get ripped asunder if they can’t re-integrate those groups into a cohesive functioning unit.

These thoughts dovetail the next post up that I’ve got on the enshittification of the tech industry and how all this will likely make it worse, but it’ll eventually get better. This era is providing a chance to stand out with what you create in a way so you don’t add to the enshittification of the world. It’ll likely be one of the key differentiators in the coming years.

Anyway, agree or disagree, hate what I’ve written here? Tell me I’m wrong, or maybe you agree? Leave a comment here there or wherever and let’s discuss. I’m game to change the shape of my opinion here but it’ll take your input.

Data Diluvium Utility, Schema, Notes, & Wrap Up

In my previous three posts, I covered the core functionality of DataDiluvium. In this follow-up post, I’ll explore the additional features, utilities, and implementation details that I’ve added to enhance the application’s functionality and developer experience.

SQL Sample Files

1. Sample Schema Repository

I’ve included a collection of sample SQL schemas in the sql-samples directory. These samples serve multiple purposes:

  1. Documentation examples
  2. Testing scenarios
  3. Quick-start templates for users

Here’s an example from the users table:

CREATE TABLE users (
    id INT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

Testing Infrastructure

1. Jest Configuration

I’ve set up the testing environment in jest.config.js and jest.setup.js:

module.exports = {
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  },
  testMatch: ['**/__tests__/**/*.test.[jt]s?(x)'],
};

2. Test Setup

I’ve added additional test configuration in jest.setup.js:

import '@testing-library/jest-dom';

// Mock localStorage
const localStorageMock = {
  getItem: jest.fn(),
  setItem: jest.fn(),
  clear: jest.fn(),
};
global.localStorage = localStorageMock;

ESLint Configuration

1. ESLint Rules

I’ve configured ESLint in .eslintrc.json with custom rules for the project:

{
  "extends": [
    "next/core-web-vitals",
    "plugin:@typescript-eslint/recommended"
  ],
  "rules": {
    "@typescript-eslint/no-explicit-any": "warn",
    "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }]
  }
}

2. Additional ESLint Config

I’ve also added a separate eslint.config.mjs for modern ESLint configuration:

export default [
  {
    files: ['**/*.{js,jsx,ts,tsx}'],
    rules: {
      'no-console': ['warn', { allow: ['warn', 'error'] }],
      'react-hooks/rules-of-hooks': 'error',
      'react-hooks/exhaustive-deps': 'warn'
    }
  }
];

Component Library

1. Core Components

I’ve built several core components in src/app/components:

  1. SchemaInput Component:
// src/app/components/SchemaInput.tsx
export function SchemaInput({
  value,
  onChange,
  ...props
}: SchemaInputProps) {
  return (
    <textarea
      aria-label="SQL Schema Input"
      role="textbox"
      aria-multiline="true"
      aria-describedby="schema-help"
      className="w-full h-64 p-4 font-mono text-sm border rounded-md"
      value={value}
      onChange={onChange}
      {...props}
    />
  );
}
  1. Navigation Component:
// src/app/components/Navigation.tsx
export function Navigation() {
  return (
    <nav
      role="navigation"
      aria-label="Main navigation"
      tabIndex={0}
      className="fixed left-0 top-0 h-full w-48 bg-white dark:bg-gray-900 border-r border-gray-200 dark:border-gray-800"
    >
      {/* Navigation items */}
    </nav>
  );
}

Performance Optimizations

1. Code Splitting

I’ve implemented Next.js’s built-in code splitting features:

// src/app/generate/page.tsx
import dynamic from 'next/dynamic';

const SchemaPreview = dynamic(() => import('../components/SchemaPreview'), {
  loading: () => <div>Loading preview...</div>
});

2. Memoization

I’ve used React memo and useMemo for performance optimization:

// src/app/components/DataGrid.tsx
const MemoizedRow = React.memo(function Row({ data, columns }) {
  return (
    <tr>
      {columns.map(column => (
        <td key={column.name}>{data[column.name]}</td>
      ))}
    </tr>
  );
});

Accessibility Features

1. ARIA Labels and Roles

I’ve added proper accessibility attributes throughout the application:

// src/app/components/SchemaInput.tsx
<textarea
  aria-label="SQL Schema Input"
  role="textbox"
  aria-multiline="true"
  aria-describedby="schema-help"
  {...props}
/>

2. Keyboard Navigation

I’ve implemented keyboard navigation support:

// src/app/components/Navigation.tsx
<nav
  role="navigation"
  aria-label="Main navigation"
  tabIndex={0}
>
  {/* Navigation items */}
</nav>

Conclusion

I’ve added these features and implementation details to make DataDiluvium a robust and maintainable application. The peripheral features enhance:

  • Developer experience through comprehensive testing and linting
  • User experience through accessibility and performance optimizations
  • Code quality through utility functions and reusable components
  • Documentation through sample files and type definitions