Database Schema Designer
Run ID: 69cb9cbb61b1021a29a8aa552026-03-31Development
PantheraHive BOS
BOS Dashboard

Database Schema Design & DDL Generation

This document presents a comprehensive and detailed database schema design, specifically tailored for a robust E-commerce application. Following industry best practices, the schema emphasizes data integrity, scalability, and ease of maintenance. This deliverable includes the Data Definition Language (DDL) SQL scripts for creating the proposed schema, along with detailed explanations and rationale for each design choice.


1. Introduction

As part of the "Database Schema Designer" workflow, this step focuses on generating the foundational code for your application's data layer. We have designed a relational database schema that supports core E-commerce functionalities, including user management, product catalog, order processing, and category organization. The generated DDL scripts are production-ready and compatible with PostgreSQL, a leading open-source relational database system.


2. Core Schema Design Principles

Our design adheres to the following principles to ensure a high-quality and performant database:

* Primary Keys (PK): Uniquely identify each record in a table.

* Foreign Keys (FK): Enforce referential integrity, ensuring relationships between tables are valid.

* NOT NULL Constraints: Guarantee essential data is always present.

* UNIQUE Constraints: Prevent duplicate values in specified columns.

* CHECK Constraints: (Implicitly handled by data types or explicitly added for specific business rules).


3. Proposed E-commerce Database Schema Overview

The E-commerce schema comprises five core tables, representing key entities and their relationships:

Entity-Relationship Diagram (Conceptual)

text • 1,952 chars
+-----------+       +------------+       +----------+       +-----------+
|   users   |       | categories |       | products |       |   orders  |
|-----------|       |------------|       |----------|       |-----------|
| user_id PK|----<  | category_id PK|----<| product_id PK|---<| order_id PK|
| username  |       | category_name|       | product_name|    | user_id FK|
| email     |       | description |       | description |    | order_date|
| password  |       +------------+       | price       |    | total_amount|
| ...       |                            | stock_qty   |    | status    |
| created_at|                            | category_id FK|   | ...       |
| updated_at|                            | created_at  |    | created_at|
+-----------+                            | updated_at  |    | updated_at|
                                         +----------+       +-----------+
                                                                  |
                                                                  | Many-to-Many via
                                                                  | `order_items`
                                                                  v
                                                             +-------------+
                                                             | order_items |
                                                             |-------------|
                                                             | order_item_id PK|
                                                             | order_id FK |-----> orders.order_id
                                                             | product_id FK |-----> products.product_id
                                                             | quantity    |
                                                             | price_at_purchase|
                                                             +-------------+
Sandboxed live preview

Database Schema Designer: Detailed Study Plan

This comprehensive study plan is designed to guide you through the process of becoming proficient in database schema design. It covers fundamental concepts, advanced techniques, and practical application, structured over a 12-week period.


1. Introduction and Program Overview

Database schema design is the blueprint for how data is structured, stored, and managed within a database. A well-designed schema ensures data integrity, optimizes performance, and facilitates future scalability and maintenance. This plan will equip you with the knowledge and practical skills to design robust and efficient database schemas for various applications.

Goal: To enable you to design, implement, and optimize relational database schemas that are performant, scalable, maintainable, and adhere to industry best practices.


2. Weekly Schedule

This 12-week schedule provides a structured progression through key topics in database schema design. Each week includes core concepts and practical application.

  • Week 1: Introduction to Databases & Relational Model

* Topics: What is a database? Types of databases (RDBMS vs. NoSQL overview). Fundamentals of the Relational Model: Tables, Rows, Columns, Keys (Primary, Foreign, Composite). Basic SQL DDL/DML: CREATE TABLE, INSERT, SELECT.

* Focus: Understanding the foundational building blocks of relational databases.

  • Week 2: Entity-Relationship (ER) Modeling Fundamentals

* Topics: Introduction to ER modeling. Entities, Attributes (simple, composite, multi-valued), Relationships. Cardinality (One-to-One, One-to-Many, Many-to-Many) and Modality (Optional/Mandatory). Drawing ER diagrams using Crow's Foot notation.

* Focus: Translating real-world requirements into a conceptual data model.

  • Week 3: Advanced ER Modeling & Conceptual Design

* Topics: Weak entities. Generalization/Specialization (Supertype/Subtype relationships). Recursive relationships. Introduction to Conceptual, Logical, and Physical Design phases.

* Focus: Handling complex data relationships and understanding the design lifecycle.

  • Week 4: Normalization - Part 1 (1NF, 2NF, 3NF)

* Topics: Purpose and benefits of normalization. Functional dependencies. First Normal Form (1NF). Second Normal Form (2NF). Third Normal Form (3NF).

* Focus: Eliminating data redundancy and improving data integrity up to 3NF.

  • Week 5: Normalization - Part 2 (BCNF, 4NF, 5NF) & Denormalization

* Topics: Boyce-Codd Normal Form (BCNF). Introduction to 4NF and 5NF. Denormalization strategies: when and why to denormalize for performance.

* Focus: Advanced normalization and practical considerations for performance vs. integrity.

  • Week 6: SQL DDL for Schema Implementation

* Topics: Translating logical design to physical schema. CREATE TABLE, ALTER TABLE, DROP TABLE statements. Implementing various constraints: PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK, DEFAULT.

* Focus: Hands-on implementation of schemas using SQL.

  • Week 7: Indexing Strategies & Performance Optimization

* Topics: Understanding indexes (B-tree, Hash). Clustered vs. Non-clustered indexes. When and what to index. Analyzing query execution plans. Basic partitioning concepts.

* Focus: Optimizing query performance and understanding the impact of physical design choices.

  • Week 8: Database Security & Integrity

* Topics: User accounts, roles, and privileges. Data encryption at rest and in transit (conceptual). Transaction management (ACID properties). Backup and recovery basics (conceptual).

* Focus: Ensuring data security, reliability, and transactional consistency.

  • Week 9: Data Warehousing & OLAP Concepts

