Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Xata
https://github.com/xataio/docs
Admin
This repository contains the documentation for Xata, a serverless data platform.
Tokens:
128,250
Snippets:
1,133
Trust Score:
9.1
Update:
1 day ago
Context
Chat
Benchmark
52.15
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Environment Setup Steps Source: https://github.com/xataio/docs/blob/main/docs/automations/ga-pr.mdx Gets the latest schema and sets up the new preview environment with the database URL and search path. ```yaml - name: Get Latest Schema id: xata-roll-get-latest-schema run: | echo LATEST_SCHEMA=`xata roll latest --with-schema=true` >> $GITHUB_OUTPUT - name: Setup New Preview Environment run: | echo DATABASE_URL=`xata branch url` >> $GITHUB_ENV echo SEARCH_PATH=${{ steps.xata-roll-get-latest-schema.outputs.LATEST_SCHEMA }} >> $GITHUB_ENV ``` -------------------------------- ### Install dependencies and run main.py Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/python.mdx Run these commands to install the dependencies from requirements.txt and execute the main.py script. This is the standard way to start the Python application. ```bash pip install -r requirements.txt python main.py ``` -------------------------------- ### Create main.go with routes and server setup Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/go.mdx Defines the main server file for a Go API using Gorilla Mux. It loads environment variables, initializes the database, sets up routes for products and orders, and starts the server on port 3000. ```go // main.go package main import ( "log" "net/http" "my-xata-app/db" "my-xata-app/handlers" "github.com/gorilla/mux" "github.com/joho/godotenv" ) func main() { // Load environment variables err := godotenv.Load() if err != nil { log.Fatal("Error loading .env file") } // Initialize database db.InitDB() defer db.DB.Close() // Create router r := mux.NewRouter() // Define routes r.HandleFunc("/api/products", handlers.GetProducts).Methods("GET") r.HandleFunc("/api/products/{id}", handlers.GetProduct).Methods("GET") r.HandleFunc("/api/products", handlers.CreateProduct).Methods("POST") r.HandleFunc("/api/orders", handlers.GetOrders).Methods("GET") // Start server log.Println("Server starting on :3000") log.Fatal(http.ListenAndServe(":3000", r)) } ``` -------------------------------- ### Create Django project and app Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/django.mdx Install Django and psycopg2-binary, start a new Django project named my_xata_app, and create the store app. ```bash pip install django psycopg2-binary django-admin startproject my_xata_app cd my_xata_app python manage.py startapp store ``` -------------------------------- ### Run FastAPI application Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/sqlalchemy.mdx Installs FastAPI and Uvicorn, then starts the API server with auto-reload. ```bash pip install fastapi uvicorn uvicorn api:app --reload ``` -------------------------------- ### Set up Cloud SQL Proxy Source: https://github.com/xataio/docs/blob/main/docs/migrations/gcp-cloudsql.mdx Install and start the Cloud SQL Proxy to securely connect to your Cloud SQL instance. ```bash # Install Cloud SQL Proxy curl -o cloud-sql-proxy https://dl.google.com/cloudsql/cloud-sql-proxy.linux.amd64 chmod +x cloud-sql-proxy # Start the proxy ./cloud-sql-proxy --instances=your-project:your-region:your-instance ``` -------------------------------- ### Install dependencies and run application Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/sqlalchemy.mdx Installs the packages from requirements.txt and runs the main application script. ```bash pip install -r requirements.txt python app.py ``` -------------------------------- ### Install and Start AlloyDB Auth Proxy Source: https://github.com/xataio/docs/blob/main/docs/migrations/alloydb.mdx Download the AlloyDB Auth Proxy binary, make it executable, and start it with your cluster instance details. ```bash # Install AlloyDB Auth Proxy curl -o alloydb-auth-proxy https://storage.googleapis.com/alloydb-auth-proxy/v1.0.0/alloydb-auth-proxy.linux.amd64 chmod +x alloydb-auth-proxy # Start the proxy ./alloydb-auth-proxy --instances=your-project:your-region:your-cluster ``` -------------------------------- ### Install psql on Ubuntu Source: https://github.com/xataio/docs/blob/main/docs/getting-started.mdx Install the PostgreSQL client version 17 on Ubuntu using apt. ```bash sudo apt install postgresql-client-17 ``` -------------------------------- ### Install Go Dependencies Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/go.mdx Install the required Go packages: lib/pq for PostgreSQL, gorilla/mux for routing, and godotenv for environment variables. ```bash go get github.com/lib/pq go get github.com/gorilla/mux go get github.com/joho/godotenv ``` -------------------------------- ### Install Express and run API Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/prisma.mdx Installs Express and its types, then runs the API with ts-node. ```bash npm install express npm install -D @types/express npx ts-node api.ts ``` -------------------------------- ### Install dependencies and run dev Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/prisma.mdx Installs ts-node and runs the development server. ```bash npm install ts-node npm run dev ``` -------------------------------- ### Install Prisma and PostgreSQL driver Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/prisma.mdx Install Prisma CLI, Prisma Client, and TypeScript dependencies. ```bash npm install prisma @prisma/client npm install -D typescript @types/node ``` -------------------------------- ### Start xata clone Source: https://github.com/xataio/docs/blob/main/docs/tutorials/migrate-to-xata.mdx Start the cloning process with `xata clone start`. Use the `--source-url` flag with your production connection string and `--validation-mode=relaxed`. The duration depends on the database size. ```sh xata clone start --source-url $CONN_STRING --validation-mode=relaxed ``` -------------------------------- ### Start the Rails development server Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/rails.mdx Run this command to start the Rails server. The API will be available at http://localhost:3000/api/products and http://localhost:3000/api/orders. ```bash rails server ``` -------------------------------- ### Install dependencies and run the application Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/typeorm.mdx Installs ts-node and dotenv, then runs the application in development mode with npm run dev. ```bash npm install ts-node dotenv npm run dev ``` -------------------------------- ### Install SQLAlchemy and PostgreSQL driver Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/sqlalchemy.mdx Install SQLAlchemy, the PostgreSQL driver, and python-decouple using pip. ```bash pip install sqlalchemy psycopg2-binary python-decouple ``` -------------------------------- ### Install GORM and PostgreSQL driver Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/gorm.mdx Install the required Go dependencies: GORM, the PostgreSQL driver, and godotenv for loading environment variables. ```bash go get -u gorm.io/gorm go get -u gorm.io/driver/postgres go get -u github.com/joho/godotenv ``` -------------------------------- ### Install dependencies with npm Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/nodejs.mdx Install Express, PostgreSQL client, CORS, dotenv, and development type definitions and nodemon. ```bash npm install express postgres cors dotenv npm install -D @types/pg @types/express @types/cors nodemon ``` -------------------------------- ### Install Dependencies Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/drizzle.mdx Commands to initialize a new Node.js project and install Drizzle ORM, the postgres driver, and development dependencies. ```bash npm init -y npm install drizzle-orm postgres npm install -D drizzle-kit @types/pg ``` -------------------------------- ### Start clone process step Source: https://github.com/xataio/docs/blob/main/docs/automations/ga-clone.mdx GitHub Actions step that initiates the cloning process from the source PostgreSQL database using the xata clone start command. ```yaml - name: Xata clone run: | xata clone start --source-url ${{ env.XATA_CLI_SOURCE_POSTGRES_URL }} ``` -------------------------------- ### GET /organizations/{organizationID} Response Source: https://github.com/xataio/docs/blob/main/docs/api/organizations.mdx Example JSON response for the GET organization endpoint, showing the organization's metadata. ```json { "id": "org_123", "name": "My Organization", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } ``` -------------------------------- ### Run the Go server Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/go.mdx Starts the development server by running the main.go file. The API will be available at http://localhost:3000/api/products and http://localhost:3000/api/orders. ```bash go run main.go ``` -------------------------------- ### Get Available Regions - Example Response Source: https://github.com/xataio/docs/blob/main/docs/api/organizations.mdx Example JSON response for the regions endpoint, showing two regions with their publicAccess settings. ```json { "regions": [ { "id": "us-east-1", "publicAccess": false }, { "id": "eu-west-1", "publicAccess": true } ] } ``` -------------------------------- ### Create Main Application Class (Main.java) Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/jpa.mdx Main entry point that creates sample products, lists all products, filters by rating, and updates a product. Uses ProductService and DatabaseUtil. Closes the EntityManagerFactory in a finally block. ```java // src/main/java/com/example/Main.java package com.example; import com.example.entity.Product; import com.example.service.ProductService; import com.example.util.DatabaseUtil; import java.math.BigDecimal; import java.util.List; import java.util.Map; public class Main { public static void main(String[] args) { try { ProductService productService = new ProductService(); // Create sample products System.out.println("Creating sample products..."); List<Product> products = List.of( productService.createProduct("Wireless Headphones", new BigDecimal("99.99"), 5), productService.createProduct("Smartphone", new BigDecimal("699.99"), 4), productService.createProduct("Laptop", new BigDecimal("1299.99"), 5), productService.createProduct("Coffee Maker", new BigDecimal("89.99"), 4) ); System.out.println("Created " + products.size() + " products"); // Display all products System.out.println("\nAll products:"); List<Product> allProducts = productService.getAllProducts(); for (Product product : allProducts) { String rating = product.getRating() != null ? product.getRating().toString() : "N/A"; System.out.printf("- %s: $%s (Rating: %s/5)%n", product.getName(), product.getPrice(), rating); } // Get products by rating System.out.println("\nTop-rated products (5 stars):"); List<Product> topProducts = productService.getProductsByRating(5); for (Product product : topProducts) { System.out.printf("- %s: $%s%n", product.getName(), product.getPrice()); } // Update a product if (!products.isEmpty()) { System.out.println("\nUpdating product..."); var updatedProduct = productService.updateProduct( products.get(0).getId(), "Premium Wireless Headphones", new BigDecimal("129.99"), null ); if (updatedProduct.isPresent()) { Product product = updatedProduct.get(); System.out.printf("Updated: %s - $%s%n", product.getName(), product.getPrice()); } } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(); } finally { DatabaseUtil.closeEntityManagerFactory(); } } } ``` -------------------------------- ### Create a new Go project Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/go.mdx Run these commands to create a new directory and initialize a Go module named my-xata-app. ```bash mkdir my-xata-app cd my-xata-app go mod init my-xata-app ``` -------------------------------- ### Example response for Get branch Source: https://github.com/xataio/docs/blob/main/docs/api/branches.mdx Example JSON response for a successful request. Shows the branch details including configuration, status, and scale-to-zero settings. ```json { "id": "br_123", "name": "main", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z", "region": "us-east-1", "publicAccess": false, "description": "Main production branch", "parentID": null, "connectionString": "postgresql://xata_user:password@host:port/database", "configuration": { "image": "postgresql:17", "instanceType": "small", "instances": 1, "region": "us-east-1" }, "status": { "instanceCount": 1, "instanceReadyCount": 1, "instances": [ { "id": "inst_123", "status": "ready", "region": "us-east-1", "createdAt": "2024-01-01T00:00:00Z" } ], "lifecycle": { "phase": "running", "message": "Branch is operational" } }, "scaleToZero": { "enabled": true, "idleTime": 300 } } ``` -------------------------------- ### GET /users/{userID} - Response 200 OK Source: https://github.com/xataio/docs/blob/main/docs/api/users.mdx Example JSON response for a successful GET request, returning the user's profile data. ```json { "id": "user_123", "email": "user@example.com", "name": "John Doe", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } ``` -------------------------------- ### Create Sample Application in Python Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/python.mdx This script demonstrates the usage of ProductService and OrderService. It creates sample products, displays all products, filters by rating and price range, creates an order, adds items, and retrieves order details. The script handles exceptions and prints error messages. ```python # main.py from decimal import Decimal from services.product_service import ProductService from services.order_service import OrderService def main(): product_service = ProductService() order_service = OrderService() try: # Create sample products print("Creating sample products...") products = [ product_service.create_product("Wireless Headphones", Decimal("99.99"), 5), product_service.create_product("Smartphone", Decimal("699.99"), 4), product_service.create_product("Laptop", Decimal("1299.99"), 5), product_service.create_product("Coffee Maker", Decimal("89.99"), 4) ] print(f"Created {len(products)} products") # Display all products print("\nAll products:") all_products = product_service.get_all_products() for product in all_products: rating = product.rating if product.rating else "N/A" print(f"- {product.name}: ${product.price} (Rating: {rating}/5)") # Get products by rating print("\nTop-rated products (5 stars):") top_products = product_service.get_products_by_rating(5) for product in top_products: print(f"- {product.name}: ${product.price}") # Create an order with items print("\nCreating an order...") order = order_service.create_order() print(f"Created order #{order.id}") # Add items to order if products: order_service.add_item_to_order(order.id, products[0].id, 2) # 2 headphones if len(products) >= 3: order_service.add_item_to_order(order.id, products[2].id, 1) # 1 laptop # Get order details with products print("\nOrder details:") order_details = order_service.get_orders_with_product_details() for detail in order_details: print(f"Order #{detail['order_id']}: {detail['product_name']} x{detail['qty']} = ${detail['total']}") # Update a product if products: print("\nUpdating product...") updated_product = product_service.update_product( products[0].id, name="Premium Wireless Headphones", price=Decimal("129.99") ) if updated_product: print(f"Updated: {updated_product.name} - ${updated_product.price}") # Get products by price range print("\nProducts between $50 and $150:") mid_range_products = product_service.get_products_by_price_range( Decimal("50.00"), Decimal("150.00") ) for product in mid_range_products: print(f"- {product.name}: ${product.price}") except Exception as e: print(f"Error: {e}") if __name__ == "__main__": main() ``` -------------------------------- ### GORM Sample Application (main.go) Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/gorm.mdx This Go program demonstrates GORM usage with Xata. It initializes the database, auto-migrates models, creates sample products, queries products by rating, creates an order with items, retrieves order details, and updates a product. It uses custom services and models from the 'my-xata-app' package. The code includes a helper function 'intPtr' to create pointer integers. ```go // main.go package main import ( "fmt" "log" "my-xata-app/config" "my-xata-app/models" "my-xata-app/services" ) func main() { // Initialize database config.InitDB() // Auto-migrate models (optional - since we created tables manually) if err := config.DB.AutoMigrate(&models.Product{}, &models.Order{}, &models.OrderItem{}); err != nil { log.Fatal("Failed to migrate database:", err) } // Initialize services productService := services.NewProductService() orderService := services.NewOrderService() // Create sample products fmt.Println("Creating sample products...") products := []*models.Product{ {Name: "Wireless Headphones", Price: 99.99, Rating: intPtr(5)}, {Name: "Smartphone", Price: 699.99, Rating: intPtr(4)}, {Name: "Laptop", Price: 1299.99, Rating: intPtr(5)}, {Name: "Coffee Maker", Price: 89.99, Rating: intPtr(4)}, } for _, product := range products { if err := productService.CreateProduct(product); err != nil { log.Printf("Failed to create product %s: %v", product.Name, err) } } fmt.Printf("Created %d products\n", len(products)) // Display all products fmt.Println("\nAll products:") allProducts, err := productService.GetAllProducts() if err != nil { log.Printf("Failed to get products: %v", err) } else { for _, product := range allProducts { rating := "N/A" if product.Rating != nil { rating = fmt.Sprintf("%d", *product.Rating) } fmt.Printf("- %s: $%.2f (Rating: %s/5)\n", product.Name, product.Price, rating) } } // Get products by rating fmt.Println("\nTop-rated products (5 stars):") topProducts, err := productService.GetProductsByRating(5) if err != nil { log.Printf("Failed to get top products: %v", err) } else { for _, product := range topProducts { fmt.Printf("- %s: $%.2f\n", product.Name, product.Price) } } // Create an order with items fmt.Println("\nCreating an order...") order, err := orderService.CreateOrder() if err != nil { log.Printf("Failed to create order: %v", err) } else { fmt.Printf("Created order #%d\n", order.ID) // Add items to order if len(allProducts) >= 3 { _, err = orderService.AddItemToOrder(order.ID, allProducts[0].ID, 2) // 2 headphones if err != nil { log.Printf("Failed to add item to order: %v", err) } _, err = orderService.AddItemToOrder(order.ID, allProducts[2].ID, 1) // 1 laptop if err != nil { log.Printf("Failed to add item to order: %v", err) } } } // Get order details with products fmt.Println("\nOrder details:") orderDetails, err := orderService.GetOrdersWithProductDetails() if err != nil { log.Printf("Failed to get order details: %v", err) } else { for _, detail := range orderDetails { fmt.Printf("Order #%.0f: %s x%.0f = $%.2f\n", detail["order_id"], detail["product_name"], detail["qty"], detail["total"]) } } // Update a product if len(allProducts) > 0 { fmt.Println("\nUpdating product...") updates := map[string]interface{}{ "name": "Premium Wireless Headphones", "price": 129.99, } updatedProduct, err := productService.UpdateProduct(allProducts[0].ID, updates) if err != nil { log.Printf("Failed to update product: %v", err) } else { fmt.Printf("Updated: %s - $%.2f\n", updatedProduct.Name, updatedProduct.Price) } } } func intPtr(i int) *int { return &i } ``` -------------------------------- ### Get project - Response 200 OK Source: https://github.com/xataio/docs/blob/main/docs/api/projects.mdx Example response for a successful project retrieval. Returns the project id, name, and timestamps. ```json { "id": "proj_123", "name": "My Project", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } ``` -------------------------------- ### Initialize and start streaming Source: https://github.com/xataio/docs/blob/main/docs/tutorials/streaming-replication.mdx Run `xata clone stream` with your connection string to create an initial snapshot, set up the streaming pipeline, and begin continuous replication. ```bash xata clone stream --source-url $CONN_STRING ``` -------------------------------- ### Create database configuration (config/database.go) Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/gorm.mdx Defines the InitDB function that loads environment variables, reads the DATABASE_URL, and opens a GORM connection with the PostgreSQL driver. Logs fatal errors if the .env file or DATABASE_URL is missing, and prints a success message on connection. ```go // config/database.go package config import ( "fmt" "log" "os" "github.com/joho/godotenv" "gorm.io/driver/postgres" "gorm.io/gorm" "gorm.io/gorm/logger" ) var DB *gorm.DB func InitDB() { // Load environment variables if err := godotenv.Load(); err != nil { log.Fatal("Error loading .env file") } dsn := os.Getenv("DATABASE_URL") if dsn == "" { log.Fatal("DATABASE_URL environment variable is required") } var err error DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{ Logger: logger.Default.LogMode(logger.Info), }) if err != nil { log.Fatal("Failed to connect to database:", err) } fmt.Println("Database connection established") } ``` -------------------------------- ### List users response - 200 OK Source: https://github.com/xataio/docs/blob/main/docs/api/users.mdx Example response for the GET /users endpoint, returning a list of user objects with basic profile information. ```json { "users": [ { "id": "user_123", "email": "user@example.com", "name": "John Doe", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } ] } ``` -------------------------------- ### Response JSON for Get API key Source: https://github.com/xataio/docs/blob/main/docs/api/api-keys.mdx Example JSON response returned with status 200 OK. Contains metadata, permissions, and access details for the API key. ```json { "id": "key_123", "name": "Production API Key", "preview": "xata_...", "created_at": "2024-01-01T00:00:00Z", "created_by": "user_123", "created_by_key": null, "expiry": "2025-01-01T00:00:00Z", "last_used": "2024-01-15T10:30:00Z", "scopes": ["read", "write"], "projects": ["proj_123"], "branches": ["br_123"] } ``` -------------------------------- ### Kubernetes CronJob manifest for nightly Xata clone Source: https://github.com/xataio/docs/blob/main/docs/automations/kubernetes-clone.mdx Defines a Kubernetes CronJob named 'xata-clone' that runs daily at midnight. It uses the 'ubuntu:latest' image, installs dependencies (curl, jq, perl, gnupg, lsb-release, postgresql-client-17), installs the Xata CLI, initializes the project, checks out the specified branch, and starts a clone with relaxed validation. Environment variables are sourced from a Kubernetes secret named 'xata-secrets'. The restart policy is 'OnFailure'. ```yaml apiVersion: batch/v1 kind: CronJob metadata: name: xata-clone namespace: xata-clone # change if needed spec: schedule: "0 0 * * *" # change if needed jobTemplate: spec: template: spec: containers: - name: xata-clone image: ubuntu:latest env: - name: XATA_CLI_SOURCE_POSTGRES_URL valueFrom: secretKeyRef: name: xata-secrets key: source-postgres-url - name: XATA_API_KEY valueFrom: secretKeyRef: name: xata-secrets key: XATA_API_KEY - name: XATA_ORGANIZATIONID valueFrom: secretKeyRef: name: xata-secrets key: XATA_ORGANIZATIONID - name: XATA_PROJECTID valueFrom: secretKeyRef: name: xata-secrets key: XATA_PROJECTID - name: XATA_BRANCHNAME valueFrom: secretKeyRef: name: xata-secrets key: XATA_BRANCHNAME - name: XATA_DATABASENAME valueFrom: secretKeyRef: name: xata-secrets key: XATA_DATABASENAME command: - /bin/bash - -c - | set -e echo "Installing dependencies" apt-get update && \ apt-get install -y curl jq perl gnupg lsb-release && \ echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list && \ curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | gpg --dearmor -o /usr/share/keyrings/postgresql.gpg && \ echo "deb [signed-by=/usr/share/keyrings/postgresql.gpg] http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list && \ apt-get update && \ apt-get install -y postgresql-client-17 echo "Installing Xata CLI" curl -fsSL https://xata.io/install.sh | bash export PATH="$HOME/.config/xata/bin/:$PATH" xata init --organization $XATA_ORGANIZATIONID --project $XATA_PROJECTID --database $XATA_DATABASENAME xata status --json echo "Checking out branch: $XATA_BRANCHNAME" xata branch checkout "$XATA_BRANCHNAME" echo "Updated status:" xata status xata branch view echo "Starting clone..." xata clone start --source-url "$XATA_CLI_SOURCE_POSTGRES_URL" --validation-mode=relaxed restartPolicy: OnFailure ``` -------------------------------- ### Create Sample Application with SQLAlchemy (app.py) Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/sqlalchemy.mdx This snippet creates a sample application that demonstrates SQLAlchemy functionality. It creates database tables, initializes ProductService and OrderService, creates sample products, queries products by rating, creates an order, adds items, retrieves order details, and updates a product. The application uses a database session from SessionLocal and closes it in a finally block. ```python # app.py from decimal import Decimal from db.config import SessionLocal from services import ProductService, OrderService from models import Base, engine def main(): # Create tables (in production, use migrations) Base.metadata.create_all(bind=engine) # Get database session db = SessionLocal() try: # Initialize services product_service = ProductService(db) order_service = OrderService(db) # Create sample products print("Creating sample products...") products = [ product_service.create_product("Wireless Headphones", Decimal("99.99"), 5), product_service.create_product("Smartphone", Decimal("699.99"), 4), product_service.create_product("Laptop", Decimal("1299.99"), 5), product_service.create_product("Coffee Maker", Decimal("89.99"), 4), ] print(f"Created {len(products)} products") # Display all products print("\nAll products:") all_products = product_service.get_all_products() for product in all_products: print(f"- {product.name}: ${product.price} (Rating: {product.rating}/5)") # Get products by rating print("\nTop-rated products (5 stars):") top_products = product_service.get_products_by_rating(5) for product in top_products: print(f"- {product.name}: ${product.price}") # Create an order with items print("\nCreating an order...") order = order_service.create_order() print(f"Created order #{order.id}") # Add items to order order_service.add_item_to_order(order.id, products[0].id, 2) # 2 headphones order_service.add_item_to_order(order.id, products[2].id, 1) # 1 laptop # Get order details with products print("\nOrder details:") order_details = order_service.get_orders_with_product_details() for detail in order_details: print(f"Order #{detail['order_id']}: {detail['product_name']} x{detail['qty']} = ${detail['total']}") # Update a product print("\nUpdating product...") updated_product = product_service.update_product( products[0].id, name="Premium Wireless Headphones", price=Decimal("129.99") ) print(f"Updated: {updated_product.name} - ${updated_product.price}") finally: db.close() if __name__ == "__main__": main() ``` -------------------------------- ### Full Xata clone workflow YAML Source: https://github.com/xataio/docs/blob/main/docs/automations/ga-clone.mdx Complete GitHub Actions workflow that schedules a daily clone at midnight and allows manual triggers. It sets required environment variables from GitHub secrets and runs steps to install the Xata CLI, check status, and start the clone. ```yaml name: Xata clone (daily, on-demand) on: schedule: - cron: "0 0 * * *" # Run daily at midnight workflow_dispatch: # Allow manual triggers env: XATA_API_KEY: ${{ secrets.XATA_API_KEY }} XATA_ORGANIZATIONID: ${{ secrets.XATA_ORGANIZATIONID }} XATA_PROJECTID: ${{ secrets.XATA_PROJECTID }} XATA_BRANCHID: ${{ secrets.XATA_BRANCHID }} XATA_BRANCHNAME: ${{ secrets.XATA_BRANCHNAME }} XATA_DATABASENAME: ${{ secrets.XATA_DATABASENAME }} XATA_CLI_SOURCE_POSTGRES_URL: ${{ secrets.XATA_CLI_SOURCE_POSTGRES_URL }} jobs: clone: name: Xata Clone runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Xata CLI run: | curl -fsSL https://xata.io/install.sh | bash echo "/home/runner/.config/xata/bin" >> $GITHUB_PATH - name: Check Xata status run: | xata status xata branch describe - name: Xata clone run: | xata clone start --source-url ${{ env.XATA_CLI_SOURCE_POSTGRES_URL }} ``` -------------------------------- ### Install and initialize Xata CLI Source: https://github.com/xataio/docs/blob/main/docs/index.mdx Install the Xata CLI globally, authenticate, initialize a project, and create or checkout branches. Use these commands to manage Xata databases from the terminal. ```bash # Install Xata CLI npm install -g @xata.io/cli # Authenticate and initialize xata auth xata init # Create and manage branches xata branch create feature-branch xata branch checkout main ``` -------------------------------- ### Install Xata CLI Source: https://github.com/xataio/docs/blob/main/docs/getting-started.mdx Installs the Xata CLI using the official install script. ```bash curl -fsSL https://xata.io/install.sh | bash ``` -------------------------------- ### Create initial migration file Source: https://github.com/xataio/docs/blob/main/docs/getting-started.mdx Creates a migration file for the initial schema with products, orders, and order_items tables. ```sh cat > .xata/migrations/001_initial_schema.yaml << 'EOL' operations: - create_table: name: products columns: - name: id type: serial - name: name type: text - name: price type: numeric(7,2) constraints: - name: products_pk type: primary_key columns: - id - create_table: name: orders columns: - name: id type: serial - name: created_at type: timestamptz default: now() constraints: - name: orders_pk type: primary_key columns: - id - create_table: name: order_items columns: - name: order_id type: int - name: product_id type: int - name: qty type: int constraints: - name: order_items_pk type: primary_key columns: - order_id - product_id - name: order_items_order_id_fk type: foreign_key columns: - order_id references: table: orders columns: - id - name: order_items_product_id_fk type: foreign_key columns: - product_id references: table: products columns: - id EOL ``` -------------------------------- ### Install gems with bundle install Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/rails.mdx Installs the gems specified in the Gemfile, including the newly added dotenv-rails gem. ```bash bundle install ``` -------------------------------- ### Compile and run with Maven Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/jpa.mdx Use these Maven commands to compile the project and execute the main class com.example.Main. ```bash mvn compile mvn exec:java -Dexec.mainClass="com.example.Main" ``` -------------------------------- ### Install Dependencies Steps Source: https://github.com/xataio/docs/blob/main/docs/automations/ga-pr.mdx Installs pnpm version 10 and the Xata CLI via the official install script. ```yaml - name: Install pnpm uses: pnpm/action-setup@v2 with: version: 10 - name: Install Xata CLI run: | curl -fsSL https://xata.io/install.sh | bash echo "/home/runner/.config/xata/bin" >> $GITHUB_PATH ``` -------------------------------- ### Install Xata CLI step Source: https://github.com/xataio/docs/blob/main/docs/automations/ga-check.mdx GitHub Actions step that installs the Xata CLI using the official installer script and adds it to the PATH. ```yaml - name: Install Xata CLI run: | curl -fsSL https://xata.io/install.sh | bash ``` -------------------------------- ### Install Xata CLI using the official install script Source: https://github.com/xataio/docs/blob/main/docs/cli/cli.mdx Installs the Xata CLI on Linux and macOS. The binary is placed in ~/.config/xata/bin/, which must be added to your PATH. ```bash # Install using the official install script curl -fsSL https://xata.io/install.sh | bash ``` -------------------------------- ### Initialize Prisma Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/prisma.mdx Run npx prisma init to initialize Prisma in your project. ```bash npx prisma init ``` -------------------------------- ### xata branch get Source: https://github.com/xataio/docs/blob/main/docs/cli/branch.mdx Get a field from a branch description. ```APIDOC ## xata branch get ### Description Get a field from a branch description. ### Method CLI command ### Command `xata branch get [--organization <id>] [--project <id>] [--branch <id>] [-h|--help] <field>` ### Parameters #### Options - `--organization` (string) - Optional - Organization ID (default: "") - `--project` (string) - Optional - Project ID (default: "") - `--branch` (string) - Optional - Branch ID (default: "") - `-h, --help` - Optional - Print help information and exit #### Arguments - `field` (string) - Required - The field to get (default: `.catalog`) ``` -------------------------------- ### Create a new Node.js project Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/nodejs.mdx Run these commands to create a new directory and initialize a Node.js project with npm. ```bash mkdir my-xata-app cd my-xata-app npm init -y ``` -------------------------------- ### Get a field from a project with xata project get Source: https://github.com/xataio/docs/blob/main/docs/cli/project.mdx Gets a field from a project description. The `field` argument defaults to `.catalog`. Supports optional `--organization` and `--project` filters. ```bash xata project get [--organization <id>] [--project <id>] <field> [-h|--help] ``` -------------------------------- ### Create store/urls.py with product and order URL patterns Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/django.mdx Defines URL patterns for product list, product detail, product creation, and order list views in the store app. ```python # store/urls.py from django.urls import path from . import views urlpatterns = [ path('products/', views.product_list, name='product_list'), path('products/<int:product_id>/', views.product_detail, name='product_detail'), path('products/create/', views.create_product, name='create_product'), path('orders/', views.order_list, name='order_list'), ] ``` -------------------------------- ### xata roll start Source: https://github.com/xataio/docs/blob/main/docs/cli/roll.mdx Starts a migration for the operations present in the given file. ```APIDOC ## xata roll start ### Description Start a migration for the operations present in the given file. ### Command `xata roll start <file> [--lock-timeout <ms>] [--pgroll-schema <schema>] [--postgres-url <url>] [--role <role>] [--schema <schema>] [--use-version-schema] [--verbose] [--backfill-batch-delay <delay>] [--backfill-batch-size <size>] [--complete] [--skip-validation] [-h|--help]` ### Arguments - `<file>` (string) - Required - The migration file to start ### Options - `--lock-timeout` (integer) - Optional - Postgres lock timeout in milliseconds for pgroll DDL operations - `--pgroll-schema` (string) - Optional - Postgres schema to use for pgroll internal state - `--postgres-url` (string) - Optional - Postgres URL - `--role` (string) - Optional - Optional postgres role to set when executing migrations - `--schema` (string) - Optional - Postgres schema to use for the migration - `--use-version-schema` (boolean) - Optional - Create version schemas for each migration - `--verbose` (boolean) - Optional - Enable verbose logging - `--backfill-batch-delay` (string) - Optional - Duration of delay between batch backfills (eg. 1s, 1000ms) - `--backfill-batch-size` (integer) - Optional - Number of rows backfilled in each batch - `--complete` (boolean) - Optional - Mark the migration as complete - `--skip-validation` (boolean) - Optional - Skip migration validation - `-h, --help` (boolean) - Optional - Print help information and exit ``` -------------------------------- ### Initialize Xata project Source: https://github.com/xataio/docs/blob/main/docs/getting-started.mdx Initializes the project in the current directory, creating a .xata directory with project configuration. ```bash xata init ``` -------------------------------- ### Create initial schema with SQL Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/drizzle.mdx Run these SQL commands in the Xata console Queries tab to create the initial schema for products, orders, and order_items tables. ```sql CREATE TABLE products ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, price NUMERIC(7,2) NOT NULL, rating INTEGER ); CREATE TABLE orders ( id SERIAL PRIMARY KEY, created_at TIMESTAMPTZ DEFAULT NOW() ); CREATE TABLE order_items ( order_id INTEGER REFERENCES orders(id), product_id INTEGER REFERENCES products(id), qty INTEGER NOT NULL, PRIMARY KEY (order_id, product_id) ); ``` -------------------------------- ### Install pgloader Source: https://github.com/xataio/docs/blob/main/docs/migrations/mysql.mdx Install pgloader on Ubuntu/Debian or macOS using the respective package manager. ```bash # Install pgloader # Ubuntu/Debian sudo apt-get install pgloader # macOS brew install pgloader ``` -------------------------------- ### Run the application Source: https://github.com/xataio/docs/blob/main/docs/quickstarts/gorm.mdx Command to run the main Go application. ```bash go run main.go ```