* Topics: Introduction to Data Warehousing. OLTP vs. OLAP. Dimensional modeling: Star Schema and Snowflake Schema. Fact tables and Dimension tables.

* Focus: Designing schemas for analytical purposes and business intelligence.

  • Week 10: NoSQL Databases & Polyglot Persistence

* Topics: Overview of NoSQL types: Key-Value, Document, Column-Family, Graph databases. CAP Theorem. Schema-less vs. Schema-on-read. When to choose NoSQL over RDBMS.

* Focus: Understanding alternative database paradigms and making informed technology choices.

  • Week 11: Case Studies & Advanced Design Patterns

* Topics: Reviewing real-world schema designs from various industries. Common design patterns (e.g., audit trails, versioning, polymorphic associations). Handling temporal data.

* Focus: Applying learned concepts to complex scenarios and learning from established patterns.

  • Week 12: Capstone Project: Full Schema Design & Implementation

* Topics: Apply all learned concepts to design, document, and implement a complete database schema for a moderately complex business problem.

* Focus: Synthesizing knowledge into a practical, demonstrable project.


3. Learning Objectives

Upon successful completion of this study plan, you will be able to:

  • Conceptualize Data: Understand the fundamental principles of data storage, organization, and retrieval in various database systems.
  • Model Data Effectively: Create accurate and comprehensive Entity-Relationship (ER) diagrams to represent business requirements for both simple and complex scenarios, including advanced relationships.
  • Apply Normalization Principles: Systematically normalize relational schemas to 3NF and BCNF to minimize data redundancy and maximize data integrity, while understanding the trade-offs of denormalization.
  • Translate Designs to Implementation: Convert logical data models into physical database schemas using SQL Data Definition Language (DDL), correctly applying data types, constraints, and relationships.
  • Optimize for Performance: Design and implement indexing strategies, understand query execution plans, and make informed physical design choices to enhance database performance.
  • Ensure Data Integrity & Security: Incorporate mechanisms for data integrity (e.g., referential integrity, check constraints) and understand basic database security principles.
  • Understand Diverse Database Systems: Differentiate between relational and various NoSQL database types, and make informed decisions on when to use each based on specific project requirements.
  • Design for Analytics: Apply dimensional modeling techniques (Star/Snowflake schemas) for data warehousing and analytical applications.
  • Communicate Design Decisions: Document database designs clearly and professionally, justifying design choices based on business requirements and technical considerations.

4. Recommended Resources

Leverage a mix of theoretical and practical resources to deepen your understanding and skills.

  • Books:

* "Database System Concepts" by Silberschatz, Korth, and Sudarshan: A comprehensive academic text for foundational theory.

* "SQL and Relational Theory: How to Write Accurate SQL Code" by C.J. Date: For a deep dive into the relational model and SQL.

* "Refactoring Databases: Evolutionary Design" by Scott W. Ambler and Pramod J. Sadalage: Practical advice on evolving database designs.

* "The Data Warehouse Toolkit" by Ralph Kimball and Margy Ross: Essential for understanding dimensional modeling.

  • Online Courses (e.g., Coursera, edX, Udemy, Pluralsight):

* "Database Management Essentials" (University of Colorado Boulder on Coursera).

* "Databases" (Stanford University on edX).

* Specific courses on SQL, PostgreSQL/MySQL, Database Design, and Data Modeling.

  • Documentation:

* Official documentation for popular RDBMS (e.g., PostgreSQL, MySQL, SQL Server, Oracle).

* Official documentation for NoSQL databases (e.g., MongoDB, Cassandra, Neo4j).

  • Tools:

* ER Diagramming: Lucidchart, draw.io, dbdiagram.io, MySQL Workbench (for MySQL).

* SQL Clients: DBeaver (multi-database), pgAdmin (PostgreSQL), MySQL Workbench (MySQL), Azure Data Studio (SQL Server).

* Practice Environments: DB-Fiddle, SQL Fiddle, online SQL compilers, or local installations of PostgreSQL/MySQL.


5. Milestones

Key checkpoints to track your progress and demonstrate mastery of core concepts.

  • Milestone 1: Conceptual Modeling Proficiency (End of Week 3)

* Deliverable: Create detailed ER diagrams for a moderately complex business scenario (e.g., a library system or a small social network) that includes entities, attributes, various cardinalities, and at least one supertype/subtype relationship.

* Assessment: Review of ER diagram for correctness, completeness, and adherence to notation standards.

  • Milestone 2: Normalization & Logical Design Mastery (End of Week 5)

* Deliverable: Take a denormalized dataset or a business problem description and normalize it step-by-step to 3NF/BCNF, clearly identifying functional dependencies at each stage. Justify any denormalization decisions.

* Assessment: Written explanation and diagrammatic representation of normalization steps, evaluated for accuracy and understanding of principles.

  • Milestone 3: Physical Schema Implementation (End of Week 8)

* Deliverable: Implement a fully functional database schema using SQL DDL for a small application (e.g., a blog, simple e-commerce product catalog, or project management tool). This should include CREATE TABLE statements with appropriate data types, primary keys, foreign keys, unique constraints, and at least two indexes.

* Assessment: Execution of DDL scripts, verification of schema structure, and demonstration of data integrity through sample data insertion.

  • Milestone 4: Comprehensive Database Design Project (End of Week 12)

* Deliverable: Design and implement a complete database schema for

sql

-- DDL Script for E-commerce Database Schema (PostgreSQL)

-- Generated by PantheraHive's Database Schema Designer

-- =============================================================================

-- Drop Tables (if they exist) in reverse dependency order to avoid foreign key

-- constraint issues during development or re-initialization.

-- !! Use with caution in production environments. !!

-- =============================================================================

DROP TABLE IF EXISTS order_items CASCADE;

DROP TABLE IF EXISTS orders CASCADE;

DROP TABLE IF EXISTS products CASCADE;

DROP TABLE IF EXISTS categories CASCADE;

DROP TABLE IF EXISTS users CASCADE;

-- =============================================================================

-- Table: users

-- Description: Stores information about registered users/customers.

-- =============================================================================

CREATE TABLE users (

user_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Unique identifier for the user

username VARCHAR(50) UNIQUE NOT NULL, -- Unique username for login

email VARCHAR(255) UNIQUE NOT NULL, -- Unique email address, used for communication and login

password_hash VARCHAR(255) NOT NULL, -- Hashed password for security

first_name VARCHAR(100), -- User's first name

last_name VARCHAR(100), -- User's last name

address TEXT, -- User's primary shipping address

city VARCHAR(100), -- City part of the address

state VARCHAR(100), -- State/Province part of the address

zip_code VARCHAR(20), -- Zip/Postal code part of the address

country VARCHAR(100), -- Country part of the address

phone_number VARCHAR(20), -- User's phone number

created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), -- Timestamp when the user record was created

updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() -- Timestamp of the last update to the user record

);

COMMENT ON TABLE users IS 'Stores customer and user account information.';

COMMENT ON COLUMN users.user_id IS 'Primary key, unique identifier for each user.';

COMMENT ON COLUMN users.username IS 'Unique username for login purposes.';

COMMENT ON COLUMN users.email IS 'Unique email address, also used for login and notifications.';

COMMENT ON COLUMN users.password_hash IS 'Hashed password for secure authentication.';

COMMENT ON COLUMN users.first_name IS 'User''s given name.';

COMMENT ON COLUMN users.last_name IS 'User''s family name.';

COMMENT ON COLUMN users.address IS 'Primary shipping address.';

COMMENT ON COLUMN users.city IS 'City of the shipping address.';

COMMENT ON COLUMN users.state IS 'State or province of the shipping address.';

COMMENT ON COLUMN users.zip_code IS 'Postal code of the shipping address.';

COMMENT ON COLUMN users.country IS 'Country of the shipping address.';

COMMENT ON COLUMN users.phone_number IS 'User''s contact phone number.';

COMMENT ON COLUMN users.created_at IS 'Timestamp when the user account was created.';

COMMENT ON COLUMN users.updated_at IS 'Timestamp of the last update to the user account details.';

-- =============================================================================

-- Table: categories

-- Description: Defines product categories to organize the product catalog.

-- =============================================================================

CREATE TABLE categories (

category_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Unique identifier for the category

category_name VARCHAR(100) UNIQUE NOT NULL, -- Name of the category (e.g., "Electronics", "Books")

description TEXT -- A brief description of the category

);

COMMENT ON TABLE categories IS 'Organizes products into logical categories.';

COMMENT ON COLUMN categories.category_id IS 'Primary key, unique identifier for each category.';

COMMENT ON COLUMN categories.category_name IS 'Unique name for the product category.';

COMMENT ON COLUMN categories.description IS 'Detailed description of the category.';

-- =============================================================================

-- Table: products

-- Description: Stores details about products available in the E-commerce store.

-- =============================================================================

CREATE TABLE products (

product_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Unique identifier for the product

product_name VARCHAR(255) NOT NULL, -- Name of the product

description TEXT, -- Detailed description of the product

price NUMERIC(10, 2) NOT NULL CHECK (price >= 0), -- Price of the product (e.g., 99.99)

stock_quantity INT NOT NULL DEFAULT 0 CHECK (stock_quantity >= 0), -- Number of units available in stock

category_id UUID NOT NULL, -- Foreign key to the categories table

image_url VARCHAR(255), -- URL to the product's main image

created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), -- Timestamp when the product record was created

updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), -- Timestamp of the last update to the product record

FOREIGN KEY (category_id) REFERENCES categories(category_id) ON DELETE RESTRICT

);

COMMENT ON TABLE products IS 'Stores details about individual products.';

COMMENT ON COLUMN products.product_id IS 'Primary key, unique identifier for each product.';

COMMENT ON COLUMN products.product_name IS 'Name of the product.';

COMMENT ON COLUMN products.description IS 'Detailed description of the product features and specifications.';

COMMENT ON COLUMN products.price IS 'Selling price of the product.';

COMMENT ON COLUMN products.stock_quantity IS 'Current number of units available in stock.';

COMMENT ON COLUMN products.category_id IS 'Foreign key linking to the product''s category.';

COMMENT ON COLUMN products.image_url IS 'URL for the main product image.';

COMMENT ON COLUMN products.created_at IS 'Timestamp when the product was added to the catalog.';

COMMENT ON COLUMN products.updated_at IS 'Timestamp of the last update to the product details.';

-- =============================================================================

-- Table: orders

-- Description: Records customer orders, including total amount and status.

-- =============================================================================

CREATE TABLE orders (

order_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Unique identifier for the order

user_id UUID NOT NULL, -- Foreign key to the users table (customer who placed the order)

order_date TIMESTAMP WITH TIME ZONE DEFAULT NOW(), -- Date and time when the order was placed

total_amount NUMERIC(10, 2) NOT NULL CHECK (total_amount >= 0), -- Total monetary value of the order

status VARCHAR(50) NOT NULL DEFAULT 'pending', -- Current status of the order (e.g., 'pending', 'processing', 'shipped', 'delivered', 'cancelled')

shipping_address TEXT NOT NULL, -- Full shipping address for the order

shipping_city VARCHAR(100) NOT NULL, -- City for shipping

shipping_state VARCHAR(100), -- State/Province for shipping

shipping_zip_code VARCHAR(20) NOT NULL, -- Zip/Postal code for shipping

shipping_country VARCHAR(100) NOT NULL, -- Country for shipping

created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), -- Timestamp when the order record was created

updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), -- Timestamp of the last update to the order record

FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE RESTRICT,

CHECK (status IN ('pending', 'processing', 'shipped', 'delivered', 'cancelled', 'returned'))

);

COMMENT ON TABLE orders IS 'Records customer orders.';

COMMENT ON COLUMN orders.order_id IS 'Primary key, unique identifier for each order.';

COMMENT ON COLUMN orders.user_id IS 'Foreign key linking to the user who placed the order.';

COMMENT ON COLUMN orders.order_date IS 'Date and time the order was placed.';

COMMENT ON COLUMN orders.total_amount IS 'Total amount of the order, including taxes and shipping.';

COMMENT ON COLUMN orders.status IS 'Current status of the order (e.g., pending, shipped).';

COMMENT ON COLUMN orders.shipping_address IS 'Full shipping address for the order.';

COMMENT ON COLUMN orders.shipping_city IS 'City for the shipping address.';

COMMENT ON COLUMN orders.shipping_state IS 'State or province for the shipping

gemini Output

We are pleased to present the comprehensive review and documentation of your proposed database schema, marking the successful completion of the "Database Schema Designer" workflow. This deliverable provides a detailed, actionable overview of the database structure, design rationale, and immediate next steps to facilitate your development and deployment processes.


Database Schema Design: Review and Documentation

1. Executive Summary

This document details the finalized database schema design, incorporating best practices for data integrity, scalability, and performance. The schema has been meticulously crafted to support the core functionalities and data requirements identified, ensuring a robust and efficient foundation for your application. This deliverable includes a complete Data Definition Language (DDL) script, a comprehensive data dictionary, an Entity-Relationship Diagram (ERD) overview, and a summary of key design decisions.

2. Database Schema Overview

The designed database schema is a relational model optimized for transactional integrity and efficient querying. It is structured around several key entities, representing the core components of your application's data. The design emphasizes clear relationships, proper normalization, and appropriate data typing to minimize redundancy and maximize data consistency.

Key Design Principles Applied:

  • Normalization: Achieved 3rd Normal Form (3NF) to reduce data redundancy and improve data integrity.
  • Data Integrity: Implemented Primary Keys, Foreign Keys, Unique Constraints, and NOT NULL constraints to enforce data validity.
  • Performance: Considered indexing strategies and appropriate data types to optimize common query patterns.
  • Extensibility: Designed with future growth and potential feature additions in mind.

3. Detailed Schema Documentation

3.1. Entity-Relationship Diagram (ERD) Overview

The ERD visually represents the entities within your database and the relationships between them. It illustrates how different tables are linked, including cardinality (one-to-one, one-to-many, many-to-many).

Conceptual ERD Summary:

  • Core Entities: (e.g., Users, Products, Orders, Categories, OrderItems)
  • Relationships:

* Users can place many Orders (One-to-Many).

* Products belong to a Category (Many-to-One).

* Orders contain many OrderItems (One-to-Many).

* OrderItems reference Products (Many-to-One).

  • Key Relationships Highlighted: The ERD clearly depicts the flow of data and dependencies, crucial for understanding the overall structure.

Note: A visual ERD file (e.g., in PNG, SVG, or Mermaid format) will be provided separately or can be generated using the DDL script with appropriate tools (e.g., dbdiagram.io, draw.io, Lucidchart).

3.2. Data Definition Language (DDL) Script

Below is the complete DDL script required to create the database schema. This script is compatible with standard SQL databases (e.g., PostgreSQL, MySQL, SQL Server) with minor adaptations for specific data types or syntax if necessary.


-- Database: YourApplicationDB
-- Schema Version: 1.0.0

-- Drop existing tables if they exist (for development/re-creation purposes)
DROP TABLE IF EXISTS OrderItems;
DROP TABLE IF EXISTS Orders;
DROP TABLE IF EXISTS Products;
DROP TABLE IF EXISTS Categories;
DROP TABLE IF EXISTS Users;

-- 1. Users Table
-- Stores information about application users.
CREATE TABLE Users (
    user_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Unique identifier for the user
    username VARCHAR(50) UNIQUE NOT NULL,               -- User's chosen username
    email VARCHAR(100) UNIQUE NOT NULL,                  -- User's email address, used for login/communication
    password_hash VARCHAR(255) NOT NULL,                 -- Hashed password for security
    first_name VARCHAR(50),                              -- User's first name
    last_name VARCHAR(50),                               -- User's last name
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, -- Timestamp of user creation
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP  -- Timestamp of last update
);

-- Index for faster username and email lookups
CREATE INDEX idx_users_username ON Users (username);
CREATE INDEX idx_users_email ON Users (email);

-- 2. Categories Table
-- Stores categories for products.
CREATE TABLE Categories (
    category_id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, -- Unique identifier for the category
    category_name VARCHAR(100) UNIQUE NOT NULL,              -- Name of the category (e.g., "Electronics", "Books")
    description TEXT                                         -- Optional description of the category
);

-- 3. Products Table
-- Stores information about products available in the application.
CREATE TABLE Products (
    product_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Unique identifier for the product
    product_name VARCHAR(255) NOT NULL,                    -- Name of the product
    description TEXT,                                      -- Detailed description of the product
    price DECIMAL(10, 2) NOT NULL CHECK (price >= 0),      -- Price of the product
    stock_quantity INT NOT NULL CHECK (stock_quantity >= 0), -- Current stock level
    category_id INT,                                       -- Foreign key to Categories table
    image_url VARCHAR(255),                                -- URL to product image
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (category_id) REFERENCES Categories(category_id) ON DELETE SET NULL -- If category is deleted, products become uncategorized
);

-- Index for faster product name and category lookups
CREATE INDEX idx_products_name ON Products (product_name);
CREATE INDEX idx_products_category_id ON Products (category_id);

-- 4. Orders Table
-- Stores information about customer orders.
CREATE TABLE Orders (
    order_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Unique identifier for the order
    user_id UUID NOT NULL,                               -- Foreign key to Users table
    order_date TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, -- Date and time the order was placed
    total_amount DECIMAL(10, 2) NOT NULL CHECK (total_amount >= 0), -- Total amount of the order
    status VARCHAR(50) NOT NULL DEFAULT 'Pending',       -- Current status of the order (e.g., 'Pending', 'Processing', 'Shipped', 'Delivered', 'Cancelled')
    shipping_address TEXT NOT NULL,                      -- Shipping address for the order
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES Users(user_id) ON DELETE CASCADE -- If user is deleted, their orders are also deleted
);

-- Index for faster user and order date lookups
CREATE INDEX idx_orders_user_id ON Orders (user_id);
CREATE INDEX idx_orders_order_date ON Orders (order_date);

-- 5. OrderItems Table
-- Stores individual items within an order.
CREATE TABLE OrderItems (
    order_item_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Unique identifier for the order item
    order_id UUID NOT NULL,                                  -- Foreign key to Orders table
    product_id UUID NOT NULL,                                -- Foreign key to Products table
    quantity INT NOT NULL CHECK (quantity > 0),              -- Quantity of the product in this order item
    unit_price DECIMAL(10, 2) NOT NULL CHECK (unit_price >= 0), -- Price of the product at the time of order
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (order_id) REFERENCES Orders(order_id) ON DELETE CASCADE, -- If order is deleted, its items are also deleted
    FOREIGN KEY (product_id) REFERENCES Products(product_id) ON DELETE RESTRICT, -- Prevent deletion of product if it's part of an order item
    UNIQUE (order_id, product_id) -- Ensures a product appears only once per order item list
);

-- Index for faster order and product lookups within order items
CREATE INDEX idx_orderitems_order_id ON OrderItems (order_id);
CREATE INDEX idx_orderitems_product_id ON OrderItems (product_id);

-- Optional: Add triggers for 'updated_at' column to automatically update on row modification
-- For PostgreSQL example:
-- CREATE OR REPLACE FUNCTION update_timestamp()
-- RETURNS TRIGGER AS $$
-- BEGIN
--    NEW.updated_at = NOW();
--    RETURN NEW;
-- END;
-- $$ LANGUAGE plpgsql;

-- CREATE TRIGGER set_users_timestamp
-- BEFORE UPDATE ON Users
-- FOR EACH ROW
-- EXECUTE FUNCTION update_timestamp();

-- ... (similar triggers for other tables)

3.3. Data Dictionary / Schema Reference

This section provides a detailed breakdown of each table, its columns, and their properties.

Table: Users

  • Description: Stores user accounts and profile information.
  • Columns:

* user_id (UUID, PK, NOT NULL): Unique identifier for the user.

* username (VARCHAR(50), UNIQUE, NOT NULL): User's unique login username.

* email (VARCHAR(100), UNIQUE, NOT NULL): User's email address, also unique.

* password_hash (VARCHAR(255), NOT NULL): Securely hashed password.

* first_name (VARCHAR(50)): User's first name.

* last_name (VARCHAR(50)): User's last name.

* created_at (TIMESTAMP WITH TIME ZONE, DEFAULT CURRENT_TIMESTAMP): Timestamp when the user account was created.

* updated_at (TIMESTAMP WITH TIME ZONE, DEFAULT CURRENT_TIMESTAMP): Last time the user's information was updated.

Table: Categories

  • Description: Defines product categories.
  • Columns:

* category_id (INT, PK, GENERATED ALWAYS AS IDENTITY): Unique identifier for the category.

* category_name (VARCHAR(100), UNIQUE, NOT NULL): Name of the category.

* description (TEXT): Optional detailed description of the category.

Table: Products

  • Description: Contains details of all products available.
  • Columns:

* product_id (UUID, PK, NOT NULL): Unique identifier for the product.

* product_name (VARCHAR(255), NOT NULL): Name of the product.

* description (TEXT): Detailed description of the product.

* price (DECIMAL(10, 2), NOT NULL, CHECK >= 0): Current selling price of the product.

* stock_quantity (INT, NOT NULL, CHECK >= 0): Number of units currently in stock.

* category_id (INT, FK Categories): Identifier of the product's category.

* image_url (VARCHAR(255)): URL to the product's image.

* created_at (TIMESTAMP WITH TIME ZONE, DEFAULT CURRENT_TIMESTAMP): Timestamp when the product was added.

* updated_at (TIMESTAMP WITH TIME ZONE, DEFAULT CURRENT_TIMESTAMP): Last time product details were updated.

Table: Orders

  • Description: Records customer orders.
  • Columns:

* order_id (UUID, PK, NOT NULL): Unique identifier for the order.

* user_id (UUID, FK Users, NOT NULL): Identifier of the user who placed the order.

* order_date (TIMESTAMP WITH TIME ZONE, DEFAULT CURRENT_TIMESTAMP): Date and time the order was placed.

* total_amount (DECIMAL(10, 2), NOT NULL, CHECK >= 0): Total monetary value of the order.

* status (VARCHAR(50), NOT NULL, DEFAULT 'Pending'): Current fulfillment status of the order.

* shipping_address (TEXT, NOT NULL): Full shipping address for the order.

* created_at (TIMESTAMP WITH TIME ZONE, DEFAULT CURRENT_TIMESTAMP): Timestamp when the order was created.

* updated_at (TIMESTAMP WITH TIME ZONE, DEFAULT CURRENT_TIMESTAMP): Last time the order details were updated.

Table: OrderItems

  • Description: Details individual products within an order.
  • Columns:

* order_item_id (UUID, PK, NOT NULL): Unique identifier for the order item.

* order_id (UUID, FK Orders, NOT NULL): Identifier of the order this item belongs to.

* product_id (UUID, FK Products, NOT NULL): Identifier of the product included in this order item.

* quantity (INT, NOT NULL, CHECK > 0): Number of units of the product ordered.

* unit_price (DECIMAL(10, 2), NOT NULL, CHECK >= 0): Price of the product at the time it was ordered (historical price).

* created_at (TIMESTAMP WITH TIME ZONE, DEFAULT CURRENT_TIMESTAMP): Timestamp when the order item was created.

* updated_at (TIMESTAMP WITH TIME ZONE, DEFAULT CURRENT_TIMESTAMP): Last time the order item details were updated.

* Constraints: UNIQUE (order_id, product_id) ensures a specific product is listed only once per order.

3.4. Design Rationale & Key Decisions

  • UUID for Primary Keys: Chosen for Users, Products, Orders, OrderItems to provide globally unique identifiers, facilitate distributed systems (if applicable in the future), and avoid sequential ID exposure. Categories uses INT GENERATED ALWAYS AS IDENTITY for simplicity as it's a smaller, more static lookup table.
  • DECIMAL(10, 2) for Monetary Values: Ensures precise storage of currency, avoiding floating-point inaccuracies.
  • TEXT for Descriptions and Addresses: Provides flexibility for longer, multi-line textual content without arbitrary length limits.
  • **`TIMESTAMP WITH TIME ZONE
database_schema_designer.txt
Download source file
Copy all content
Full output as text
Download ZIP
IDE-ready project ZIP
Copy share link
Permanent URL for this run
Get Embed Code
Embed this result on any website
Print / Save PDF
Use browser print dialog
\n\n\n"); var hasSrcMain=Object.keys(extracted).some(function(k){return k.indexOf("src/main")>=0;}); if(!hasSrcMain) zip.file(folder+"src/main."+ext,"import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\nimport './index.css'\n\nReactDOM.createRoot(document.getElementById('root')!).render(\n \n \n \n)\n"); var hasSrcApp=Object.keys(extracted).some(function(k){return k==="src/App."+ext||k==="App."+ext;}); if(!hasSrcApp) zip.file(folder+"src/App."+ext,"import React from 'react'\nimport './App.css'\n\nfunction App(){\n return(\n
\n
\n

"+slugTitle(pn)+"

\n

Built with PantheraHive BOS

\n
\n
\n )\n}\nexport default App\n"); zip.file(folder+"src/index.css","*{margin:0;padding:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;background:#f0f2f5;color:#1a1a2e}\n.app{min-height:100vh;display:flex;flex-direction:column}\n.app-header{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:40px}\nh1{font-size:2.5rem;font-weight:700}\n"); zip.file(folder+"src/App.css",""); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/pages/.gitkeep",""); zip.file(folder+"src/hooks/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nnpm run dev\n\`\`\`\n\n## Build\n\`\`\`bash\nnpm run build\n\`\`\`\n\n## Open in IDE\nOpen the project folder in VS Code or WebStorm.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n"); } /* --- Vue (Vite + Composition API + TypeScript) --- */ function buildVue(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{\n "name": "'+pn+'",\n "version": "0.0.0",\n "type": "module",\n "scripts": {\n "dev": "vite",\n "build": "vue-tsc -b && vite build",\n "preview": "vite preview"\n },\n "dependencies": {\n "vue": "^3.5.13",\n "vue-router": "^4.4.5",\n "pinia": "^2.3.0",\n "axios": "^1.7.9"\n },\n "devDependencies": {\n "@vitejs/plugin-vue": "^5.2.1",\n "typescript": "~5.7.3",\n "vite": "^6.0.5",\n "vue-tsc": "^2.2.0"\n }\n}\n'); zip.file(folder+"vite.config.ts","import { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport { resolve } from 'path'\n\nexport default defineConfig({\n plugins: [vue()],\n resolve: { alias: { '@': resolve(__dirname,'src') } }\n})\n"); zip.file(folder+"tsconfig.json",'{"files":[],"references":[{"path":"./tsconfig.app.json"},{"path":"./tsconfig.node.json"}]}\n'); zip.file(folder+"tsconfig.app.json",'{\n "compilerOptions":{\n "target":"ES2020","useDefineForClassFields":true,"module":"ESNext","lib":["ES2020","DOM","DOM.Iterable"],\n "skipLibCheck":true,"moduleResolution":"bundler","allowImportingTsExtensions":true,\n "isolatedModules":true,"moduleDetection":"force","noEmit":true,"jsxImportSource":"vue",\n "strict":true,"paths":{"@/*":["./src/*"]}\n },\n "include":["src/**/*.ts","src/**/*.d.ts","src/**/*.tsx","src/**/*.vue"]\n}\n'); zip.file(folder+"env.d.ts","/// \n"); zip.file(folder+"index.html","\n\n\n \n \n "+slugTitle(pn)+"\n\n\n
\n \n\n\n"); var hasMain=Object.keys(extracted).some(function(k){return k==="src/main.ts"||k==="main.ts";}); if(!hasMain) zip.file(folder+"src/main.ts","import { createApp } from 'vue'\nimport { createPinia } from 'pinia'\nimport App from './App.vue'\nimport './assets/main.css'\n\nconst app = createApp(App)\napp.use(createPinia())\napp.mount('#app')\n"); var hasApp=Object.keys(extracted).some(function(k){return k.indexOf("App.vue")>=0;}); if(!hasApp) zip.file(folder+"src/App.vue","\n\n\n\n\n"); zip.file(folder+"src/assets/main.css","*{margin:0;padding:0;box-sizing:border-box}body{font-family:system-ui,sans-serif;background:#fff;color:#213547}\n"); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/views/.gitkeep",""); zip.file(folder+"src/stores/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nnpm run dev\n\`\`\`\n\n## Build\n\`\`\`bash\nnpm run build\n\`\`\`\n\nOpen in VS Code or WebStorm.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n"); } /* --- Angular (v19 standalone) --- */ function buildAngular(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var sel=pn.replace(/_/g,"-"); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{\n "name": "'+pn+'",\n "version": "0.0.0",\n "scripts": {\n "ng": "ng",\n "start": "ng serve",\n "build": "ng build",\n "test": "ng test"\n },\n "dependencies": {\n "@angular/animations": "^19.0.0",\n "@angular/common": "^19.0.0",\n "@angular/compiler": "^19.0.0",\n "@angular/core": "^19.0.0",\n "@angular/forms": "^19.0.0",\n "@angular/platform-browser": "^19.0.0",\n "@angular/platform-browser-dynamic": "^19.0.0",\n "@angular/router": "^19.0.0",\n "rxjs": "~7.8.0",\n "tslib": "^2.3.0",\n "zone.js": "~0.15.0"\n },\n "devDependencies": {\n "@angular-devkit/build-angular": "^19.0.0",\n "@angular/cli": "^19.0.0",\n "@angular/compiler-cli": "^19.0.0",\n "typescript": "~5.6.0"\n }\n}\n'); zip.file(folder+"angular.json",'{\n "$schema": "./node_modules/@angular/cli/lib/config/schema.json",\n "version": 1,\n "newProjectRoot": "projects",\n "projects": {\n "'+pn+'": {\n "projectType": "application",\n "root": "",\n "sourceRoot": "src",\n "prefix": "app",\n "architect": {\n "build": {\n "builder": "@angular-devkit/build-angular:application",\n "options": {\n "outputPath": "dist/'+pn+'",\n "index": "src/index.html",\n "browser": "src/main.ts",\n "tsConfig": "tsconfig.app.json",\n "styles": ["src/styles.css"],\n "scripts": []\n }\n },\n "serve": {"builder":"@angular-devkit/build-angular:dev-server","configurations":{"production":{"buildTarget":"'+pn+':build:production"},"development":{"buildTarget":"'+pn+':build:development"}},"defaultConfiguration":"development"}\n }\n }\n }\n}\n'); zip.file(folder+"tsconfig.json",'{\n "compileOnSave": false,\n "compilerOptions": {"baseUrl":"./","outDir":"./dist/out-tsc","forceConsistentCasingInFileNames":true,"strict":true,"noImplicitOverride":true,"noPropertyAccessFromIndexSignature":true,"noImplicitReturns":true,"noFallthroughCasesInSwitch":true,"paths":{"@/*":["src/*"]},"skipLibCheck":true,"esModuleInterop":true,"sourceMap":true,"declaration":false,"experimentalDecorators":true,"moduleResolution":"bundler","importHelpers":true,"target":"ES2022","module":"ES2022","useDefineForClassFields":false,"lib":["ES2022","dom"]},\n "references":[{"path":"./tsconfig.app.json"}]\n}\n'); zip.file(folder+"tsconfig.app.json",'{\n "extends":"./tsconfig.json",\n "compilerOptions":{"outDir":"./dist/out-tsc","types":[]},\n "files":["src/main.ts"],\n "include":["src/**/*.d.ts"]\n}\n'); zip.file(folder+"src/index.html","\n\n\n \n "+slugTitle(pn)+"\n \n \n \n\n\n \n\n\n"); zip.file(folder+"src/main.ts","import { bootstrapApplication } from '@angular/platform-browser';\nimport { appConfig } from './app/app.config';\nimport { AppComponent } from './app/app.component';\n\nbootstrapApplication(AppComponent, appConfig)\n .catch(err => console.error(err));\n"); zip.file(folder+"src/styles.css","* { margin: 0; padding: 0; box-sizing: border-box; }\nbody { font-family: system-ui, -apple-system, sans-serif; background: #f9fafb; color: #111827; }\n"); var hasComp=Object.keys(extracted).some(function(k){return k.indexOf("app.component")>=0;}); if(!hasComp){ zip.file(folder+"src/app/app.component.ts","import { Component } from '@angular/core';\nimport { RouterOutlet } from '@angular/router';\n\n@Component({\n selector: 'app-root',\n standalone: true,\n imports: [RouterOutlet],\n templateUrl: './app.component.html',\n styleUrl: './app.component.css'\n})\nexport class AppComponent {\n title = '"+pn+"';\n}\n"); zip.file(folder+"src/app/app.component.html","
\n
\n

"+slugTitle(pn)+"

\n

Built with PantheraHive BOS

\n
\n \n
\n"); zip.file(folder+"src/app/app.component.css",".app-header{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:60vh;gap:16px}h1{font-size:2.5rem;font-weight:700;color:#6366f1}\n"); } zip.file(folder+"src/app/app.config.ts","import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';\nimport { provideRouter } from '@angular/router';\nimport { routes } from './app.routes';\n\nexport const appConfig: ApplicationConfig = {\n providers: [\n provideZoneChangeDetection({ eventCoalescing: true }),\n provideRouter(routes)\n ]\n};\n"); zip.file(folder+"src/app/app.routes.ts","import { Routes } from '@angular/router';\n\nexport const routes: Routes = [];\n"); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nng serve\n# or: npm start\n\`\`\`\n\n## Build\n\`\`\`bash\nng build\n\`\`\`\n\nOpen in VS Code with Angular Language Service extension.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n.angular/\n"); } /* --- Python --- */ function buildPython(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^\`\`\`[\w]*\n?/m,"").replace(/\n?\`\`\`$/m,"").trim(); var reqMap={"numpy":"numpy","pandas":"pandas","sklearn":"scikit-learn","tensorflow":"tensorflow","torch":"torch","flask":"flask","fastapi":"fastapi","uvicorn":"uvicorn","requests":"requests","sqlalchemy":"sqlalchemy","pydantic":"pydantic","dotenv":"python-dotenv","PIL":"Pillow","cv2":"opencv-python","matplotlib":"matplotlib","seaborn":"seaborn","scipy":"scipy"}; var reqs=[]; Object.keys(reqMap).forEach(function(k){if(src.indexOf("import "+k)>=0||src.indexOf("from "+k)>=0)reqs.push(reqMap[k]);}); var reqsTxt=reqs.length?reqs.join("\n"):"# add dependencies here\n"; zip.file(folder+"main.py",src||"# "+title+"\n# Generated by PantheraHive BOS\n\nprint(title+\" loaded\")\n"); zip.file(folder+"requirements.txt",reqsTxt); zip.file(folder+".env.example","# Environment variables\n"); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\npython3 -m venv .venv\nsource .venv/bin/activate\npip install -r requirements.txt\n\`\`\`\n\n## Run\n\`\`\`bash\npython main.py\n\`\`\`\n"); zip.file(folder+".gitignore",".venv/\n__pycache__/\n*.pyc\n.env\n.DS_Store\n"); } /* --- Node.js --- */ function buildNode(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^\`\`\`[\w]*\n?/m,"").replace(/\n?\`\`\`$/m,"").trim(); var depMap={"mongoose":"^8.0.0","dotenv":"^16.4.5","axios":"^1.7.9","cors":"^2.8.5","bcryptjs":"^2.4.3","jsonwebtoken":"^9.0.2","socket.io":"^4.7.4","uuid":"^9.0.1","zod":"^3.22.4","express":"^4.18.2"}; var deps={}; Object.keys(depMap).forEach(function(k){if(src.indexOf(k)>=0)deps[k]=depMap[k];}); if(!deps["express"])deps["express"]="^4.18.2"; var pkgJson=JSON.stringify({"name":pn,"version":"1.0.0","main":"src/index.js","scripts":{"start":"node src/index.js","dev":"nodemon src/index.js"},"dependencies":deps,"devDependencies":{"nodemon":"^3.0.3"}},null,2)+"\n"; zip.file(folder+"package.json",pkgJson); var fallback="const express=require(\"express\");\nconst app=express();\napp.use(express.json());\n\napp.get(\"/\",(req,res)=>{\n res.json({message:\""+title+" API\"});\n});\n\nconst PORT=process.env.PORT||3000;\napp.listen(PORT,()=>console.log(\"Server on port \"+PORT));\n"; zip.file(folder+"src/index.js",src||fallback); zip.file(folder+".env.example","PORT=3000\n"); zip.file(folder+".gitignore","node_modules/\n.env\n.DS_Store\n"); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\n\`\`\`\n\n## Run\n\`\`\`bash\nnpm run dev\n\`\`\`\n"); } /* --- Vanilla HTML --- */ function buildVanillaHtml(zip,folder,app,code){ var title=slugTitle(app); var isFullDoc=code.trim().toLowerCase().indexOf("=0||code.trim().toLowerCase().indexOf("=0; var indexHtml=isFullDoc?code:"\n\n\n\n\n"+title+"\n\n\n\n"+code+"\n\n\n\n"; zip.file(folder+"index.html",indexHtml); zip.file(folder+"style.css","/* "+title+" — styles */\n*{margin:0;padding:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;background:#fff;color:#1a1a2e}\n"); zip.file(folder+"script.js","/* "+title+" — scripts */\n"); zip.file(folder+"assets/.gitkeep",""); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Open\nDouble-click \`index.html\` in your browser.\n\nOr serve locally:\n\`\`\`bash\nnpx serve .\n# or\npython3 -m http.server 3000\n\`\`\`\n"); zip.file(folder+".gitignore",".DS_Store\nnode_modules/\n.env\n"); } /* ===== MAIN ===== */ var sc=document.createElement("script"); sc.src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"; sc.onerror=function(){ if(lbl)lbl.textContent="Download ZIP"; alert("JSZip load failed — check connection."); }; sc.onload=function(){ var zip=new JSZip(); var base=(_phFname||"output").replace(/\.[^.]+$/,""); var app=base.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"my_app"; var folder=app+"/"; var vc=document.getElementById("panel-content"); var panelTxt=vc?(vc.innerText||vc.textContent||""):""; var lang=detectLang(_phCode,panelTxt); if(_phIsHtml){ buildVanillaHtml(zip,folder,app,_phCode); } else if(lang==="flutter"){ buildFlutter(zip,folder,app,_phCode,panelTxt); } else if(lang==="react-native"){ buildReactNative(zip,folder,app,_phCode,panelTxt); } else if(lang==="swift"){ buildSwift(zip,folder,app,_phCode,panelTxt); } else if(lang==="kotlin"){ buildKotlin(zip,folder,app,_phCode,panelTxt); } else if(lang==="react"){ buildReact(zip,folder,app,_phCode,panelTxt); } else if(lang==="vue"){ buildVue(zip,folder,app,_phCode,panelTxt); } else if(lang==="angular"){ buildAngular(zip,folder,app,_phCode,panelTxt); } else if(lang==="python"){ buildPython(zip,folder,app,_phCode); } else if(lang==="node"){ buildNode(zip,folder,app,_phCode); } else { /* Document/content workflow */ var title=app.replace(/_/g," "); var md=_phAll||_phCode||panelTxt||"No content"; zip.file(folder+app+".md",md); var h=""+title+""; h+="

"+title+"

"; var hc=md.replace(/&/g,"&").replace(//g,">"); hc=hc.replace(/^### (.+)$/gm,"

$1

"); hc=hc.replace(/^## (.+)$/gm,"

$1

"); hc=hc.replace(/^# (.+)$/gm,"

$1

"); hc=hc.replace(/\*\*(.+?)\*\*/g,"$1"); hc=hc.replace(/\n{2,}/g,"

"); h+="

"+hc+"

Generated by PantheraHive BOS
"; zip.file(folder+app+".html",h); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\nFiles:\n- "+app+".md (Markdown)\n- "+app+".html (styled HTML)\n"); } zip.generateAsync({type:"blob"}).then(function(blob){ var a=document.createElement("a"); a.href=URL.createObjectURL(blob); a.download=app+".zip"; a.click(); URL.revokeObjectURL(a.href); if(lbl)lbl.textContent="Download ZIP"; }); }; document.head.appendChild(sc); } function phShare(){navigator.clipboard.writeText(window.location.href).then(function(){var el=document.getElementById("ph-share-lbl");if(el){el.textContent="Link copied!";setTimeout(function(){el.textContent="Copy share link";},2500);}});}function phEmbed(){var runId=window.location.pathname.split("/").pop().replace(".html","");var embedUrl="https://pantherahive.com/embed/"+runId;var code='';navigator.clipboard.writeText(code).then(function(){var el=document.getElementById("ph-embed-lbl");if(el){el.textContent="Embed code copied!";setTimeout(function(){el.textContent="Get Embed Code";},2500);}});}