diff --git a/.github/ISSUE_TEMPLATE/UPDATE.md b/.github/ISSUE_TEMPLATE/UPDATE.md new file mode 100644 index 0000000..c131553 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/UPDATE.md @@ -0,0 +1,31 @@ +--- +name: Documentation Update +about: Suggest updates, additions, or improvements to the documentation +title: '[Docs Update] ' +labels: 'documentation' +assignees: '' +--- + +## Documentation Area +*Indicate the area of the documentation that needs updating (e.g., API reference, user guide, tutorials, etc.).* + +### Current Documentation Link +*Provide a link to the current documentation that needs updating (if applicable).* + +[Link to the current documentation] + +## Description of Changes +*Describe the changes you would like to see in the documentation.* + +## Rationale +*Explain why these changes are necessary or how they improve the documentation.* + +## Examples and Code Snippets +*Include any examples or code snippets that should be added to the documentation.* + +### Example 1 + +### Example 2 + +## Additional Context and Relevant Repos +*Provide any additional context or information that will help in making the necessary updates.* diff --git a/.github/workflows/aisearch.yaml b/.github/workflows/aisearch.yaml new file mode 100644 index 0000000..c5e8eac --- /dev/null +++ b/.github/workflows/aisearch.yaml @@ -0,0 +1,24 @@ +name: Process docs for SQLite AI Search + +on: + push: + branches: + - main + - stage + workflow_dispatch: + +jobs: + docsearch: + runs-on: ubuntu-latest + environment: ${{ github.ref_name }} + + steps: + - uses: actions/checkout@v4 + + - uses: sqliteai/sqlite-aisearch-action@v1 + with: + connection_string: ${{ secrets.PROJECT_STRING }} + base_url: ${{ vars.BASE_URL }} + database_name: documentation_ai.sqlite + source_files: ./ + only_extensions: "md,mdx" diff --git a/.github/workflows/search.yml b/.github/workflows/search.yml index 96b127e..2c48cf0 100644 --- a/.github/workflows/search.yml +++ b/.github/workflows/search.yml @@ -13,12 +13,12 @@ jobs: steps: - uses: actions/checkout@v4 - - uses: sqlitecloud/docsearch-action@v3 + - uses: sqlitecloud/docsearch-action@v6 with: project-string: ${{ secrets.PROJECT_STRING }} base-url: ${{ vars.BASE_URL }} database: documentation.sqlite - strip-astro-header: true + use-front-matter: true strip-md-titles: true strip-jsx: true strip-html: true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e43b0f9 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.DS_Store diff --git a/README.md b/README.md index 941e356..4d0dcde 100644 --- a/README.md +++ b/README.md @@ -7,5 +7,5 @@ status: publish # SQLite Cloud Documentation The content folder contains all the documentation files that the docs.sqlitecloud.io website imports. -These pages are open source and can be edited by anyone. +These pages are open source and can be edited by anyone. Just submit a pull request. diff --git a/sqlite-cloud/_nav.ts b/sqlite-cloud/_nav.ts index 8fc25c0..ec1fb7b 100644 --- a/sqlite-cloud/_nav.ts +++ b/sqlite-cloud/_nav.ts @@ -1,166 +1,840 @@ import type { SidebarNavStruct } from "@docs-website/types/sidebar-navigation"; + + const sidebarNav: SidebarNavStruct = [ - { title: "", type: "primary" }, - { title: "Getting Started", type: "secondary", icon: "docs-star" }, - { title: "Introduction", href: "/docs/sqlite-cloud", type: "inner", level: 0 }, // should be index page for /docs and highlight "introduction" in nav - { title: "Fundamentals", type: "inner", level: 0 }, - { title: "Connecting", filePath: "sqlite-cloud/connect-cluster", type: "inner", level: 1 }, - { title: "Creating a database", filePath: "sqlite-cloud/create-database", type: "inner", level: 1 }, - { title: "Writing data", filePath: "sqlite-cloud/write-data", type: "inner", level: 1 }, - { title: "Quick Start Guides", type: "inner", level: 0 }, - { title: "React", filePath: "sqlite-cloud/quick-start-react", type: "inner", level: 1 }, - { title: "React Native", filePath: "sqlite-cloud/quick-start-react-native", type: "inner", level: 1 }, - - { title: "Platform", type: "secondary", icon: "docs-plat" }, - { title: "Edge Functions", filePath: "edge-functions", type: "inner", level: 0 }, - { title: "Webhooks", filePath: "webhooks", type: "inner", level: 0 }, - { title: "Pub/Sub", filePath: "pub-sub", type: "inner", level: 0 }, - { title: "Scaling", type: "inner", filePath: "scaling", level: 0 }, - { title: "Security and Access Control", filePath: "security", type: "inner", level: 0 }, - { title: "Backups", filePath: "backups", type: "inner", level: 0 }, - { title: "Query Analyzer", filePath: "analyzer", type: "inner", level: 0 }, - { title: "Extensions", filePath: "extensions", type: "inner", level: 0 }, - // { title: "Storage", type: "inner", level: 0 }, - // { title: "Partitioning", type: "inner", level: 0 }, - { title: "Settings", filePath: "settings", type: "inner", level: 0 }, - - { title: "SDKs", type: "secondary", icon: "docs-sdk" }, - { title: "C/C++", type: "inner", level: 0 }, - { title: "Introduction", type: "inner", filePath: "sqlite-cloud/sdks/c/getting-started", level: 1, }, - { title: 'Basic APIs', type: "inner", level: 1 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudConnect', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudConnectWithString', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudExec', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudExecArray', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudUUID', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudDisconnect', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudConfig', type: "inner", level: 2 }, - - { title: 'Result APIs', type: "inner", level: 1 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudResultIsOK', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudResultIsError', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudResultType', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudResultLen', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudResultInt32', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudResultInt64', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudResultFloat', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudResultDouble', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudResultFree', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudResultDump', type: "inner", level: 2 }, - - { title: "Rowset APIs", type: "inner", level: 1 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudRowsetValueType', type: "inner", level: 3 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudRowsetColumnName', type: "inner", level: 3 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudRowsetValue', type: "inner", level: 3 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudRowsetInt32Value', type: "inner", level: 3 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudRowsetInt64Value', type: "inner", level: 3 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudRowsetFloatValue', type: "inner", level: 3 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudRowsetDoubleValue', type: "inner", level: 3 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudRowsetDump', type: "inner", level: 3 }, - - - { title: "Array APIs", type: "inner", level: 1 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudArrayValueType', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudArrayCount', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudArrayValue', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudArrayInt32Value', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudArrayInt64Value', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudArrayFloatValue', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudArrayDoubleValue', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudArrayDump', type: "inner", level: 2 }, - - { title: "Error APIs", type: "inner", level: 1 }, - { title: 'SQCloudIsError', filePath: 'sqlite-cloud/sdks/c/SQCloudError', type: "inner", level: 2 }, - { title: 'SQCloudIsSQLiteError', filePath: 'sqlite-cloud/sdks/c/SQCloudError', type: "inner", level: 2 }, - { title: 'SQCloudErrorCode', filePath: 'sqlite-cloud/sdks/c/SQCloudError', type: "inner", level: 2 }, - { title: 'SQCloudExtendedErrorCode', filePath: 'sqlite-cloud/sdks/c/SQCloudError', type: "inner", level: 2 }, - { title: 'SQCloudErrorOffset', filePath: 'sqlite-cloud/sdks/c/SQCloudError', type: "inner", level: 2 }, - { title: 'SQCloudErrorMsg', filePath: 'sqlite-cloud/sdks/c/SQCloudError', type: "inner", level: 2 }, - - { title: "VM APIs", type: "inner", level: 1 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMCompile', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMStep', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMResult', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMClose', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMErrorMsg', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMErrorCode', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMIsReadOnly', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMIsExplain', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMIsFinalized', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMBindParameterCount', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMBindParameterIndex', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMBindParameterName', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMColumnCount', type: "inner", level: 2 }, - { title: 'SQCloudVMBindDouble', filePath: 'sqlite-cloud/sdks/c/SQCloudVMBind', type: "inner", level: 2 }, - { title: 'SQCloudVMBindInt', filePath: 'sqlite-cloud/sdks/c/SQCloudVMBind', type: "inner", level: 2 }, - { title: 'SQCloudVMBindInt64', filePath: 'sqlite-cloud/sdks/c/SQCloudVMBind', type: "inner", level: 2 }, - { title: 'SQCloudVMBindNull', filePath: 'sqlite-cloud/sdks/c/SQCloudVMBind', type: "inner", level: 2 }, - { title: 'SQCloudVMBindText', filePath: 'sqlite-cloud/sdks/c/SQCloudVMBind', type: "inner", level: 2 }, - { title: 'SQCloudVMBindBlob', filePath: 'sqlite-cloud/sdks/c/SQCloudVMBind', type: "inner", level: 2 }, - { title: 'SQCloudVMBindZeroBlob', filePath: 'sqlite-cloud/sdks/c/SQCloudVMBind', type: "inner", level: 2 }, - { title: 'SQCloudVMColumnBlob', filePath: 'sqlite-cloud/sdks/c/SQCloudVMColumn', type: "inner", level: 2 }, - { title: 'SQCloudVMColumnText', filePath: 'sqlite-cloud/sdks/c/SQCloudVMColumn', type: "inner", level: 2 }, - { title: 'SQCloudVMColumnDouble', filePath: 'sqlite-cloud/sdks/c/SQCloudVMColumn', type: "inner", level: 2 }, - { title: 'SQCloudVMColumnInt32', filePath: 'sqlite-cloud/sdks/c/SQCloudVMColumn', type: "inner", level: 2 }, - { title: 'SQCloudVMColumnInt64', filePath: 'sqlite-cloud/sdks/c/SQCloudVMColumn', type: "inner", level: 2 }, - { title: 'SQCloudVMColumnLen', filePath: 'sqlite-cloud/sdks/c/SQCloudVMColumn', type: "inner", level: 2 }, - { title: 'SQCloudVMColumnType', filePath: 'sqlite-cloud/sdks/c/SQCloudVMColumn', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMLastRowID', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMChanges', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudVMTotalChanges', type: "inner", level: 2 }, - { title: "Blob APIs", type: "inner", level: 1 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudBlobOpen', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudBlobReOpen', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudBlobClose', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudBlobBytes', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudBlobRead', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudBlobWrite', type: "inner", level: 2 }, - { title: "Pub/Sub APIs", type: "inner", level: 1 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudSetPubSubCallback', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudSetPubSubOnly', type: "inner", level: 2 }, - { title: "Upload/Download APIs", type: "inner", level: 1 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudUploadDatabase', type: "inner", level: 2 }, - { filePath: 'sqlite-cloud/sdks/c/SQCloudDownloadDatabase', type: "inner", level: 2 }, - - { title: "JavaScript", type: "inner", level: 0 }, - { title: 'Introduction', type: "inner", filePath: "sqlite-cloud/sdks/js/getting-started", level: 1 }, - { title: 'React Quick Start', type: "inner", filePath: "sqlite-cloud/quick-start-react", level: 1 }, - - { title: "Python", type: "inner", level: 0 }, - { title: 'Introduction', type: "inner", filePath: "sdk-python-introduction", level: 1 }, - - { title: "Go", type: "inner", level: 0 }, - { title: 'Introduction', type: "inner", filePath: "sqlite-cloud/sdks/go/getting-started", level: 1 }, - - { title: "PHP", type: "inner", level: 0 }, - { title: 'Introduction', type: "inner", filePath: "sqlite-cloud/sdks/php/getting-started", level: 1 }, - { title: "Methods", filePath: "sqlite-cloud/sdks/php/methods", type: "inner", level: 1 }, - - { title: "Reference", type: "secondary", icon: "docs-ref" }, - { title: "Server-side Commands", type: "inner", level: 0 }, - { title: "Introduction", filePath: "server-side-commands", type: "inner", level: 1 }, - { title: "API Keys", filePath: "api-key-commands", type: "inner", level: 1 }, - { title: "Authentication", filePath: "auth-commands", type: "inner", level: 1 }, - { title: "Backups", filePath: "backup-commands", type: "inner", level: 1 }, - { title: "Cluster", filePath: "cluster-commands", type: "inner", level: 1 }, - { title: "Database", filePath: "database-commands", type: "inner", level: 1 }, - { title: "General Info", filePath: "general-commands", type: "inner", level: 1 }, - { title: "IP", filePath: "ip-commands", type: "inner", level: 1 }, - { title: "Logs", filePath: "log-commands", type: "inner", level: 1 }, - { title: "Plugins", filePath: "plugin-commands", type: "inner", level: 1 }, - { title: "Privileges", filePath: "privilege-commands", type: "inner", level: 1 }, - { title: "Pub/Sub", filePath: "pub-sub-commands", type: "inner", level: 1 }, - { title: "Query Analyzer", filePath: "query-analyzer-commands", type: "inner", level: 1 }, - { title: "Roles", filePath: "role-commands", type: "inner", level: 1 }, - { title: "Settings", filePath: "settings-commands", type: "inner", level: 1 }, - { title: "User", filePath: "user-commands", type: "inner", level: 1 }, - - { title: "CLI", type: "inner", level: 0 }, - { title: "Introduction", filePath: "cli-commands", type: "inner", level: 1 }, - - { title: "SQLite", type: "inner", level: 0, href: "/docs/sqlite/" } + { title: "", type: "primary" }, + // ### AI ### + { title: "AI", type: "secondary", icon: "docs-star" }, + { title: "Overview", filePath: "ai-overview", type: "inner", level: 0 }, + { title: "SQLite-AI", filePath: "sqlite-ai", type: "inner", level: 0 }, + { title: "SQLite-JS", filePath: "sqlite-js", type: "inner", level: 0 }, + { title: "SQLite-Sync", type: "inner", level: 0 }, + { + title: "Introduction", + filePath: "sqlite-sync-introduction", + type: "inner", + level: 1, + }, + { + title: "Getting Started", + filePath: "sqlite-sync-getting-started", + type: "inner", + level: 1, + }, + { + title: "Best Practices", + filePath: "sqlite-sync-best-practices", + type: "inner", + level: 1, + }, + { title: "Quick Starts", type: "inner", level: 1 }, + { + title: "Android", + filePath: "sqlite-sync-quick-start-android", + type: "inner", + level: 2, + }, + { + title: "iOS", + filePath: "sqlite-sync-quick-start-ios", + type: "inner", + level: 2, + }, + { + title: "Linux", + filePath: "sqlite-sync-quick-start-linux", + type: "inner", + level: 2, + }, + { + title: "macOS", + filePath: "sqlite-sync-quick-start-macos", + type: "inner", + level: 2, + }, + { + title: "React Native Expo", + filePath: "sqlite-sync-quick-start-expo", + type: "inner", + level: 2, + }, + { + title: "WASM", + filePath: "sqlite-sync-quick-start-wasm", + type: "inner", + level: 2, + }, + { + title: "Windows", + filePath: "sqlite-sync-quick-start-windows", + type: "inner", + level: 2, + }, + { title: "API Reference", type: "inner", level: 1 }, + { + title: "cloudsync_init", + filePath: "sqlite-sync-api-cloudsync-init", + type: "inner", + level: 2, + }, + { + title: "cloudsync_enable", + filePath: "sqlite-sync-api-cloudsync-enable", + type: "inner", + level: 2, + }, + { + title: "cloudsync_disable", + filePath: "sqlite-sync-api-cloudsync-disable", + type: "inner", + level: 2, + }, + { + title: "cloudsync_is_enabled", + filePath: "sqlite-sync-api-cloudsync-is-enabled", + type: "inner", + level: 2, + }, + { + title: "cloudsync_cleanup", + filePath: "sqlite-sync-api-cloudsync-cleanup", + type: "inner", + level: 2, + }, + { + title: "cloudsync_terminate", + filePath: "sqlite-sync-api-cloudsync-terminate", + type: "inner", + level: 2, + }, + { + title: "cloudsync_version", + filePath: "sqlite-sync-api-cloudsync-version", + type: "inner", + level: 2, + }, + { + title: "cloudsync_siteid", + filePath: "sqlite-sync-api-cloudsync-siteid", + type: "inner", + level: 2, + }, + { + title: "cloudsync_db_version", + filePath: "sqlite-sync-api-cloudsync-db-version", + type: "inner", + level: 2, + }, + { + title: "cloudsync_uuid", + filePath: "sqlite-sync-api-cloudsync-uuid", + type: "inner", + level: 2, + }, + { + title: "cloudsync_begin_alter", + filePath: "sqlite-sync-api-cloudsync-begin-alter", + type: "inner", + level: 2, + }, + { + title: "cloudsync_commit_alter", + filePath: "sqlite-sync-api-cloudsync-commit-alter", + type: "inner", + level: 2, + }, + { + title: "cloudsync_network_init", + filePath: "sqlite-sync-api-cloudsync-network-init", + type: "inner", + level: 2, + }, + { + title: "cloudsync_network_cleanup", + filePath: "sqlite-sync-api-cloudsync-network-cleanup", + type: "inner", + level: 2, + }, + { + title: "cloudsync_network_set_token", + filePath: "sqlite-sync-api-cloudsync-network-set-token", + type: "inner", + level: 2, + }, + { + title: "cloudsync_network_set_apikey", + filePath: "sqlite-sync-api-cloudsync-network-set-apikey", + type: "inner", + level: 2, + }, + { + title: "cloudsync_network_has_unsent_changes", + filePath: "sqlite-sync-api-cloudsync-network-has-unsent-changes", + type: "inner", + level: 2, + }, + { + title: "cloudsync_network_send_changes", + filePath: "sqlite-sync-api-cloudsync-network-send-changes", + type: "inner", + level: 2, + }, + { + title: "cloudsync_network_check_changes", + filePath: "sqlite-sync-api-cloudsync-network-check-changes", + type: "inner", + level: 2, + }, + { + title: "cloudsync_network_sync", + filePath: "sqlite-sync-api-cloudsync-network-sync", + type: "inner", + level: 2, + }, + { + title: "cloudsync_network_reset_sync_version", + filePath: "sqlite-sync-api-cloudsync-network-reset-sync-version", + type: "inner", + level: 2, + }, + { + title: "cloudsync_network_logout", + filePath: "sqlite-sync-api-cloudsync-network-logout", + type: "inner", + level: 2, + }, + { + title: "SQLite-Vector", + filePath: "sqlite-vector", + type: "inner", + level: 0, + }, + { + title: "MCP (Model Context Protocol)", + filePath: "mcp-server", + type: "inner", + level: 0, + }, + { + title: "AI-Powered Docs Search", + filePath: "aisearch-documents", + type: "inner", + level: 0, + }, + + // ### CLOUD ### + { title: "Cloud", type: "secondary", icon: "docs-star" }, + { title: "Overview", filePath: "overview", type: "inner", level: 0 }, + { title: "Scaling", filePath: "architecture", type: "inner", level: 0 }, + { title: "Getting Started", type: "inner", level: 0 }, + { title: "Connecting", filePath: "connect-cluster", type: "inner", level: 1 }, + { + title: "Creating a database", + filePath: "create-database", + type: "inner", + level: 1, + }, + { title: "Writing data", filePath: "write-data", type: "inner", level: 1 }, + { title: "Quick Start Guides", type: "inner", level: 0 }, + { title: "CDN", filePath: "quick-start-cdn", type: "inner", level: 1 }, + { title: "Node.js", filePath: "quick-start-node", type: "inner", level: 1 }, + { title: "React", filePath: "quick-start-react", type: "inner", level: 1 }, + { + title: "React Native", + filePath: "quick-start-react-native", + type: "inner", + level: 1, + }, + { + title: "Apollo / GraphQL", + filePath: "quick-start-apollo-graphql", + type: "inner", + level: 1, + }, + { title: "Next.js", filePath: "quick-start-next", type: "inner", level: 1 }, + { title: "Django", filePath: "quick-start-django", type: "inner", level: 1 }, + { title: "Flask", filePath: "quick-start-flask", type: "inner", level: 1 }, + { + title: "SQLAlchemy", + filePath: "quick-start-sqlalchemy-orm", + type: "inner", + level: 1, + }, + { + title: "Streamlit", + filePath: "quick-start-streamlit", + type: "inner", + level: 1, + }, + { + title: "PHP / Laravel", + filePath: "quick-start-php-laravel", + type: "inner", + level: 1, + }, + { title: "Gin", filePath: "quick-start-gin", type: "inner", level: 1 }, + { title: "Knex.js", filePath: "quick-start-knex", type: "inner", level: 1 }, + + // ### PLATFORM ### + { title: "Platform", type: "secondary", icon: "docs-plat" }, + { + title: "Edge Functions", + filePath: "edge-functions", + type: "inner", + level: 0, + }, + { title: "Webhooks", filePath: "webhooks", type: "inner", level: 0 }, + { title: "Pub/Sub", filePath: "pub-sub", type: "inner", level: 0 }, + //{ title: "Vector", filePath: "vector", type: "inner", level: 0 }, + { title: "Users and Roles", filePath: "security", type: "inner", level: 0 }, + { title: "API Keys", filePath: "apikey", type: "inner", level: 0 }, + { title: "Row-Level Security", filePath: "rls", type: "inner", level: 0 }, + { title: "OffSync", filePath: "offsync", type: "inner", level: 0 }, + { + title: "Access Tokens", + filePath: "access-tokens", + type: "inner", + level: 0, + }, + { title: "Backups", filePath: "backups", type: "inner", level: 0 }, + { title: "Query Analyzer", filePath: "analyzer", type: "inner", level: 0 }, + { title: "Logs", filePath: "logs", type: "inner", level: 0 }, + { title: "Extensions", filePath: "extensions", type: "inner", level: 0 }, + { title: "Weblite (REST API)", filePath: "weblite", type: "inner", level: 0 }, + + // ### CLOUD SDK ### + { title: "Cloud SDK", type: "secondary", icon: "docs-sdk" }, + { title: "C/C++", type: "inner", level: 0 }, + { + title: "Introduction", + type: "inner", + filePath: "sdk-c-introduction", + level: 1, + }, + { title: "Basic APIs", type: "inner", level: 1 }, + { filePath: "sqlite-cloud/sdks/c/SQCloudConnect", type: "inner", level: 2 }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudConnectWithString", + type: "inner", + level: 2, + }, + { filePath: "sqlite-cloud/sdks/c/SQCloudExec", type: "inner", level: 2 }, + { filePath: "sqlite-cloud/sdks/c/SQCloudExecArray", type: "inner", level: 2 }, + { filePath: "sqlite-cloud/sdks/c/SQCloudUUID", type: "inner", level: 2 }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudDisconnect", + type: "inner", + level: 2, + }, + { filePath: "sqlite-cloud/sdks/c/SQCloudConfig", type: "inner", level: 2 }, + + { title: "Result APIs", type: "inner", level: 1 }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudResultIsOK", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudResultIsError", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudResultType", + type: "inner", + level: 2, + }, + { filePath: "sqlite-cloud/sdks/c/SQCloudResultLen", type: "inner", level: 2 }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudResultInt32", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudResultInt64", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudResultFloat", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudResultDouble", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudResultFree", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudResultDump", + type: "inner", + level: 2, + }, + + { title: "Rowset APIs", type: "inner", level: 1 }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudRowsetValueType", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudRowsetColumnName", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudRowsetValue", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudRowsetInt32Value", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudRowsetInt64Value", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudRowsetFloatValue", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudRowsetDoubleValue", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudRowsetDump", + type: "inner", + level: 2, + }, + + { title: "Array APIs", type: "inner", level: 1 }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudArrayValueType", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudArrayCount", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudArrayValue", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudArrayInt32Value", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudArrayInt64Value", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudArrayFloatValue", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudArrayDoubleValue", + type: "inner", + level: 2, + }, + { filePath: "sqlite-cloud/sdks/c/SQCloudArrayDump", type: "inner", level: 2 }, + + { title: "Error APIs", type: "inner", level: 1 }, + { + title: "SQCloudIsError", + filePath: "sqlite-cloud/sdks/c/SQCloudError", + type: "inner", + level: 2, + }, + { + title: "SQCloudIsSQLiteError", + filePath: "sqlite-cloud/sdks/c/SQCloudError", + type: "inner", + level: 2, + }, + { + title: "SQCloudErrorCode", + filePath: "sqlite-cloud/sdks/c/SQCloudError", + type: "inner", + level: 2, + }, + { + title: "SQCloudExtendedErrorCode", + filePath: "sqlite-cloud/sdks/c/SQCloudError", + type: "inner", + level: 2, + }, + { + title: "SQCloudErrorOffset", + filePath: "sqlite-cloud/sdks/c/SQCloudError", + type: "inner", + level: 2, + }, + { + title: "SQCloudErrorMsg", + filePath: "sqlite-cloud/sdks/c/SQCloudError", + type: "inner", + level: 2, + }, + + { title: "VM APIs", type: "inner", level: 1 }, + { filePath: "sqlite-cloud/sdks/c/SQCloudVMCompile", type: "inner", level: 2 }, + { filePath: "sqlite-cloud/sdks/c/SQCloudVMStep", type: "inner", level: 2 }, + { filePath: "sqlite-cloud/sdks/c/SQCloudVMResult", type: "inner", level: 2 }, + { filePath: "sqlite-cloud/sdks/c/SQCloudVMClose", type: "inner", level: 2 }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudVMErrorMsg", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudVMErrorCode", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudVMIsReadOnly", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudVMIsExplain", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudVMIsFinalized", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudVMBindParameterCount", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudVMBindParameterIndex", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudVMBindParameterName", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudVMColumnCount", + type: "inner", + level: 2, + }, + { + title: "SQCloudVMBindDouble", + filePath: "sqlite-cloud/sdks/c/SQCloudVMBind", + type: "inner", + level: 2, + }, + { + title: "SQCloudVMBindInt", + filePath: "sqlite-cloud/sdks/c/SQCloudVMBind", + type: "inner", + level: 2, + }, + { + title: "SQCloudVMBindInt64", + filePath: "sqlite-cloud/sdks/c/SQCloudVMBind", + type: "inner", + level: 2, + }, + { + title: "SQCloudVMBindNull", + filePath: "sqlite-cloud/sdks/c/SQCloudVMBind", + type: "inner", + level: 2, + }, + { + title: "SQCloudVMBindText", + filePath: "sqlite-cloud/sdks/c/SQCloudVMBind", + type: "inner", + level: 2, + }, + { + title: "SQCloudVMBindBlob", + filePath: "sqlite-cloud/sdks/c/SQCloudVMBind", + type: "inner", + level: 2, + }, + { + title: "SQCloudVMBindZeroBlob", + filePath: "sqlite-cloud/sdks/c/SQCloudVMBind", + type: "inner", + level: 2, + }, + { + title: "SQCloudVMColumnBlob", + filePath: "sqlite-cloud/sdks/c/SQCloudVMColumn", + type: "inner", + level: 2, + }, + { + title: "SQCloudVMColumnText", + filePath: "sqlite-cloud/sdks/c/SQCloudVMColumn", + type: "inner", + level: 2, + }, + { + title: "SQCloudVMColumnDouble", + filePath: "sqlite-cloud/sdks/c/SQCloudVMColumn", + type: "inner", + level: 2, + }, + { + title: "SQCloudVMColumnInt32", + filePath: "sqlite-cloud/sdks/c/SQCloudVMColumn", + type: "inner", + level: 2, + }, + { + title: "SQCloudVMColumnInt64", + filePath: "sqlite-cloud/sdks/c/SQCloudVMColumn", + type: "inner", + level: 2, + }, + { + title: "SQCloudVMColumnLen", + filePath: "sqlite-cloud/sdks/c/SQCloudVMColumn", + type: "inner", + level: 2, + }, + { + title: "SQCloudVMColumnType", + filePath: "sqlite-cloud/sdks/c/SQCloudVMColumn", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudVMLastRowID", + type: "inner", + level: 2, + }, + { filePath: "sqlite-cloud/sdks/c/SQCloudVMChanges", type: "inner", level: 2 }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudVMTotalChanges", + type: "inner", + level: 2, + }, + { title: "Blob APIs", type: "inner", level: 1 }, + { filePath: "sqlite-cloud/sdks/c/SQCloudBlobOpen", type: "inner", level: 2 }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudBlobReOpen", + type: "inner", + level: 2, + }, + { filePath: "sqlite-cloud/sdks/c/SQCloudBlobClose", type: "inner", level: 2 }, + { filePath: "sqlite-cloud/sdks/c/SQCloudBlobBytes", type: "inner", level: 2 }, + { filePath: "sqlite-cloud/sdks/c/SQCloudBlobRead", type: "inner", level: 2 }, + { filePath: "sqlite-cloud/sdks/c/SQCloudBlobWrite", type: "inner", level: 2 }, + { title: "Pub/Sub APIs", type: "inner", level: 1 }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudSetPubSubCallback", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudSetPubSubOnly", + type: "inner", + level: 2, + }, + { title: "Upload/Download APIs", type: "inner", level: 1 }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudUploadDatabase", + type: "inner", + level: 2, + }, + { + filePath: "sqlite-cloud/sdks/c/SQCloudDownloadDatabase", + type: "inner", + level: 2, + }, + + { title: "JavaScript", type: "inner", level: 0 }, + { + title: "Introduction", + type: "inner", + filePath: "sdk-js-introduction", + level: 1, + }, + { title: "Quick Starts", type: "inner", level: 1 }, + { title: "React", ref: "/docs/quick-start-react", type: "inner", level: 2 }, + { title: "Node.js", ref: "/docs/quick-start-node", type: "inner", level: 2 }, + { title: "Next.js", ref: "/docs/quick-start-next", type: "inner", level: 2 }, + { title: "Tutorials", type: "inner", level: 1 }, + { + title: "Using SQLite Extensions - Geopoly", + ref: "/docs/tutorial-geopoly", + type: "inner", + level: 2, + }, + { title: "Classes", type: "inner", level: 1 }, + { + title: "Database", + filePath: "sqlite-cloud/sdks/js/classes/Database", + type: "inner", + level: 2, + }, + { + title: "SQLiteCloudConnection", + filePath: "sqlite-cloud/sdks/js/classes/SQLiteCloudConnection", + type: "inner", + level: 2, + }, + { + title: "SQLiteCloudError", + filePath: "sqlite-cloud/sdks/js/classes/SQLiteCloudError", + type: "inner", + level: 2, + }, + { + title: "SQLiteCloudRow", + filePath: "sqlite-cloud/sdks/js/classes/SQLiteCloudRow", + type: "inner", + level: 2, + }, + { + title: "SQLiteCloudRowset", + filePath: "sqlite-cloud/sdks/js/classes/SQLiteCloudRowset", + type: "inner", + level: 2, + }, + { + title: "SQLiteCloudStatement", + filePath: "sqlite-cloud/sdks/js/classes/Statement", + type: "inner", + level: 2, + }, + + { title: "Interfaces", type: "inner", level: 1 }, + { + title: "SQLCloudRowsetMetadata", + filePath: "sqlite-cloud/sdks/js/interfaces/SQLCloudRowsetMetadata", + type: "inner", + level: 2, + }, + { + title: "SQLiteCloudConfig", + filePath: "sqlite-cloud/sdks/js/interfaces/SQLiteCloudConfig", + type: "inner", + level: 2, + }, + { title: "Modules", filePath: "sdk-js-modules", type: "inner", level: 1 }, + + { title: "Python", type: "inner", level: 0 }, + { + title: "Introduction", + type: "inner", + filePath: "sdk-python-introduction", + level: 1, + }, + { title: "Django", ref: "/docs/quick-start-django", type: "inner", level: 1 }, + { title: "Flask", ref: "/docs/quick-start-flask", type: "inner", level: 1 }, + { + title: "SQLAlchemy", + ref: "/docs/quick-start-sqlalchemy-orm", + type: "inner", + level: 1, + }, + + { title: "Go", type: "inner", level: 0 }, + { + title: "Introduction", + type: "inner", + filePath: "sdk-go-introduction", + level: 1, + }, + + { title: "PHP", type: "inner", level: 0 }, + { + title: "Introduction", + type: "inner", + filePath: "sdk-php-introduction", + level: 1, + }, + { title: "Methods", filePath: "sdk-php-methods", type: "inner", level: 1 }, + + { title: "Swift", type: "inner", level: 0 }, + { + title: "Introduction", + type: "inner", + filePath: "sdk-swift-introduction", + level: 1, + }, + + // ### REFERENCE ### + { title: "Reference", type: "secondary", icon: "docs-ref" }, + { title: "Server-side Commands", type: "inner", level: 0 }, + { + title: "Introduction", + filePath: "server-side-commands", + type: "inner", + level: 1, + }, + { title: "API Keys", filePath: "api-key-commands", type: "inner", level: 1 }, + { + title: "Authentication", + filePath: "auth-commands", + type: "inner", + level: 1, + }, + { title: "Backups", filePath: "backup-commands", type: "inner", level: 1 }, + { title: "Cluster", filePath: "cluster-commands", type: "inner", level: 1 }, + { title: "Database", filePath: "database-commands", type: "inner", level: 1 }, + { + title: "General Info", + filePath: "general-commands", + type: "inner", + level: 1, + }, + { title: "IP", filePath: "ip-commands", type: "inner", level: 1 }, + { title: "Logs", filePath: "log-commands", type: "inner", level: 1 }, + { title: "Plugins", filePath: "plugin-commands", type: "inner", level: 1 }, + { + title: "Privileges", + filePath: "privilege-commands", + type: "inner", + level: 1, + }, + { title: "Pub/Sub", filePath: "pub-sub-commands", type: "inner", level: 1 }, + { + title: "Query Analyzer", + filePath: "query-analyzer-commands", + type: "inner", + level: 1, + }, + { title: "Roles", filePath: "role-commands", type: "inner", level: 1 }, + { title: "Settings", filePath: "settings-commands", type: "inner", level: 1 }, + { title: "User", filePath: "user-commands", type: "inner", level: 1 }, + + { title: "CLI", type: "inner", level: 0 }, + { title: "Introduction", filePath: "cli-commands", type: "inner", level: 1 }, + { title: "SQLite", type: "inner", level: 0, href: "/docs/sqlite" }, ]; -export default sidebarNav +export default sidebarNav; diff --git a/sqlite-cloud/_wip-index-with-card.mdx b/sqlite-cloud/_wip-index-with-card.mdx new file mode 100644 index 0000000..36642ea --- /dev/null +++ b/sqlite-cloud/_wip-index-with-card.mdx @@ -0,0 +1,35 @@ +--- +title: Getting Started +description: Index page for getting started section +category: getting-started +status: publish +icon: docs-star +slug: getting-started +--- +import IndexPage from "@docs-website-components/Docs/IndexPage.astro" + +export const introduction = "SQLite Cloud is a distributed relational database system built on top of the SQLite database engine. It has been specifically designed from the ground up to ensure the strong consistency of your data across all nodes in a cluster while simultaneously managing the technical aspects of scaling, security, and data distribution." + +export const sections = [ + { + icon: "curvedArrow", + title: "Introduction", + description: "SQLite Cloud introduction and getting started guide.", + href: "/docs/introduction", + }, + { + icon: "twoColsGrid", + title: "Fundamentals", + description: "Learn how to connect to a cluster and start using SQLite Cloud.", + href: "/docs/connect-cluster", + }, + { + icon: "puzzle", + title: "Quick start guide", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/quick-start-cdn", + } +] + + + \ No newline at end of file diff --git a/sqlite-cloud/platform/scaling.mdx b/sqlite-cloud/architecture.mdx similarity index 71% rename from sqlite-cloud/platform/scaling.mdx rename to sqlite-cloud/architecture.mdx index 122a8a3..42eba8c 100644 --- a/sqlite-cloud/platform/scaling.mdx +++ b/sqlite-cloud/architecture.mdx @@ -1,11 +1,20 @@ --- -title: Scaling -description: How to scale your SQLite Cloud cluster. -category: platform +title: Architecture +description: SQLite Cloud Architecture +category: getting-started status: publish -slug: scaling +slug: architecture --- + +## Architecture +SQLite Cloud uses the Raft consensus algorithm to distribute your data changes across a cluster of computing systems, ensuring that each node in the cluster agrees upon the same series of state transitions. Raft implements consensus with a leader approach. + +SQLite Cloud is written in ANSI C and GO, and it works on most POSIX systems (Linux, *BSD, Mac OS X) and Windows. + +SQLite Cloud supports all the SQLite features without any limitations, including ACID compliance and non-deterministic SQL statements. + +## Scaling your cluster SQLite Cloud leverages a customized Raft algorithm to maintain a robust and highly available database cluster. Here’s an essential guide on the node types within SQLite Cloud and strategic tips for scaling your cluster effectively. ## Overview of Node types diff --git a/sqlite-cloud/connect-cluster.mdx b/sqlite-cloud/connect-cluster.mdx index ac44370..ef7b444 100644 --- a/sqlite-cloud/connect-cluster.mdx +++ b/sqlite-cloud/connect-cluster.mdx @@ -3,14 +3,16 @@ title: Connecting to a Cluster description: Learn how to connect to a cluster in SQLite Cloud. category: getting-started status: publish +slug: connect-cluster --- SQLite databases in SQLite Cloud are distributed across a cluster of nodes. Each cluster comes with a multi-region load balancer that routes traffic to the nearest appropriate node. -For this reason, we strongly recommend connecting to your cluster via your project connection string. To retrive your project connection string, navigate to the **Nodes** page and click on any node. -{/* ![Project connection string modal](@docs-website-assets/connect-cluster-1.png) */} +Click "Connect" in the bottom left-hand corner of your dashboard to get your connection string to use with a SQLite Cloud client library. + + +--- -Copy the connection string and use it with a client library to connect to your cluster. ## Connecting with JavaScript Here's an example of how you can connect to your cluster using the `@sqlitecloud/drivers` JavaScript client library: @@ -35,6 +37,8 @@ fetchAlbums().then((albums) => console.log(albums)); // [{ Title: 'For Those About To Rock We Salute You', ... }, ...] ``` +--- + ## Connecting with Python Install the Python client library: @@ -61,6 +65,8 @@ conn.close() # (1, 'For Those About To Rock We Salute You', 1) ``` +--- + ## Next Steps -- [Importing databases](#) -- [Writing data](#) +- [Creating a database](/docs/create-database) +- [Writing data](/docs/write-data) diff --git a/sqlite-cloud/create-database.mdx b/sqlite-cloud/create-database.mdx index fbf69c6..f98e205 100644 --- a/sqlite-cloud/create-database.mdx +++ b/sqlite-cloud/create-database.mdx @@ -3,30 +3,53 @@ title: Creating a Database description: Learn how to import a database into SQLite Cloud. category: getting-started status: publish +slug: create-database --- -Create a new database in SQLite Cloud by importing an existing SQLite database, or using the SQLite Cloud UI, API, or client libraries. +import VideoPlayer from '@commons-components/Video/VideoPlayer.astro'; +import uploadDb from '@docs-website-assets/introduction/video/dashboard_upload_db.mp4'; +import createDb from '@docs-website-assets/introduction/video/dashboard_create_db.mp4'; -## Importing an existing SQLite database -SQLite Cloud allows you to import existing SQLite databases into the platform. +You can import an existing SQLite databases, or create new databases using the SQLite Cloud UI, API, or client libraries. -Note that you can download, modify, and re-upload the database file at any time. You can also upload encrypted SQLite databases if you used the official SEE SQLite encryption extension. +--- + +## Uploading an existing SQLite Database +### Via HTTP API +You can upload an existing SQLite database to your cluster using the SQLite Cloud UI or the Weblite API. + +To upload a local SQLite database via weblite, make a POST request to the `/v2/weblite/.sqlite` endpoint. + +```bash +curl -X 'POST' \ + 'https://.sqlite.cloud:8090/v2/weblite/.sqlite' \ + -H 'accept: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' \ + -d '' +``` + +To upload a local SQLite database via the SQLite Cloud UI, navigate to the Database tab in the left-hand navigation. Click the "Upload Database" button and select your local SQLite database. +### Via Dashboard UI To import a database from the UI, navigate to the Databases tab and click the "Upload Database" button. -![Dashbord Upload Database](@docs-website-assets/introduction/dashboard_upload_db.png) Select the database file you want to upload, and click "Upload Database". The database will be available in your cluster within a few minutes. + + +--- + ## Creating a new database ### From the Dashboard To create a new database from the SQLite Cloud UI, navigate to the Databases tab and click the "Create Database" button. -![Dashboard Create Database](@docs-website-assets/introduction/dashboard_create_database.png) The default encoding is set to UTF-8, and the default page size is 4096KB. + + ### From the API -To create a new database or upload an existing database via [Weblite](#), our REST API, you can make a request with the following parameters: +To create a new database or upload an existing database via [Weblite](/docs/weblite), our REST API, you can make a request with the following parameters: ```bash curl -X 'POST' \ 'https://.sqlite.cloud:8090/v2/weblite/.sqlite' \ @@ -36,11 +59,15 @@ curl -X 'POST' \ ``` ### From client libraries -To create a new database from a client library, use the CREATE DATABASE command. +To create a new database from a client library, connect to your cluster using a connection string without a specified database. + +Then, use the CREATE DATABASE command to create a new database. + +To start using the database within the connection, you can use the `USE DATABASE` command. ```javascript import { Database } from '@sqlitecloud/drivers'; - +// note that no database name is specified in the connection string path const db = new Database('sqlitecloud://.sqlite.cloud:?apikey=') const createDatabase = async () => await db.sql`CREATE DATABASE ;`; @@ -48,5 +75,16 @@ const createDatabase = async () => await db.sql`CREATE DATABASE ; createDatabase().then((res) => console.log(res)); // "OK" + +db.exec('USE DATABASE ;') + +// now you can use the database +const fetchAlbums = async () => await db.exec`SELECT * FROM albums;`; + +fetchAlbums().then((albums) => console.log(albums)); + +// [{ Title: 'For Those About To Rock We Salute You', ... }, ...] ``` +## Next Steps +- [Writing data](/docs/write-data) diff --git a/sqlite-cloud/index.mdx b/sqlite-cloud/index.mdx deleted file mode 100644 index 733e36c..0000000 --- a/sqlite-cloud/index.mdx +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Introduction to SQLite Cloud -description: SQLite Cloud is a distributed relational database system built on top of the SQLite database engine. -category: getting-started -status: publish ---- - -## Overview -**SQLite Cloud** is a distributed relational database system built on top of the SQLite database engine. - -It has been designed from the ground up to ensure the strong consistency of your data across all nodes in a cluster while simultaneously managing the technical aspects of scaling, security, and data distribution. This ensures that you can focus on your core tasks while relying on **SQLite Cloud** to handle the complexities of managing your databases. - -**SQLite Cloud** is written in ANSI C and GO, and it works on most POSIX systems like Linux, *BSD, and Mac OS X (Windows is supported too). You can use **SQLite Cloud** from the [most popular programming](../docs/sdk/) languages or its REST API. - ---- - -## Architecture - -**SQLite Cloud** uses the [Raft](https://raft.github.io) consensus algorithm to distribute your data changes across a cluster of computing systems, ensuring that each node in the cluster agrees upon the same series of state transitions. Raft implements consensus with a leader approach. - -**SQLite Cloud** supports all the SQLite features without any limitations. It is fully ACID compliant, supports non-deterministic SQL statements, and guarantees to be strongly consistent across all the cluster nodes. This ensures that data read from any node in the system returns the most up-to-date version of the data that has been committed. - -In a distributed database system, where data is distributed across multiple nodes, ensuring strong consistency can be challenging due to the potential for network delays, node failures, and concurrent transactions. Maintaining strong consistency is crucial for ensuring that the system behaves as expected and that applications built on top of the system can rely on the accuracy and integrity of the data. - -## Features -SQLite Cloud also provides a suite of tools for building realtime, local-first applications. -* **Local Sync**: Query your local SQLite database and syncronize with the cloud and across devices in real-time (**In development**). -* **Offline-first**: Resolve conflicts between devices and the cloud with CRDTs (**In developmpent**). -* **[Webhooks](/webhooks)**: Send changes to your database to external endpoints, or use to trigger edge functions via HTTP, Websockets, or on database events like INSERT, UPDATE, and DELETE. -* **[Edge Functions](/edge_functions)**: Run serverless functions on the same node that stores your data for low-latency operations. Trigger with webhooks or on database operations. -* **[Pub/Sub](/pub_sub)**: Subscribe to changes in your database to replicate data, power notifications, and build multiplayer experiences. -* **[Weblite](/weblite)**: Autogenerated REST APIs to interact with your database and edge functions. -* **[Query Analyzer](/query_analyzer)**: Receive optimization recommendations for your queries to improve performance. -* **Multi-region Load Balancer**: Connect to SQLite Cloud from anywhere in the world and SQLite Cloud automatically routes traffic to the nearest node for optimal performance. diff --git a/sqlite-cloud/multi-code-example.mdx b/sqlite-cloud/multi-code-example.mdx index e98af34..bf43d97 100644 --- a/sqlite-cloud/multi-code-example.mdx +++ b/sqlite-cloud/multi-code-example.mdx @@ -1,7 +1,7 @@ --- title: Multi Code Component Examples description: Multi Code Component Examples -slug: components/multicode +slug: multicode category: getting-started status: draft --- @@ -10,8 +10,8 @@ import MultiCode from '@commons-components/Code/MultiCode.astro'; In this examples, we will show how to use the `MultiCode` component: -- [Here](https://github.com/sqlitecloud/website/blob/docs-stage/commons/components/Code/MultiCode.astro) the definition of the `MultiCode` component. -- [Here](https://github.com/sqlitecloud/website/blob/docs-stage/commons/components/Code/Code.astro) the definition of the `Code` component that is used inside the `MultiCode` component. +- Here the definition of the `MultiCode` component. +- Here the definition of the `Code` component that is used inside the `MultiCode` component. In these two files there are the TypeScript definitions usefull to know all the avaible properties. diff --git a/sqlite-cloud/overview.mdx b/sqlite-cloud/overview.mdx new file mode 100644 index 0000000..fcece7c --- /dev/null +++ b/sqlite-cloud/overview.mdx @@ -0,0 +1,30 @@ +--- +title: Getting Started with SQLite Cloud +description: SQLite Cloud is a distributed relational database system built on top of the SQLite database engine. +category: getting-started +status: publish +slug: overview +--- + +## Overview +**SQLite Cloud** is a managed, distributed relational database system built on top of the SQLite database engine. + +It has been designed from the ground up to ensure strong consistency across all nodes in a cluster while simultaneously managing the technical aspects of scaling, security, and data distribution. This ensures that you can focus on your core tasks while relying on SQLite Cloud to handle the complexities of managing your databases. + +SQLite Cloud is built on the open source SQLite engine, ensuring complete feature parity. You get all of SQLite's core strengths: ACID compliance, support for complex SQL operations, and compatibility with the rich SQLite extension ecosystem. + +You can access SQLite Cloud from the most popular programming languages or its REST API. + +Like SQLite, each database in SQLite Cloud is a separate file, giving you flexible deployment options: + +* Create separate databases for each customer in a multi-tenant application +* Share a single database among multiple users with built-in access controls +* Mix both approaches based on your application's needs + +### Features +SQLite Cloud provides a comprehensive suite of tools for building realtime, local-first, edge AI applications. +* **[Webhooks](/docs/webhooks)**: Trigger edge functions or send change payloads via HTTP, Websockets, or on database events like INSERT, UPDATE, and DELETE. +* **[Edge Functions](/docs/edge-functions)**: Run serverless functions on the same nodes that store your data for lightning-fast data access. +* **[Pub/Sub](/docs/pub-sub)**: Subscribe to changes in your database to replicate data, power notifications, and build multiplayer experiences. +* **[Weblite](/docs/weblite)**: Autogenerated REST APIs to interact with the SQLite Cloud platform. +* **[Query Analyzer](/docs/analyzer)**: Receive optimization recommendations for your queries to improve performance. \ No newline at end of file diff --git a/sqlite-cloud/platform/_vector.mdx b/sqlite-cloud/platform/_vector.mdx new file mode 100644 index 0000000..886c9ac --- /dev/null +++ b/sqlite-cloud/platform/_vector.mdx @@ -0,0 +1,109 @@ +--- +title: SQLite Cloud Vector Search +description: Vector storage extension for similarity search in SQLite Cloud. +category: platform +status: publish +slug: vector +--- +Every SQLite Cloud database comes with the `sqlite-vec` extension pre-installed. This allows you to store and query vectors in your database, which enables similarity search functionality. + +## Overview +`sqlite-vec` is a no-dependency SQLite extension for vector search, written entirely in a single C file. It's extremely portable, works in most operating systems and environments, and is MIT/Apache-2 dual licensed. + +Using sqlite-vec is similar to using full-text search in SQLite. Declare a "virtual table" with vector columns, insert data with normal INSERT INTO statements, and query with normal SELECT statements. + +`sqlite-vec` is currently built and optimized for brute-force vector search. This means there is no approximate nearest neighbor search available at this time. + +## Usage +### Create a vector table + +To create a virtual vector table, use vec0 and the following syntax: + +```sql +create virtual table vec_table_name using vec0( + id integer primary key autoincrement, + embedding float[384] +-- other columns like: +-- text text, +-- metadata blob, +); +``` + +### Insert vectors +Insert vectors as you would with any other data: + +```sql +insert into vec_table_name(embedding) values + ('[0.1, 0.2, ...]'), + ('[0.3, 0.4, ...]'), + ('[0.5, 0.6, ...]'); +``` +### Execute a similarity search query +To search for similar vectors, use the following syntax: + +```sql +select + rowid, + distance +from vec_table_name +where embedding match + and k = 20; +``` + +The value of k sets the number of nearest neighbors to return. For more on nearest neighbor searches, check out our article on the topic. + +## Quantization +Vector quantization is a category of techniques to compress the individual elements inside of a floating point vector. In a float vector, each element is stored as a 32-bit floating point number. For longer vectors, this will quickly require a large amount of storage. + +To reduce storage requirements with minimal loss of accuracy, we recommend using bit vectors as a method of quantization. With bit vector, each dimension in the vector takes up 1 bit. This method delivers up to a 32x reduction in storage requirements. + +When using bit vectors, we recommend using embedding models that are trained on binary quantization loss. This will help maintain accuracy even after converting to binary. + +To convert a float vector to a binary vector, use the vec_quantize_binary() function: + +```sql +create virtual table vec_table using vec0( + embedding float[1536] +); + +-- slim because "embedding_coarse" is quantized 32x to a bit vector +create virtual table vec_table_slim using vec0( + embedding_coarse bit[1536] +); + +insert into vec_table_slim + select rowid, vec_quantize_binary(embedding) from vec_table; +``` +## Matryoshka embeddings +sqlite-vec also supports Matryoshka embeddings, a technique in some embeddings models that allows you to "truncate" excess dimensions of a given vector, without a significant loss in quality. + +Matryoshka embedding save on storage and result in faster queries. + +To create a Matryoshka embedding, use the vec_slice() function: + +```sql + +create virtual table vec_items using vec0( + embedding float[1536] +); + +-- slim because "embedding" is a truncated version of the full vector +create virtual table vec_items_slim using vec0( + embedding_coarse float[512] +); + +insert into vec_items_slim + select + rowid, + vec_normalize(vec_slice(embedding, 0, 512)) + from vec_items; +``` + +## Performance considerations +Free SQLite Cloud plans are not optimized for large-scale vector workloads. To speak to the team about upgrading your plan, please reach out. + +## Next Steps +Combined with [edge functions](/docs/edge-functions), SQLite Cloud's vector search capabilities make it a great choice for serverless RAG applications. + + + diff --git a/sqlite-cloud/platform/_wip-index-with-card.mdx b/sqlite-cloud/platform/_wip-index-with-card.mdx new file mode 100644 index 0000000..3aba1f5 --- /dev/null +++ b/sqlite-cloud/platform/_wip-index-with-card.mdx @@ -0,0 +1,86 @@ +--- +title: Platform +description: Index page for platform section +category: platform +status: publish +icon: docs-plat +slug: platform +--- +import IndexPage from "@docs-website-components/Docs/IndexPage.astro" + + +export const introduction = "SQLite Cloud is a distributed relational database system built on top of the SQLite database engine. It has been specifically designed from the ground up to ensure the strong consistency of your data across all nodes in a cluster while simultaneously managing the technical aspects of scaling, security, and data distribution." + + + +export const sections = [ + { + icon: "puzzle", + title: "Edge Functions", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/edge-functions", + }, + { + icon: "puzzle", + title: "Webhooks", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/webhooks", + }, + { + icon: "puzzle", + title: "Pub/Sub", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/pub-sub", + }, + { + icon: "puzzle", + title: "Vector", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/vector", + }, + { + icon: "puzzle", + title: "Scaling", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/scaling", + }, + { + icon: "puzzle", + title: "Security and Access Control", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/security", + }, + { + icon: "puzzle", + title: "Backups", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/backups", + }, + { + icon: "puzzle", + title: "Query Analyzer", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/analyzer", + }, + { + icon: "puzzle", + title: "Extensions", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/extensions", + }, + { + icon: "puzzle", + title: "Weblite", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/weblite", + }, + { + icon: "puzzle", + title: "Settings", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/settings", + }, +] + + + \ No newline at end of file diff --git a/sqlite-cloud/platform/access-tokens.mdx b/sqlite-cloud/platform/access-tokens.mdx new file mode 100644 index 0000000..83664b7 --- /dev/null +++ b/sqlite-cloud/platform/access-tokens.mdx @@ -0,0 +1,81 @@ +--- +title: Access Tokens +description: Grant to your users, devices, tenant, access to SQLite Cloud database and services. +category: platform +status: publish +slug: access-tokens +--- + +Access Tokens let backend systems securely grant users, devices, tenants, etc. access to SQLite Cloud database and services (SQLite Sync, Weblite, etc.). These endpoints enable full token lifecycle management: creation, inspection, validation, update, and revocation. All endpoints require authentication. Use an **API Key** or an **Access Token** via the `Authorization` header. + +The API Documentation for the Access Tokens API can be found in the **Weblite** section in the Dashboard. + +--- + +## Example Using SQLite Cloud Access Tokens with Google Login + +In the repository on GitHub sqlitecloud/examples, we created a simple app to demonstrate how to generate and use Access Tokens. + +We’ll log in with Google, grab a token, and use it to interact with SQLite Cloud Weblite APIs. Here’s how it works. + +In the snippet below, we handle the Google Login callback when the user has completed the login on Google. Here, you can exchange the `code` with the Google Access Token and then decide what to do with it as needed. + +```typescript +if (pathname === "/auth/callback") { + const q = query; + if (q.state !== STATE || !q.code) { + return send(res, 400, "Invalid state or missing code"); + } + + try { + // Exchange code for tokens + // Store the Google Token in the database + const googleToken = await getGoogleTokens(q.code as string); + ... +``` + +Now we have authenticated the user, we are ready to request SQLite Cloud to create a new SQLite Cloud Access Token assigned to this user. + +```typescript +async function getSQLiteCloudToken(userId: string) { + const payload = { + name: "test-user-token", // A name for the token, can be anything you want + userId, + expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // expires in 24 hours + }; + + const res = await fetch("https:///v2/tokens", { + method: "POST", + headers: { + Authorization: `Bearer ${SQLITE_CLOUD_API_KEY}`, + "Content-Type": "application/json", + }, + body: JSON.stringify(payload), + }); + if (!res.ok) { + throw new Error(`Failed to create SQLite Cloud token: ${res.statusText}`); + } + + return res.json(); +} +``` + +In the response JSON, the `data.token` field contains the Access Token. + +Finally, the user is authorized to securely access SQLite Cloud services like the Weblite API to perform a query on the database: + +```typescript +const res = await fetch("https:///v2/weblite/sql", { + method: "POST", + headers: { + Authorization: "Bearer " + sqliteCloudToken, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + sql: "USE DATABASE chinook.sqlite;SELECT * FROM artists LIMIT 10;", + }), +}); +... +``` + +The result depends on the [Row Level Security](rls) policies you enabled for the tables. diff --git a/sqlite-cloud/platform/analyzer.mdx b/sqlite-cloud/platform/analyzer.mdx index e3b830a..42ffac4 100644 --- a/sqlite-cloud/platform/analyzer.mdx +++ b/sqlite-cloud/platform/analyzer.mdx @@ -1,29 +1,57 @@ --- -title: Analyzer +title: Query Analyzer description: The Analyzer panel is a powerful tool that collects and categorizes all the queries executed on your cluster based on their execution time. category: platform status: publish slug: analyzer --- +import VideoPlayer from '@commons-components/Video/VideoPlayer.astro'; +import enableAnalyzer from '@docs-website-assets/introduction/video/dashboard_enable_query_analyzer.mp4'; +import applyAnalyzer from '@docs-website-assets/introduction/video/dashboard_analyzer_apply_suggestion.mp4'; -The Analyzer panel is a powerful tool that collects and categorizes all the queries executed on your cluster based on their execution time. It allows for intelligent and proactive analysis, and provides recommendations on which indexes to use to optimize frequently used queries. +import Callout from "@commons-components/Information/Callout.astro"; -![Dashboard Empty Analyzer](@docs-website-assets/introduction/dashboard_analyzer_empty.png) -By default, the Analyzer is turned off to avoid a small performance penalty. However, you can enable it by accessing the Settings button and setting the `query_analyzer_enabled` flag to 1, then pressing Save. You can also adjust the `query_analyzer_threshold` flag to set the minimum threshold query time (in milliseconds) that triggers a query to be included in the Analyzer. If the default value is too low, it's recommended to increase it to avoid having too many queries included in the panel. +The Query Analyzer panel is a powerful tool that collects and categorizes all the queries executed on your cluster based on their execution time. It allows for intelligent and proactive analysis, and provides recommendations on which indexes to use to optimize frequently used queries. -![Dashboard Analyzer Settings](@docs-website-assets/introduction/dashboard_analyzer_settings.png) +--- + +## Getting Started + +By default, the Analyzer is disabled to avoid unnecessary overhead. You can enable it directly from the top-left dropdown menu in the Analyzer panel. + +Simply click on the dropdown (initially labeled **Disabled**) and select a monitoring threshold. You can choose a preset value (e.g., **Threshold 10ms**, **Threshold 100ms**) or define a **Custom Threshold**. Only queries taking longer than the selected time (in milliseconds) will be recorded and analyzed. + + + +Query Analyzer is a **debugging tool**.
It's recommended to keep it active only for the time strictly necessary to identify and optimize queries. +
+ + + + + + +---- +## Testing the Analyzer +To test the Analyzer, we can navigate to the `Studio -> chinook.sqlite -> SQL Console` section and perform a query that filters the non-indexed `Composer` column of the `Track` table using the following statement: + +`SELECT * FROM Tracks WHERE Composer = 'AC/DC';` + + -To test the Analyzer, we can go to the `Databases -> Chinook.sqlite -> Console` section and perform a query that filters the non-indexed Composer column of the Track table with the following statement: `SELECT * FROM Tracks WHERE Composer = 'AC/DC'`; +Once the query is executed, return to the **Analyzer** panel. You will see the query listed in the table along with execution statistics, such as **Count**, **Avg. Time (ms)**, and **Max Time (ms)**. -![Dashboard Analyzer Console](@docs-website-assets/introduction/dashboard_analyzer_console.png) +### Analyzing Performance and Applying Suggestions -Once we have executed this query, we can go back to the Analyzer panel and see that it has been successfully analyzed by the **nemtfenosk** node. +Click on the query row to open the **Query Details** side panel. This panel provides in-depth information organized into three tabs: -![Dashboard Analyzer Query](@docs-website-assets/introduction/dashboard_analyzer_query.png) +1. **Query**: Displays the full SQL statement (with an option to copy it). +2. **Current Execution Plan**: Shows how the database engine currently processes the query (e.g., `SCAN TABLE` indicates a full table scan, which is often inefficient). +3. **Index Suggestions**: This is the most critical section for optimization. It displays **Candidate Indexes** and a **Suggested Index**. -By selecting **Details** and **Plan**, we can get more in-depth information about the execution of this query over time. However, what we're most interested in is the intelligent recommendation, which can be found by selecting **Suggest**. In the Indexes field, we can find the optimal index to apply to our database, which will speed up all queries on the Track table filtered by the Composer column. +To optimize your database performance, navigate to the **Index Suggestions** tab. -![Dashboard Analyzer Suggestion](@docs-website-assets/introduction/dashboard_analyzer_suggest.png) +If an optimization is available, you will see a proposed `CREATE INDEX` statement. -To apply the recommended index(es), simply select **Apply** and they will be automatically written and distributed in the `Chinook.sqlite` database. +Simply click the **Apply All Suggestions** button. The Analyzer will automatically create and distribute the optimal index in the `chinook.sqlite` database, speeding up future queries filtered by the `Composer` column. \ No newline at end of file diff --git a/sqlite-cloud/platform/apikey.mdx b/sqlite-cloud/platform/apikey.mdx new file mode 100644 index 0000000..87a5a97 --- /dev/null +++ b/sqlite-cloud/platform/apikey.mdx @@ -0,0 +1,20 @@ +--- +title: Security and Access Control +description: SQLite Cloud provides secure access to resources through role-based authorization, which ensures user isolation and enhances security and manageability. +category: platform +status: publish +slug: apikey +--- + +## API KEYs + +API KEYs can be used as an alternative authentication mechanism. +Authentication through API keys ensures the same privileges as the user to which they are associated. +API KEYs are recommended for all server-to-server authentication cases and are necessary for using the REST APIs and the SDKs that uses the WebSocket APIs. + +To create an API key for a user, click on the **Create API KEY** button. + +![Dashboard Create APIKEY](@docs-website-assets/introduction/dashboard_create_apikey.png) + +The resulting table will display all the API keys associated with each user, along with their name. +![Dashboard List APIKEY](@docs-website-assets/introduction/dashboard_list_apikey.png) diff --git a/sqlite-cloud/platform/backups.mdx b/sqlite-cloud/platform/backups.mdx index b726ff8..6d7cacc 100644 --- a/sqlite-cloud/platform/backups.mdx +++ b/sqlite-cloud/platform/backups.mdx @@ -6,11 +6,16 @@ status: publish slug: backups --- -## Overview -Backups provide a robust solution for mitigating data loss and resolving data corruption issues. +import VideoPlayer from '@commons-components/Video/VideoPlayer.astro'; +import enableDisableBackup from '@docs-website-assets/introduction/video/dashboard_enable_disable_backup.mp4'; +import restoreBackup from '@docs-website-assets/introduction/video/dashboard_restore_backup.mp4'; + +Backups provide a robust solution for mitigating data loss and resolving data corruption issues. Backups are available for databases in all Dev, Pro and Startup projects. SQLite Cloud creates a full snapshot backup of your data once a day, and stores incremental changes once per second, on commodity object storage. +---- + ## Features #### Automated Backups @@ -20,21 +25,17 @@ SQLite Cloud creates a full snapshot backup of your data once a day, and stores - **Easy Restoration Process**: Restoring from a backup automatically overwrites the existing database, seamlessly reverting it to the desired state without additional configuration. - **Consistency and Reliability**: After restoration, the database functions as it did at the chosen point in time, ensuring operational continuity. -## Getting Started -Setting up and managing backups in SQLite Cloud is designed to be straightforward, allowing you to implement robust data protection strategies effortlessly. - -First, navigate to the backups section. -![Backup Empty](@docs-website-assets/introduction/backup_empty.png) +--- -Then, click on settings to see a list of your databases. From here, you can enable backups for each database. -![Backup Modal](@docs-website-assets/introduction/backup_modal.png) +## Getting Started +Setting up and managing backups in SQLite Cloud is designed to be straightforward, allowing you to implement robust data protection strategies effortlessly. -Click save, and your database backups will appear below. -![Backup Items](@docs-website-assets/introduction/backup_items.png) + -### Restoring from a Backup +--- +## Restoring from a Backup Click on a backup to begin the restore process. Select Yes to confirm the restoration, and your database will be restored to the selected point in time. -![Restore Backup](@docs-website-assets/introduction/restore_backup.png) + diff --git a/sqlite-cloud/platform/edge-functions.mdx b/sqlite-cloud/platform/edge-functions.mdx index 6278789..8f08269 100644 --- a/sqlite-cloud/platform/edge-functions.mdx +++ b/sqlite-cloud/platform/edge-functions.mdx @@ -5,21 +5,29 @@ category: platform status: publish slug: edge-functions --- +import VideoPlayer from '@commons-components/Video/VideoPlayer.astro'; +import edgeFunctions from '@docs-website-assets/introduction/video/dashboard_edge_functions.mp4'; -Edge Functions are server-side functions that run directly within your database environment. Edge functions in SQLite Cloud ensure maximum performance and minimal latency by running functions on the same server as your database. +import Callout from "@commons-components/Information/Callout.astro"; + +Edge functions let you define custom logic to run on the same nodes as your database files for ultra-fast performance. You can write edge functions directly in the SQLite Cloud dashboard using JavaScript, TypeScript, or SQL. Importing modules is not currently supported. -Edge functions can be called remotely over HTTP or Websockets via API, or triggered by database events via SQLite Cloud [Webhooks](https://docs.sqlitecloud.io/docs/introduction/webhooks). Each function runs in an isolated environment using the Bun runtime. +Edge functions can be called remotely over HTTP or Websockets via API, or triggered by database events via SQLite Cloud Webhooks. Each function runs in an isolated environment using the Bun runtime. Turning on linearizable reads ensures strong consistency, but may introduce some latency. When eventual consistency is sufficient, we recommend leaving linearizable reads off. +--- + ## Getting Started -1. Navigate to the Edge Functions page from your dashboard. -1. Under "Development", select "Edge Function", then click the "Create" button. -1. Write and test your function. - 1. Select the database you want to access and an API key if necessary - 2. When you're finished, click deploy. + +Use the **Edge Functions panel** to effortlessly create, deploy, and test Edge Functions directly in the SQLite Cloud dashboard. +The editor allows you to choose the language of your function — **JavaScript**, **TypeScript**, or **SQL** — and connect it to the database of your choice. + +Once deployed, the function can be tested immediately in the dashboard or invoked externally through its Function URL. + + #### Note: Functions should return a JSON-serializable object with a data field: @@ -31,6 +39,38 @@ return { } ``` + + + +Enabling **linearizable reads** guarantees strong consistency but may introduce additional latency. +For most cases, we recommend keeping it disabled to benefit from lower response times. + + + +### Function Details + +In the **Details** tab you will find key information about your function, including: + +- The **last deployment date and time** +- The **Function URL**, which you can use to call the function from external applications + +![Edge Function Details](@docs-website-assets/introduction/dahsboard-edge-function-details.png) + + + +### Authorization +Edge functions that access your SQLite databases must be authorized via API key. + +An API key must be sent in the request url as a query parameter (`?apikey=YOUR_API_KEY`) or as an attribute in the request body (`{ apikey: YOUR_API_KEY }`). + +### Execution + +Edge functions can be called via HTTP GET and POST methods. You can pass additional values to your edge function in two ways: +- Query parameters: Accessible via `request.params` +- Request body: Accessible via `request.data` + +--- + ## Guides ### Interacting with your Database Use the global `connection` object to access and manipulate your database. @@ -41,7 +81,7 @@ return { } ``` -Select the database you would like to access from the "Database" dropdown, or select the database you want to use in your SQL query with the [USE command](https://docs.sqlitecloud.io/docs/commands/use-database). +Select the database you would like to access from the "Database" dropdown, or select the database you want to use in your SQL query with the USE command. ```js const customers = await connection.sql`USE DATABASE chinook.sqlite; SELECT * FROM customers;`; @@ -54,10 +94,10 @@ return { Environment variables can be accessed and stored with the ENV command. ENV variables are stored in the server settings file and are project-specific. Use the following commands to set and read values in your server settings file: -* [LIST ENV](https://docs.sqlitecloud.io/docs/settings-commands#list-env) -* [SET ENV](https://docs.sqlitecloud.io/docs/settings-commands#set-env) key VALUE value -* [GET ENV](https://docs.sqlitecloud.io/docs/settings-commands#get-env) key -* [REMOVE ENV](https://docs.sqlitecloud.io/docs/settings-commands#remove-env) key +* LIST ENV +* SET ENV key VALUE value +* GET ENV key +* REMOVE ENV key You can also add environment variables in the UI by navigating to the "Environment Variables" section and clicking the "Create" button. @@ -65,6 +105,9 @@ You can also add environment variables in the UI by navigating to the "Environme ### Handling Errors In case of error we return an HTTP error code and a JSON with the error message. Manually throwing an error in your code results in a 500 response. You may also return an error. + +--- + ## Examples ### Assigning and Notifying a Support Rep on User Sign up diff --git a/sqlite-cloud/platform/extensions.mdx b/sqlite-cloud/platform/extensions.mdx index b12bb81..8722cda 100644 --- a/sqlite-cloud/platform/extensions.mdx +++ b/sqlite-cloud/platform/extensions.mdx @@ -6,13 +6,17 @@ status: publish slug: extensions --- -SQLite Cloud comes with the following pre-installed SQLite extensions. These extensions are available for use in your SQLite Cloud databases. +SQLite Cloud comes with the following pre-installed SQLite extensions. +These extensions are available for use in your SQLite Cloud databases. ## Extensions -- **[Full-text Search 5](https://www.sqlite.org/fts5.html)**: Full-text search engine that allows you to search for text in a database. -- **[JSON1](https://www.sqlite.org/json1.html)**: Extension that allows you to store, query, and manipulate JSON data. -- **[Math](https://www.sqlite.org/lang_mathfunc.html)**: Extension that provides mathematical functions. -- **[RTree](https://www.sqlite.org/rtree.html)**: Extension that provides an R-Tree index for storing and querying spatial data. -- **[Geopoly](https://www.sqlite.org/geopoly.html)**: Extension that provides functions for working with geospatial data. +- **[SQLite-Vector](sqlite-vector)**: High performance vector storage extension for similarity search. +- **[SQLite-Sync](sqlite-sync)**: Local-first extension for true local-first data synchronization for your applications. +- **[SQLite-JS](sqlite-js)**: Enables JavaScript integration in SQLite for executing server-side logic. +- **Full-text Search 5**: Full-text search engine that allows you to search for text in a database. +- **JSON1**: Allows you to easily store, query, and manipulate JSON data. +- **Math**: Mathematical functions. +- **RTree**: R-Tree index for storing and querying spatial data. +- **Geopoly**: A set of functions for working with geospatial data. For a complete guide, see the [comprehensive tutorial here](tutorial-geopoly). -In the future, we plan to allow users to install their own extensions. If you have a specific extension you would like to use, please let us know by [adding to this issue](https://github.com/sqlitecloud/docs/issues/34). \ No newline at end of file +In the future, we plan to allow users to install their own extensions. If you have a specific extension you would like to use, please let us know by adding to this issue. \ No newline at end of file diff --git a/sqlite-cloud/platform/logs.mdx b/sqlite-cloud/platform/logs.mdx new file mode 100644 index 0000000..f7a511b --- /dev/null +++ b/sqlite-cloud/platform/logs.mdx @@ -0,0 +1,84 @@ +--- +title: Logs +description: View detailed insights into your SQLite Cloud project's operations to monitor activity, debug issues, and track system behavior in real time. +category: platform +status: publish +slug: logs +--- +import VideoPlayer from '@commons-components/Video/VideoPlayer.astro'; +import logsVideo from '@docs-website-assets/introduction/video/dashboard_logs.mp4'; + + +Logs provide detailed insights into your SQLite Cloud project's operations, helping you monitor activity, debug issues, and track system behavior in real time. The Logs panel displays a comprehensive view of all events occurring across your cluster nodes. + + +--- + +## Key Features + +- **Log Monitoring**: View recent log entries with manual refresh capability to get the latest activity +- **Filtering Options**: Filter logs by time range, specific nodes, and search through messages +- **Detailed Context**: Each log entry includes timestamp, severity level, source, and detailed message information + + + +--- + +## Accessing Logs + +Navigate to the **Logs** section from your SQLite Cloud dashboard to view your project's log entries. The interface displays logs in a table format with the following columns: + +- **Time**: Timestamp when the event occurred (in UTC) +- **Level**: Severity level of the log entry +- **Source**: Component or service that generated the log +- **Log Type**: Category of the log entry +- **Message**: Detailed description of the logged event + +--- + +## Filtering Logs + +### Timestamp Range + +Use the timestamp range selector to filter logs by time period. Available options include: + +- Last 30 minutes +- Last hour +- Last 12 hours +- Last day +- Last 3 days +- Last week +- Last 2 weeks +- Last 30 days +- Custom date range (using the calendar picker) + +### Node Filtering + +Filter logs by specific cluster nodes using the **Nodes** section on the left sidebar. You can: + +- Search for specific nodes using the search box +- Select individual nodes to view their logs +- View the node location (e.g., US East) + +### Search Logs + +Use the search box at the top of the logs table to filter entries by message content. This helps you quickly locate specific errors or events. + +--- + +## Viewing Log Details + +Click on any log entry to view detailed information in the **Log Details** panel. This panel displays: + +- **Timestamp**: Exact time of the event +- **Level**: Severity level +- **Source**: Originating component +- **Node ID**: Specific node that generated the log +- **Log Type**: Category of the event +- **Message**: Full message with complete error details or event information + +--- + +## Refreshing Logs + +Click the **Refresh** button in the top-right corner to manually update the log list and view the most recent entries. This ensures you're viewing the latest activity from your cluster. diff --git a/sqlite-cloud/platform/offsync.mdx b/sqlite-cloud/platform/offsync.mdx new file mode 100644 index 0000000..5b64c90 --- /dev/null +++ b/sqlite-cloud/platform/offsync.mdx @@ -0,0 +1,65 @@ +--- +title: OffSync +description: Enable local-first applications with automatic data synchronization between edge devices and SQLite Cloud. +category: platform +status: publish +slug: offsync +--- + +import VideoPlayer from '@commons-components/Video/VideoPlayer.astro'; +import enableSync from '@docs-website-assets/introduction/video/dashboard_sqlite_sync_enabling.mp4'; +import connectionUrlSync from '@docs-website-assets/introduction/video/dashboard_sync_connection_url.mp4'; +import devicesSync from '@docs-website-assets/introduction/video/dashboard_sync_devices.mp4'; + +import Callout from "@commons-components/Information/Callout.astro"; + +OffSync is a powerful SQLite Cloud feature that enables true **local-first** data synchronization for your applications. Powered by the SQLite Sync extension, it allows you to build robust, offline-capable applications where data is stored and processed on edge devices and seamlessly synchronized with a central SQLite Cloud database. + +This architecture is ideal for mobile apps, IoT devices, and any application requiring high availability and low latency, even with intermittent network connectivity. By leveraging Conflict-free Replicated Data Types (CRDTs), OffSync ensures that changes made offline are merged automatically and without conflicts when the device reconnects. + + +--- + +## How It Works + +OffSync extends standard SQLite tables with built-in support for offline work and automatic synchronization. This allows multiple devices to operate independently and then seamlessly merge their changes. + +- **Offline-First by Design**: Applications work seamlessly even when devices are offline. Changes are queued locally and synced automatically when connectivity is restored. +- **CRDT-Based Conflict Resolution**: Merges updates deterministically and efficiently, ensuring eventual consistency across all replicas without complex merge logic. +- **Seamless Integration**: The sync layer is tightly integrated with SQLite Cloud, enabling secure data sharing across devices, users, and platforms. + +When combined with [Row-Level Security (RLS)](/docs/rls), OffSync allows you to build secure, multi-tenant applications where each user's data is safely isolated, both on the edge and in the cloud. + + +--- + +## Configuring OffSync + +You can enable and manage OffSync for your databases directly from the SQLite Cloud dashboard. +Below are the main steps: + +### Enable Tables for Synchronization +From the **Sync Tables** tab, select which tables in your database you want to keep synchronized. +Once enabled, all changes to those tables will automatically sync with connected devices. + + + + +### Get the Connection String +In the **Configuration** tab, copy the connection string. +Use this in your application to initialize OffSync and connect your local SQLite database with SQLite Cloud. + + + + +### Manage Connected Devices +In the **Devices** tab, you can view all devices currently connected to your database. +Here you can check their sync status and remove devices if needed. + + + + +For OffSync to work correctly, the list of tables configured for synchronization—and their corresponding schemas—must be identical in both your local SQLite database and your SQLite Cloud database. + + +Once enabled, any changes made to the selected tables via the SQLite Sync extension will be automatically synchronized with your SQLite Cloud database. diff --git a/sqlite-cloud/platform/pub-sub.mdx b/sqlite-cloud/platform/pub-sub.mdx index c1de946..73ebad9 100644 --- a/sqlite-cloud/platform/pub-sub.mdx +++ b/sqlite-cloud/platform/pub-sub.mdx @@ -6,138 +6,257 @@ status: publish slug: pub-sub --- -Pub/Sub is a messaging pattern that allows multiple applications to communicate with each other asynchronously. In the context of **SQLiteCloud**, Pub/Sub can be used to provide real-time updates and notifications to subscribed applications whenever data changes in the database or it can be used to send payloads (messages) to anyone subscribed to a channel. Here's how it works: +# SQLiteCloud Pub/Sub System -**Publishers:** Publishers are responsible for sending messages or notifications to the system whenever a change occurs in the database. Publishers can be any application that has write access to the database, including web servers, mobile apps, or background processes. A Publisher can also be anyone who NOTIFY a payload to a specific channel (without any write database operation). +**Publish/Subscribe (Pub/Sub)** is a messaging pattern that enables asynchronous communication between multiple applications. In the context of **SQLiteCloud**, Pub/Sub provides a robust way to deliver real-time updates or custom messages to subscribed clients when data changes or explicit notifications are issued. -**Subscribers:** Subscribers are applications that want to receive updates whenever a change occurs in the database or whenever someone send a message to a specific channel. +This feature is particularly useful for building reactive applications, synchronizing distributed systems, and enabling event-driven architectures around your SQLite databases. -**Channels:** Channels are messaging patterns through which messages are sent and received. Publishers send messages to specific channel, and subscribers can subscribe to one or more channel to receive notifications. A channel can be a database table or a unique name not bound to any database entity. +--- + +## Core Concepts + +### **Publishers** + +Publishers are entities that send messages or notifications. In **SQLiteCloud**, a publisher can: + +* Modify a database (triggering automatic Pub/Sub events on commit). +* Explicitly send a message using the `NOTIFY` command, even without making changes to the database. + +Any client with write access—such as a web server, mobile app, or background process—can act as a publisher. + +### **Subscribers** + +Subscribers are clients that listen for messages or data change events. They can subscribe to: + +* A **channel** representing a database table (to receive change events). +* A **named message channel** (for general-purpose messages). + +Subscribers will receive all messages published on the channels they subscribe to. + +### **Channels** + +Channels are the communication endpoints used for Pub/Sub messaging. A channel can be: + +* A **database table name**, used to deliver change notifications. +* A **custom channel name**, used to send arbitrary messages. + +Channels are **not bound** to any database entity unless explicitly tied to a table. + +--- + +## Benefits of Pub/Sub in SQLiteCloud -Here are some of the capabilities that Pub/Sub provides for a database management system: +* **Real-time Updates** + Instantly notify subscribers when data changes. Useful for dashboards, live feeds, or collaborative apps. -* Real-time updates: With Pub/Sub, subscribers can receive real-time updates whenever data changes in the database. This can be useful for applications that need to display real-time information to users, such as stock tickers or social media feeds. +* **Scalability** + One publisher can broadcast to many subscribers with minimal overhead on the database. -* Scalability: Pub/Sub provides a scalable solution for database notifications, allowing multiple subscribers to receive updates without impacting database performance. +* **Message Filtering** + Subscribers can choose specific channels, reducing unnecessary data traffic. -* Customizable filtering: Pub/Sub allows subscribers to customize the types of messages they receive by filtering on specific topics or keywords. This can help reduce network traffic and improve application performance. +* **Fault Tolerance** + Notifications are delivered reliably. If a subscriber or publisher disconnects, the system continues to function without losing messages. + +--- -* Fault tolerance: Pub/Sub systems are designed to be fault-tolerant, ensuring that messages are not lost even if a subscriber or publisher goes offline. +## Payload Format -Overall, Pub/Sub provides a powerful messaging system for database management systems, enabling real-time updates and notifications for subscribed applications while maintaining scalability, reliability, and performance. +All Pub/Sub messages in **SQLiteCloud** are delivered as **JSON** objects. The structure of the payload depends on the type of event: -## Pub/Sub Payload Format +### 1. **NOTIFY Message Payload** -JSON is used to deliver payload to all listening clients. JSON format depends on the operation type. In case of database tables, notifications occur on COMMIT so the same JSON can collect more changes related to that table. **SQLite Cloud** guarantees **one JSON per channel**. +Sent explicitly by clients using the `NOTIFY` command. -**1. NOTIFY payload** ```json { - sender: "UUID", - channel: "name", - type: "MESSAGE", - payload: "Message content here" // payload is optional + "sender": "UUID", + "channel": "name", + "channel_type": "MESSAGE", + "payload": "Message content here" } ``` +* **sender**: UUID of the client that sent the message. +* **channel**: Target channel name. +* **channel\_type**: Always `"MESSAGE"` for this type. +* **payload**: Optional message content. + +--- + +### 2. **Database Table Change Payload** + +Generated automatically when a transaction modifies a subscribed table. Triggered at **COMMIT** time and may include multiple row operations. -**2. Multiple TABLE modification payload** ```json { - sender: "UUID", - channel: "tablename", - type: "TABLE", - pk: ["id", col1"] // array of primary key name(s) - payload: [ // array of operations that affect table name - { - type: "INSERT", - id: 12, - col1: "value1", - col2: 3.14 - }, - { - type: "DELETE", - pv: [13] // primary key value (s) in the same order as the pk array - }, - { - type: "UPDATE", - id: 15, // new value - col1: "newvalue", - col2: 0.0 - // if primary key is updated during this update then add it to: - // UPDATE TABLE SET col1='newvalue', col2=0.0, id = 15 WHERE id=14 - pv: [14] // primary key value (s) set prior to this UPDATE operation - ] - } - ] + "sender": "UUID", + "channel": "tablename", + "channel_type": "TABLE", + "sqlite_pk_name": ["id", "col1"], + "payload": [ + { + "sqlite_type": "INSERT", + "id": 12, + "col1": "value1", + "col2": 3.14 + }, + { + "sqlite_type": "DELETE", + "sqlite_pk_value": [13] + }, + { + "sqlite_type": "UPDATE", + "id": 15, + "col1": "newvalue", + "col2": 0.0, + "sqlite_pk_value": [14] + } + ] } ``` -**Details:** +#### Field Descriptions: -* **sender**: is the UUID of the client who sent the NOTIFY event or who initiated the WRITE operation that triggers the notification. It is common for a client that executes **NOTIFY** to be listening on the same notification channel itself. In that case it will get back a notification event, just like all the other listening sessions. Depending on the application logic, this could result in useless work, for example, reading a database table to find the same updates that that session just wrote out. It is possible to avoid such extra work by noticing whether the notifying **UUID** (supplied in the notification event message) is the same as one's **UUID** (available from SDK). When they are the same, the notification event is one's own work bouncing back, and can be ignored. If **UUID** is 0 it means that server sent that payload. -* **channel**: this field represents the channel/table affected. -* **type**: determine the type of operation, it can be: MESSAGE, TABLE, INSERT, UPDATE, or DELETE (more to come). -* **pk/pv**: these fields represent the primary key name(s) and value(s) affected by this table operation. -* **payload**: TODO +* **sender**: UUID of the client initiating the change, or `0` if triggered by the server. +* **channel**: Table name where the change occurred. +* **channel\_type**: `"TABLE"`. +* **sqlite\_pk\_name**: Array of primary key column names for the table. +* **payload**: Array of individual row operations. -**More SQL examples:** -``` + * **sqlite\_type**: `"INSERT"`, `"UPDATE"`, or `"DELETE"`. + * **sqlite\_pk\_value**: Previous primary key values (used in `DELETE` or `UPDATE`). + * Other keys represent column values (for `INSERT` and `UPDATE`). + +> **Tip:** If a client is subscribed to a channel and also publishes to it, it will receive its own notifications. Use the **sender UUID** to filter out self-generated events if needed. + +--- + +## Example SQL Usage + +```sql > USE DATABASE test.sqlite OK > GET SQL foo -CREATE TABLE "foo" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "col1" TEXT, "col2" TEXT) +CREATE TABLE "foo" ( + "id" INTEGER PRIMARY KEY AUTOINCREMENT, + "col1" TEXT, + "col2" TEXT +) > LISTEN TABLE foo OK ``` -**3. DELETE FROM foo WHERE id=14;** +--- + +## Example Event Payloads + +### DELETE + +```sql +DELETE FROM foo WHERE id=14; +``` + ```json { - "sender": "b7a92805-ef82-4ad1-8c2f-92da6df6b1d5", - "channel": "foo", - "type": "TABLE", - "pk": ["id"], - "payload": [{ - "type": "DELETE", - "pv": [14] - }] + "sender": "b7a92805-ef82-4ad1-8c2f-92da6df6b1d5", + "channel": "foo", + "channel_type": "TABLE", + "sqlite_pk_name": ["id"], + "payload": [{ + "sqlite_type": "DELETE", + "sqlite_pk_value": [14] + }] } ``` -**4. INSERT INTO foo(col1, col2) VALUES ('test100', 'test101');** +--- + +### INSERT + +```sql +INSERT INTO foo(col1, col2) VALUES ('test100', 'test101'); +``` + ```json { - "sender": "b7a92805-ef82-4ad1-8c2f-92da6df6b1d5", - "channel": "foo", - "type": "TABLE", - "pk": ["id"], - "payload": [{ - "type": "INSERT", - "id": 15, - "col1": "test100", - "col2": "test101" - }] + "sender": "b7a92805-ef82-4ad1-8c2f-92da6df6b1d5", + "channel": "foo", + "channel_type": "TABLE", + "sqlite_pk_name": ["id"], + "payload": [{ + "sqlite_type": "INSERT", + "id": 15, + "col1": "test100", + "col2": "test101" + }] } ``` -**5. UPDATE foo SET id=14,col1='test200' WHERE id=15;** +--- + +### UPDATE (Primary Key Changed) + +```sql +UPDATE foo SET id=14, col1='test200' WHERE id=15; +``` + ```json { - "sender": "b7a92805-ef82-4ad1-8c2f-92da6df6b1d5", - "channel": "foo", - "type": "TABLE", - "pk": ["id"], - "payload": [{ - "type": "DELETE", - "pv": [15] - }, { - "type": "INSERT", - "id": 14, - "col1": "test200", - "col2": "test101" - }] + "sender": "b7a92805-ef82-4ad1-8c2f-92da6df6b1d5", + "channel": "foo", + "channel_type": "TABLE", + "sqlite_pk_name": ["id"], + "payload": [ + { + "sqlite_type": "DELETE", + "sqlite_pk_value": [15] + }, + { + "sqlite_type": "INSERT", + "id": 14, + "col1": "test200", + "col2": "test101" + } + ] } -``` \ No newline at end of file +``` + +--- + +## Summary + +SQLiteCloud's Pub/Sub system enables: + +* Real-time data sync across applications. +* Lightweight messaging between distributed components. +* Fine-grained, reliable notifications with minimal overhead. + +By leveraging Pub/Sub, developers can build responsive, event-driven applications that scale seamlessly and remain in sync with the database state. + +## Client Library Examples + +```javascript +import { Database } from '@sqlitecloud/drivers' +import { PubSub, PUBSUB_ENTITY_TYPE } from '@sqlitecloud/drivers/lib/drivers/pubsub' + +let database = new Database('sqlitecloud://user:password@xxx.sqlite.cloud:8860/chinook.sqlite') +// or use sqlitecloud://xxx.sqlite.cloud:8860?apikey=xxxxxxx + +const pubSub: PubSub = await database.getPubSub() + +await pubSub.listen(PUBSUB_ENTITY_TYPE.TABLE, 'albums', (error, results, data) => { + if (results) { + // Changes on albums table will be received here as JSON object + console.log('Received message:', results) + } +}) + +await database.sql`INSERT INTO albums (Title, ArtistId) values ('Brand new song', 1)` + +// Stop listening changes on the table +await pubSub.unlisten(PUBSUB_ENTITY_TYPE.TABLE, 'albums') +``` diff --git a/sqlite-cloud/platform/rls.mdx b/sqlite-cloud/platform/rls.mdx new file mode 100644 index 0000000..07bc7f4 --- /dev/null +++ b/sqlite-cloud/platform/rls.mdx @@ -0,0 +1,277 @@ +--- +title: Row-Level Security +description: Configure fine-grained access control policies to determine which rows in a table a user can access. +category: platform +status: publish +slug: rls +--- + +import VideoPlayer from '@commons-components/Video/VideoPlayer.astro'; +import rlsEnable from '@docs-website-assets/introduction/video/dashboard_rls_enable.mp4'; +import rlsTest from '@docs-website-assets/introduction/video/dashboard_rls_test.mp4'; + +import Callout from "@commons-components/Information/Callout.astro"; + +Row-Level Security (RLS) allows you to define fine-grained access control policies that determine which rows in a table a user can access. This ensures that users can only view or modify data they are authorized to see, enhancing data security and privacy. + + +RLS rules only affect users who are authenticated using [Access Tokens](/docs/access-tokens). Admins, APIKEYs, or other non-token users are not restricted by RLS. + + +RLS is a powerful feature for building secure, multi-tenant applications. When combined with SQLite Sync, it enables you to create robust **local-first apps** where user data is stored on the device for offline availability and superior performance. + +This architecture simplifies development by allowing your application to interact with a local database while SQLite Cloud [OffSync](/docs/offsync) transparently handles the synchronization with a central database. RLS ensures that each user's data is securely isolated during this process. The centralized database can then be used for powerful business analytics and reporting across all tenants, without compromising individual data privacy. + +--- + +## Policy Enforcement + +RLS in SQLite Cloud operates based on the following principles: + +Access is denied by default. + +Unless explicitly allowed by RLS rules, access is blocked. Specifically: + +- If RLS is enabled and rules are defined, only permitted operations will succeed. +- If RLS is enabled but a rule is missing for an operation (e.g., `SELECT`), that operation will be denied. +- If RLS is not enabled or not configured for a table, token-authenticated users won't see any rows at all. + +To make data accessible to token-authenticated users, you must both enable RLS for the table and define rules for the desired operations (like `SELECT`, `INSERT`, etc.). + +Otherwise, they will be blocked from accessing any rows. + +--- + +## Configuring RLS + +You can configure RLS policies for your databases through the SQLite Cloud dashboard. + + + +1. **Navigate to the Databases Page**: From the main dashboard, go to the "Databases" page. +2. **Select the RLS Column**: In the list of your databases, click on the button in the "RLS" column for the desired database. +3. **Configure RLS Settings**: On the RLS settings page, you can define the policies for each table. + + + For each table, you can specify the following RLS policies: + + - **SELECT**: A SQL expression that determines which rows a user can `SELECT`. + - **INSERT**: A SQL expression that determines if a user can `INSERT` a new row. + - **UPDATE**: A SQL expression that determines which rows a user can `UPDATE`. + - **DELETE**: A SQL expression that determines which rows a user can `DELETE`. + + + The SQL expressions can be any valid SQLite expression that returns a boolean value. You can use built-in SQLite functions, and even custom functions to define your policies. + + +### User Information Functions + +To help you create dynamic RLS policies, SQLite Cloud provides two functions to retrieve information about the current authenticated user: + +- `auth_userid()`: Returns the `userid` of the current token-authenticated user. +- `auth_json()`: Returns a JSON object with all the details of the current token-authenticated user, including `user_id`, `name`, `attributes`, `created_at`, and `expires_at`. + +These functions are particularly useful for creating policies that are based on user attributes. + +For more information on Access Tokens, see the [Access Tokens documentation](/docs/access-tokens). The API Documentation for the Access Tokens API can be found in the Weblite section in the Dashboard. + +### OLD and NEW References + +Your RLS policies for `INSERT`, `UPDATE`, and `DELETE` operations can reference column values as they are being changed. This is done using the special `OLD.column` and `NEW.column` identifiers. Their availability and meaning depend on the operation being performed: + +| Operation | `OLD.column` Reference | `NEW.column` Reference | +| :--- | :--- | :--- | +| `INSERT` | Not available | The value for the new row. | +| `UPDATE` | The value of the row *before* the update. | The value of the row *after* the update. | +| `DELETE` | The value of the row being deleted. | Not available | + +--- + +## Testing RLS + + + +To verify that your Row-Level Security (RLS) policies work as expected, you can use the **Test RLS** feature in the dashboard: + +1. **Open the Test Panel** + On the RLS policies page, click **Test** to open the dedicated testing panel. + +2. **Generate an Access Token** + - Go to the **Weblite page** and use the `POST /v2/tokens` endpoint. + - Provide a request body with a `userId`, a `name`, and any attributes required by your RLS policies (for example: `role`, `enabled`, etc.). + - Execute the request and copy the `token` value from the response. + +3. **Authenticate in the Test Panel** + - Paste the generated token into the **Enter Access Token** field and click **Authorize**. + - The dashboard will now simulate queries to the database as if they were executed by the user identified in the token. + +4. **View Filtered Data** + - Once authenticated, you can navigate through the database tables directly from the test panel. + - Only the rows allowed by your RLS rules will be displayed (for example, activities tied to the `user_id` in the token or accessible with the `coach` role). + +5. **Compare with Full Data** + - By switching back to **Database Studio**, you can see all rows in the table without RLS filters. + - This allows you to compare the filtered view (via token) with the complete dataset and confirm that your policies are correctly enforced. + + + + +--- + +## Example + +Suppose you have a `tasks` table with the following schema: + +```sql +CREATE TABLE tasks ( + id TEXT PRIMARY KEY NOT NULL, + user_id TEXT, + title TEXT, + status TEXT +); +``` + +Here are a few examples of RLS policies you can create: + +**1. Users can only see their own tasks.** + +```sql +-- SELECT policy +user_id = auth_userid() +``` + +**2. Users can only insert tasks for themselves.** + +```sql +-- INSERT policy +NEW.user_id = auth_userid() +``` + +**3. Users can only update the status of their own tasks.** + +```sql +-- UPDATE policy +OLD.user_id = auth_userid() +``` + +**4. Users can only delete their own tasks.** + +```sql +-- DELETE policy +OLD.user_id = auth_userid() +``` + +**5. Users with the 'admin' group can see all tasks.** + +```sql +-- SELECT policy +json_extract(auth_json(), '$.attributes.group') = 'admin' +``` + +**6. Role-Based Access within a Tenancy** + +```sql +-- SELECT policy +org_id = json_extract(auth_json(), '$.attributes.org_id') AND +(json_extract(auth_json(), '$.attributes.role') = 'admin' OR user_id = auth_userid()) +``` + +**7. Access via a Membership Linking Table** + +```sql +-- SELECT policy +EXISTS ( + SELECT 1 FROM project_members + WHERE project_members.project_id = tasks.project_id + AND project_members.user_id = auth_userid() +) +``` + +**8. Public vs. Private Record Visibility** + +```sql +-- SELECT policy +visibility = 'public' OR user_id = auth_userid() +``` + +With these policies, when a user executes a query, SQLite Cloud will automatically enforce the defined RLS rules, ensuring data security and compliance. + +### Additional Real-World Examples + +Here are a few more examples to illustrate how you can use RLS policies to solve common security challenges. + +#### 1. Team-Based Access (Multi-Tenancy) + +**Use Case:** A user should only be able to see documents that belong to their organization or team. This is a classic multi-tenancy scenario. + +**Assumptions:** +* Your `documents` table has an `org_id` column. +* The user's access token contains their organization ID in the JSON attributes (e.g., `{"org_id": "acme_corp"}`). + +**RLS Policy (`SELECT`):** +```sql +-- On the 'documents' table +org_id = json_extract(auth_json(), '$.attributes.org_id') +``` + +**Explanation:** +This policy ensures that the `org_id` in the document row must match the `org_id` stored in the authenticated user's token. This effectively isolates data between different organizations. + +--- + +#### 2. Content Publishing Workflow + +**Use Case:** In a simple CMS or blog, any user (even anonymous ones, if applicable) can see articles with a `published` status. However, only the original author can see their own articles when they are in the `draft` status. + +**Assumptions:** +* Your `articles` table has a `status` column (`'draft'` or `'published'`) and an `author_id` column. + +**RLS Policy (`SELECT`):** +```sql +-- On the 'articles' table +status = 'published' OR (status = 'draft' AND author_id = auth_userid()) +``` + +**Explanation:** +This policy uses a boolean `OR` to combine two conditions. A user can see a row if: +1. The article's status is `published`, OR +2. The article's status is `draft` AND the user is the author. + +--- + +#### 3. Making Records Read-Only + +**Use Case:** Once an invoice has been marked as `paid`, it should become immutable. No user should be able to update it. + +**Assumptions:** +* Your `invoices` table has a `status` column (`'pending'`, `'paid'`, etc.). + +**RLS Policy (`UPDATE`):** +```sql +-- On the 'invoices' table +OLD.status <> 'paid' +``` + +**Explanation:** +This policy uses the `OLD` reference to check the value of the `status` column *before* the update is applied. If the status is already `'paid'`, the condition `OLD.status <> 'paid'` will be false, and the `UPDATE` operation will be denied. This effectively makes paid invoices read-only. + + +--- + +## Advanced: RLS and SQLite Sync + +When using RLS in conjunction with SQLite Sync, it's important to understand how they interact. The Sync protocol applies changes on a column-by-column basis, which can affect how `INSERT` and `UPDATE` policies are evaluated. + +To accommodate this, SQLite Cloud offers two modes for handling RLS during sync operations, configurable via the `rls_mode` server setting using the SQLite Cloud builtin command `SET KEY rls_mode TO `. + +#### Default Mode (`rls_mode = 1`) + +To simplify policy creation for the most common use cases, the default mode does **not** enforce `INSERT` and `UPDATE` policies while applying changes from SQLite Sync. + +Instead, after the sync operation is complete, the `SELECT` policy is used to validate the final state of the row. If the user does not have permission to view the resulting row, the entire transaction is rolled back. This ensures that users cannot introduce changes that they are not allowed to see. + +#### Manual Policy Mode (`rls_mode = 0`) + +For more complex scenarios, such as implementing separate read/write permissions or restricting write access to specific columns, you can set `rls_mode` to `0`. + +In this mode, your `INSERT` and `UPDATE` policies are enforced for every incremental change applied by SQLite Sync. Because of Sync's column-by-column operation, your policies must be written to permit intermediate states. This means the policies must allow `NEW` values for non-primary key columns to be temporarily set to their default values during the sync process. diff --git a/sqlite-cloud/platform/security.mdx b/sqlite-cloud/platform/security.mdx index 22605d4..961c842 100644 --- a/sqlite-cloud/platform/security.mdx +++ b/sqlite-cloud/platform/security.mdx @@ -15,6 +15,8 @@ To add new users to your cluster, simply click on the **Create User** button. Once a user is successfully created, you can assign one or more roles to them to determine their level of access to the system. +--- + ## Roles In SQLite Cloud, a role is a set of permissions that allows a user to perform specific actions on a particular resource, such as a database or table. Users can have multiple roles, which determine their access to the system. @@ -29,10 +31,10 @@ There are two types of roles in SQLite Cloud: ![Dashboard Roles](@docs-website-assets/introduction/dashboard_roles.png) -## Built-in roles +### Built-in roles import Callout from "@commons-components/Information/Callout.astro"; -SQLite Cloud offers a comprehensive system of built-in roles designed to provide essential privileges within a database framework. These roles can be assigned using the [GRANT ROLE](https://docs.sqlitecloud.io/docs/commands/grant-role) command, and custom roles can be created with the [CREATE ROLE](https://docs.sqlitecloud.io/docs/commands/create-role) command. Privileges represent fundamental operations that can be executed on specific databases or tables and can be granted, revoked, or assigned to specific roles. +SQLite Cloud offers a comprehensive system of built-in roles designed to provide essential privileges within a database framework. These roles can be assigned using the GRANT ROLE command, and custom roles can be created with the CREATE ROLE command. Privileges represent fundamental operations that can be executed on specific databases or tables and can be granted, revoked, or assigned to specific roles. Here is an overview of the built-in roles: @@ -58,7 +60,7 @@ Here is an overview of the built-in roles: -To further refine the scope of a role or privilege, you can specify a database and table name during the [CREATE ROLE](/docs/commands/create-role), [GRANT ROLE](/docs/commands/grant-role), [GRANT PRIVILEGE](https://docs.sqlitecloud.io/docs/commands/grant-privilege) and [SET PRIVILEGE](https://docs.sqlitecloud.io/docs/commands/set-privilege) commands, as well as during the [CREATE USER](https://docs.sqlitecloud.io/docs/commands/create-user) command. If `NULL` is used, it means that the role or privilege is not assigned and cannot function without specifying a database and table name combination. To extend the validity to any database and table, you can utilize the special `*` character. +To further refine the scope of a role or privilege, you can specify a database and table name during the [CREATE ROLE](/docs/role-commands), [GRANT ROLE](/docs/role-commands), GRANT PRIVILEGE and SET PRIVILEGE commands, as well as during the CREATE USER command. If `NULL` is used, it means that the role or privilege is not assigned and cannot function without specifying a database and table name combination. To extend the validity to any database and table, you can utilize the special `*` character. ```bash @@ -98,7 +100,7 @@ In a role-based access control system, a privilege represents a specific action It defines what a user can or cannot do, such as reading, writing, or managing certain resources like tables, databases, or settings. Essentially, a privilege is a **right** or **ability** granted to a user or role, specifying their level of access and control over the system's resources. -A privilege can be [granted](https://docs.sqlitecloud.io/docs/commands/grant-privilege), [revoked](https://docs.sqlitecloud.io/docs/commands/revoke-privilege) and [assigned](https://docs.sqlitecloud.io/docs/commands/set-privilege) to a given role. +A privilege can be granted, revoked and assigned to a given role. A role can contains any combination of privileges. ```bash @@ -148,9 +150,9 @@ A role can contains any combination of privileges. -----------------| ``` - +{/* ## IP Restrictions -The IP Restrictions panel enables the restriction of access for a role or user by allowing only specific IP addresses or ranges in [CIDR notation](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) (for example 10.10.10.0/24). Both IPv4 and IPv6 addresses are supported. +The IP Restrictions panel enables the restriction of access for a role or user by allowing only specific IP addresses or ranges in CIDR notation (for example 10.10.10.0/24). Both IPv4 and IPv6 addresses are supported. To add a new IP restriction to a user or role, click on the **Add IP** button. @@ -159,14 +161,4 @@ To add a new IP restriction to a user or role, click on the **Add IP** button. The IP Restrictions table will display all current IP restrictions for the selected user or role. ![Dashboard List IP Restrictions](@docs-website-assets/introduction/dashboard_list_ip.png) - -## API KEYs - -API KEYs can be used as an alternative authentication mechanism. Authentication through API keys ensures the same privileges as the user to which they are associated. API KEYs are recommended for all server-to-server authentication cases and are necessary for using the [REST APIs](/docs/introduction/api) and the [SDK](/docs/sdk) that uses the WebSocket APIs. - -To create an API key for a user, click on the **Create API KEY** button. - -![Dashboard Create APIKEY](@docs-website-assets/introduction/dashboard_create_apikey.png) - -The resulting table will display all the API keys associated with each user, along with their name and restrictions. -![Dashboard List APIKEY](@docs-website-assets/introduction/dashboard_list_apikey.png) +*/} \ No newline at end of file diff --git a/sqlite-cloud/platform/settings.mdx b/sqlite-cloud/platform/settings.mdx deleted file mode 100644 index 3e1cc46..0000000 --- a/sqlite-cloud/platform/settings.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Settings -description: The Settings panel displays a list of all the settings currently applied to your cluster. -category: platform -status: publish -slug: settings ---- - -The Settings panel displays a list of all the settings currently applied to your cluster. You have the option to modify each setting individually or reset them to their default values. - -![Dashboard Settings](@docs-website-assets/introduction/dashboard_settings.png) \ No newline at end of file diff --git a/sqlite-cloud/platform/webhooks.mdx b/sqlite-cloud/platform/webhooks.mdx index e306a7d..2b00f2a 100644 --- a/sqlite-cloud/platform/webhooks.mdx +++ b/sqlite-cloud/platform/webhooks.mdx @@ -5,15 +5,108 @@ category: platform status: publish slug: webhooks --- +import VideoPlayer from '@commons-components/Video/VideoPlayer.astro'; +import webhooksUrl from '@docs-website-assets/introduction/video/dashboard_webhooks_trigger_url.mp4'; +import webhooksEdgeFunction from '@docs-website-assets/introduction/video/dashboard_webhooks_trigger_edge_function.mp4.mp4'; -Utilize the Webhooks panel to effortlessly establish real-time notifications for write operations within your SQLite database. In this instance, we'll seamlessly notify a webhook.site service each time a write operation occurs within the albums table of the chinook.sqlite database. +**Webhooks** are HTTP callbacks that allow your applications to receive real-time notifications when specific events occur. In the context of SQLite Cloud, webhooks make it easy to build reactive systems by automatically sending notifications when data changes happen within your databases. -![Dashboard Projects](@docs-website-assets/introduction/dashboard_webhook_create.png) -Upon creation, you'll receive a secret value that ensures the authenticity of each notification request. +--- + + +## Real-Time Notifications for Database Writes + + +Use the **Webhooks panel** to effortlessly create real-time notifications for write operations—such as inserts, updates, or deletes—within your SQLite Cloud database. + +For example, you can configure SQLite Cloud to notify a webhook.site endpoint every time a write operation occurs on the `albums` table of the `chinook.sqlite` database. + + + +--- + +## Change Data Capture + +Change Data Webhooks let you send structured HTTP requests to any external service whenever a row in a specific database and/or table is modified. These webhooks include: + +* **Database name** +* **Table name** +* **Operation type** (insert, update, delete) +* **Changed row data** + +This enables seamless integration with logging systems, monitoring dashboards, or external APIs that react to database activity. + + +### Payload Fields + +```json +{ + "type": "insert", + "database": "chinook.sqlite", + "table": "albums", + "column": [ + "AlbumId" + ], + "data": [ + 349 + ], + "webhook": { + "id": 1, + "action": "https://webhook.site/70792a3c-2a18-4a48-9ded-df1c90e758ce", + "options": { + "type": "url" + } + } +} +``` + +* **type** – The operation type (`insert`, `update`, or `delete`). +* **database** – The name of the database where the change occurred. +* **table** – The table affected by the operation. +* **column** – An array listing the column(s) involved in the operation. +* **data** – The values corresponding to the affected row(s). +* **webhook** – Metadata about the webhook itself, including its unique `id`, target `action` (URL or Edge Function), and configuration `options`. + +--- + +## Security + +Upon creation, each webhook is assigned a **secret key** used to verify the authenticity of incoming requests. + +![Dashboard Projects](@docs-website-assets/introduction/dashboard_webhook_secret.png) + +--- + +## Trigger Edge Functions + +Webhooks in SQLite Cloud aren't limited to data capture—they can also **trigger Edge Functions**: + +* Via HTTP or WebSocket +* In response to database write events + + + +Within an Edge Function, the webhook payload containing the **Change Data Capture** information is directly accessible through the `request.data` variable, which is available by default in all Edge Functions. + +```js +// Get secret from database +const slackWebhookEndpoint = await connection.sql`GET ENV slack_webhook_endpoint`; + +// Get record sent in body via webhook +const content = request.data; + +// Define helpers to assign and notify +const notifyRep = async ( ) => { + await fetch(slackWebhookEndpoint, { body: JSON.stringify({ text: "Discover the Latest Album Releases" + JSON.stringify(request.data)}), method: 'POST', 'Content-type': 'application/json' }); +} -![Dashboard Projects](@docs-website-assets/introduction/dashboard_webhook_create2.png) +// Call async functions +await notifyRep(); -Additionally, access a comprehensive list of all enabled webhooks for your project. +return { + data: 'OK' +} +``` -![Dashboard Projects](@docs-website-assets/introduction/dashboard_webhook_list.png) \ No newline at end of file +This allows developers to build distributed, event-driven applications that react immediately to changes at the edge. \ No newline at end of file diff --git a/sqlite-cloud/platform/weblite.mdx b/sqlite-cloud/platform/weblite.mdx new file mode 100644 index 0000000..9a44fc9 --- /dev/null +++ b/sqlite-cloud/platform/weblite.mdx @@ -0,0 +1,752 @@ +--- +title: Weblite +description: With Weblite, adding robust database capabilities to your site is as simple as adding Google Analytics. +category: platform +status: publish +slug: weblite +--- + +Weblite consists of an autogenerated HTTP/JSON REST API for programmatically interacting with SQLite Cloud. + +It is the simplest way to add a robust database backend to your application. + +## Overview + +First, navigate to the Weblite panel from the left-hand navigation menu. + +From here, you'll find a list of APIs you can use to interact with your SQLite Cloud instance, including: + +- **Services**: Endpoints for health checks, metrics, and more. +- **Weblite**: Endpoints for executing SQLiteCloudArrayType, and interacting with databases and tables. +- **Functions**: Endpoints for executing SQLite functions. +- **Webhooks**: Endpoints for creating and managing webhooks. +- **Files**: Endpoints for uploading and downloading files. + +## Services + +Services are endpoints for health checks, server information, and more. + +### Health Check + +Example request: + +```bash +curl -X 'GET' \ + 'https://.sqlite.cloud:8090/v2/health' \ + -H 'accept: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' +``` + +Example response: + +```json +{ + "data": { + "name": "@sqlitecloud/gateway", + "version": "x.x.x", + "project": "xxxxxxxxxx", + "node": "xxxxxxxxxx", + "hostname": "xxxxxxxxxx", + "started": "YYYY-MM-DDTHH:mm:ss.sssZ", + "uptime": "XXh:XXm:XXs" + }, + "metadata": { + "connectedMs": "XX", + "executedMs": "X", + "elapsedMs": "XX" + } +} +``` + +### Info + +Example request: + +```bash +curl -X 'GET' \ + 'https://.sqlite.cloud:8090/v2/info' \ + -H 'accept: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' +``` + +Example response: + +```json +{ + "data": { + "name": "@sqlitecloud/gateway", + "version": "x.x.x", + "project": "xxxxxxxxxx", + "node": "xxxxxxxxxx", + "hostname": "xxxxxxxxxx", + "started": "YYYY-MM-DDTHH:mm:ss.sssZ", + "uptime": "XXh:XXm:XXs", + "drivers": { + "name": "@sqlitecloud/drivers", + "version": "x.x.x" + }, + "runtime": { + "name": "xxxxxxx", + "version": "x.x.x", + "path": "/path/to/runtime", + "main": "/path/to/main/file" + }, + "environment": { + "events": true, + "settings": true, + "stats": true, + "logs": true + }, + "metrics": { + "js_heap_size": 00000000, + "js_heap_capacity": 00000000, + "js_heap_object_count": 000000, + "cpu_user": 00.0, + "cpu_system": 0.00, + "http_requests": 00000, + "http_get": 00000, + "http_completed": 00000, + "http_options": 00, + "ws_requests": 00, + "ws_get": 00, + "ws_completed": 00, + "http_patch": 0, + "http_post": 0 + }, + "internetAccess": true + }, + "metadata": { + "connectedMs": 00, + "executedMs": 00, + "elapsedMs": 00 + } +} +``` + +## Stats + +Example request: + +```bash +curl -X 'GET' \ + 'https://.sqlite.cloud:8090/v2/stats' \ + -H 'accept: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' +``` + +Example response: + +```json +{ + "data": { + "physicalMemory": 0000000000, + "bytesIn": 00000, + "bytesOut": 000000, + "cpuLoad": 0.0, + "currentClients": 0, + "currentMemory": 0000000, + "maxClients": 0, + "maxMemory": 0000000, + "numCommands": 000, + "numReads": 00, + "numWrites": 0 + }, + "metadata": { + "connectedMs": 00, + "executedMs": 00, + "elapsedMs": 00 + } +} +``` + +## Weblite + +Weblite are endpoints for executing SQLiteCloudArrayType, and interacting with databases and tables. + +### Run SQL queries on the node - GET + +Example request: + +```bash +sql_query="SELECT * FROM artists LIMIT 3" + +encoded_query=$(printf '%s' "$sql_query" | jq -sRr @uri) + +curl -X 'GET' \ + "https://.sqlite.cloud:8090/v2/weblite/sql?sql=$&database=" \ + -H 'accept: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' +``` + +Example response: + +```json +{ + "data": [ + { "ArtistId": 1, "Name": "AC/DC" }, + { "ArtistId": 2, "Name": "Accept" }, + { "ArtistId": 3, "Name": "Aerosmith" } + ], + "metadata": { + "connectedMs": "X", + "executedMs": "XX", + "elapsedMs": "XX", + "database": "chinook.sqlite", + "sql": "SELECT * FROM artists LIMIT 3", + "version": "X", + "numberOfRows": "X", + "numberOfColumns": "X", + "columns": [ + { + "name": "ArtistId", + "type": "INTEGER", + "database": "main", + "table": "artists", + "column": "ArtistId", + "notNull": 1, + "primaryKey": 1, + "autoIncrement": 1 + }, + { + "name": "Name", + "type": "NVARCHAR(120)", + "database": "main", + "table": "artists", + "column": "Name", + "notNull": 0, + "primaryKey": 0, + "autoIncrement": 0 + } + ] + } +} +``` + +### Run SQL queries on the node - POST + +Example request: + +```bash +sql="SELECT * FROM albums LIMIT 5" + +curl -X 'POST' \ + 'https://.sqlite.cloud:8090/v2/weblite/sql \ + -H 'Content-Type: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' + -d "{\"sql\":\"$sql\", \"database\": \"chinook.sqlite\"}" +``` + +Example response: + +```json +{ + "data": [ + { + "AlbumId": 1, + "Title": "For Those About To Rock We Salute You", + "ArtistId": 1 + }, + { "AlbumId": 2, "Title": "Balls to the Wall", "ArtistId": 2 }, + { "AlbumId": 3, "Title": "Restless and Wild", "ArtistId": 2 }, + { "AlbumId": 4, "Title": "Let There Be Rock", "ArtistId": 1 }, + { "AlbumId": 5, "Title": "Big Ones", "ArtistId": 3 } + ], + "metadata": { + "connectedMs": "XX", + "executedMs": "XX", + "elapsedMs": "XX", + "database": "chinook.sqlite", + "sql": "SELECT * FROM albums LIMIT 5", + "version": "X", + "numberOfRows": "X", + "numberOfColumns": "X", + "columns": [ + { + "name": "AlbumId", + "type": "INTEGER", + "database": "main", + "table": "albums", + "column": "AlbumId", + "notNull": 1, + "primaryKey": 1, + "autoIncrement": 1 + }, + { + "name": "Title", + "type": "NVARCHAR(160)", + "database": "main", + "table": "albums", + "column": "Title", + "notNull": 1, + "primaryKey": 0, + "autoIncrement": 0 + }, + { + "name": "ArtistId", + "type": "INTEGER", + "database": "main", + "table": "albums", + "column": "ArtistId", + "notNull": 1, + "primaryKey": 0, + "autoIncrement": 0 + } + ] + } +} +``` + +### List databases on the node + +Example request: + +```bash +curl -X 'GET' \ + 'https://.sqlite.cloud:8090/v2/weblite/databases' \ + -H 'accept: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' +``` + +Example response: + +```json +{ + "data": [ + { + "type": "database", + "name": "chinook.sqlite", + "size": "XXXXXX", + "connections": "X", + "encryption": null, + "backup": "X", + "nread": "X", + "nwrite": "X", + "inbytes": "X", + "outbytes": "X", + "fragmentation": "X.XX", + "pagesize": "XXXX", + "encoding": "UTF-8", + "status": "X" + }, + ], + "metadata": { + "connectedMs": "XX", + "executedMs": "X", + "elapsedMs": "XX" + } +} +``` + +### List all tables in a database + +Example request: + +```bash +curl -X 'GET' \ + 'https://.sqlite.cloud:8090/v2/weblite//tables' \ + -H 'accept: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' +``` + +Example response: + +```json +{ + "data": [ + { + "type": "table", + "name": "albums" + }, + { + "type": "table", + "name": "artists" + } + ], + "metadata": { + "connectedMs": "XX", + "executedMs": "X", + "elapsedMs": "XX" + } +} +``` + +### List all columns in a table + +Example request: + +```bash +curl -X 'GET' \ + 'https://.sqlite.cloud:8090/v2/weblite///columns' \ + -H 'accept: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' +``` + +Example response: + +```json +{ + "data": [ + { + "cid": 0, + "name": "AlbumId", + "type": "INTEGER", + "notnull": 1, + "dflt_value": null, + "pk": 1 + }, + { + "cid": 1, + "name": "Title", + "type": "NVARCHAR(160)", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 2, + "name": "ArtistId", + "type": "INTEGER", + "notnull": 1, + "dflt_value": null, + "pk": 0 + } + ], + "metadata": { + "connectedMs": "XX", + "executedMs": "X", + "elapsedMs": "XX" + } +} +``` + +### Download database from the node + +Example request: + +```bash +curl -X 'GET' -o chinook.sqlite \ + 'https://.sqlite.cloud:8090/v2/weblite/' \ + -H 'accept: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' +``` + +Example response: + +A binary file representing the database, eg.chinook.sqlite. + +```bash + % Total % Received % Xferd Average Speed Time Time Time Current + Dload Upload Total Spent Left Speed +100 866k 100 866k 0 0 1146k 0 --:--:-- --:--:-- --:--:-- 1145k +``` + +### Upload new database to the node + +Example request: + +```bash +curl -X 'POST' \ + 'https://.sqlite.cloud:8090/v2/weblite/' \ + -H 'Content-Type: application/octet-stream' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' + --data-binary @ +``` + +Example response: + +```json +{ + "data": { + "name": "newchinook.sqlite", + "size": "XXXXXX", + "connections": "X", + "encryption": null, + "backup": "X", + "nread": "X", + "nwrite": "X", + "inbytes": "X", + "outbytes": "X", + "fragmentation": "X.XX", + "pagesize": "XXXX", + "encoding": "UTF-8", + "status": "X" + }, + "metadata": { + "connectedMs": "XX", + "executedMs": "X", + "elapsedMs": "XX" + } +} +``` + +### Replace existing database on the node + +Example request: + +```bash +curl -X 'PATCH' \ + 'https://.sqlite.cloud:8090/v2/weblite/' \ + -H 'Content-Type: application/octet-stream' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' + --data-binary @ +``` + +Example response: + +```json +{ + "data": { + "name": "chinook.sqlite", + "size": "XXXXXX", + "connections": "X", + "encryption": null, + "backup": "X", + "nread": "X", + "nwrite": "X", + "inbytes": "X", + "outbytes": "X", + "fragmentation": "X.XX", + "pagesize": "XXXX", + "encoding": "UTF-8", + "status": "X" + }, + "metadata": { + "connectedMs": "XX", + "executedMs": "X", + "elapsedMs": "XX" + } +} +``` + +### Delete database from the node + +Example request: + +```bash +curl -X 'DELETE' \ + 'https://.sqlite.cloud:8090/v2/weblite/' \ + -H 'accept: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' +``` + +Example response: + +```json +{ + "data": "OK", + "metadata": { + "connectedMs": "XX", + "executedMs": "X", + "elapsedMs": "XX" + } +} +``` + +### Select all rows from a table + +Example request: + +```bash +curl -X 'GET' \ + 'https://.sqlite.cloud:8090/v2/weblite//' \ + -H 'accept: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' +``` + +Example response: + +```json +{ + "data": [ + { + "AlbumId": 1, + "Title": "For Those About To Rock We Salute You", + "ArtistId": 1 + }, + { + "AlbumId": 2, + "Title": "Balls to the Wall", + "ArtistId": 2 + } + ], + "metadata": { + "connectedMs": "XX", + "executedMs": "X", + "elapsedMs": "XX" + } +} +``` + +### Insert one or more rows into a table + +Example request: + +```bash +curl -X 'POST' \ + 'https://.sqlite.cloud:8090/v2/weblite//' \ + -H 'Content-Type: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' + -d '[{"Name": "Il Divo"}, {"Name": "Natalia LaFourcade"}]' +``` + +Example response: + +```json +{ + "data": "OK", + "metadata": { + "connectedMs": "XX", + "executedMs": "X", + "elapsedMs": "XX" + } +} +``` + +### Delete all rows in a table (or only those rows specified in search string parameters) + +Example request: + +```bash +curl -X 'DELETE' \ + 'https://.sqlite.cloud:8090/v2/weblite//' \ + -H 'accept: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' +``` + +Example response: + +```json +{ + "data": "OK", + "metadata": { + "connectedMs": "XX", + "executedMs": "X", + "elapsedMs": "XX" + } +} +``` + +### Select single row by row id + +Example request: + +```bash +curl -X 'GET' \ + 'https://.sqlite.cloud:8090/v2/weblite///' \ + -H 'accept: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' +``` + +Example response: + +```json +{ + "data": { + "ArtistId": 10, + "Name": "Billy Cobham" + }, + "metadata": { + "connectedMs": "XX", + "executedMs": "X", + "elapsedMs": "XX" + } +} +``` + +### Insert specific single row into a table + +Example request: + +```bash +curl -X 'POST' \ + 'https://.sqlite.cloud:8090/v2/weblite///' \ + -H 'Content-Type: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' + -d '{"Name": "Alessandro Safina"}' +``` + +Example response: + +```json +{ + "data": { + "type": "XX", + "index": "X", + "lastID": "XXX", + "changes": 1, + "totalChanges": 1, + "finalized": 1, + "rowId": "X" + }, + "metadata": { + "connectedMs": "XX", + "executedMs": "X", + "elapsedMs": "XX" + } +} +``` + +### Update specific row by row id + +Example request: + +```bash +curl -X 'PATCH' \ + 'https://.sqlite.cloud:8090/v2/weblite///' \ + -H 'Content-Type: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' + -d '{"title": "TEST"}' +``` + +Example response: + +```json +{ + "data": { + "type": "XX", + "index": "X", + "lastID": "XXX", + "changes": 1, + "totalChanges": 1, + "finalized": 1, + "rowId": "X" + }, + "metadata": { + "connectedMs": "XX", + "executedMs": "X", + "elapsedMs": "XX" + } +} +``` + +### Delete specific row in a table + +Example request: + +```bash +curl -X 'DELETE' \ + 'https://.sqlite.cloud:8090/v2/weblite///' \ + -H 'accept: application/json' \ + -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' +``` + +Example response: + +```json +{ + "data": { + "type": "XX", + "index": "X", + "lastID": "X", + "changes": 1, + "totalChanges": 1, + "finalized": 1, + "rowId": "X" + }, + "metadata": { + "connectedMs": "XX", + "executedMs": "X", + "elapsedMs": "XX" + } +} +``` diff --git a/sqlite-cloud/quick-start-django.mdx b/sqlite-cloud/quick-start-django.mdx deleted file mode 100644 index 63a7e84..0000000 --- a/sqlite-cloud/quick-start-django.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: Django Quick Start Guide -description: Get started with SQLite Cloud using Django. -category: getting-started -status: draft ---- - -In this quickstart, we will show you how to get started with SQLite Cloud and Django by building a simple application that connects to and reads from a SQLite Cloud database, and returns the result to a lightweight client. - -1. **Set up a SQLite Cloud account** - - If you haven't already, [sign up for a SQLite Cloud account](https://sqlitecloud.io/register) and create a new database. - - In this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. - -2. **Create a Django app** - - Create a Django app using the following command: -```bash -django-admin startproject sqlitecloud_quickstart -``` - - Create a new app within the project: -```bash -cd sqlitecloud_quickstart -python manage.py startapp quickstart -``` - -3. **Install the SQLite Cloud SDK** -```bash -pip install sqlitecloud -``` - -4. **Query data** - - Grab a connection string by clicking on a node in your dashboard. - - Create a file `services.py` within the quickstart directory. Use the following code to display data from your database. - -```python -import sqlitecloud - -# Create your models here. -db = sqlitecloud.connect('') - -def get_albums(): - result = db.execute(''' - USE DATABASE chinook.sqlite; - SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist - FROM albums - INNER JOIN artists - WHERE artists.ArtistId = albums.ArtistId - LIMIT 20; - ''') - return result.fetchall() - -``` - - Use the following code to display the data in a Django view: -```python -from django.http import JsonResponse -from .services import get_albums - -def albums(request): - data = get_albums() - return JsonResponse(data, safe=False) -``` - - Add the following URL pattern to your project's `urls.py` file: -```python -from django.urls import path -from quickstart import albums - -urlpatterns = [ - path('albums/', albums), -] -``` - - Run the Django development server: -```bash -python manage.py runserver -``` - - Visit `http://localhost:8000/albums/` to see the data returned from your SQLite Cloud database. - -And that's it! You've successfully built a Django app that reads data from a SQLite Cloud database. diff --git a/sqlite-cloud/quick-start-react-native.mdx b/sqlite-cloud/quick-start-react-native.mdx deleted file mode 100644 index 4436d3b..0000000 --- a/sqlite-cloud/quick-start-react-native.mdx +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: React Native Quick Start Guide -description: Get started with SQLite Cloud using React Native. -category: getting-started -status: publish ---- -In this quickstart, we will show you how to get started with SQLite Cloud and React Native by building a simple application that connects to and reads from a SQLite Cloud database. - ---- - -1. **Set up a SQLite Cloud account** - - If you haven't already, [sign up for a SQLite Cloud account](https://sqlitecloud.io/register) and create a new database. - - In this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. -2. **Create a React Native app** - - Create a React Native app using officially recommended framework Expo with the following command: -```bash - npx create-expo-app@latest -``` - - After creating your project, navigate to the project directory and install the SQLite Cloud SDK: -```bash - npm install @sqlitecloud/drivers -``` - -3. **Add data and service layers** - - Create a folder named `db`, then create a file in that folder named `database.js`. This file will be responsible for instantiating the database connection: -```javascript -import { Database } from '@sqlitecloud/drivers'; - -const db = new Database(''); - -export default db; -``` - - Next, create a folder named `services` in the root directory of your project. Create a file named `albums.js` within the `services` folder. This file will be responsible for querying data from the database: -```javascript -import db from '../db/database'; - -export const getAlbums = async () => { - const result = await db.exec` - USE DATABASE chinook.sqlite; - SELECT albums.AlbumId as id, albums.Title as title, albums.name as artist - FROM albums - INNER JOIN artists - WHERE artists.ArtistId = albums.ArtistId - LIMIT 20;`; - return result.fetchall(); -}; -``` -4. **Create a React Native component** - - Navigate to the index.js file in the /app/(tabs) directory and replace the existing code with the following code: -```javascript -import React, { useEffect, useState } from 'react'; -import { Text, View } from 'react-native'; -import { getAlbums } from './services/albums'; - -export default function HomeScreen() { - const [albums, setAlbums] = useState([]); - - useEffect(() => { - getAlbums().then((data) => setAlbums(data)); - }, []); - - return ( - - Albums - {albums.map((album) => ( - {album.title} by {album.artist} - ))} - - ); -} -``` - -5. **Run your app** - - Start your React Native app using the following command: -```bash - npm start -``` - - Open your Expo Go app on your mobile device and scan the QR code to view your app. - -And that's it! You've successfully built a React Native app that reads data from a SQLite Cloud database. \ No newline at end of file diff --git a/sqlite-cloud/quickstart/quick-start-apollo-graphql.mdx b/sqlite-cloud/quickstart/quick-start-apollo-graphql.mdx new file mode 100644 index 0000000..06397bf --- /dev/null +++ b/sqlite-cloud/quickstart/quick-start-apollo-graphql.mdx @@ -0,0 +1,187 @@ +--- +title: Apollo / GraphQL Quick Start Guide +description: Get started with SQLite Cloud using Apollo and GraphQL. +category: getting-started +status: publish +slug: quick-start-apollo-graphql +--- + +In this quickstart, we will show you how to get started with SQLite Cloud and Apollo/GraphQL by writing a simple GraphQL wrapper around a SQLite Cloud database connection. + +1. **Set up a SQLite Cloud account** + - If you haven't already, sign up for a SQLite Cloud account and create a new project. + - In this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. + +2. **Install the necessary dependencies** + - In your terminal run the following commands to install a new Apollo Server app. + +```bash +mkdir sqlc-quickstart +cd sqlc-quickstart +npm install apollo-server graphql +``` + +3. **Create a new Apollo Server app** + - Create a new file called `server.js` and add the following code. + - Import the necessary packages, and instantiate a new Database connection. +```js +import { ApolloServer } from '@apollo/server'; +import { startStandaloneServer } from '@apollo/server/standalone'; +import { Database } from '@sqlitecloud/drivers'; + +const connStr = '' + +const db = new Database(connStr) +``` +- Next, define your GraphQL schema and resolvers. +```js +const typeDefs = `#graphql + type Album { + AlbumId: Int + Title: String + ArtistId: Int + } + + type Artist { + ArtistId: Int + Name: String + } + + type Track { + TrackId: Int + Name: String + AlbumId: Int + MediaTypeId: Int + GenreId: Int + Composer: String + Milliseconds: Int + Bytes: Int + UnitPrice: Float + } + + type Genre { + GenreId: Int + Name: String + } + + type MediaType { + MediaTypeId: Int + Name: String + } + + type Join { + AlbumId: Int + Title: String + ArtistName: String + } + + type Query { + albums: [Album] + artists: [Artist] + tracks: [Track] + genres: [Genre] + mediaTypes: [MediaType] + joins: [Join] + artist(name: String): Artist + albumsByArtist(artistId: Int): [Album] + } + + type Mutation { + createArtist(name: String): Artist + createAlbum(title: String, artistId: Int): Album + } +`; + +const resolvers = { + Query: { + albums: async () => { + return await db.sql`SELECT * FROM albums`; + }, + artists: async () => { + return await db.sql`SELECT * FROM artists`; + }, + tracks: async () => { + return await db.sql`SELECT * FROM tracks`; + }, + genres: async () => { + return await db.sql`SELECT * FROM genres`; + }, + mediaTypes: async () => { + return await db.sql`SELECT * FROM media_types`; + }, + artist: async (_, { name }) => { + const res = await db.sql`SELECT * FROM artists WHERE Name LIKE ${name};`; + if (res.length === 0) return null; + return res[0]; + }, + albumsByArtist: async (_, { artistId }) => { + return await db.sql`SELECT albums.AlbumId, albums.Title FROM albums INNER JOIN artists ON albums.ArtistId = artists.ArtistId WHERE artists.ArtistId = ${artistId}`; + }, + }, + Mutation: { + createArtist: async (_, { name }) => { + const res = + await db.sql`INSERT INTO artists (Name) VALUES (${name})`; + if (res.changes === 0) return null; + return { ArtistId: res.lastID, Name: name }; + }, + createAlbum: async (_, { title, artistId }) => { + const res = + await db.sql`INSERT INTO albums (Title, ArtistId) VALUES (${title}, ${artistId})`; + if (res.changes === 0) return null; + return { + AlbumId: res.lastID, + Title: title, + ArtistId: artistId, + }; + }, + }, +}; +``` + +- Lastly, pass the GraphQL type definitions and resolvers into a new ApolloServer instance, and start the server. +```js +const server = new ApolloServer({ typeDefs, resolvers }); + +const { url } = await startStandaloneServer(server, { + listen: { port: 4000 }, + context: async () => ({ db }) +}); + +console.log(`🚀 Server ready at: ${url}`); +``` + +4. **Run your app** + - In your terminal, run the following command to start your Apollo Server. +```bash +node server.js +``` + +5. **Query your data** + - Open your browser and navigate to `http://localhost:4000` to access the Apollo GraphQL Playground. + - Use the following queries to interact with your SQLite Cloud database. + +Read operation: +```graphql +query { + albums { + AlbumId + Title + ArtistId + } +} +``` + +Write operation: +```graphql +mutation { + createArtist(name: "New Artist") { + ArtistId + Name + } +} +``` + +And that's it! You've successfully built an Apollo/GraphQL server that reads and writes data to a SQLite Cloud database. + +For the full code example, see the SQLite Cloud Apollo/GraphQL example repo. diff --git a/sqlite-cloud/quickstart/quick-start-cdn.mdx b/sqlite-cloud/quickstart/quick-start-cdn.mdx new file mode 100644 index 0000000..39a7fc5 --- /dev/null +++ b/sqlite-cloud/quickstart/quick-start-cdn.mdx @@ -0,0 +1,175 @@ +--- +title: CDN Quick Start Guide +description: Get started with SQLite Cloud using a Content Delivery Network +category: getting-started +status: publish +slug: quick-start-cdn +--- + +In this quickstart, we demonstrate how to locally serve the SQLite Cloud JS Drivers from a CDN. + +--- + +1. **Set up a SQLite Cloud account** + - If you haven't already, sign up for a SQLite Cloud account and create a new project. + - In this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. + +2. **Create a JavaScript / TypeScript app** + - The following commands bootstrap a TypeScript app. +```bash +mkdir sqlc-quickstart +cd sqlc-quickstart + +npm init -y +npm install typescript ts-node @types/node --save-dev +npx tsc --init +``` + +3. **Install the SQLite Cloud JS SDK** +```bash +npm install @sqlitecloud/drivers +``` + +4. **Load our example in your browser** + +Copy the following to your ```index.html``` file: +```html + + + + + SQLite Cloud CDN Quickstart + + + + + +

+ SQLite Cloud Example: Checking Chinook Customers +

+ +
+ + + + +
+ + +

Results:

+
    + + + + +``` + + - This HTML form sends a query to the `chinook.sqlite` database. You can load the form by simply dragging and dropping the file into your browser. + - To use SQLite Cloud's JS drivers, the example includes an additional script in the `` tag: ``. Update `{version}` with the most recent repo release. + +5. **Query data** + - There are 2 ways to query data. + 1. In your SQLite Cloud account dashboard, click on a Node, copy the Connection String, and paste it into the form's `Database Connection String` input. The expected string format is: `sqlitecloud://{host}.sqlite.cloud:8860?apikey={apikey}`. + + - Since this Connection String format does NOT contain the database to query, you MUST include the database name in your query. The expected query format is: `USE DATABASE {database}; select * from {table}`. + - IMPORTANT: The example SQL we provide (`USE DATABASE chinook.sqlite; select * from customers limit 3`) queries the `customers` table in the `chinook` database. The results are specifically parsed to be more readable. To display raw data from any table, uncomment the `index.html` code starting after `// list raw data` and comment out the later `for` loop. + + 2. An alternative Connection String format is: `sqlitecloud://{username}:{password}@{host}.sqlite.cloud:8860/{database}`. + + - Since this Connection String format DOES contain the database to query, you can exclude the database name from your query: `select * from {table}`. + - To get your admin username, go to your SQLite Cloud account dashboard. In the left nav, open Security and select Users. Your admin username has already been created. Replace `{username}` the connection string. + - To set your admin user's password, click the row's down chevron and select Edit. Enter a new Password and click Save. Replace `{password}` in the connection string. + - To get the host, see under your Project name `{host}.sqlite.cloud`. + - To get the database name, in the left nav, open Databases and select Tables. All of your databases are listed in the Select Database dropdown. + + - Send your query! Returned results will be listed, from most to least recent, below the form inputs. + +And that's it! You've successfully submitted a simple form to read data from a SQLite Cloud database. \ No newline at end of file diff --git a/sqlite-cloud/quickstart/quick-start-django.mdx b/sqlite-cloud/quickstart/quick-start-django.mdx new file mode 100644 index 0000000..8d467b6 --- /dev/null +++ b/sqlite-cloud/quickstart/quick-start-django.mdx @@ -0,0 +1,155 @@ +--- +title: Django Quick Start Guide +description: Get started with SQLite Cloud using Django. +category: getting-started +status: publish +slug: quick-start-django +--- + +In this quickstart, we will show you how to get started with SQLite Cloud and Django by building a simple application that connects to and reads from a SQLite Cloud database. + +1. **Set up a SQLite Cloud account** + - If you haven't already, sign up for a SQLite Cloud account and create a new project. + - In this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. + +2. **Create a Django app** + - If you haven't already done so, install Python and Django. + - The following command creates an outer directory (the container for your project) AND an inner directory (the Python package for your project). Both directories will be named `sqlitecloud_quickstart`. + +```bash +django-admin startproject sqlitecloud_quickstart +``` + - The following command creates your app as a separate package within the project container directory. + +```bash +cd sqlitecloud_quickstart +python manage.py startapp albums +``` + +3. **Install the SQLite Cloud Python SDK** + - Run this command from your current directory (i.e. the outer `sqlitecloud_quickstart`). + +```bash +pip install sqlitecloud +``` + +4. **App setup** + - Create a new file `albums/services.py` and copy in the following code. + - In your SQLite Cloud account dashboard, click on a Node, copy the Connection String, and replace `` below. + +```python +import sqlitecloud + +def get_albums(): + conn = sqlitecloud.connect('') + + db_name = "chinook.sqlite" + db_query = "SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist FROM albums INNER JOIN artists WHERE artists.ArtistId = albums.ArtistId LIMIT 20" + + conn.execute(f"USE DATABASE {db_name}") + + cursor = conn.execute(db_query) + + conn.close() + + result = cursor.fetchall() + + return result +``` + + - Copy the following code into `albums/views.py`. This view function invokes the `get_albums()` function defined in `services.py` to connect to the database and return album and artist information. + - The view function converts each returned row from a list to an object to more easily access the information in our HTML template (will discuss further later). + +```python +from django.http import HttpResponse +from django.template import loader +from .services import get_albums + +def index(request): + albumsList = get_albums() + + albumObjsList = [{'album': row[1], 'artist': row[2]} for row in albumsList] + + template = loader.get_template("albums/index.html") + context = { + "albumObjsList": albumObjsList, + } + return HttpResponse(template.render(context, request)) +``` + + - Create a new file `albums/urls.py` and copy in the following code. This URL configuration (URLconf) maps the above view to a URL so we can access the view in the browser. + +```python +from django.urls import path +from . import views + +urlpatterns = [ + path("", views.index, name="index") +] +``` + + - Adjust the code in `sqlitecloud_quickstart/urls.py` to be as follows. We must configure this global URLconf in the inner `sqlitecloud_quickstart` to include the URLconf we defined above in our app. + +```python +from django.contrib import admin +from django.urls import include, path + +# global URLconfs +urlpatterns = [ + path("albums/", include("albums.urls")), + path('admin/', admin.site.urls), +] +``` + + - Now we'll create a Django template the view can use to render HTML. Under `albums`, create a new file at `templates/albums/index.html` and copy in the following code. + - Bear in mind, there are now 2 (outer and inner) `albums` directories. + - The `index` view function above is already set up to load and render the template `albums/index.html`. (NOTE: `albums` here is the inner `albums` dir.) + +```html +
    +

    Albums

    +
      + {% for row in albumObjsList %} +
    • {{ row.album }} by {{ row.artist }}
    • + {% endfor %} +
    +
    +``` + - Lastly, in `sqlitecloud_quickstart/settings.py`, configure `DIRS` in `TEMPLATES` as follows. + - `'APP_DIRS': True` tells Django's templating engine to look for template source files inside project apps. + - `DIRS` provides the filepath to the correct app's `templates` dir. + +```python +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': ['albums/templates'], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] +``` + +5. **Run the Django dev server** + +```bash +python manage.py runserver +``` + + - Visit `http://127.0.0.1:8000/albums/` to see your app data. + +6. **FOLLOW-UP:** +This Quickstart goes a bit deeper into the framework than the other Quickstarts since Django requires more boilerplate to get up-and-running with a simple app. + +If you're new to Django and want to learn more, we referenced the following Django Tutorial pages extensively when writing this Quickstart: + - Part 1 + - Part 3 + +And that's it! You've successfully built a Django app that reads data from a SQLite Cloud database. \ No newline at end of file diff --git a/sqlite-cloud/quickstart/quick-start-flask.mdx b/sqlite-cloud/quickstart/quick-start-flask.mdx new file mode 100644 index 0000000..dfe33ec --- /dev/null +++ b/sqlite-cloud/quickstart/quick-start-flask.mdx @@ -0,0 +1,80 @@ +--- +title: Flask Quick Start Guide +description: Get started with SQLite Cloud using Flask. +category: getting-started +status: publish +slug: quick-start-flask +--- + +In this quickstart, we will show you how to get started with SQLite Cloud and Flask by building a simple application that connects to and reads from a SQLite Cloud database. + +--- + +1. **Set up a SQLite Cloud account** + - If you haven't already, sign up for a SQLite Cloud account and create a new project. + - In this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. + +2. **Create a Flask app** + - You should have the latest Python version (3) installed locally. + +```bash +mkdir sqlc-quickstart +cd sqlc-quickstart + +python3 -m venv .venv +. .venv/bin/activate + +pip install flask +``` + +3. **Install the SQLite Cloud SDK** + +```bash +pip install sqlitecloud +``` + +4. **Query data** + - Copy the following code into a new `app.py` file. + - In your SQLite Cloud account dashboard, click on a Node, copy the Connection String, and replace `` below. + +```py +from flask import Flask +import sqlitecloud + +app = Flask(__name__) + +@app.route('/') +def get_albums(): + conn = sqlitecloud.connect('') + + db_name = 'chinook.sqlite' + db_query = "SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist FROM albums INNER JOIN artists WHERE artists.ArtistId = albums.ArtistId LIMIT 20" + + conn.execute(f"USE DATABASE {db_name}") + + cursor = conn.execute(db_query) + + conn.close() + + result = '

    Albums

    ' + + for row in cursor: + album = f"{row[1]} by {row[2]}" + result += f"
  • {album}
  • " + + return result + '
    ' +``` + +5. **Run your app** + - If you're using port 5000 or on MacOS, also pass the `--port` option to provdie an open port. + - Pass the --debug option to enable hot reloading and interactive debugging on your dev server. + +```bash +flask run --port 3000 --debug +``` + +6. **View your app** + - Open your browser and navigate to `http://127.0.0.1:3000/` to see your app data. + - If you're unfamiliar with Flask, the code above calls the `get_albums` function when you load the root URL. The function returns a string with HTML for the browser to render. + +And that's it! You've successfully built a Flask app that reads data from a SQLite Cloud database. diff --git a/sqlite-cloud/quickstart/quick-start-gin.mdx b/sqlite-cloud/quickstart/quick-start-gin.mdx new file mode 100644 index 0000000..655f381 --- /dev/null +++ b/sqlite-cloud/quickstart/quick-start-gin.mdx @@ -0,0 +1,141 @@ +--- +title: Gin Quick Start Guide +description: Get started with SQLite Cloud using Gin. +category: getting-started +status: publish +slug: quick-start-gin +--- + +In this quickstart, we will show you how to get started with SQLite Cloud and Go by building a simple Gin application that connects to and reads from a SQLite Cloud database. + +--- + +1. **Set up a SQLite Cloud account** + - If you haven't already, sign up for a SQLite Cloud account and create a new database. + - In this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. + +2. **Create a Gin app** + - You should have Go installed locally. + - Set up your Go workspace. +```bash +mkdir sqlc-quickstart +cd sqlc-quickstart + +go mod init example.com/sqlc-quickstart +``` + - Create a file called `app.go`. + - Add the following code to your `app.go` file. +```go +package main + +import "fmt" +``` + - Import the Gin package in your Go source code. +```go +import "github.com/gin-gonic/gin" +``` + - Run the `go mod tidy` command to synchronize your module's dependencies. +```bash +$ go mod tidy +go: finding module for package github.com/gin-gonic/gin +go: found github.com/gin-gonic/gin in github.com/gin-gonic/gin v1.10.0 +go: downloading github.com/google/go-cmp v0.5.5 +``` + +3. **Install the SQLite Cloud package** +- Import the package in your Go source code. +```go +import sqlitecloud "github.com/sqlitecloud/sqlitecloud-go" +``` +- Download the package, and run the `go mod tidy` command to synchronize your module’s dependencies. +```bash +$ go mod tidy +go: downloading github.com/sqlitecloud/sqlitecloud-go v1.0.0 +``` + +4. **Connect with a valid SQLite Cloud connection string** +```go +sqlitecloud://{username}:{password}@{host}.sqlite.cloud:8860/{database} +``` +- To get your admin username, go to your SQLite Cloud account dashboard. In the left nav, open Security and select Users. Your admin username has already been created. Replace `{username}` in the connection string. +- To set your admin user’s password, click the row’s down chevron and select Edit. Enter a new Password and click Save. Replace `{password}` in the connection string. +- To get the host, see under your Project name `{host}.sqlite.cloud`. +- To get the database name, in the left nav, open Databases and select Tables. All of your databases are listed in the Select Database dropdown. + + +5. **Query data** + - Copy the following code into the `app.go` file. + - Replace ``. + +```go +type Artist struct { + ArtistID int64 `json:"artist id"` + Name string `json:"name"` +} + +func readArtists(resultSet *sqlitecloud.Result) ([]Artist, error) { + var artists []Artist + + for r := uint64(0); r < resultSet.GetNumberOfRows(); r++ { + id, err := resultSet.GetInt64Value(r, 0) + if err != nil { + return nil, err + } + + name, err := resultSet.GetStringValue(r, 1) + if err != nil { + return nil, err + } + + artists = append(artists, Artist{ + ArtistID: id, + Name: name, + }) + } + + return artists, nil +} + +func main() { + r := gin.Default() + + r.GET("/artists", func(c *gin.Context) { + const connectionString = "" + + db, err := sqlitecloud.Connect(connectionString) + if err != nil { + fmt.Println("Connect error: ", err) + panic("Connect error") + } + + dbResult, err := db.Select("SELECT * FROM artists LIMIT 10;") + if err != nil { + fmt.Println("Select error: ", err) + panic("Select error") + } + + artists, err := readArtists(dbResult) + if err != nil { + fmt.Println("Read artists error: ", err) + panic("Read artists error") + } + + c.JSON(200, artists) + + }) + + r.Run() // listen and serve on 0.0.0.0:8080 +} + +``` + +6. **Run your app** + +```bash +$ go run app.go +``` + +7. **View your app** + - Open your browser and navigate to `localhost:8080/artists`. + +And that's it! You've successfully built a Gin app that reads data from a SQLite Cloud database. \ No newline at end of file diff --git a/sqlite-cloud/quickstart/quick-start-knex.mdx b/sqlite-cloud/quickstart/quick-start-knex.mdx new file mode 100644 index 0000000..ef52c05 --- /dev/null +++ b/sqlite-cloud/quickstart/quick-start-knex.mdx @@ -0,0 +1,154 @@ +--- +title: Knex.js Integration +description: Integrate SQLite Cloud with Knex.js, a popular SQL query builder. +category: getting-started +status: publish +slug: quick-start-knex +--- + +In this tutorial, we'll show you how to connect your TypeScript application to a SQLite Cloud database using the popular SQL builder, Knex.js. + +--- + +**Prerequisites** + +- Node.js and npm installed on your system +- A SQLite Cloud account (you can sign up for a free account here) + +1. **How to connect** + +- Create a Knex.js instance that uses the SQLite Cloud JavaScript driver to connect to your database. + +```typescript +import 'dotenv/config' +import { knex } from 'knex' + +const Client_SQLite3 = require('knex/lib/dialects/sqlite3') + +// client will have sqlite3 dialect, but will use sqlitecloud-js driver +class Client_Libsql extends Client_SQLite3 { + _driver() { + return require('@sqlitecloud/drivers') + } +} + +// Create a Knex.js instance with the custom SQLite3 client +const db = knex({ + client: Client_Libsql as any, + connection: { + filename: process.env.DATABASE_URL as string + } +}) +``` + +2. **Basic Usage** + +In this example, we will use the sample datasets that come pre-loaded with SQLite Cloud. + +- Initialize a new Node project: + +```bash +npm init -y +``` + +- Install the required dependencies: + +```bash +npm install @sqlitecloud/drivers knex dotenv --save +``` + +- Install the necessary development dependencies: + +```bash +npm install @types/node nodemon ts-node typescript --save-dev +``` + +- Create a `.env` file in the root of your project and add your SQLite Cloud connection string: + +```bash +DATABASE_URL="sqlitecloud://{USER}:{PASSWORD}@{HOST}.sqlite.cloud:8860" +``` + +Replace `{USER}`, `{PASSWORD}`, and `{HOST}` with your actual SQLite Cloud credentials and server hostname. + +- Create a `tsconfig.json` file to configure your TypeScript compiler: + +```bash +tsc --init +``` + +- Create a new file called `example.ts` and add the following code: + +```typescript +import 'dotenv/config' +import { knex } from 'knex' + +const Client_SQLite3 = require('knex/lib/dialects/sqlite3') + +class Client_Libsql extends Client_SQLite3 { + _driver() { + return require('@sqlitecloud/drivers') + } +} + +console.assert(process.env.DATABASE_URL, 'Define DATABASE_URL environment variable') + +const db = knex({ + client: Client_Libsql as any, + connection: { + filename: process.env.DATABASE_URL as string + } +}) + +db.raw('USE DATABASE chinook.sqlite; SELECT * FROM customers') + .then(result => { + console.log(`Connected to database via knex and received ${result.length} rows`) + console.log(JSON.stringify(result, null, 2)) + db.destroy() + }) + .catch(err => { + console.error(err) + db.destroy() + }) +``` + +- Update your `package.json` file to include a script for running the example: + +```bash +{ + "scripts": { + "dev": "nodemon --exec ts-node example.ts" + } +} +``` + +- Start the development server: + +```bash +npm run dev +``` + +This will run the `example.ts` file using `ts-node` and will automatically restart the server when you make changes to your code. + +- Observe the output in the console, which should display the customer data fetched from the SQLite Cloud database. +```bash + [ + { + "CustomerId": 1, + "FirstName": "Luís", + "LastName": "Gonçalves", + "Company": "Embraer - Empresa Brasileira de Aeronáutica S.A.", + "Address": "Av. Brigadeiro Faria Lima, 2170", + "City": "São José dos Campos", + "State": "SP", + "Country": "Brazil", + "PostalCode": "12227-000", + "Phone": "+55 (12) 3923-5555", + "Fax": "+55 (12) 3923-5566", + "Email": "luisg@embraer.com.br", + "SupportRepId": 3 + }, + ] +``` + +And that's it! You've successfully connected your TypeScript application to a SQLite Cloud database using Knex.js. diff --git a/sqlite-cloud/quickstart/quick-start-laravel.mdx b/sqlite-cloud/quickstart/quick-start-laravel.mdx new file mode 100644 index 0000000..f2ee817 --- /dev/null +++ b/sqlite-cloud/quickstart/quick-start-laravel.mdx @@ -0,0 +1,147 @@ +--- +title: PHP / Laravel Quick Start Guide +description: Get started with SQLite Cloud using PHP and Laravel. +category: getting-started +status: publish +slug: quick-start-php-laravel +--- + +In this quickstart, we will show you how to get started with SQLite Cloud and PHP by building a simple Laravel application that connects to and reads from a SQLite Cloud database. + +--- + +1. **Set up a SQLite Cloud account** + - If you haven't already, sign up for a SQLite Cloud account and create a new project. + - In this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. + +2. **Create a Laravel app** + - If you haven't already done so, install PHP, Laravel, and Composer. + - If you use macOS, you can install all 3 in 1 click by downloading Laravel Herd, a PHP dev environment. + - Create a new Laravel project. + +```bash +composer create-project laravel/laravel sqlc-quickstart +``` + + - In the project directory, start Laravel's local dev server. + +```bash +cd sqlc-quickstart +php artisan serve +``` + + - Visit `http://127.0.0.1:8000` to see your Laravel app. + +3. **Configure a Blade frontend** + - Open another terminal. Again in your project dir, install Laravel Breeze. + - By default, Breeze uses simple Blade templates for your app's view layer. Blade is a templating engine included with Laravel. HTML is rendered server-side so you can include dynamic content from your database. + +```bash +composer require laravel/breeze --dev +php artisan breeze:install blade +``` + + - Start a Vite dev server that will hot reload updates to your app. (No need to load the provided localhost link, just keep the Vite server running.) + +```bash +npm run dev +``` + + - Refresh your app in the browser. Click the "Register" link at the top right. Register an account and log in. Save your credentials. + +4. **App setup** + + - Open another terminal. Again in your project dir, run `php artisan make:model -rc Album` to create an Eloquent Model (which we'll ignore) and a HTTP resource controller: `app/Http/Controllers/AlbumController.php`. We'll add functionality to this file to process app requests and return responses later. + - Replace the code in `routes/web.php` with the following snippet to add a route named `albums.index`. + - Run `php artisan route:list` to view all your app routes. + - `albums.index` will route GET requests to the `albums` endpoint to `AlbumController`'s `index` method (will set up later). + +```php +only(['index']); +``` + + - Create a new file `resources/views/albums/index.blade.php` and copy in the following code to create your Blade view template. + +```php +

    Albums

    +
      +@foreach ($albums as $album) +
    • {{ $album['albumTitle'] }} by {{ $album['artistName'] }}
    • +@endforeach +
    +``` + +5. **Install the SQLite Cloud SDK** + +```bash +composer require sqlitecloud/sqlitecloud +``` + +6. **Query data** + + - Replace the code in `app/Http/Controllers/AlbumController.php` with the following snippet. + - In your SQLite Cloud account dashboard, click on `Show connection strings`, copy the Connection String, and replace `` below. + - The `index` method will: + - connect to and query the database, + - create an array of arrays `albums` containing each returned album's title and artist, + - use the global `view` helper to pass `albums` to your view template stored at `resources/views/albums/index.blade.php` (and already set up to list the data), and + - return the completed Blade view to the browser. + +```php +connectWithString(''); + + $db_name = 'chinook.sqlite'; + $db_query = 'SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist FROM albums INNER JOIN artists WHERE artists.ArtistId = albums.ArtistId LIMIT 20'; + + $sqlite->execute("USE DATABASE {$db_name}"); + + $rowset = $sqlite->execute($db_query); + + $sqlite->disconnect(); + + $albums = []; + + for($i = 0; $i < $rowset->nrows; $i++) { + $albums[] = [ + 'albumTitle' => $rowset->value($i, 1), + 'artistName' => $rowset->value($i, 2), + ]; + } + + return view('albums.index', [ + 'albums' => $albums + ]); + } +} +``` + +7. **View your app** + - Visit `http://127.0.0.1:8000/albums` to see your app data. + +8. **FOLLOW-UP:** +This Quickstart goes a bit deeper into the framework than the other Quickstarts since Laravel requires more boilerplate to get up-and-running with a simple app. + +If you're new to Laravel and want to learn more, we referenced the following Laravel Tutorial pages extensively when writing this Quickstart: + - Installation + - Controllers, Routing, Blade + +And that's it! You've successfully built a PHP / Laravel app that reads data from a SQLite Cloud database. \ No newline at end of file diff --git a/sqlite-cloud/quickstart/quick-start-next.mdx b/sqlite-cloud/quickstart/quick-start-next.mdx new file mode 100644 index 0000000..4636cf2 --- /dev/null +++ b/sqlite-cloud/quickstart/quick-start-next.mdx @@ -0,0 +1,436 @@ +--- +title: Next.js Quick Start Guide +description: Get started with SQLite Cloud using Next.js. +category: getting-started +status: publish +slug: quick-start-next +--- + +This quick start guide will walk you through setting up a Next.js application that connects to and queries a SQLite Cloud database. + +--- + +1. **Set up a SQLite Cloud account** + - If you haven't already, sign up for a SQLite Cloud account and create a new project. + - For this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. + +2. **Create a Next.js app** + - Use ```create-next-app``` to set up a new Next.js project. The following command creates a minimal app with TypeScript and the latest App Router, keeping the focus on querying data. +```bash +npx create-next-app@latest sqlc-quickstart --ts --no-tailwind --eslint --app --src-dir --import-alias "@/*" --use-npm +``` + +3. **Install the SQLite Cloud SDK** +```bash +cd sqlc-quickstart && npm install @sqlitecloud/drivers +``` + +4. **Configure the Database Connection** + - Create a `.env.local` file in the root of your Next.js project and add your SQLite Cloud connection string: +```bash +SQLITECLOUD_URL=sqlitecloud://abcd1234.global1.qwerty.sqlite.cloud:8860/chinook.sqlite?apikey=your-api-key +NEXT_PUBLIC_SQLITECLOUD_URL=sqlitecloud://abcd1234.global1.qwerty.sqlite.cloud:8860/chinook.sqlite?apikey=your-api-key +``` + - The database driver establishes a TLS connection in Node.js and a WebSocket connection in the browser. + + +5. **Set Up the Folder Structure** +```bash +mkdir -p src/app/api/albums +mkdir -p src/app/components +mkdir -p src/constants + +touch src/app/api/albums/route.ts +touch src/app/components/GetAlbumsClient.tsx +touch src/app/components/GetAlbumsServer.tsx +touch src/app/components/UpdateAlbumsClient.tsx +touch src/constants/queries.ts +touch src/types.ts +``` + +6. **Define Data Types** +```ts +// +// src/type.ts (Server Component) +// + +export interface Album { + id: number; + title: string; + artist: string; +} + +``` + +7. **Define Queries** +```ts +// +// src/constants/queries.ts +// + +export const GET_ALBUMS = ` + USE DATABASE chinook.sqlite; + SELECT albums.AlbumId AS id, albums.Title AS title, artists.Name AS artist + FROM albums + INNER JOIN artists ON albums.ArtistId = artists.ArtistId + LIMIT 20; +`; + +export const GET_LAST_TEN_ALBUMS = ` + USE DATABASE chinook.sqlite; + SELECT albums.AlbumId AS id, albums.Title AS title, artists.Name AS artist + FROM albums + INNER JOIN artists ON albums.ArtistId = artists.ArtistId + ORDER BY albums.AlbumId DESC + LIMIT 10; +`; + +export const INSERT_ALBUM = ` + USE DATABASE chinook.sqlite; + INSERT INTO albums (Title, ArtistId) VALUES (?, ?); +`; +``` + +8. **Fetch Data via a Route Handler** + +You can create a route handler for handling `GET` and `POST` requests. + +```ts +// +// src/app/api/albums/route.ts (Route Handler) +// + +import { NextResponse } from "next/server"; +import { Database } from "@sqlitecloud/drivers"; +import { GET_LAST_TEN_ALBUMS, INSERT_ALBUM } from "@/constants/queries"; + +export async function GET() { + let db; + + try { + db = new Database(process.env.SQLITECLOUD_URL!); + const result = await db.sql(GET_LAST_TEN_ALBUMS); + + return NextResponse.json(result); + } catch (error) { + let message = "An unknown error occurred"; + + if (error instanceof Error) { + message = error.message; + } + + return NextResponse.json({ error: message }, { status: 500 }); + } finally { + db?.close(); + } +} + +export async function POST(req: Request) { + const { title, artistId } = await req.json(); + let db; + + try { + db = new Database(process.env.SQLITECLOUD_URL!); + await db.sql(INSERT_ALBUM, ...[title, artistId]); + + return NextResponse.json({ success: true }); + } catch (error) { + let message = "An unknown error occurred"; + + if (error instanceof Error) { + message = error.message; + } + + return NextResponse.json({ error: message }, { status: 500 }); + } finally { + db?.close(); + } +} +``` + +9. **Fetch Data in a Server Component** + +To fetch data directly from the server and render it in a Server Component: + +```tsx +// +// src/app/components/GetAlbumsServer.tsx (Server Component) +// + +import { GET_ALBUMS } from "@/constants/queries"; +import { Album } from "@/types"; +import { Database } from "@sqlitecloud/drivers"; +import { unstable_noStore as noStore } from "next/cache"; + +export default async function GetAlbumsServer() { + noStore(); // Prevents Next.js from caching the database request + let db; + + try { + db = new Database(process.env.SQLITECLOUD_URL!); + const result = await db.sql(GET_ALBUMS); + + return ( +
    +

    + Albums (Server Component) +

    +
      + {result.map((album: Album) => ( +
    • + {album.title} -{" "} + {album.artist} +
    • + ))} +
    +
    + ); + } catch (error) { + let message = "An unknown error occurred"; + + if (error instanceof Error) { + message = error.message; + } + return

    Error loading albums: {message}

    ; + } finally { + db?.close(); + } +} +``` + +10. **Fetch Data in a Client Component** +Since the SQLite Cloud driver can run in the browser, you can use it directly in a Client Component without needing an API route. + +```tsx +// +// src/app/components/GetAlbumsClient.tsx (Client Component) +// + +"use client"; + +import { useEffect, useState } from "react"; +import { Database } from "@sqlitecloud/drivers"; +import { Album } from "@/types"; +import { GET_ALBUMS } from "@/constants/queries"; + +export default function GetAlbumsClient() { + const [albums, setAlbums] = useState([]); + const [error, setError] = useState(null); + + useEffect(() => { + async function fetchAlbums() { + let db; + try { + console.log(process.env.NEXT_PUBLIC_SQLITECLOUD_URL); + db = new Database(process.env.NEXT_PUBLIC_SQLITECLOUD_URL!); + const result = await db.sql(GET_ALBUMS); + setAlbums(result); + } catch (error) { + let message = "An unknown error occurred"; + + if (error instanceof Error) { + message = error.message; + } + setError(message); + } finally { + db?.close(); + } + } + + fetchAlbums(); + }, []); + + if (error) return

    Error: {error}

    ; + + return ( +
    +

    Albums (Client Component)

    + {error ? ( +

    Error: {error}

    + ) : ( +
      + {albums.map((album) => ( +
    • + {album.title} -{" "} + {album.artist} +
    • + ))} +
    + )} +
    + ); +} +``` + +11. **Update Data in a Client Component** +You can also update data directly from a Client Component: + +```tsx +// +// src/app/components/UpdateAlbumsClient.tsx (Client Component) +// + +"use client"; + +import { useState, useEffect } from "react"; + +export default function UpdateAlbumsClient() { + const [albums, setAlbums] = useState< + { id: number; title: string; artist: string }[] + >([]); + const [loading, setLoading] = useState(false); + + // Function to fetch albums from the API route + async function fetchAlbums() { + try { + const res = await fetch("/api/albums"); + if (!res.ok) throw new Error("Failed to fetch albums"); + const data = await res.json(); + setAlbums(data); + } catch (error) { + console.error("Error fetching albums:", error); + } + } + + // Function to add a new album and then reload the albums list + async function addAlbum() { + setLoading(true); + + try { + // Generate a random album name + const randomAlbumTitle = `Album ${Math.random() + .toString(36) + .substring(7)}`; + + // Generate a random artist ID between 1 and 100 + const randomArtistId = Math.floor(Math.random() * 100) + 1; + + const res = await fetch("/api/albums", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + title: randomAlbumTitle, + artistId: randomArtistId, + }), + }); + + if (!res.ok) throw new Error("Failed to add album"); + + await fetchAlbums(); // Refresh album list after adding + } catch (error) { + console.error("Error adding album:", error); + } finally { + setLoading(false); + } + } + + // Fetch albums when component mounts + useEffect(() => { + fetchAlbums(); + }, []); + + return ( +
    + + +

    Latest Albums

    + {albums.length === 0 ? ( +

    No albums found.

    + ) : ( +
      + {albums.map((album) => ( +
    • + {album.title} -{" "} + {album.artist} +
    • + ))} +
    + )} +
    + ); +} + +``` + +12. **Create a Page to Display Components** + +Replace the content of `page.tsx` with: + +```tsx +// +// src/app/page.tsx (Unified Page) +// + +import GetAlbumsClient from "./components/GetAlbumsClient"; +import GetAlbumsServer from "./components/GetAlbumsServer"; +import UpdateAlbumsClient from "./components/UpdateAlbumsClient"; + +export default function page() { + return ( +
    +
    +

    Albums Overview

    + +
    + +
    + +
    + +
    + +
    + +
    +
    +
    + ); +} +``` + +Replace the content of `layout.tsx` with: + +```tsx +// +// src/app/layout.tsx +// + +export default function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { + return ( + + + {/* ✅ Add Tailwind CDN */} + + + {children} + + ); +} + +``` + +13. **Run Your App** +```bash +npm run dev +``` + +14. **View Your App** + - Open your browser and navigate to the provided localhost link to see your app in action. + + +--- + +Congratulations! You’ve successfully built a Next.js app that interacts with a SQLite Cloud database. \ No newline at end of file diff --git a/sqlite-cloud/quickstart/quick-start-node.mdx b/sqlite-cloud/quickstart/quick-start-node.mdx new file mode 100644 index 0000000..419a0af --- /dev/null +++ b/sqlite-cloud/quickstart/quick-start-node.mdx @@ -0,0 +1,68 @@ +--- +title: Node.js Quick Start Guide +description: Get started with SQLite Cloud using Node.js and Express. +category: getting-started +status: publish +slug: quick-start-node +--- + +In this quickstart, we will show you how to get started with SQLite Cloud and Node.js by building a simple web server that connects to and reads from a SQLite Cloud database, then serves that data to the client. + +--- + +1. **Set up a SQLite Cloud account** + - If you haven't already, sign up for a SQLite Cloud account and create a new project. + - In this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. +2. **Create a Node.js app** + - Navigate to your target directory and run the following command to initialize your Node.js app and install the necessary depedencies: +```bash +npm init +``` + - After creating your project, install the SQLite Cloud SDK: +```bash +npm install express @sqlitecloud/drivers --save +``` + - Create a file named `index.js` in the root directory of your project. + +3. **Query data** + - Grab a connection string by clicking on a node in your dashboard. + - Paste the following into your `index.js` file: + +```javascript +const express = require("express"); +const { Database } = require("@sqlitecloud/drivers"); + +const connectionString = process.env.SQLITECLOUD_CONNECTION_STRING +const app = express(); + +app.get("/albums", async (req, res) => { + let db = null; + try { + db = new Database(connectionString) + const result = await db.sql(` + USE DATABASE chinook.sqlite; + SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist + FROM albums + INNER JOIN artists + WHERE artists.ArtistId = albums.ArtistId + LIMIT 20;`); + res.json(result); + } catch (error) { + res.status(500).json({ error: error.message }); + } finally { + db?.close(); + } +}); + +app.listen(3000, () => { + console.log("Server running on port 3000"); +}); +``` +5. **Run your app** +```bash +node index.js +``` +6. **View your web server response** + - Open your browser and navigate to `http://localhost:3000/albums` to see your app in action. + +And that's it! You've successfully built a Node.js app that reads and serves data from a SQLite Cloud database. diff --git a/sqlite-cloud/quickstart/quick-start-prisma.mdx b/sqlite-cloud/quickstart/quick-start-prisma.mdx new file mode 100644 index 0000000..f0fb1c5 --- /dev/null +++ b/sqlite-cloud/quickstart/quick-start-prisma.mdx @@ -0,0 +1,87 @@ +--- +title: Prisma Quick Start Guide +description: Get started with SQLite Cloud using Prisma ORM. +category: getting-started +status: draft +slug: quick-start-prisma +--- + +In this quickstart, we will show you how to get started with SQLite Cloud and Prisma by building a simple application that connects to and reads from a SQLite Cloud database. + +--- + +1. **Set up a SQLite Cloud account** + - If you haven't already, sign up for a SQLite Cloud account and create a new project. + - In this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. +2. **Create a Next.js app** + - Create a Next app using ```create-next-app```. The following command creates a very simple app (JS, no Tailwind, uses the latest App Router) to keep the focus on querying the data. +```bash +npx create-next-app@latest sqlc-quickstart --js --no-tailwind --eslint --app --src-dir --import-alias "@/*" --use-npm +``` +3. **Install the SQLite Cloud SDK** +```bash +cd sqlc-quickstart && npm install @sqlitecloud/drivers +``` +4. **Query data** + - Replace the code in ```layout.js``` and ```page.js``` with the following snippets. + - Click a node in your account dashboard and copy the connection string. Replace `````` in ```page.js``` with your connection string. + +In ```src/app/layout.js```: +```jsx +export const metadata = { + title: 'Create Next App', + description: 'Generated by create next app', +}; + +export default function RootLayout({ children }) { + return ( + + {children} + + ); +} +``` + +In ```src/app/page.js```: +```jsx +import { Database } from '@sqlitecloud/drivers'; + +async function getAlbums() { + const db = new Database(''); + + const result = await db.sql`USE DATABASE chinook.sqlite; + SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist + FROM albums + INNER JOIN artists + WHERE artists.ArtistId = albums.ArtistId + LIMIT 20;`; + + return result; +} + +export default async function Home() { + const res = await getAlbums(); + + return ( +
    +

    Albums

    +
      + {res.map(({ id, title, artist }) => ( +
    • + {title} by {artist} +
    • + ))} +
    +
    + ); +} +``` + +5. **Run your app** +```bash +npm run dev +``` +6. **View your app** + - Open your browser and navigate to the localhost link provided by the previous command to see your app data. + +And that's it! You've successfully built a Next app that reads data from a SQLite Cloud database. \ No newline at end of file diff --git a/sqlite-cloud/quickstart/quick-start-react-native.mdx b/sqlite-cloud/quickstart/quick-start-react-native.mdx new file mode 100644 index 0000000..8ba114f --- /dev/null +++ b/sqlite-cloud/quickstart/quick-start-react-native.mdx @@ -0,0 +1,115 @@ +--- +title: React Native Quick Start Guide +description: Get started with SQLite Cloud using React Native. +category: getting-started +status: publish +slug: quick-start-react-native +--- + +In this quickstart, we will show you how to get started with SQLite Cloud and React Native by building a simple application that connects to and reads from a SQLite Cloud database. + +--- + +1. **Set up a SQLite Cloud account** + - If you haven't already, sign up for a SQLite Cloud account and create a new project. + - In this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. + +2. **Create a React Native project** + - If you haven't already, sign up for an Expo account. + - Create a new remote EAS project with the name `sqlc-quickstart`. + - Link your remote project to a new local project. Replace `{id}` below with the project ID provided by Expo. + +```bash +npm install --global eas-cli +npx create-expo-app sqlc-quickstart +cd sqlc-quickstart +eas init --id {id} +``` + +3. **Install the SQLite Cloud JS SDK and peer dependencies** + +```bash +npm install @sqlitecloud/drivers react-native-tcp-socket react-native-fast-base64 +``` + +4. **Query data** + - Replace the code in `app/(tabs)/index.tsx` with the following snippet. + - In your SQLite Cloud account dashboard, click on a Node, copy the Connection String, and replace `` below. + +```jsx +import { Database } from '@sqlitecloud/drivers'; +import { useState, useEffect } from 'react'; +import { View, Text, FlatList, StyleSheet } from 'react-native'; + +export default function App() { + const [albums, setAlbums] = useState([]); + + useEffect(() => { + async function getAlbums() { + let db = null; + try { + db = new Database(''); + + const result = + await db.sql(`USE DATABASE chinook.sqlite; + SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist + FROM albums + INNER JOIN artists + WHERE artists.ArtistId = albums.ArtistId LIMIT 20;`); + + setAlbums(result); + } catch (error) { + // manage error state + console.error(`getAlbums - ${error}`, error) + } finally { + db?.close(); + } + } + + getAlbums(); + }, []); + + return ( + + Albums + item.id} + renderItem={({ item }) => ( + + • {item.title} by {item.artist} + + )} + /> + + ); +} + +const styles = StyleSheet.create({ + container: { + padding: 15, + }, + title: { + fontSize: 34, + fontWeight: 600, + }, + listItem: { + paddingVertical: 3, + }, +}); +``` + - On `App` component mount, `useEffect` defines and calls a function that connects to and queries your database, updates the component's state with the most up-to-date `albums` data, and renders the data in a list. + +5. **Run your app** + +Expo run iOS +```bash +npx expo prebuild && npx expo run:ios +``` + +Expo run Android +```bash +npx expo prebuild && npx expo run:android +``` + +And that's it! You've successfully built a React Native app that reads data from a SQLite Cloud database. \ No newline at end of file diff --git a/sqlite-cloud/quick-start-react.mdx b/sqlite-cloud/quickstart/quick-start-react.mdx similarity index 64% rename from sqlite-cloud/quick-start-react.mdx rename to sqlite-cloud/quickstart/quick-start-react.mdx index ce6ef72..696b4b6 100644 --- a/sqlite-cloud/quick-start-react.mdx +++ b/sqlite-cloud/quickstart/quick-start-react.mdx @@ -3,6 +3,7 @@ title: React Quick Start Guide description: Get started with SQLite Cloud using React. category: getting-started status: publish +slug: quick-start-react --- In this quickstart, we will show you how to get started with SQLite Cloud and React by building a simple application that connects to and reads from a SQLite Cloud database. @@ -10,7 +11,7 @@ In this quickstart, we will show you how to get started with SQLite Cloud and Re --- 1. **Set up a SQLite Cloud account** - - If you haven't already, [sign up for a SQLite Cloud account](https://sqlitecloud.io/register) and create a new database. + - If you haven't already, sign up for a SQLite Cloud account and create a new project. - In this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. 2. **Create a React app** - Create a React app using a Vite template @@ -28,20 +29,27 @@ cd sqlc-quickstart && npm install @sqlitecloud/drivers import { useEffect, useState } from "react"; import { Database } from '@sqlitecloud/drivers'; -const db = new Database(''); - function App() { const [data, setData] = useState([]); const getAlbums = async () => { - const result = await db.sql` - USE DATABASE chinook.sqlite; - SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist - FROM albums - INNER JOIN artists - WHERE artists.ArtistId = albums.ArtistId - LIMIT 20;`; - setData(result); + let db = null; + try { + db = new Database('') + const result = await db.sql(` + USE DATABASE chinook.sqlite; + SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist + FROM albums + INNER JOIN artists + WHERE artists.ArtistId = albums.ArtistId + LIMIT 20;`); + setData(result); + } catch (err) { + // manage error state + console.error(`getAlbums - ${error}`, error); + } finally { + db?.close(); + } }; useEffect(() => { @@ -67,7 +75,7 @@ export default App npm run dev ``` 6. **View your app** - - Open your browser and navigate to `http://localhost:3000` to see your app in action. + - Open your browser and navigate to the localhost link provided by the previous command to see your app data. And that's it! You've successfully built a React app that reads data from a SQLite Cloud database. diff --git a/sqlite-cloud/quickstart/quick-start-sqlalchemy-orm.mdx b/sqlite-cloud/quickstart/quick-start-sqlalchemy-orm.mdx new file mode 100644 index 0000000..9a723c7 --- /dev/null +++ b/sqlite-cloud/quickstart/quick-start-sqlalchemy-orm.mdx @@ -0,0 +1,167 @@ +--- +title: SQLAlchemy ORM Quick Start Guide +description: Get started with SQLite Cloud using SQLAlchemy ORM in FastAPI. +category: getting-started +status: publish +slug: quick-start-sqlalchemy-orm +--- + +In this Quick Start, we will show you how to get started with SQLite Cloud by building a FastAPI backend that connects to and reads from a SQLite Cloud database using SQLAlchemy. + +NOTE that FastAPI framework: + - does NOT require you to use a relational database or any database at all. + - CAN work with any ORM library (including SQLAlchemy) or database (including SQLite, which comes pre-installed in Python and is a database supported by SQLAlchemy). + - code is MINIMAL in the example below. Most of the code is standard SQLAlchemy and framework-agnostic. + +--- + +1. **Set up a SQLite Cloud account** + - If you haven't already, sign up for a SQLite Cloud account and create a new project. + - In this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. + +2. **Create a new Python project** + - You should have the latest Python version (3) installed locally. + +```bash +mkdir sqlalchemy-quickstart +cd sqlalchemy-quickstart + +# open the project in VSCode / another editor +code . + +python3 -m venv .venv +. .venv/bin/activate +``` + +3. **Install dependencies** + - Run this command from your current directory: + +```bash +pip install "fastapi[standard]" sqlalchemy sqlalchemy-sqlitecloud +``` + + - Do NOT remove the quotes around the FastAPI package. + - `sqlalchemy-sqlitecloud` includes `sqlitecloud`, so no need to install the latter separately. + +4. **App setup** + - From your current directory, create a sub-directory `fastapi_sqlc_app` with an empty `__init__.py` file to indicate the new sub-directory is a package. + - NOTE: We will create all remaining project files in this sub-directory. + +```bash +mkdir fastapi_sqlc_app +cd fastapi_sqlc_app +touch __init__.py +``` + + - Create a new file `database.py` and copy in the following code. + - In your SQLite Cloud account dashboard, click on `Show connection strings`, copy the Connection String, and replace `` below. Modify your string to include the name of the DB we'll query: `sqlitecloud://{hostname}:8860/chinook.sqlite?apikey={apikey}`. + +```py +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker +from sqlalchemy.ext.declarative import declarative_base + +engine = create_engine('') + +SessionLocal = sessionmaker(bind=engine) + +Base = declarative_base() +``` + + - Create a new file `models.py` and copy in the following code defining 2 SQLAlchemy ORM "models", or classes, to interact with the DB. + - `__tablename__` is the name of a model's corresponding DB table. + - The `Album` class' `id` attribute maps to the `AlbumId` column in the `albums` table. All other class attribute names match their corresponding table column names. + +```py +from .database import Base + +from sqlalchemy import Column, ForeignKey, Integer, String + +class Artist(Base): + __tablename__ = "artists" + + ArtistId = Column(Integer, primary_key=True) + Name = Column(String) + +class Album(Base): + __tablename__ = "albums" + + id = Column("AlbumId", Integer, primary_key=True) + Title = Column(String) + ArtistId = Column(Integer, ForeignKey('artists.ArtistId')) +``` + + - Create a new file `schemas.py` and copy in the following code defining a Pydantic model, or "schema", to validate the shape of the response data. + +```py +from pydantic import BaseModel + +class AlbumResponse(BaseModel): + id: int + Title: str + ArtistName: str +``` + + - Create a new file `read.py` and copy in the following code creating a reusable utility function to read album data. + +```py +from . import models + +from sqlalchemy.orm import Session + +def get_albums(db: Session, skip: int = 0, num: int = 20): + return db.query(models.Album.id, models.Album.Title, models.Artist.Name.label('ArtistName')).join(models.Artist).offset(skip).limit(num).all() +``` + + - Create a new file `main.py` and copy in the following code. + - The `get_db` function handles creating and closing a new `SessionLocal` instance, or DB connection/ session, for every request. + - A GET request to the `/albums/` endpoint calls the `read_albums` function, which returns a list of SQLAlchemy `Album` models. The `response_model` ensures only data declared in the Pydantic schema is returned to the client. + - The `AlbumResponse` Pydantic model in `schemas.py` has `ArtistName`, as opposed to `ArtistId` defined in the `Album` SQLAlchemy model in `models.py`. + - `read_albums` calls the `get_albums` function in `read.py`. `get_albums` queries the `Album` ORM model/ `albums` DB table for the first 20 albums, and joins the `Artist` ORM model/ `artists` DB table to retrieve the `Artist.Name` (re-labeled `ArtistName`) expected by the `AlbumResponse` Pydantic model. + +```py +from .database import SessionLocal +from . import read, schemas + +from fastapi import FastAPI, Depends +from sqlalchemy.orm import Session + +app = FastAPI() + +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() + +@app.get("/albums/", response_model=list[schemas.AlbumResponse]) +def read_albums(skip: int = 0, num: int = 20, db: Session = Depends(get_db)): + albums = read.get_albums(db, skip=skip, num=num) + return albums +``` + +5. **Run your FastAPI app** + - From your `sqlalchemy-quickstart` directory, run the following command: + +```bash +uvicorn fastapi_sqlc_app.main:app --reload +``` + + - Visit `http://127.0.0.1:8000/albums/` to see your app data. + +6. **Troubleshooting** + + - If you encounter the following error, restart your IDE and re-run your app. + +```bash +AttributeError: module 'sqlitecloud.dbapi2' has no attribute 'sqlite_version_info'` +``` + +7. **References** + + - FastAPI introductory example + - FastAPI SQL Databases tutorial + - Latest SQLAlchemy docs + +And that's it! You've successfully built a FastAPI app that uses SQLAlchemy ORM to read data from a SQLite Cloud database. diff --git a/sqlite-cloud/quickstart/quick-start-streamlit.mdx b/sqlite-cloud/quickstart/quick-start-streamlit.mdx new file mode 100644 index 0000000..634c735 --- /dev/null +++ b/sqlite-cloud/quickstart/quick-start-streamlit.mdx @@ -0,0 +1,66 @@ +--- +title: Streamlit Quick Start Guide +description: Get started with SQLite Cloud using Streamlit. +category: getting-started +status: publish +slug: quick-start-streamlit +--- + +In this quickstart, we will show you how to get started with SQLite Cloud and Streamlit by building a simple application that connects to and reads from a SQLite Cloud database. + +--- + +1. **Set up a SQLite Cloud account** + - If you haven't already, sign up for a SQLite Cloud account and create a new project. + - In this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. + +2. **Create a Streamlit app** + - You should have the latest Python version (3) installed locally. + +```bash +mkdir sqlc-quickstart +cd sqlc-quickstart + +python3 -m venv .venv +. .venv/bin/activate + +pip install streamlit +``` + +3. **Install the SQLite Cloud SDK** + +```bash +pip install sqlitecloud +``` + +4. **Query data** + - Copy the following code into a new `app.py` file. + - In your SQLite Cloud account dashboard, click your Project name, copy the Connection String, and replace `` below. + +```py +import streamlit as st +import sqlitecloud +import pandas as pd + +st.header('Invoices') + +conn = sqlitecloud.connect('') + +db_name = "chinook.sqlite" +conn.execute(f"USE DATABASE {db_name}") + +invoices = pd.read_sql("SELECT * FROM invoices LIMIT 20", conn) + +st.dataframe(invoices, hide_index=True) +``` + +5. **Run your app** + +```bash +streamlit run app.py +``` + +6. **View your app** + - Open your browser and navigate to the localhost link provided by the previous command to see your app data. + +And that's it! You've successfully built a Streamlit app that reads data from a SQLite Cloud database. \ No newline at end of file diff --git a/sqlite-cloud/reference/_wip-index-with-card.mdx b/sqlite-cloud/reference/_wip-index-with-card.mdx new file mode 100644 index 0000000..f6669b2 --- /dev/null +++ b/sqlite-cloud/reference/_wip-index-with-card.mdx @@ -0,0 +1,35 @@ +--- +title: Reference +description: Index page for reference section +category: reference +status: publish +icon: docs-ref +slug: reference +--- +import IndexPage from "@docs-website-components/Docs/IndexPage.astro" + +export const introduction = "SQLite Cloud is a distributed relational database system built on top of the SQLite database engine. It has been specifically designed from the ground up to ensure the strong consistency of your data across all nodes in a cluster while simultaneously managing the technical aspects of scaling, security, and data distribution." + +export const sections = [ + { + icon: "curvedArrow", + title: "Server-side Commands", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/server-side-commands", + }, + { + icon: "twoColsGrid", + title: "CLI", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/cli-commands", + }, + { + icon: "sqlite-stacked", + title: "SQLite", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/sqlite", + }, +] + + + \ No newline at end of file diff --git a/sqlite-cloud/reference/api-key-commands.mdx b/sqlite-cloud/reference/api-key-commands.mdx index 8e4baa7..1d37cbb 100644 --- a/sqlite-cloud/reference/api-key-commands.mdx +++ b/sqlite-cloud/reference/api-key-commands.mdx @@ -8,7 +8,7 @@ slug: api-key-commands ## CREATE APIKEY USER The CREATE APIKEY USER command creates a new APIKEY associated to a specific username and with a mnemonic name. The RESTRICTION option is currently unused and an expiration date can be set using the EXPIRATION parameter. -It returns a [String](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the new APIKEY. +It returns a String with the new APIKEY. ### Syntax ```bash @@ -22,7 +22,7 @@ USERADMIN ## LIST APIKEYS The LIST APIKEYS command retrieves all the APIKEYS created on the server. The USER parameter can be used to filter the result further. -It returns a [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +It returns a Rowset with the following columns: * **username**: user name * **key**: API KEY * **name**: mnemonic name @@ -41,7 +41,7 @@ USERADMIN ## LIST MY APIKEYS The LIST MY APIKEYS command returns a list of all the APIKEYs associated with the username used in the current connection. -It returns a [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +It returns a Rowset with the following columns: * **username**: user name * **key**: API KEY * **name**: mnemonic name @@ -60,7 +60,7 @@ USERADMIN ## SET APIKEY The SET KEY command sets or updates a **keyname** to a specific **keyvalue**. Once set, the server immediately uses the updated value (and automatically distributes it on the cluster). -It returns OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +It returns OK string or error value (see SCSP protocol). ### Syntax @@ -75,7 +75,7 @@ SETTINGS ## REMOVE APIKEY The REMOVE APIKEY command permanently removes an APIKEY from the server. -It returns OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +It returns OK string or error value (see SCSP protocol). ### Syntax diff --git a/sqlite-cloud/reference/auth-commands.mdx b/sqlite-cloud/reference/auth-commands.mdx index 3c1feff..a4250ab 100644 --- a/sqlite-cloud/reference/auth-commands.mdx +++ b/sqlite-cloud/reference/auth-commands.mdx @@ -22,4 +22,4 @@ NONE ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). diff --git a/sqlite-cloud/reference/backup-commands.mdx b/sqlite-cloud/reference/backup-commands.mdx index 66d8666..9c3138e 100644 --- a/sqlite-cloud/reference/backup-commands.mdx +++ b/sqlite-cloud/reference/backup-commands.mdx @@ -7,7 +7,7 @@ slug: backup-commands --- ## APPLY BACKUP SETTINGS -Several backup-related settings can be applied using the SET DATABASE KEY command. +Several backup-related settings can be applied using the SET DATABASE KEY command. The following keys affect the backup settings: * **backup**: set to 1 to activate a backup, 0 to disable. @@ -28,7 +28,7 @@ BACKUP ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ## LIST BACKUP SETTINGS @@ -49,7 +49,7 @@ BACKUP ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **name**: database name * **enabled**: 1 enabled, 0 disabled * **backup_retention**: retention period @@ -91,7 +91,7 @@ BACKUP ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **type**: can be snapshot or wal * **replica**: always S3 in this version * **generation**: backup generation ID @@ -145,7 +145,7 @@ BACKUP ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with a single **name** column that returns all the databases with backup enabled. +A Rowset with a single **name** column that returns all the databases with backup enabled. ### Example @@ -172,7 +172,7 @@ RESTORE BACKUP DATABASE **database_name** [GENERATION **generation**] [INDEX **i ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Privileges diff --git a/sqlite-cloud/reference/cli-commands.mdx b/sqlite-cloud/reference/cli-commands.mdx index cd92e44..197ba0a 100644 --- a/sqlite-cloud/reference/cli-commands.mdx +++ b/sqlite-cloud/reference/cli-commands.mdx @@ -10,9 +10,9 @@ The **SQLite Cloud Command Line Interface** is a user-friendly interface that ru It's worth noting that there are two versions of the CLI available: one written in C and one written in GO. Both versions offer the same functionality, and the source code is provided for both. The C version was the first to be developed and was extensively used during the development of SQLite Cloud. It's based on the C SDK. The GO version, on the other hand, was created later, after the GO SDK was released. In the future, we plan to combine both projects into a unified CLI. -* Binaries can be downloaded from [GitHub](https://github.com/sqlitecloud/sdk/releases). -* C source code can be downloaded from the [C SDK repo](https://github.com/sqlitecloud/sdk/tree/master/C). -* GO source code can be downlaoded from the [GO SDK repo](https://github.com/sqlitecloud/sdk/tree/master/GO). +* Binaries can be downloaded from GitHub. +* C source code can be downloaded from the C SDK repo. +* GO source code can be downlaoded from the GO SDK repo. The C cli (sqlitecloud-cli) is available for Linux (x86) and macOS (Intel and ARM). diff --git a/sqlite-cloud/reference/cluster-commands.mdx b/sqlite-cloud/reference/cluster-commands.mdx index f7f9bb0..00c3680 100644 --- a/sqlite-cloud/reference/cluster-commands.mdx +++ b/sqlite-cloud/reference/cluster-commands.mdx @@ -20,8 +20,8 @@ CLUSTERADMIN, CLUSTERMONITOR ### Return -A [String](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) containing the IP address and port of the leader. -If the ID parameter is specified then the [Integer](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) nodeID of the leader node is returned. +A String containing the IP address and port of the leader. +If the ID parameter is specified then the Integer nodeID of the leader node is returned. ### Example @@ -49,7 +49,7 @@ CLUSTERADMIN, CLUSTERMONITOR ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **id**: node ID * **node**: public node DNS name and port * **cluster**: DNS name and port used for Raft intra-node communication @@ -88,7 +88,7 @@ CLUSTERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example diff --git a/sqlite-cloud/reference/database-commands.mdx b/sqlite-cloud/reference/database-commands.mdx index 0ac9aae..ed15ea1 100644 --- a/sqlite-cloud/reference/database-commands.mdx +++ b/sqlite-cloud/reference/database-commands.mdx @@ -26,7 +26,7 @@ CREATE_DATABASE ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -55,7 +55,7 @@ CREATE_DATABASE ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -80,7 +80,7 @@ DBADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -105,7 +105,7 @@ CREATE_DATABASE ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -130,8 +130,8 @@ HOSTADMIN ### Return -An [Integer](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) if **key** is ID or SIZE. -A [String](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) if **key** is NAME. +An Integer if **key** is ID or SIZE. +A String if **key** is NAME. ### Example @@ -166,7 +166,7 @@ PRAGMA ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **key**: database key * **value**:database value @@ -198,7 +198,7 @@ NONE ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with only the column **name** if the DETAILED flag is omitted, otherwise several other columns: +A Rowset with only the column **name** if the DETAILED flag is omitted, otherwise several other columns: * **name**: database name * **size**: database size (in bytes) * **connections**: number of clients connected to the database @@ -249,7 +249,7 @@ HOSTADMIN ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **id**: client ID * **address**: client IP address * **username**: username of the connected client @@ -287,7 +287,7 @@ DROP_DATABASE ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -312,7 +312,7 @@ PRIVILEGE_DBADMIN or PRIVILEGE_PUBSUB, which means that the USE DATABASE command ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -337,7 +337,7 @@ READWRITE ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example diff --git a/sqlite-cloud/reference/general-commands.mdx b/sqlite-cloud/reference/general-commands.mdx index 9cb7cec..84bd73e 100644 --- a/sqlite-cloud/reference/general-commands.mdx +++ b/sqlite-cloud/reference/general-commands.mdx @@ -22,7 +22,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -54,7 +54,7 @@ CLUSTERADMIN, CLUSTERMONITOR ### Return -A single value (usually a [String](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md)) that depends on the input **key**. +A single value (usually a String) that depends on the input **key**. ### Example @@ -79,7 +79,7 @@ READWRITE ### Return -A [String](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) set to the CREATE TABLE sql statement. +A String set to the CREATE TABLE sql statement. ### Example @@ -104,7 +104,7 @@ NONE ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **command**: command syntax * **count**: how many times the command was executed * **avgtime**: average command execution time @@ -160,7 +160,7 @@ USERADMIN, HOSTADMIN ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **id**: unique connection (client) ID * **address**: source connection IP address * **username**: username used to authenticate the connection @@ -196,7 +196,7 @@ READWRITE ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **name**: index name * **tbl_name**: table name @@ -236,7 +236,7 @@ CLUSTERADMIN, CLUSTERMONITOR ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **key**: server key * **value**: server value @@ -307,7 +307,7 @@ READWRITE, DBADMIN ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with one **key** column that returns all the reserved SQLite keywords. +A Rowset with one **key** column that returns all the reserved SQLite keywords. ### Example @@ -482,7 +482,7 @@ READWRITE ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with several columns that depends on the filters used in the command. The output is similar to the one obtains by calling the [sqlite3_table_column_metadata](https://www.sqlite.org/c3ref/table_column_metadata.html) API. +A Rowset with several columns that depends on the filters used in the command. The output is similar to the one obtains by calling the sqlite3_table_column_metadata API. ### Example @@ -589,7 +589,7 @@ READWRITE ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **schema**: database schema name * **name**: table name * **type**: always 'table' in this version @@ -636,7 +636,7 @@ CLUSTERADMIN ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **datetime**: the data time of the stat * **key**: stat name * **value**: stat value @@ -710,7 +710,7 @@ NONE ### Return -It returns the "PONG" [String](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md). +It returns the "PONG" String. ### Example @@ -735,7 +735,7 @@ NONE ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example diff --git a/sqlite-cloud/reference/ip-commands.mdx b/sqlite-cloud/reference/ip-commands.mdx index ceb40a7..14baf4c 100644 --- a/sqlite-cloud/reference/ip-commands.mdx +++ b/sqlite-cloud/reference/ip-commands.mdx @@ -21,7 +21,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -46,10 +46,10 @@ USERADMIN ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **address**: IP address(es) allowed * **name**: user name or role name -* **type**: user or role [String](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) +* **type**: user or role String ### Example @@ -79,7 +79,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example diff --git a/sqlite-cloud/reference/log-commands.mdx b/sqlite-cloud/reference/log-commands.mdx index 8e4eafc..e12e027 100644 --- a/sqlite-cloud/reference/log-commands.mdx +++ b/sqlite-cloud/reference/log-commands.mdx @@ -45,9 +45,9 @@ HOSTADMIN ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: `datetime`, `log_type`, `log_level, `description`, `username`, `database`, `ip_address`, `connection_id`. +A Rowset with the following columns: `datetime`, `log_type`, `log_level, `description`, `username`, `database`, `ip_address`, `connection_id`. -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **datetime**: log entry date and time * **log_type**: log type (a number from 1 to 8, see description) * **log_level**: log level (a number from 0 to 5, see description) diff --git a/sqlite-cloud/reference/plugin-commands.mdx b/sqlite-cloud/reference/plugin-commands.mdx index 69d5476..f657ef0 100644 --- a/sqlite-cloud/reference/plugin-commands.mdx +++ b/sqlite-cloud/reference/plugin-commands.mdx @@ -22,7 +22,7 @@ PLUGIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -47,7 +47,7 @@ PLUGIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -72,7 +72,7 @@ PLUGIN ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **name**: plugin name * **type**: plugin type (SQLite or SQLiteCloud) * **enabled**: 1 enabled, 0 disabled @@ -120,7 +120,7 @@ PLUGIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example diff --git a/sqlite-cloud/reference/privilege-commands.mdx b/sqlite-cloud/reference/privilege-commands.mdx index 688e91f..4b6b3d5 100644 --- a/sqlite-cloud/reference/privilege-commands.mdx +++ b/sqlite-cloud/reference/privilege-commands.mdx @@ -21,7 +21,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -46,7 +46,7 @@ USERADMIN ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with one privilege **name** column. +A Rowset with one privilege **name** column. ### Example @@ -110,7 +110,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -135,7 +135,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example diff --git a/sqlite-cloud/reference/pub-sub-commands.mdx b/sqlite-cloud/reference/pub-sub-commands.mdx index 6cc61aa..6777d8f 100644 --- a/sqlite-cloud/reference/pub-sub-commands.mdx +++ b/sqlite-cloud/reference/pub-sub-commands.mdx @@ -22,7 +22,7 @@ PUBSUBCREATE ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -48,7 +48,7 @@ PUBSUB ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with a single **chname** column that returns all channels created for Pub/Sub. +A Rowset with a single **chname** column that returns all channels created for Pub/Sub. ### Example @@ -88,7 +88,7 @@ SUB ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -112,7 +112,7 @@ PUB ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -137,7 +137,7 @@ PUBSUBCREATE ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -165,7 +165,7 @@ NONE ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example diff --git a/sqlite-cloud/reference/query-analyzer-commands.mdx b/sqlite-cloud/reference/query-analyzer-commands.mdx index e708e98..4de10d6 100644 --- a/sqlite-cloud/reference/query-analyzer-commands.mdx +++ b/sqlite-cloud/reference/query-analyzer-commands.mdx @@ -21,7 +21,7 @@ DBADMIN ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with an analysis about the query id. +A Rowset with an analysis about the query id. ### Example @@ -51,7 +51,7 @@ DBADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -79,7 +79,7 @@ DBADMIN ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **statement**: reference to original statement (when multiple suggestions are returned) * **type**: 1 means SQL, 2 means INDEX, 3 means PLAN and 4 means CANDIDATE * **report**: sql or suggestion computed by the SQLite engine @@ -116,7 +116,7 @@ DBADMIN ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with columns that depend on the command flags. +A Rowset with columns that depend on the command flags. ### Example diff --git a/sqlite-cloud/reference/role-commands.mdx b/sqlite-cloud/reference/role-commands.mdx index 4906acc..2dd78ce 100644 --- a/sqlite-cloud/reference/role-commands.mdx +++ b/sqlite-cloud/reference/role-commands.mdx @@ -23,7 +23,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -48,7 +48,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -73,7 +73,7 @@ USERADMIN ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **rolename**: the name of the role * **builtin**: 1 if it is a built-in role, 0 otherwise * **privileges**: a comma separated list of privileges associated to the role @@ -125,7 +125,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -150,7 +150,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -175,7 +175,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example diff --git a/sqlite-cloud/reference/settings-commands.mdx b/sqlite-cloud/reference/settings-commands.mdx index c7999ec..9ab989e 100644 --- a/sqlite-cloud/reference/settings-commands.mdx +++ b/sqlite-cloud/reference/settings-commands.mdx @@ -21,7 +21,7 @@ NONE ### Return -A single value (usually a [String](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md)) that depends on the input **keyname**. +A single value (usually a String) that depends on the input **keyname**. ### Example @@ -49,7 +49,7 @@ PRAGMA ### Return -A [String](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the requested value. +A String with the requested value. ### Example @@ -74,7 +74,7 @@ SETTINGS ### Return -A single value (usually a [String](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md)) that depends on the input **keyname**. +A single value (usually a String) that depends on the input **keyname**. ### Example @@ -102,7 +102,7 @@ NONE ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **key**: client key * **value**: client value @@ -146,7 +146,7 @@ SETTINGS ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **key**: settings key * **value**: settings value * **default_value**: default value @@ -202,7 +202,7 @@ NONE ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -227,7 +227,7 @@ PRAGMA ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -252,7 +252,7 @@ SETTINGS ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -277,7 +277,7 @@ NONE ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -306,7 +306,7 @@ PRAGMA ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -331,7 +331,7 @@ SETTINGS ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example diff --git a/sqlite-cloud/reference/user-commands.mdx b/sqlite-cloud/reference/user-commands.mdx index 00ffeb8..4d97509 100644 --- a/sqlite-cloud/reference/user-commands.mdx +++ b/sqlite-cloud/reference/user-commands.mdx @@ -21,7 +21,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -47,7 +47,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -72,7 +72,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -97,7 +97,7 @@ NONE ### Return -A [String](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) set to the current username. +A String set to the current username. ### Example @@ -122,7 +122,7 @@ USERADMIN ### Return -A [Rowset](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) with the following columns: +A Rowset with the following columns: * **username**: user name * **enabled**: 1 enabled, 0 disabled * **roles**: list of roles @@ -165,7 +165,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -190,7 +190,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -215,7 +215,7 @@ NONE ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example @@ -240,7 +240,7 @@ USERADMIN ### Return -OK string or error value (see [SCSP](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md) protocol). +OK string or error value (see SCSP protocol). ### Example diff --git a/sqlite-cloud/sdks/_wip-index-with-card.mdx b/sqlite-cloud/sdks/_wip-index-with-card.mdx new file mode 100644 index 0000000..0556522 --- /dev/null +++ b/sqlite-cloud/sdks/_wip-index-with-card.mdx @@ -0,0 +1,53 @@ +--- +title: SDKs +description: Index page for sdks section +category: sdks +status: publish +icon: docs-sdks +slug: sdks +--- +import IndexPage from "@docs-website-components/Docs/IndexPage.astro" + +export const introduction = "SQLite Cloud is a distributed relational database system built on top of the SQLite database engine. It has been specifically designed from the ground up to ensure the strong consistency of your data across all nodes in a cluster while simultaneously managing the technical aspects of scaling, security, and data distribution." + +export const sections = [ + { + icon: "docsSdkC", + title: "C/C++", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/sdk-c-introduction", + }, + { + icon: "docsSdkJs", + title: "JavaScript", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/sdk-js-introduction", + }, + { + icon: "docsSdkPython", + title: "Python", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/sdk-python-introduction", + }, + { + icon: "docsSdkGo", + title: "Go", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/sdk-go-introduction", + }, + { + icon: "docsSdkPhp", + title: "PHP", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/sdk-php-introduction", + }, + { + icon: "docsSdkSwift", + title: "Swift", + description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", + href: "/docs/sdk-swift-introduction", + }, +] + + + \ No newline at end of file diff --git a/sqlite-cloud/sdks/c/SQCloudArrayCount.mdx b/sqlite-cloud/sdks/c/SQCloudArrayCount.mdx index 4e27ac2..37dfdf3 100644 --- a/sqlite-cloud/sdks/c/SQCloudArrayCount.mdx +++ b/sqlite-cloud/sdks/c/SQCloudArrayCount.mdx @@ -10,7 +10,7 @@ uint32_t SQCloudArrayCount (SQCloudResult *result); ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_ARRAY then use this function to retrieve the number of items in the SQCloudResult array. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_ARRAY then use this function to retrieve the number of items in the SQCloudResult array. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. diff --git a/sqlite-cloud/sdks/c/SQCloudArrayDoubleValue.mdx b/sqlite-cloud/sdks/c/SQCloudArrayDoubleValue.mdx index 8b4db0b..91300cd 100644 --- a/sqlite-cloud/sdks/c/SQCloudArrayDoubleValue.mdx +++ b/sqlite-cloud/sdks/c/SQCloudArrayDoubleValue.mdx @@ -10,11 +10,11 @@ double SQCloudArrayDoubleValue (SQCloudResult *result, uint32_t index); ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_ARRAY then use this function to retrieve a double value. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_ARRAY then use this function to retrieve a double value. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. -* **index**: An array index (from 0 to [SQCloudArrayCount](/docs/sdk/c/sqcloudarraycount)-1) +* **index**: An array index (from 0 to [SQCloudArrayCount](/docs/sqlite-cloud/sdks/c/sqcloudarraycount)-1) ### Return value An `double` value. diff --git a/sqlite-cloud/sdks/c/SQCloudArrayFloatValue.mdx b/sqlite-cloud/sdks/c/SQCloudArrayFloatValue.mdx index 9ddc0f8..0b0314a 100644 --- a/sqlite-cloud/sdks/c/SQCloudArrayFloatValue.mdx +++ b/sqlite-cloud/sdks/c/SQCloudArrayFloatValue.mdx @@ -10,11 +10,11 @@ float SQCloudArrayFloatValue (SQCloudResult *result, uint32_t index); ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_ARRAY then use this function to retrieve a float value. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_ARRAY then use this function to retrieve a float value. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. -* **index**: An array index (from 0 to [SQCloudArrayCount](/docs/sdk/c/sqcloudarraycount)-1) +* **index**: An array index (from 0 to [SQCloudArrayCount](/docs/sqlite-cloud/sdks/c/sqcloudarraycount)-1) ### Return value A `float` value. diff --git a/sqlite-cloud/sdks/c/SQCloudArrayInt32Value.mdx b/sqlite-cloud/sdks/c/SQCloudArrayInt32Value.mdx index 39fb064..30beeb9 100644 --- a/sqlite-cloud/sdks/c/SQCloudArrayInt32Value.mdx +++ b/sqlite-cloud/sdks/c/SQCloudArrayInt32Value.mdx @@ -10,11 +10,11 @@ int32_t SQCloudArrayInt32Value (SQCloudResult *result, uint32_t index); ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_ARRAY then use this function to retrieve an Int32 value. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_ARRAY then use this function to retrieve an Int32 value. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. -* **index**: An array index (from 0 to [SQCloudArrayCount](/docs/sdk/c/sqcloudarraycount)-1) +* **index**: An array index (from 0 to [SQCloudArrayCount](/docs/sqlite-cloud/sdks/c/sqcloudarraycount)-1) ### Return value An `int32_t` value. diff --git a/sqlite-cloud/sdks/c/SQCloudArrayInt64Value.mdx b/sqlite-cloud/sdks/c/SQCloudArrayInt64Value.mdx index fee7569..e8f3c79 100644 --- a/sqlite-cloud/sdks/c/SQCloudArrayInt64Value.mdx +++ b/sqlite-cloud/sdks/c/SQCloudArrayInt64Value.mdx @@ -10,11 +10,11 @@ int64_t SQCloudArrayInt64Value (SQCloudResult *result, uint32_t index); ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_ARRAY then use this function to retrieve an Int64 value. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_ARRAY then use this function to retrieve an Int64 value. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. -* **index**: An array index (from 0 to [SQCloudArrayCount](/docs/sdk/c/sqcloudarraycount)-1) +* **index**: An array index (from 0 to [SQCloudArrayCount](/docs/sqlite-cloud/sdks/c/sqcloudarraycount)-1) ### Return value An `int64_t` value. diff --git a/sqlite-cloud/sdks/c/SQCloudArrayValue.mdx b/sqlite-cloud/sdks/c/SQCloudArrayValue.mdx index e7d3de6..875b525 100644 --- a/sqlite-cloud/sdks/c/SQCloudArrayValue.mdx +++ b/sqlite-cloud/sdks/c/SQCloudArrayValue.mdx @@ -10,11 +10,11 @@ char *SQCloudArrayValue (SQCloudResult *result, uint32_t index, uint32_t *len); ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_ARRAY then use this function to retrieve a pointer and a length for an array value. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_ARRAY then use this function to retrieve a pointer and a length for an array value. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function -* **index**: An array index (from 0 to [SQCloudArrayCount](/docs/sdk/c/sqcloudarraycount)-1) +* **index**: An array index (from 0 to [SQCloudArrayCount](/docs/sqlite-cloud/sdks/c/sqcloudarraycount)-1) * **len**: On output the length of the returned buffer ### Return value diff --git a/sqlite-cloud/sdks/c/SQCloudArrayValueType.mdx b/sqlite-cloud/sdks/c/SQCloudArrayValueType.mdx index 15c0f37..195f0a3 100644 --- a/sqlite-cloud/sdks/c/SQCloudArrayValueType.mdx +++ b/sqlite-cloud/sdks/c/SQCloudArrayValueType.mdx @@ -10,11 +10,11 @@ SQCLOUD_VALUE_TYPE SQCloudArrayValueType (SQCloudResult *result, uint32_t index) ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_ARRAY then use this function to retrieve the type of each array item. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_ARRAY then use this function to retrieve the type of each array item. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. -* **index**: An array index (from 0 to [SQCloudArrayCount](/docs/sdk/c/sqcloudarraycount)-1) +* **index**: An array index (from 0 to [SQCloudArrayCount](/docs/sqlite-cloud/sdks/c/sqcloudarraycount)-1) ### Return value An `int` represented by the SQCLOUD_VALUE_TYPE enum type: diff --git a/sqlite-cloud/sdks/c/SQCloudBlobBytes.mdx b/sqlite-cloud/sdks/c/SQCloudBlobBytes.mdx index c6d6db4..9985677 100644 --- a/sqlite-cloud/sdks/c/SQCloudBlobBytes.mdx +++ b/sqlite-cloud/sdks/c/SQCloudBlobBytes.mdx @@ -13,10 +13,10 @@ int SQCloudBlobBytes (SQCloudBlob *blob); This function returns the size in bytes of the BLOB accessible via the successfully opened BLOB handle in its only argument. The incremental blob I/O routines can only read or overwriting existing blob content; they cannot change the size of a blob. -This function resembles the [sqlite3_blob_bytes](https://www.sqlite.org/c3ref/blob_bytes.html) SQLite API. +This function resembles the sqlite3_blob_bytes SQLite API. ### Parameters -* **blob**: a valid SQCloudBlob opaque datatype obtained by [SQCloudBlobOpen](/docs/sdk/c/sqcloudblobopen) +* **blob**: a valid SQCloudBlob opaque datatype obtained by [SQCloudBlobOpen](/docs/sqlite-cloud/sdks/c/sqcloudblobopen) ### Return value An `int` value with the size in bytes of the BLOB. diff --git a/sqlite-cloud/sdks/c/SQCloudBlobClose.mdx b/sqlite-cloud/sdks/c/SQCloudBlobClose.mdx index bd237f8..4040283 100644 --- a/sqlite-cloud/sdks/c/SQCloudBlobClose.mdx +++ b/sqlite-cloud/sdks/c/SQCloudBlobClose.mdx @@ -10,10 +10,10 @@ bool SQCloudBlobClose (SQCloudBlob *blob); ``` ### Description -This function closes an open BLOB handle. The BLOB handle is closed unconditionally. Even if this routine returns an error code, the handle is still closed. This function resembles the [sqlite3_blob_close](https://www.sqlite.org/c3ref/blob_close.html) SQLite API. +This function closes an open BLOB handle. The BLOB handle is closed unconditionally. Even if this routine returns an error code, the handle is still closed. This function resembles the sqlite3_blob_close SQLite API. ### Parameters -* **blob**: a valid SQCloudBlob opaque datatype obtained by [SQCloudBlobOpen](/docs/sdk/c/sqcloudblobopen) +* **blob**: a valid SQCloudBlob opaque datatype obtained by [SQCloudBlobOpen](/docs/sqlite-cloud/sdks/c/sqcloudblobopen) ### Return value `true` if operation succed, otherwise `false` diff --git a/sqlite-cloud/sdks/c/SQCloudBlobOpen.mdx b/sqlite-cloud/sdks/c/SQCloudBlobOpen.mdx index c62d397..d5cf26b 100644 --- a/sqlite-cloud/sdks/c/SQCloudBlobOpen.mdx +++ b/sqlite-cloud/sdks/c/SQCloudBlobOpen.mdx @@ -22,10 +22,10 @@ This function fails if any of the following conditions are true: * Column **colname** is part of an index, PRIMARY KEY or UNIQUE constraint and the blob is being opened for read/write access * Foreign key constraints are enabled, column **colname** is part of a child key definition and the blob is being opened for read/write access -This function resembles the [sqlite3_blob_open](https://www.sqlite.org/c3ref/blob_open.html) SQLite API. +This function resembles the sqlite3_blob_open SQLite API. ### Parameters -* **connection**: a valid connection object obtained by [SQCloudConnect](/docs/sdk/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sdk/c/sqcloudconnectwithstring) +* **connection**: a valid connection object obtained by [SQCloudConnect](/docs/sqlite-cloud/sdks/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sqlite-cloud/sdks/c/sqcloudconnectwithstring) * **dbname**: symbolic name of the database (usually `main`, if NULL `main` is used) * **tablename**: table name that contains the BLOB column * **colname**: name of the BLOB column diff --git a/sqlite-cloud/sdks/c/SQCloudBlobReOpen.mdx b/sqlite-cloud/sdks/c/SQCloudBlobReOpen.mdx index a25a270..bf827c1 100644 --- a/sqlite-cloud/sdks/c/SQCloudBlobReOpen.mdx +++ b/sqlite-cloud/sdks/c/SQCloudBlobReOpen.mdx @@ -12,10 +12,10 @@ bool SQCloudBlobReOpen (SQCloudBlob *blob, int64_t rowid); ### Description This function is used to move an existing BLOB handle so that it points to a different row of the same database table. The new row is identified by the **rowid** value passed as the second argument. Only the row can be changed. The database, table and column on which the blob handle is open remain the same. -This function resembles the [sqlite3_blob_reopen](https://www.sqlite.org/c3ref/blob_reopen.html) SQLite API. +This function resembles the sqlite3_blob_reopen SQLite API. ### Parameters -* **blob**: a valid SQCloudBlob opaque datatype obtained by [SQCloudBlobOpen](/docs/sdk/c/sqcloudblobopen) +* **blob**: a valid SQCloudBlob opaque datatype obtained by [SQCloudBlobOpen](/docs/sqlite-cloud/sdks/c/sqcloudblobopen) * **rowid**: rowid of the BLOB to open diff --git a/sqlite-cloud/sdks/c/SQCloudBlobRead.mdx b/sqlite-cloud/sdks/c/SQCloudBlobRead.mdx index 48b2854..0ec896a 100644 --- a/sqlite-cloud/sdks/c/SQCloudBlobRead.mdx +++ b/sqlite-cloud/sdks/c/SQCloudBlobRead.mdx @@ -12,10 +12,10 @@ int SQCloudBlobRead (SQCloudBlob *blob, void *buffer, int blen, int offset); ### Description The **SQCloudBlobRead** function is used to read data from an open BLOB handle into a caller-supplied buffer. **blen** bytes of data are copied into buffer **buffer** from the open BLOB, starting at offset **offset**. -This function resembles the [sqlite3_blob_read](https://www.sqlite.org/c3ref/blob_read.html) SQLite API. +This function resembles the sqlite3_blob_read SQLite API. ### Parameters -* **blob**: a valid SQCloudBlob opaque datatype obtained by [SQCloudBlobOpen](/docs/sdk/c/sqcloudblobopen) +* **blob**: a valid SQCloudBlob opaque datatype obtained by [SQCloudBlobOpen](/docs/sqlite-cloud/sdks/c/sqcloudblobopen) * **buffer**: an user-supplied pre-allocated buffer * **blen**: the length of the input buffer * **offset**: the offset value set to where to start the read operation diff --git a/sqlite-cloud/sdks/c/SQCloudBlobWrite.mdx b/sqlite-cloud/sdks/c/SQCloudBlobWrite.mdx index 9e77167..d42ee93 100644 --- a/sqlite-cloud/sdks/c/SQCloudBlobWrite.mdx +++ b/sqlite-cloud/sdks/c/SQCloudBlobWrite.mdx @@ -13,10 +13,10 @@ int SQCloudBlobWrite (SQCloudBlob *blob, const void *buffer, int blen, int offse The **SQCloudBlobWrite** function is used to write data into an open BLOB handle from a caller-supplied buffer. **blen** bytes of data are copied from the buffer **buffer**into the open BLOB, starting at offset **offset**. -This function resembles the [sqlite3_blob_write](https://www.sqlite.org/c3ref/blob_write.html) SQLite API. +This function resembles the sqlite3_blob_write SQLite API. ### Parameters -* **blob**: a valid SQCloudBlob opaque datatype obtained by [SQCloudBlobOpen](/docs/sdk/c/sqcloudblobopen) +* **blob**: a valid SQCloudBlob opaque datatype obtained by [SQCloudBlobOpen](/docs/sqlite-cloud/sdks/c/sqcloudblobopen) * **buffer**: an user-supplied pre-allocated buffer * **blen**: the length of the input buffer * **offset**: the offset value set to where to start the write operation diff --git a/sqlite-cloud/sdks/c/SQCloudConfig.mdx b/sqlite-cloud/sdks/c/SQCloudConfig.mdx index bffb389..d49319c 100644 --- a/sqlite-cloud/sdks/c/SQCloudConfig.mdx +++ b/sqlite-cloud/sdks/c/SQCloudConfig.mdx @@ -7,7 +7,7 @@ status: publish ### Description -The **SQCloudConfig** struct is used in the [SQCloudConnect](/docs/sdk/c/sqcloudconnect) and in the [SQCloudConnectWithString](/docs/sdk/c/sqcloudconnectwithstring) functions to set connection specific configuration parameters. +The **SQCloudConfig** struct is used in the [SQCloudConnect](/docs/sqlite-cloud/sdks/c/sqcloudconnect) and in the [SQCloudConnectWithString](/docs/sqlite-cloud/sdks/c/sqcloudconnectwithstring) functions to set connection specific configuration parameters. ### SQCloudConfig diff --git a/sqlite-cloud/sdks/c/SQCloudConnect.mdx b/sqlite-cloud/sdks/c/SQCloudConnect.mdx index 3839466..d144d64 100644 --- a/sqlite-cloud/sdks/c/SQCloudConnect.mdx +++ b/sqlite-cloud/sdks/c/SQCloudConnect.mdx @@ -15,7 +15,7 @@ Initiate a new connection to a database node specified by hostname and port. Thi ### Parameters * **hostname**: a NULL terminated string that contains host name or host ip address * **port**: database server port (you can use the `SQCLOUD_DEFAULT_PORT` macro) -* **config**: a pointer to a [SQCloudConfig struct](/docs/sdk/c/sqcloudconfig) (cannot be NULL) +* **config**: a pointer to a [SQCloudConfig struct](/docs/sqlite-cloud/sdks/c/sqcloudconfig) (cannot be NULL) ### Return value A pointer to an opaque **SQCloudConnection** struct. diff --git a/sqlite-cloud/sdks/c/SQCloudConnectWithString.mdx b/sqlite-cloud/sdks/c/SQCloudConnectWithString.mdx index a64c76d..eb12181 100644 --- a/sqlite-cloud/sdks/c/SQCloudConnectWithString.mdx +++ b/sqlite-cloud/sdks/c/SQCloudConnectWithString.mdx @@ -16,7 +16,7 @@ Initiate a new connection to a database node specified by a connection string. T String `s` must be an URL encoded string with the following format: `sqlitecloud://user:pass@host.com:port/dbname?timeout=10&key2=value2&key3=value3`. -An easy way to obtain a valid connection string is to click on the node address in the [Dashboard Nodes](/docs/introduction/nodes) section. A valid connection string will be copied in your clipboard. +An easy way to obtain a valid connection string is to click on the node address in the [Dashboard Nodes](/docs/scaling) section. A valid connection string will be copied in your clipboard. Key(s) can be: @@ -34,11 +34,11 @@ Key(s) can be: * client_certificate * client_certificate_key -These key(s) are equivalent to the fields specified in the [SQCloudConfig struct](/docs/sdk/c/sqcloudconfig). +These key(s) are equivalent to the fields specified in the [SQCloudConfig struct](/docs/sqlite-cloud/sdks/c/sqcloudconfig). ### Parameters * **s**: an URL encoded NULL terminated string that contains connection info -* **pconfig**: a pointer to a [SQCloudConfig struct](/docs/sdk/c/sqcloudconfig) (can be NULL) used to override configurations found in the connection string +* **pconfig**: a pointer to a [SQCloudConfig struct](/docs/sqlite-cloud/sdks/c/sqcloudconfig) (can be NULL) used to override configurations found in the connection string ### Return value A pointer to an opaque **SQCloudConnection** struct. diff --git a/sqlite-cloud/sdks/c/SQCloudDisconnect.mdx b/sqlite-cloud/sdks/c/SQCloudDisconnect.mdx index 83f8042..87194b4 100644 --- a/sqlite-cloud/sdks/c/SQCloudDisconnect.mdx +++ b/sqlite-cloud/sdks/c/SQCloudDisconnect.mdx @@ -13,7 +13,7 @@ void SQCloudDisconnect (SQCloudConnection *connection); Closes the connection to the server. Also frees memory used by the SQCloudConnection object. ### Parameters -* **connection**: a valid connection object obtained by [SQCloudConnect](/docs/sdk/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sdk/c/sqcloudconnectwithstring) +* **connection**: a valid connection object obtained by [SQCloudConnect](/docs/sqlite-cloud/sdks/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sqlite-cloud/sdks/c/sqcloudconnectwithstring) ### Return value Nothing. diff --git a/sqlite-cloud/sdks/c/SQCloudDownloadDatabase.mdx b/sqlite-cloud/sdks/c/SQCloudDownloadDatabase.mdx index 8f6f321..3944308 100644 --- a/sqlite-cloud/sdks/c/SQCloudDownloadDatabase.mdx +++ b/sqlite-cloud/sdks/c/SQCloudDownloadDatabase.mdx @@ -14,7 +14,7 @@ bool SQCloudDownloadDatabase (SQCloudConnection *connection, const char *dbname, Initiate an SQLite database download from an already connected SQLite Cloud node. ### Parameters -* **connection**: a valid connection object obtained by [SQCloudConnect](/docs/sdk/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sdk/c/sqcloudconnectwithstring) +* **connection**: a valid connection object obtained by [SQCloudConnect](/docs/sqlite-cloud/sdks/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sqlite-cloud/sdks/c/sqcloudconnectwithstring) * **dbname**: the name of the database to download * **xdata**: a pointer to an opaque datatype that will be passed as-is to the callback * **xcallback**: callback that will be automatically called to read from the input database file diff --git a/sqlite-cloud/sdks/c/SQCloudError.mdx b/sqlite-cloud/sdks/c/SQCloudError.mdx index ebad0de..5d140b3 100644 --- a/sqlite-cloud/sdks/c/SQCloudError.mdx +++ b/sqlite-cloud/sdks/c/SQCloudError.mdx @@ -16,17 +16,17 @@ const char *SQCloudErrorMsg (SQCloudConnection *connection); ### Description If the most recent API call associated with with database connection failed, then this APIs return information about the error. -These functions resemble the [sqlite3_error_*](https://www.sqlite.org/c3ref/errcode.html) SQLite APIs. +These functions resemble the sqlite3_error_* SQLite APIs. ### Parameters -* **connection**: a valid connection object obtained by [SQCloudConnect](/docs/sdk/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sdk/c/sqcloudconnectwithstring) +* **connection**: a valid connection object obtained by [SQCloudConnect](/docs/sqlite-cloud/sdks/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sqlite-cloud/sdks/c/sqcloudconnectwithstring) ### Return value * **SQLiteIsError** returns `true` if the most recent API call failed. * **SQCloudIsSQLiteError** returns `true` if the most recent error is related to an SQLite operation. * **SQCloudErrorCode** returns the numeric error code (or 0 if no error). -* **SQCloudExtendedErrorCode** returns the numeric [extended error code](https://www.sqlite.org/rescode.html#extrc) related to the failed SQLite operation. +* **SQCloudExtendedErrorCode** returns the numeric extended error code related to the failed SQLite operation. * **SQCloudErrorOffset** returns the byte offset of the start of the most recent error references a specific token in the input SQL (if any). If the most recent error does not reference a specific token in the input SQL, then the **SQCloudErrorOffset** function returns -1. * **SQCloudErrorMsg** return English-language text that describes the error. diff --git a/sqlite-cloud/sdks/c/SQCloudExec.mdx b/sqlite-cloud/sdks/c/SQCloudExec.mdx index a76653c..66470b6 100644 --- a/sqlite-cloud/sdks/c/SQCloudExec.mdx +++ b/sqlite-cloud/sdks/c/SQCloudExec.mdx @@ -13,11 +13,11 @@ SQCloudResult *SQCloudExec (SQCloudConnection *connection, const char *command); Submits a command to the server and waits for the result. The command can be any SQLite statement or any built-in [SQLite Cloud command](/docs/commands). ### Parameters -* **connection**: a valid connection object obtained by [SQCloudConnect](/docs/sdk/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sdk/c/sqcloudconnectwithstring) +* **connection**: a valid connection object obtained by [SQCloudConnect](/docs/sqlite-cloud/sdks/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sqlite-cloud/sdks/c/sqcloudconnectwithstring) * **command**: a NULL terminated string with the command to execute (multiple commands can be sent if separated by the semicolon character) ### Return value -A pointer to an opaque **SQCloudResult** struct that must be explicitly deallocated with [SQCloudResultFree](/docs/sdk/c/sqcloudresultfree) +A pointer to an opaque **SQCloudResult** struct that must be explicitly deallocated with [SQCloudResultFree](/docs/sqlite-cloud/sdks/c/sqcloudresultfree) ### Example ```c diff --git a/sqlite-cloud/sdks/c/SQCloudExecArray.mdx b/sqlite-cloud/sdks/c/SQCloudExecArray.mdx index 1023d5c..ad4dcb8 100644 --- a/sqlite-cloud/sdks/c/SQCloudExecArray.mdx +++ b/sqlite-cloud/sdks/c/SQCloudExecArray.mdx @@ -10,10 +10,10 @@ SQCloudResult *SQCloudExecArray (SQCloudConnection *connection, const char *comm ``` ### Description -Submits a command to the server and waits for the result. The command can be any SQLite statement or any built-in [SQLite Cloud command](/docs/commands). This function is equivalent to the [SQCloudExec](/docs/sdk/c/sqcloudexec) function but special placeholders can be used to bind values to the statement (most of the time avoiding the need to perform copies and to encode data). +Submits a command to the server and waits for the result. The command can be any SQLite statement or any built-in [SQLite Cloud command](/docs/commands). This function is equivalent to the [SQCloudExec](/docs/sqlite-cloud/sdks/c/sqcloudexec) function but special placeholders can be used to bind values to the statement (most of the time avoiding the need to perform copies and to encode data). ### Parameters -* **connection**: a valid connection object obtained by [SQCloudConnect](/docs/sdk/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sdk/c/sqcloudconnectwithstring) +* **connection**: a valid connection object obtained by [SQCloudConnect](/docs/sqlite-cloud/sdks/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sqlite-cloud/sdks/c/sqcloudconnectwithstring) * **command**: a NULL terminated string with the command to execute * **values**: an array of n values * **len**: an array of n length @@ -21,7 +21,7 @@ Submits a command to the server and waits for the result. The command can be any * **n** number of array elements ### Return value -A pointer to an opaque **SQCloudResult** struct that must be explicitly deallocated with [SQCloudResultFree](/docs/sdk/c/sqcloudresultfree) +A pointer to an opaque **SQCloudResult** struct that must be explicitly deallocated with [SQCloudResultFree](/docs/sqlite-cloud/sdks/c/sqcloudresultfree) ### Example ```c diff --git a/sqlite-cloud/sdks/c/SQCloudResultDouble.mdx b/sqlite-cloud/sdks/c/SQCloudResultDouble.mdx index ad91dea..06e8859 100644 --- a/sqlite-cloud/sdks/c/SQCloudResultDouble.mdx +++ b/sqlite-cloud/sdks/c/SQCloudResultDouble.mdx @@ -10,7 +10,7 @@ double SQCloudResultDouble (SQCloudResult *result); ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_FLOAT then use this function to retrieve a Double value. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_FLOAT then use this function to retrieve a Double value. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. diff --git a/sqlite-cloud/sdks/c/SQCloudResultDump.mdx b/sqlite-cloud/sdks/c/SQCloudResultDump.mdx index deb2514..c78ef36 100644 --- a/sqlite-cloud/sdks/c/SQCloudResultDump.mdx +++ b/sqlite-cloud/sdks/c/SQCloudResultDump.mdx @@ -13,7 +13,7 @@ void SQCloudResultDump (SQCloudConnection *connection, SQCloudResult *result); Print the result on standard output. ### Parameters -* **connection**: a valid connection object obtained by [SQCloudConnect](/docs/sdk/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sdk/c/sqcloudconnectwithstring) +* **connection**: a valid connection object obtained by [SQCloudConnect](/docs/sqlite-cloud/sdks/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sqlite-cloud/sdks/c/sqcloudconnectwithstring) * **result**: A valid SQCloudResult pointer returned by an SQCloud function. ### Return value diff --git a/sqlite-cloud/sdks/c/SQCloudResultFloat.mdx b/sqlite-cloud/sdks/c/SQCloudResultFloat.mdx index 4fa8b70..e958871 100644 --- a/sqlite-cloud/sdks/c/SQCloudResultFloat.mdx +++ b/sqlite-cloud/sdks/c/SQCloudResultFloat.mdx @@ -10,7 +10,7 @@ float SQCloudResultFloat (SQCloudResult *result); ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_FLOAT then use this function to retrieve a Float value. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_FLOAT then use this function to retrieve a Float value. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. diff --git a/sqlite-cloud/sdks/c/SQCloudResultInt32.mdx b/sqlite-cloud/sdks/c/SQCloudResultInt32.mdx index 567e946..966ccca 100644 --- a/sqlite-cloud/sdks/c/SQCloudResultInt32.mdx +++ b/sqlite-cloud/sdks/c/SQCloudResultInt32.mdx @@ -10,7 +10,7 @@ int32_t SQCloudResultInt32 (SQCloudResult *result); ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_INTEGER then use this function to retrieve an Int32 value. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_INTEGER then use this function to retrieve an Int32 value. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. diff --git a/sqlite-cloud/sdks/c/SQCloudResultInt64.mdx b/sqlite-cloud/sdks/c/SQCloudResultInt64.mdx index dc78c43..dfab2b8 100644 --- a/sqlite-cloud/sdks/c/SQCloudResultInt64.mdx +++ b/sqlite-cloud/sdks/c/SQCloudResultInt64.mdx @@ -10,7 +10,7 @@ int64_t SQCloudResultInt64 (SQCloudResult *result); ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_INTEGER then use this function to retrieve an Int64 value. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_INTEGER then use this function to retrieve an Int64 value. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. diff --git a/sqlite-cloud/sdks/c/SQCloudRowsetCols.mdx b/sqlite-cloud/sdks/c/SQCloudRowsetCols.mdx index fba7236..e8e1974 100644 --- a/sqlite-cloud/sdks/c/SQCloudRowsetCols.mdx +++ b/sqlite-cloud/sdks/c/SQCloudRowsetCols.mdx @@ -10,7 +10,7 @@ uint32_t SQCloudRowsetCols (SQCloudResult *result); ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve the number of columns in the Rowset. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve the number of columns in the Rowset. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. diff --git a/sqlite-cloud/sdks/c/SQCloudRowsetColumnName.mdx b/sqlite-cloud/sdks/c/SQCloudRowsetColumnName.mdx index 54f1f95..2792b25 100644 --- a/sqlite-cloud/sdks/c/SQCloudRowsetColumnName.mdx +++ b/sqlite-cloud/sdks/c/SQCloudRowsetColumnName.mdx @@ -10,11 +10,11 @@ char *SQCloudRowsetColumnName (SQCloudResult *result, uint32_t col, uint32_t *le ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve the name of a column. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve the name of a column. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. -* **col**: A column index (from 0 to [SQCloudRowsetCols](/docs/sdk/c/sqcloudrowsetcols)-1) +* **col**: A column index (from 0 to [SQCloudRowsetCols](/docs/sqlite-cloud/sdks/c/sqcloudrowsetcols)-1) * **len**: On output the column name length ### Return value diff --git a/sqlite-cloud/sdks/c/SQCloudRowsetDoubleValue.mdx b/sqlite-cloud/sdks/c/SQCloudRowsetDoubleValue.mdx index fddc77e..df3f89c 100644 --- a/sqlite-cloud/sdks/c/SQCloudRowsetDoubleValue.mdx +++ b/sqlite-cloud/sdks/c/SQCloudRowsetDoubleValue.mdx @@ -10,12 +10,12 @@ double SQCloudRowsetDoubleValue (SQCloudResult *result, uint32_t row, uint32_t c ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve the Double value of the item at row/col. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve the Double value of the item at row/col. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. -* **row**: A row index (from 0 to [SQCloudRowsetRows](/docs/sdk/c/sqcloudrowsetrows)-1) -* **col**: A column index (from 0 to [SQCloudRowsetCols](/docs/sdk/c/sqcloudrowsetcols)-1) +* **row**: A row index (from 0 to [SQCloudRowsetRows](/docs/sqlite-cloud/sdks/c/sqcloudrowsetrows)-1) +* **col**: A column index (from 0 to [SQCloudRowsetCols](/docs/sqlite-cloud/sdks/c/sqcloudrowsetcols)-1) ### Return value A `double` value. diff --git a/sqlite-cloud/sdks/c/SQCloudRowsetFloatValue.mdx b/sqlite-cloud/sdks/c/SQCloudRowsetFloatValue.mdx index cef4dae..fcbbbcc 100644 --- a/sqlite-cloud/sdks/c/SQCloudRowsetFloatValue.mdx +++ b/sqlite-cloud/sdks/c/SQCloudRowsetFloatValue.mdx @@ -10,12 +10,12 @@ float SQCloudRowsetFloatValue (SQCloudResult *result, uint32_t row, uint32_t col ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve the Float value of the item at row/col. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve the Float value of the item at row/col. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. -* **row**: A row index (from 0 to [SQCloudRowsetRows](/docs/sdk/c/sqcloudrowsetrows)-1) -* **col**: A column index (from 0 to [SQCloudRowsetCols](/docs/sdk/c/sqcloudrowsetcols)-1) +* **row**: A row index (from 0 to [SQCloudRowsetRows](/docs/sqlite-cloud/sdks/c/sqcloudrowsetrows)-1) +* **col**: A column index (from 0 to [SQCloudRowsetCols](/docs/sqlite-cloud/sdks/c/sqcloudrowsetcols)-1) ### Return value A `float` value. diff --git a/sqlite-cloud/sdks/c/SQCloudRowsetInt32Value.mdx b/sqlite-cloud/sdks/c/SQCloudRowsetInt32Value.mdx index dec580a..5714c6d 100644 --- a/sqlite-cloud/sdks/c/SQCloudRowsetInt32Value.mdx +++ b/sqlite-cloud/sdks/c/SQCloudRowsetInt32Value.mdx @@ -10,12 +10,12 @@ int32_t SQCloudRowsetInt32Value (SQCloudResult *result, uint32_t row, uint32_t c ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve the `int32_t` value of the item at row/col. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve the `int32_t` value of the item at row/col. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. -* **row**: A row index (from 0 to [SQCloudRowsetRows](/docs/sdk/c/sqcloudrowsetrows)-1) -* **col**: A column index (from 0 to [SQCloudRowsetCols](/docs/sdk/c/sqcloudrowsetcols)-1) +* **row**: A row index (from 0 to [SQCloudRowsetRows](/docs/sqlite-cloud/sdks/c/sqcloudrowsetrows)-1) +* **col**: A column index (from 0 to [SQCloudRowsetCols](/docs/sqlite-cloud/sdks/c/sqcloudrowsetcols)-1) ### Return value An `int32_t` value. diff --git a/sqlite-cloud/sdks/c/SQCloudRowsetInt64Value.mdx b/sqlite-cloud/sdks/c/SQCloudRowsetInt64Value.mdx index ba2a731..9808f14 100644 --- a/sqlite-cloud/sdks/c/SQCloudRowsetInt64Value.mdx +++ b/sqlite-cloud/sdks/c/SQCloudRowsetInt64Value.mdx @@ -10,12 +10,12 @@ int64_t SQCloudRowsetInt64Value (SQCloudResult *result, uint32_t row, uint32_t c ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve the `int64_t` value of the item at row/col. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve the `int64_t` value of the item at row/col. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. -* **row**: A row index (from 0 to [SQCloudRowsetRows](/docs/sdk/c/sqcloudrowsetrows)-1) -* **col**: A column index (from 0 to [SQCloudRowsetCols](/docs/sdk/c/sqcloudrowsetcols)-1) +* **row**: A row index (from 0 to [SQCloudRowsetRows](/docs/sqlite-cloud/sdks/c/sqcloudrowsetrows)-1) +* **col**: A column index (from 0 to [SQCloudRowsetCols](/docs/sqlite-cloud/sdks/c/sqcloudrowsetcols)-1) ### Return value An `int64_t` value. diff --git a/sqlite-cloud/sdks/c/SQCloudRowsetRows.mdx b/sqlite-cloud/sdks/c/SQCloudRowsetRows.mdx index 96bb0fa..386d711 100644 --- a/sqlite-cloud/sdks/c/SQCloudRowsetRows.mdx +++ b/sqlite-cloud/sdks/c/SQCloudRowsetRows.mdx @@ -10,7 +10,7 @@ uint32_t SQCloudRowsetRows (SQCloudResult *result); ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve the number of rows in the Rowset. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve the number of rows in the Rowset. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. diff --git a/sqlite-cloud/sdks/c/SQCloudRowsetValue.mdx b/sqlite-cloud/sdks/c/SQCloudRowsetValue.mdx index 4fcbdfe..7b3d03c 100644 --- a/sqlite-cloud/sdks/c/SQCloudRowsetValue.mdx +++ b/sqlite-cloud/sdks/c/SQCloudRowsetValue.mdx @@ -10,12 +10,12 @@ char *SQCloudRowsetValue (SQCloudResult *result, uint32_t row, uint32_t col, uin ``` ### Description -If the result of the function [SQCloudResultType](/docs/sdk/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve a pointer and a length for a rowset item identified by a given row and column index. +If the result of the function [SQCloudResultType](/docs/sqlite-cloud/sdks/c/sqcloudresulttype) is RESULT_ROWSET then use this function to retrieve a pointer and a length for a rowset item identified by a given row and column index. ### Parameters * **result**: A valid SQCloudResult pointer returned by an SQCloud function. -* **row**: A row index (from 0 to [SQCloudRowsetRows](/docs/sdk/c/sqcloudrowsetrows)-1) -* **col**: A column index (from 0 to [SQCloudRowsetCols](/docs/sdk/c/sqcloudrowsetcols)-1) +* **row**: A row index (from 0 to [SQCloudRowsetRows](/docs/sqlite-cloud/sdks/c/sqcloudrowsetrows)-1) +* **col**: A column index (from 0 to [SQCloudRowsetCols](/docs/sqlite-cloud/sdks/c/sqcloudrowsetcols)-1) * **len**: On output the length of the returned buffer ### Return value @@ -50,7 +50,7 @@ int main (int argc, const char * argv[]) { // print column names for (uint32_t i=0; isqlite3_bind_* SQLite APIs. ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). -* **index**: Represents the index of the SQL parameter to be set. The leftmost SQL parameter has an index of 1. When the same named SQL parameter is used more than once, second and subsequent occurrences have the same index as the first occurrence. The index for named parameters can be looked up using the [SQCloudVMBindParameterIndex](/docs/sdk/c/sqcloudvmbindparameterindex) API if desired. The index for "?NNN" parameters is the value of NNN. +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). +* **index**: Represents the index of the SQL parameter to be set. The leftmost SQL parameter has an index of 1. When the same named SQL parameter is used more than once, second and subsequent occurrences have the same index as the first occurrence. The index for named parameters can be looked up using the [SQCloudVMBindParameterIndex](/docs/sqlite-cloud/sdks/c/sqcloudvmbindparameterindex) API if desired. The index for "?NNN" parameters is the value of NNN. * **value**: The the value to bind to the parameter. * **len**: The number of bytes in the parameter. To be clear: the value is the number of bytes in the value, not the number of characters. diff --git a/sqlite-cloud/sdks/c/SQCloudVMBindParameterCount.mdx b/sqlite-cloud/sdks/c/SQCloudVMBindParameterCount.mdx index a1ab262..f1b5e47 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMBindParameterCount.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMBindParameterCount.mdx @@ -12,10 +12,10 @@ int SQCloudVMBindParameterCount (SQCloudVM *vm); ### Description This routine can be used to find the number of SQL parameters in a prepared statement. SQL parameters are tokens of the form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as placeholders for values that are bound to the parameters at a later time. This routine actually returns the index of the largest (rightmost) parameter. For all forms except ?NNN, this will correspond to the number of unique parameters. If parameters of the ?NNN form are used, there may be gaps in the list. -This function resembles the [bind_parameter_count](https://www.sqlite.org/c3ref/bind_parameter_count.html) SQLite API. +This function resembles the bind_parameter_count SQLite API. ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). ### Return value diff --git a/sqlite-cloud/sdks/c/SQCloudVMBindParameterIndex.mdx b/sqlite-cloud/sdks/c/SQCloudVMBindParameterIndex.mdx index be06db1..0ba61e5 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMBindParameterIndex.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMBindParameterIndex.mdx @@ -10,12 +10,12 @@ int SQCloudVMBindParameterIndex (SQCloudVM *vm, const char *name); ``` ### Description -Return the index of an SQL parameter given its name. The index value returned is suitable for use as the second parameter to [SQCloudVMBind](/docs/sdk/c/sqcloudvmbind). A zero is returned if no matching parameter is found. +Return the index of an SQL parameter given its name. The index value returned is suitable for use as the second parameter to [SQCloudVMBind](/docs/sqlite-cloud/sdks/c/sqcloudvmbind). A zero is returned if no matching parameter is found. -This function resembles the [bind_parameter_index](https://www.sqlite.org/c3ref/bind_parameter_index.html) SQLite API. +This function resembles the bind_parameter_index SQLite API. ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). * **name**: The SQL parameter name. ### Return value diff --git a/sqlite-cloud/sdks/c/SQCloudVMBindParameterName.mdx b/sqlite-cloud/sdks/c/SQCloudVMBindParameterName.mdx index dce7a6f..78a47a0 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMBindParameterName.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMBindParameterName.mdx @@ -15,10 +15,10 @@ The **SQCloudVMBindParameterName** interface returns the name of the N-th SQL pa The first host parameter has an index of 1, not 0. If the value of index is out of range or if the N-th parameter is nameless, then NULL is returned. -This function resembles the [bind_parameter_name](https://www.sqlite.org/c3ref/bind_parameter_name.html) SQLite API. +This function resembles the bind_parameter_name SQLite API. ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). * **index**: The SQL parameter index. ### Return value diff --git a/sqlite-cloud/sdks/c/SQCloudVMChanges.mdx b/sqlite-cloud/sdks/c/SQCloudVMChanges.mdx index 479a979..9d7672b 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMChanges.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMChanges.mdx @@ -18,7 +18,7 @@ If you need to get the changes from a SQCloudConnection object you can send a `D ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). ### Return value diff --git a/sqlite-cloud/sdks/c/SQCloudVMClose.mdx b/sqlite-cloud/sdks/c/SQCloudVMClose.mdx index b2a6c15..5b5595b 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMClose.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMClose.mdx @@ -11,11 +11,11 @@ bool SQCloudVMClose (SQCloudVM *vm); ### Description Frees the storage associated with a SQCloudVM. The application must finalize every compiled statement in order to avoid resource leaks. -This function resembles the [sqlite3_finalize](https://www.sqlite.org/c3ref/finalize.html) SQLite API. +This function resembles the sqlite3_finalize SQLite API. ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). ### Return value diff --git a/sqlite-cloud/sdks/c/SQCloudVMColumn.mdx b/sqlite-cloud/sdks/c/SQCloudVMColumn.mdx index 0dac957..13d47dc 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMColumn.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMColumn.mdx @@ -17,12 +17,12 @@ SQCLOUD_VALUE_TYPE SQCloudVMColumnType (SQCloudVM *vm, int index); ### Description These routines return information about a single column of the current result row of a query. -These functions resemble the [sqlite3_column_*](https://www.sqlite.org/c3ref/column_blob.html) SQLite APIs. +These functions resemble the sqlite3_column_* SQLite APIs. ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). -* **index**: The index of the column for which information should be returned. The leftmost column of the result set has the index 0. The number of columns in the result can be determined using [SQCloudVMColumnCount](/docs/sdk/c/sqcloudvmcolumncount). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). +* **index**: The index of the column for which information should be returned. The leftmost column of the result set has the index 0. The number of columns in the result can be determined using [SQCloudVMColumnCount](/docs/sqlite-cloud/sdks/c/sqcloudvmcolumncount). * **len**: The number of bytes of the returned value. The **SQCloudVMColumnType** routine returns the datatype code for the initial data type of the result column. The returned value is one of following: diff --git a/sqlite-cloud/sdks/c/SQCloudVMColumnCount.mdx b/sqlite-cloud/sdks/c/SQCloudVMColumnCount.mdx index ef01411..9317ed8 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMColumnCount.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMColumnCount.mdx @@ -12,11 +12,11 @@ int SQCloudVMColumnCount (SQCloudVM *vm); ### Description The **SQCloudVMColumnCount** returns the number of columns in the result set returned by the prepared statement. If this routine returns 0, that means the prepared statement returns no data (for example an UPDATE). However, just because this routine returns a positive number does not mean that one or more rows of data will be returned. A SELECT statement will always have a positive **SQCloudVMColumnCount** but depending on the WHERE clause constraints and the table content, it might return no rows. -This function resembles the [sqlite3_column_count](https://sqlite.org/c3ref/column_count.html) SQLite APIs. +This function resembles the sqlite3_column_count SQLite APIs. ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). Return value An `int` with the number of columns. diff --git a/sqlite-cloud/sdks/c/SQCloudVMCompile.mdx b/sqlite-cloud/sdks/c/SQCloudVMCompile.mdx index f278c1a..2c43e47 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMCompile.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMCompile.mdx @@ -11,10 +11,10 @@ SQCloudVM *SQCloudVMCompile (SQCloudConnection *connection, const char *sql, int ### Description Compile an SQL statement into a byte-code virtual machine. -This function resembles the [sqlite3_prepare](https://www.sqlite.org/c3ref/prepare.html) SQLite API. +This function resembles the sqlite3_prepare SQLite API. ### Parameters -* **connection**: A valid connection object obtained by [SQCloudConnect](/docs/sdk/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sdk/c/sqcloudconnectwithstring) +* **connection**: A valid connection object obtained by [SQCloudConnect](/docs/sqlite-cloud/sdks/c/sqcloudconnect) or [SQCloudConnectWithString](/docs/sqlite-cloud/sdks/c/sqcloudconnectwithstring) * **sql**: The statement to be compiled. * **len**: If the len argument is negative, then sql is read up to the first zero terminator. If len is positive, then it is the number of bytes read from sql. * **tail**: If the tail argument is not NULL then *tail is made to point to the first byte past the end of the first SQL statement in sql. SQCloudVMCompile compiles only the first statement in sql, so *tail is left pointing to what remains uncompiled. diff --git a/sqlite-cloud/sdks/c/SQCloudVMErrorCode.mdx b/sqlite-cloud/sdks/c/SQCloudVMErrorCode.mdx index b6421ed..4fff303 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMErrorCode.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMErrorCode.mdx @@ -14,7 +14,7 @@ Retrieve the latest error code (if any) from the associated vm. ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). ### Return value diff --git a/sqlite-cloud/sdks/c/SQCloudVMErrorMsg.mdx b/sqlite-cloud/sdks/c/SQCloudVMErrorMsg.mdx index 5c3c44f..080e116 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMErrorMsg.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMErrorMsg.mdx @@ -14,7 +14,7 @@ Retrieve the latest error message (if any) from the associated vm. ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). ### Return value diff --git a/sqlite-cloud/sdks/c/SQCloudVMIsExplain.mdx b/sqlite-cloud/sdks/c/SQCloudVMIsExplain.mdx index 3cc8e16..bafe737 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMIsExplain.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMIsExplain.mdx @@ -10,10 +10,10 @@ int SQCloudVMIsExplain (SQCloudVM *vm); ``` ### Description -The **SQCloudVMIsExplain** interface returns 1 if the prepared statement S is an EXPLAIN statement, or 2 if the statement S is an EXPLAIN QUERY PLAN. **SQCloudVMIsExplain** interface returns 0 if the statement is an ordinary statement or a NULL pointer. This function resembles the [sqlite3_stmt_isexplain](https://www.sqlite.org/c3ref/stmt_isexplain.html) SQLite API. +The **SQCloudVMIsExplain** interface returns 1 if the prepared statement S is an EXPLAIN statement, or 2 if the statement S is an EXPLAIN QUERY PLAN. **SQCloudVMIsExplain** interface returns 0 if the statement is an ordinary statement or a NULL pointer. This function resembles the sqlite3_stmt_isexplain SQLite API. ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). ### Return value An `int` value representing if the original statement was an EXPLAIN. diff --git a/sqlite-cloud/sdks/c/SQCloudVMIsFinalized.mdx b/sqlite-cloud/sdks/c/SQCloudVMIsFinalized.mdx index 4491e59..f79741e 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMIsFinalized.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMIsFinalized.mdx @@ -10,11 +10,11 @@ bool SQCloudVMIsFinalized (SQCloudVM *vm); ``` ### Description -The **SQCloudVMIsFinalized** interface returns true if the prepared statement bound to the vm has been stepped at least once using [SQCloudVMStep](/docs/sdk/c/sqcloudvmstep) but has neither run to completion nor been reset. This function resembles the [sqlite3_stmt_busy](https://www.sqlite.org/c3ref/stmt_busy.html) SQLite API. +The **SQCloudVMIsFinalized** interface returns true if the prepared statement bound to the vm has been stepped at least once using [SQCloudVMStep](/docs/sqlite-cloud/sdks/c/sqcloudvmstep) but has neither run to completion nor been reset. This function resembles the sqlite3_stmt_busy SQLite API. ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). ### Return value diff --git a/sqlite-cloud/sdks/c/SQCloudVMIsReadOnly.mdx b/sqlite-cloud/sdks/c/SQCloudVMIsReadOnly.mdx index 5aca6d9..08ef626 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMIsReadOnly.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMIsReadOnly.mdx @@ -10,10 +10,10 @@ bool SQCloudVMIsReadOnly (SQCloudVM *vm); ``` ### Description -The **SQCloudVMIsReadOnly** interface returns true if and only if the prepared statement bound to vm makes no direct changes to the content of the database file. This routine returns false if there is any possibility that the statement might change the database file. A false return does not guarantee that the statement will change the database file. This function resembles the [sqlite3_stmt_readonly](https://www.sqlite.org/c3ref/stmt_readonly.html) SQLite API. +The **SQCloudVMIsReadOnly** interface returns true if and only if the prepared statement bound to vm makes no direct changes to the content of the database file. This routine returns false if there is any possibility that the statement might change the database file. A false return does not guarantee that the statement will change the database file. This function resembles the sqlite3_stmt_readonly SQLite API. ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). ### Return value diff --git a/sqlite-cloud/sdks/c/SQCloudVMLastRowID.mdx b/sqlite-cloud/sdks/c/SQCloudVMLastRowID.mdx index 84fda71..da5661d 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMLastRowID.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMLastRowID.mdx @@ -21,7 +21,7 @@ If you need to get the last inserted rowid from a SQCloudConnection object you c ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). ### Return value diff --git a/sqlite-cloud/sdks/c/SQCloudVMResult.mdx b/sqlite-cloud/sdks/c/SQCloudVMResult.mdx index de15189..ff39a73 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMResult.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMResult.mdx @@ -13,7 +13,7 @@ SQCloudResult *SQCloudVMResult (SQCloudVM *vm); Retrieve the raw SQCloudResult associated with the VM. You can then use the SQCloudResult API to further process the SQCloudResult. ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). ### Return value diff --git a/sqlite-cloud/sdks/c/SQCloudVMStep.mdx b/sqlite-cloud/sdks/c/SQCloudVMStep.mdx index 507ed3d..8271d28 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMStep.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMStep.mdx @@ -10,11 +10,11 @@ SQCLOUD_RESULT_TYPE SQCloudVMStep (SQCloudVM *vm); ``` ### Description -Evaluate an SQL statement previously compiled by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). -This function resembles the [sqlite3_step](https://www.sqlite.org/c3ref/step.html) SQLite API. +Evaluate an SQL statement previously compiled by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). +This function resembles the sqlite3_step SQLite API. ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). ### Return value diff --git a/sqlite-cloud/sdks/c/SQCloudVMTotalChanges.mdx b/sqlite-cloud/sdks/c/SQCloudVMTotalChanges.mdx index 333c7b6..38684a2 100644 --- a/sqlite-cloud/sdks/c/SQCloudVMTotalChanges.mdx +++ b/sqlite-cloud/sdks/c/SQCloudVMTotalChanges.mdx @@ -19,7 +19,7 @@ If you need to get the total changes from a SQCloudConnection object you can sen ### Parameters -* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sdk/c/sqcloudvmcompile). +* **vm**: A valid VM obtained by [SQCloudVMCompile](/docs/sqlite-cloud/sdks/c/sqcloudvmcompile). ### Return value An `int64_t` with the number of total changes. diff --git a/sqlite-cloud/sdks/c/getting-started.mdx b/sqlite-cloud/sdks/c/getting-started.mdx index fa14c1b..547249f 100644 --- a/sqlite-cloud/sdks/c/getting-started.mdx +++ b/sqlite-cloud/sdks/c/getting-started.mdx @@ -3,9 +3,10 @@ title: C description: SQCloud C Interface category: sdks status: publish +slug: sdk-c-introduction --- -SQCloud is the C application programmer's interface to SQLite Cloud. SQCloud is a set of library functions that allow client programs to pass queries and SQL commands to the SQLite Cloud backend server and to receive the results of these queries. In addition to the standard SQLite statements, several other [commands](/docs/commands) are supported. +SQCloud is the C application programmer's interface to SQLite Cloud. SQCloud is a set of library functions that allow client programs to pass queries and SQL commands to the SQLite Cloud backend server and to receive the results of these queries. In addition to the standard SQLite statements, several other [commands](server-side-commands) are supported. The following files are required when compiling a C application: * sqcloud.c/.h @@ -14,6 +15,6 @@ The following files are required when compiling a C application: The header file `sqcloud.h` must be included in your C application. -All the communications between the client and the server are encrypted and so, you are required to link the LibreSSL (libtls) library with your client. More information about LibreSSL and how to compile it can be found in the official [LibreSSL](http://www.libressl.org) website. +All the communications between the client and the server are encrypted and so, you are required to link the LibreSSL (libtls) library with your client. More information about LibreSSL and how to compile it can be found in the official LibreSSL website. -The SQCloud APIs implement the [SQLiteCloud Serialization Protocol](https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md). \ No newline at end of file +The SQCloud APIs implement the SQLiteCloud Serialization Protocol. \ No newline at end of file diff --git a/sqlite-cloud/sdks/go/getting-started.mdx b/sqlite-cloud/sdks/go/getting-started.mdx deleted file mode 100644 index 096d0c5..0000000 --- a/sqlite-cloud/sdks/go/getting-started.mdx +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: GO SDK Getting Started -description: Here's the how gettting started to use the SQLite Cloud in your Go code. -customClass: sdk-doc badge-doc go-doc -category: sdks -status: publish ---- - -## Use the SQLite Cloud SDK in your Go code - -1. Import the package in your Go source code: - - ```go - import sqlitecloud "github.com/sqlitecloud/sqlitecloud-go" - ``` - -2. Download the package, and run the [`go mod tidy` command](https://go.dev/ref/mod#go-mod-tidy) to synchronize your module's dependencies: - - ```bash - $ go mod tidy - go: downloading github.com/sqlitecloud/sqlitecloud-go v1.0.0 - ``` - -3. Connect to a SQLite Cloud database with a valid [connection string](#get-a-connection-string): - - ```go - db, err := sqlitecloud.Connect("sqlitecloud://user:pass@host.sqlite.cloud:port/dbname") - ``` - -4. Execute queries using a [method](#api-documentation) defined on the `SQCloud` struct, for example `Select`: - - ```go - result, _ := db.Select("SELECT * FROM table1;") - ``` - -The following example shows how to print the content of the table `table1`: - -```go -package main - -import ( - "fmt" - "strings" - - sqlitecloud "github.com/sqlitecloud/sqlitecloud-go" -) - -const connectionString = "sqlitecloud://admin:password@host.sqlite.cloud:8860/dbname.sqlite" - -func main() { - db, err := sqlitecloud.Connect(connectionString) - if err != nil { - fmt.Println("Connect error: ", err) - } - - tables, _ := db.ListTables() - fmt.Printf("Tables:\n\t%s\n", strings.Join(tables, "\n\t")) - - fmt.Printf("Table1:\n") - result, _ := db.Select("SELECT * FROM t1;") - for r := uint64(0); r < result.GetNumberOfRows(); r++ { - id, _ := result.GetInt64Value(r, 0) - value, _ := result.GetStringValue(r, 1) - fmt.Printf("\t%d: %s\n", id, value) - } -} -``` - -## Get a connection string - -You can connect to any cloud database using a special connection string in the form: - -``` -sqlitecloud://user:pass@host.com:port/dbname?timeout=10&key2=value2&key3=value3 -``` - -To get a valid connection string, follow these instructions: - -- Get a [SQLite Cloud](https://sqlitecloud.io/) account. See the [documentation](https://docs.sqlitecloud.io/docs/introduction/login) for details. -- Create a [SQLite Cloud project](https://docs.sqlitecloud.io/docs/introduction/projects) -- Create a [SQLite Cloud database](https://docs.sqlitecloud.io/docs/introduction/databases) -- Get the connection string by clicking on the node address in the [Dashboard Nodes](https://docs.sqlitecloud.io/docs/introduction/nodes) section. A valid connection string will be copied to your clipboard. -- Add the database name to your connection string. - -## API Documentation - -The complete documentation is available at: [https://pkg.go.dev/github.com/sqlitecloud/sqlitecloud-go](https://pkg.go.dev/github.com/sqlitecloud/sqlitecloud-go) - -[![Test and QA](https://github.com/sqlitecloud/sqlitecloud-go/actions/workflows/testing.yaml/badge.svg?branch=main)](https://github.com/sqlitecloud/sqlitecloud-go/actions/workflows/testing.yaml) -[![codecov](https://codecov.io/gh/sqlitecloud/sqlitecloud-go/graph/badge.svg?token=5MAG3G4X01)](https://codecov.io/gh/sqlitecloud/sqlitecloud-go) -[![GitHub Tag](https://img.shields.io/github/v/tag/sqlitecloud/sqlitecloud-go?label=version&link=https%3A%2F%2Fpkg.go.dev%2Fgithub.com%2Fsqlitecloud%2Fsqlitecloud-go)](https://pkg.go.dev/github.com/sqlitecloud/sqlitecloud-go) -[![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/sqlitecloud/sqlitecloud-go?link=https%3A%2F%2Fpkg.go.dev%2Fgithub.com%2Fsqlitecloud%2Fsqlitecloud-go)](https://pkg.go.dev/github.com/sqlitecloud/sqlitecloud-go) - -[SQLite Cloud](https://sqlitecloud.io) for Go is a powerful package that allows you to interact with the SQLite Cloud database seamlessly. It provides methods for various database operations. This package is designed to simplify database operations in Go applications, making it easier than ever to work with SQLite Cloud. In addition to the standard SQLite statements, several other [commands](https://docs.sqlitecloud.io/docs/commands) are supported. - diff --git a/sqlite-cloud/sdks/go/introduction.mdx b/sqlite-cloud/sdks/go/introduction.mdx new file mode 100644 index 0000000..c7d49c0 --- /dev/null +++ b/sqlite-cloud/sdks/go/introduction.mdx @@ -0,0 +1,112 @@ +--- +title: GO SDK Getting Started +description: Here's the how gettting started to use the SQLite Cloud in your Go code. +category: sdks +status: publish +slug: sdk-go-introduction +--- + +## Use the SQLite Cloud SDK in your Go code + +1. Import the package in your Go source code: + + ```go + import sqlitecloud "github.com/sqlitecloud/sqlitecloud-go" + ``` + +2. Download the package, and run the `go mod tidy` command to synchronize your module's dependencies: + + ```bash + $ go mod tidy + go: downloading github.com/sqlitecloud/sqlitecloud-go v1.0.0 + ``` + +3. Connect to a SQLite Cloud database with a valid [connection string](#get-a-connection-string): + + ```go + db, err := sqlitecloud.Connect("sqlitecloud://user:pass@host.sqlite.cloud:port/dbname") + ``` + +4. Execute queries using a [method](#api-documentation) defined on the `SQCloud` struct, for example `Select`: + + ```go + result, _ := db.Select("SELECT * FROM table1;") + ``` + +The following example shows how to print the content of the table `table1`: + +```go +package main + +import ( + "fmt" + "strings" + + sqlitecloud "github.com/sqlitecloud/sqlitecloud-go" +) + +const connectionString = "sqlitecloud://admin:password@host.sqlite.cloud:8860/dbname.sqlite" + +func main() { + db, err := sqlitecloud.Connect(connectionString) + if err != nil { + fmt.Println("Connect error: ", err) + } + + tables, _ := db.ListTables() + fmt.Printf("Tables:\n\t%s\n", strings.Join(tables, "\n\t")) + + fmt.Printf("Table1:\n") + result, _ := db.Select("SELECT * FROM t1;") + for r := uint64(0); r < result.GetNumberOfRows(); r++ { + id, _ := result.GetInt64Value(r, 0) + value, _ := result.GetStringValue(r, 1) + fmt.Printf("\t%d: %s\n", id, value) + } +} +``` + +## Get a connection string + +You can connect to any cloud database using a special connection string in the form: + +``` +sqlitecloud://user:pass@host.com:port/dbname?timeout=10&key2=value2&key3=value3 +``` + +To get a valid connection string, follow these instructions: + +- Get a SQLite Cloud account. See the documentation for details. +- Create a SQLite Cloud project +- Create a SQLite Cloud database +- Get the connection string by clicking on the node address in the Dashboard Nodes section. A valid connection string will be copied to your clipboard. +- Add the database name to your connection string. + +## API Documentation + +The complete documentation is available +here. + + + Test and QA + + +
    + + + codecov + + +
    + + + GitHub Tag + + +
    + + + GitHub go.mod Go version + + +SQLite Cloud for Go is a powerful package that allows you to interact with the SQLite Cloud database seamlessly. It provides methods for various database operations. This package is designed to simplify database operations in Go applications, making it easier than ever to work with SQLite Cloud. In addition to the standard SQLite statements, several other [commands](server-side-commands) are supported. \ No newline at end of file diff --git a/sqlite-cloud/sdks/js/classes/Database.md b/sqlite-cloud/sdks/js/classes/Database.md index 6c138ca..c625d9a 100644 --- a/sqlite-cloud/sdks/js/classes/Database.md +++ b/sqlite-cloud/sdks/js/classes/Database.md @@ -1,7 +1,7 @@ --- title: Database description: SQLite Cloud Javascript SDK -customClass: sdk-doc badge-doc js-doc +customClass: sdk-doc js-doc category: sdks status: publish --- @@ -84,7 +84,7 @@ EventEmitter.constructor #### Defined in -[src/drivers/database.ts:33](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L33) +src/drivers/database.ts:33 • **new Database**(`config`, `mode?`, `callback?`): [`Database`](database) @@ -106,7 +106,7 @@ EventEmitter.constructor #### Defined in -[src/drivers/database.ts:34](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L34) +src/drivers/database.ts:34 ## Properties @@ -118,7 +118,7 @@ Configuration used to open database connections #### Defined in -[src/drivers/database.ts:57](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L57) +src/drivers/database.ts:57 ___ @@ -130,7 +130,7 @@ Database connections #### Defined in -[src/drivers/database.ts:60](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L60) +src/drivers/database.ts:60 ___ @@ -215,7 +215,7 @@ calls to retrieve a previously unknown amount of rows. #### Defined in -[src/drivers/database.ts:273](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L273) +src/drivers/database.ts:273 ▸ **all**\<`T`\>(`sql`, `params`, `callback?`): [`Database`](database) @@ -239,7 +239,7 @@ calls to retrieve a previously unknown amount of rows. #### Defined in -[src/drivers/database.ts:274](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L274) +src/drivers/database.ts:274 ___ @@ -266,7 +266,7 @@ parameters is emitted, regardless of whether a callback was provided or not. #### Defined in -[src/drivers/database.ts:394](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L394) +src/drivers/database.ts:394 ___ @@ -289,7 +289,7 @@ Set a configuration option for the database #### Defined in -[src/drivers/database.ts:190](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L190) +src/drivers/database.ts:190 ___ @@ -330,7 +330,7 @@ way to abort execution. #### Defined in -[src/drivers/database.ts:312](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L312) +src/drivers/database.ts:312 ▸ **each**\<`T`\>(`sql`, `params`, `callback?`, `complete?`): [`Database`](database) @@ -355,7 +355,7 @@ way to abort execution. #### Defined in -[src/drivers/database.ts:313](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L313) +src/drivers/database.ts:313 ___ @@ -411,7 +411,7 @@ Emits given event with optional arguments on the next tick so callbacks can comp #### Defined in -[src/drivers/database.ts:160](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L160) +src/drivers/database.ts:160 ___ @@ -462,7 +462,7 @@ will be emitted on the database object. #### Defined in -[src/drivers/database.ts:368](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L368) +src/drivers/database.ts:368 ___ @@ -498,7 +498,7 @@ the only supported way is by column name. #### Defined in -[src/drivers/database.ts:235](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L235) +src/drivers/database.ts:235 ▸ **get**\<`T`\>(`sql`, `params`, `callback?`): [`Database`](database) @@ -522,7 +522,7 @@ the only supported way is by column name. #### Defined in -[src/drivers/database.ts:236](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L236) +src/drivers/database.ts:236 ___ @@ -542,7 +542,7 @@ A configuration object #### Defined in -[src/drivers/database.ts:176](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L176) +src/drivers/database.ts:176 ___ @@ -564,7 +564,7 @@ Returns first available connection from connection pool #### Defined in -[src/drivers/database.ts:67](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L67) +src/drivers/database.ts:67 ___ @@ -588,7 +588,7 @@ Handles an error by closing the connection, calling the callback and/or emitting #### Defined in -[src/drivers/database.ts:117](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L117) +src/drivers/database.ts:117 ___ @@ -607,7 +607,7 @@ open to use this function. #### Defined in -[src/drivers/database.ts:429](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L429) +src/drivers/database.ts:429 ___ @@ -688,7 +688,7 @@ Loads a compiled SQLite extension into the database connection object. #### Defined in -[src/drivers/database.ts:413](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L413) +src/drivers/database.ts:413 ___ @@ -822,7 +822,7 @@ they are bound to the prepared statement before calling the callback. #### Defined in -[src/drivers/database.ts:353](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L353) +src/drivers/database.ts:353 ___ @@ -854,7 +854,7 @@ https://github.com/TryGhost/node-sqlite3/wiki/API#runsql--param---callback #### Defined in -[src/drivers/database.ts:141](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L141) +src/drivers/database.ts:141 ___ @@ -948,7 +948,7 @@ which it was called to allow for function chaining. #### Defined in -[src/drivers/database.ts:202](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L202) +src/drivers/database.ts:202 ▸ **run**\<`T`\>(`sql`, `params`, `callback?`): [`Database`](database) @@ -972,7 +972,7 @@ which it was called to allow for function chaining. #### Defined in -[src/drivers/database.ts:203](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L203) +src/drivers/database.ts:203 ___ @@ -1001,7 +1001,7 @@ metadata in case of insert, update, delete. #### Defined in -[src/drivers/database.ts:447](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L447) +src/drivers/database.ts:447 ___ @@ -1017,4 +1017,4 @@ Enable verbose mode #### Defined in -[src/drivers/database.ts:181](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/database.ts#L181) +src/drivers/database.ts:181 diff --git a/sqlite-cloud/sdks/js/classes/SQLiteCloudConnection.md b/sqlite-cloud/sdks/js/classes/SQLiteCloudConnection.md index e929584..d428d66 100644 --- a/sqlite-cloud/sdks/js/classes/SQLiteCloudConnection.md +++ b/sqlite-cloud/sdks/js/classes/SQLiteCloudConnection.md @@ -1,7 +1,7 @@ --- title: SQLiteCloudConnection description: SQLite Cloud Javascript SDK -customClass: sdk-doc badge-doc js-doc +customClass: sdk-doc js-doc category: sdks status: publish --- @@ -55,7 +55,7 @@ Parse and validate provided connectionString or configuration #### Defined in -[src/drivers/connection.ts:16](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/connection.ts#L16) +src/drivers/connection.ts:16 ## Properties @@ -67,7 +67,7 @@ Configuration passed by client or extracted from connection string #### Defined in -[src/drivers/connection.ts:28](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/connection.ts#L28) +src/drivers/connection.ts:28 ___ @@ -79,7 +79,7 @@ Operations are serialized by waiting an any pending promises #### Defined in -[src/drivers/connection.ts:31](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/connection.ts#L31) +src/drivers/connection.ts:31 ## Accessors @@ -95,7 +95,7 @@ Returns true if connection is open #### Defined in -[src/drivers/connection.ts:74](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/connection.ts#L74) +src/drivers/connection.ts:74 ## Methods @@ -111,7 +111,7 @@ Disconnect from server, release transport. #### Defined in -[src/drivers/connection.ts:100](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/connection.ts#L100) +src/drivers/connection.ts:100 ___ @@ -133,7 +133,7 @@ Connect will establish a tls or websocket transport to the server based on confi #### Defined in -[src/drivers/connection.ts:38](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/connection.ts#L38) +src/drivers/connection.ts:38 ___ @@ -154,7 +154,7 @@ ___ #### Defined in -[src/drivers/connection.ts:56](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/connection.ts#L56) +src/drivers/connection.ts:56 ___ @@ -177,7 +177,7 @@ Will log to console if verbose mode is enabled #### Defined in -[src/drivers/connection.ts:62](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/connection.ts#L62) +src/drivers/connection.ts:62 ___ @@ -200,7 +200,7 @@ Will enquee a command to be executed and callback with the resulting rowset/resu #### Defined in -[src/drivers/connection.ts:82](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/connection.ts#L82) +src/drivers/connection.ts:82 ___ @@ -223,7 +223,7 @@ Send a command, return the rowset/result or throw an error #### Defined in -[src/drivers/connection.ts:59](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/connection.ts#L59) +src/drivers/connection.ts:59 ___ @@ -239,4 +239,4 @@ Enable verbose logging for debug purposes #### Defined in -[src/drivers/connection.ts:77](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/connection.ts#L77) +src/drivers/connection.ts:77 diff --git a/sqlite-cloud/sdks/js/classes/SQLiteCloudError.md b/sqlite-cloud/sdks/js/classes/SQLiteCloudError.md index f080ec1..eea1af3 100644 --- a/sqlite-cloud/sdks/js/classes/SQLiteCloudError.md +++ b/sqlite-cloud/sdks/js/classes/SQLiteCloudError.md @@ -1,7 +1,7 @@ --- title: SQLiteCloudError description: SQLite Cloud Javascript SDK -customClass: sdk-doc badge-doc js-doc +customClass: sdk-doc js-doc category: sdks status: publish --- @@ -59,7 +59,7 @@ Error.constructor #### Defined in -[src/drivers/types.ts:102](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L102) +src/drivers/types.ts:102 ## Properties @@ -75,7 +75,7 @@ Error.cause #### Defined in -[src/drivers/types.ts:111](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L111) +src/drivers/types.ts:111 ___ @@ -87,7 +87,7 @@ Error code returned by drivers or server #### Defined in -[src/drivers/types.ts:113](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L113) +src/drivers/types.ts:113 ___ @@ -99,7 +99,7 @@ Additional error code #### Defined in -[src/drivers/types.ts:115](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L115) +src/drivers/types.ts:115 ___ @@ -139,7 +139,7 @@ Additional offset code in commands #### Defined in -[src/drivers/types.ts:117](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L117) +src/drivers/types.ts:117 ___ diff --git a/sqlite-cloud/sdks/js/classes/SQLiteCloudRow.md b/sqlite-cloud/sdks/js/classes/SQLiteCloudRow.md index 104ae7f..d0eea36 100644 --- a/sqlite-cloud/sdks/js/classes/SQLiteCloudRow.md +++ b/sqlite-cloud/sdks/js/classes/SQLiteCloudRow.md @@ -1,7 +1,7 @@ --- title: SQLiteCloudRow description: SQLite Cloud Javascript SDK -customClass: sdk-doc badge-doc js-doc +customClass: sdk-doc js-doc category: sdks status: publish --- @@ -50,7 +50,7 @@ Column values are accessed by column name #### Defined in -[src/drivers/rowset.ts:9](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L9) +src/drivers/rowset.ts:9 ## Properties @@ -60,7 +60,7 @@ Column values are accessed by column name #### Defined in -[src/drivers/rowset.ts:21](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L21) +src/drivers/rowset.ts:21 ___ @@ -70,7 +70,7 @@ ___ #### Defined in -[src/drivers/rowset.ts:18](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L18) +src/drivers/rowset.ts:18 ## Methods @@ -86,7 +86,7 @@ Returns rowset data as a plain array of values #### Defined in -[src/drivers/rowset.ts:31](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L31) +src/drivers/rowset.ts:31 ___ @@ -102,4 +102,4 @@ Returns the rowset that this row belongs to #### Defined in -[src/drivers/rowset.ts:25](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L25) +src/drivers/rowset.ts:25 diff --git a/sqlite-cloud/sdks/js/classes/SQLiteCloudRowset.md b/sqlite-cloud/sdks/js/classes/SQLiteCloudRowset.md index 2bb6c4e..472551d 100644 --- a/sqlite-cloud/sdks/js/classes/SQLiteCloudRowset.md +++ b/sqlite-cloud/sdks/js/classes/SQLiteCloudRowset.md @@ -1,7 +1,7 @@ --- title: SQLiteCloudRowset description: SQLite Cloud Javascript SDK -customClass: sdk-doc badge-doc js-doc +customClass: sdk-doc js-doc category: sdks status: publish --- @@ -98,7 +98,7 @@ Array\<SQLiteCloudRow\>.constructor #### Defined in -[src/drivers/rowset.ts:41](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L41) +src/drivers/rowset.ts:41 ## Properties @@ -110,7 +110,7 @@ Actual data organized in rows #### Defined in -[src/drivers/rowset.ts:72](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L72) +src/drivers/rowset.ts:72 ___ @@ -122,7 +122,7 @@ Metadata contains number of rows and columns, column names, types, etc. #### Defined in -[src/drivers/rowset.ts:69](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L69) +src/drivers/rowset.ts:69 ___ @@ -168,7 +168,7 @@ Array of columns names #### Defined in -[src/drivers/rowset.ts:93](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L93) +src/drivers/rowset.ts:93 ___ @@ -184,7 +184,7 @@ Get rowset metadata #### Defined in -[src/drivers/rowset.ts:98](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L98) +src/drivers/rowset.ts:98 ___ @@ -200,7 +200,7 @@ Number of columns in row set #### Defined in -[src/drivers/rowset.ts:88](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L88) +src/drivers/rowset.ts:88 ___ @@ -216,7 +216,7 @@ Number of rows in row set #### Defined in -[src/drivers/rowset.ts:83](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L83) +src/drivers/rowset.ts:83 ___ @@ -236,7 +236,7 @@ https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md #### Defined in -[src/drivers/rowset.ts:78](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L78) +src/drivers/rowset.ts:78 ## Methods @@ -522,7 +522,7 @@ Array.filter #### Defined in -[src/drivers/rowset.ts:141](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L141) +src/drivers/rowset.ts:141 ___ @@ -726,7 +726,7 @@ Return value of item at given row and column #### Defined in -[src/drivers/rowset.ts:103](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L103) +src/drivers/rowset.ts:103 ___ @@ -877,7 +877,7 @@ Array.map #### Defined in -[src/drivers/rowset.ts:131](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L131) +src/drivers/rowset.ts:131 ___ @@ -1145,7 +1145,7 @@ Array.slice #### Defined in -[src/drivers/rowset.ts:113](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/rowset.ts#L113) +src/drivers/rowset.ts:113 ___ diff --git a/sqlite-cloud/sdks/js/classes/Statement.md b/sqlite-cloud/sdks/js/classes/Statement.md index 0fa438a..efbb082 100644 --- a/sqlite-cloud/sdks/js/classes/Statement.md +++ b/sqlite-cloud/sdks/js/classes/Statement.md @@ -1,7 +1,7 @@ --- title: Statement description: SQLite Cloud Javascript SDK -customClass: sdk-doc badge-doc js-doc +customClass: sdk-doc js-doc category: sdks status: publish --- @@ -60,7 +60,7 @@ A statement generated by Database.prepare used to prepare SQL with ? bindings #### Defined in -[src/drivers/statement.ts:13](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/statement.ts#L13) +src/drivers/statement.ts:13 ## Properties @@ -72,7 +72,7 @@ Statement belongs to this database #### Defined in -[src/drivers/statement.ts:25](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/statement.ts#L25) +src/drivers/statement.ts:25 ___ @@ -84,7 +84,7 @@ The SQL statement with binding values applied #### Defined in -[src/drivers/statement.ts:31](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/statement.ts#L31) +src/drivers/statement.ts:31 ___ @@ -96,7 +96,7 @@ The SQL statement with ? binding placeholders #### Defined in -[src/drivers/statement.ts:28](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/statement.ts#L28) +src/drivers/statement.ts:28 ## Methods @@ -120,7 +120,7 @@ for function chaining. The parameters are the same as the Statement#run function #### Defined in -[src/drivers/statement.ts:121](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/statement.ts#L121) +src/drivers/statement.ts:121 ▸ **all**(`params`, `callback?`): [`Statement`](statement)\<`T`\> @@ -137,7 +137,7 @@ for function chaining. The parameters are the same as the Statement#run function #### Defined in -[src/drivers/statement.ts:122](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/statement.ts#L122) +src/drivers/statement.ts:122 ___ @@ -165,7 +165,7 @@ are escaped client side and turned into literals before being executed on the se #### Defined in -[src/drivers/statement.ts:42](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/statement.ts#L42) +src/drivers/statement.ts:42 ___ @@ -190,7 +190,7 @@ are the same as the Database#each function. #### Defined in -[src/drivers/statement.ts:147](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/statement.ts#L147) +src/drivers/statement.ts:147 ▸ **each**(`params`, `callback?`, `complete?`): [`Statement`](statement)\<`T`\> @@ -208,7 +208,7 @@ are the same as the Database#each function. #### Defined in -[src/drivers/statement.ts:148](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/statement.ts#L148) +src/drivers/statement.ts:148 ___ @@ -235,7 +235,7 @@ the second parameter is undefined, otherwise it is an object containing the valu #### Defined in -[src/drivers/statement.ts:95](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/statement.ts#L95) +src/drivers/statement.ts:95 ▸ **get**(`params`, `callback?`): [`Statement`](statement)\<`T`\> @@ -252,7 +252,7 @@ the second parameter is undefined, otherwise it is an object containing the valu #### Defined in -[src/drivers/statement.ts:96](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/statement.ts#L96) +src/drivers/statement.ts:96 ___ @@ -279,7 +279,7 @@ can run it multiple times. #### Defined in -[src/drivers/statement.ts:66](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/statement.ts#L66) +src/drivers/statement.ts:66 ▸ **run**(`params`, `callback?`): [`Statement`](statement)\<`T`\> @@ -296,4 +296,4 @@ can run it multiple times. #### Defined in -[src/drivers/statement.ts:67](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/statement.ts#L67) +src/drivers/statement.ts:67 diff --git a/sqlite-cloud/sdks/js/getting-started.mdx b/sqlite-cloud/sdks/js/getting-started.mdx deleted file mode 100644 index ead3f32..0000000 --- a/sqlite-cloud/sdks/js/getting-started.mdx +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: JS SDK Introduction -description: SQLite Cloud Javascript SDK -customClass: sdk-doc badge-doc js-doc -category: sdks -status: publish ---- - -[![npm package][npm-img]][npm-url] -[![Build Status][build-img]][build-url] -[![Downloads][downloads-img]][downloads-url] -[![Issues][issues-img]][issues-url] -[![codecov](https://codecov.io/gh/sqlitecloud/sqlitecloud-js/graph/badge.svg?token=ZOKE9WFH62)](https://codecov.io/gh/sqlitecloud/sqlitecloud-js) - -## Install - -```bash -npm install @sqlitecloud/drivers -``` - -## Usage - -```ts -import { Database } from '@sqlitecloud/drivers' - -let database = new Database('sqlitecloud://user:password@xxx.sqlite.cloud:8860/chinook.db') - -let name = 'Breaking The Rules' - -let results = await database.sql`SELECT * FROM tracks WHERE name = ${name}` -// => returns [{ AlbumId: 1, Name: 'Breaking The Rules', Composer: 'Angus Young... }] -``` - -Use [Database.sql](/docs/sdk/js/classes/database#sql) to execute prepared statements or plain SQL queries asynchronously. This method returns an array of rows for SELECT queries and supports the standard syntax for UPDATE, INSERT, and DELETE. - -We aim for full compatibility with the established [sqlite3 API](https://www.npmjs.com/package/sqlite3), with the primary distinction being that our driver connects to SQLiteCloud databases. This allows you to migrate your [SQLite to the cloud](https://sqlitecloud.io) while continuing to use your existing codebase. - -The package is developed entirely in TypeScript and is fully compatible with JavaScript. It doesn't require any native libraries. This makes it a straightforward and effective tool for managing cloud-based databases in a familiar SQLite environment. - -## More - -How do I deploy SQLite in the cloud? -[https://sqlitecloud.io](https://sqlitecloud.io) - -How do I connect SQLite cloud with Javascript? -[https://sqlitecloud.github.io/sqlitecloud-js/](https://sqlitecloud.github.io/sqlitecloud-js/) - -How can I contribute or suggest features? -[https://github.com/sqlitecloud/sqlitecloud-js/issues](https://github.com/sqlitecloud/sqlitecloud-js/issues) - -[build-img]: https://github.com/sqlitecloud/sqlitecloud-js/actions/workflows/build-test-deploy.yml/badge.svg -[build-url]: https://github.com/sqlitecloud/sqlitecloud-js/actions/workflows/build-test-deploy.yml -[downloads-img]: https://img.shields.io/npm/dt/@sqlitecloud/drivers -[downloads-url]: https://www.npmtrends.com/@sqlitecloud/drivers -[npm-img]: https://img.shields.io/npm/v/@sqlitecloud/drivers -[npm-url]: https://www.npmjs.com/package/@sqlitecloud/drivers -[issues-img]: https://img.shields.io/github/issues/sqlitecloud/sqlitecloud-js -[issues-url]: https://github.com/sqlitecloud/sqlitecloud-js/issues diff --git a/sqlite-cloud/sdks/js/interfaces/SQLCloudRowsetMetadata.md b/sqlite-cloud/sdks/js/interfaces/SQLCloudRowsetMetadata.md index c89ad0a..91bcd89 100644 --- a/sqlite-cloud/sdks/js/interfaces/SQLCloudRowsetMetadata.md +++ b/sqlite-cloud/sdks/js/interfaces/SQLCloudRowsetMetadata.md @@ -1,7 +1,7 @@ --- title: SQLCloudRowsetMetadata description: SQLite Cloud Javascript SDK -customClass: sdk-doc badge-doc js-doc +customClass: sdk-doc js-doc category: sdks status: publish --- @@ -27,7 +27,7 @@ Columns' metadata #### Defined in -[src/drivers/types.ts:77](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L77) +src/drivers/types.ts:77 ___ @@ -39,7 +39,7 @@ Number of columns #### Defined in -[src/drivers/types.ts:74](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L74) +src/drivers/types.ts:74 ___ @@ -51,7 +51,7 @@ Number of rows #### Defined in -[src/drivers/types.ts:72](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L72) +src/drivers/types.ts:72 ___ @@ -63,4 +63,4 @@ Rowset version 1 has column's name, version 2 has extended metadata #### Defined in -[src/drivers/types.ts:70](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L70) +src/drivers/types.ts:70 diff --git a/sqlite-cloud/sdks/js/interfaces/SQLiteCloudConfig.md b/sqlite-cloud/sdks/js/interfaces/SQLiteCloudConfig.md index 32e3ff0..e96a76e 100644 --- a/sqlite-cloud/sdks/js/interfaces/SQLiteCloudConfig.md +++ b/sqlite-cloud/sdks/js/interfaces/SQLiteCloudConfig.md @@ -1,7 +1,7 @@ --- title: SQLiteCloudConfig description: SQLite Cloud Javascript SDK -customClass: sdk-doc badge-doc js-doc +customClass: sdk-doc js-doc category: sdks status: publish --- @@ -45,7 +45,7 @@ Optional identifier used for verbose logging #### Defined in -[src/drivers/types.ts:62](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L62) +src/drivers/types.ts:62 ___ @@ -55,7 +55,7 @@ ___ #### Defined in -[src/drivers/types.ts:41](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L41) +src/drivers/types.ts:41 ___ @@ -67,7 +67,7 @@ Connection string in the form of sqlitecloud://user:password@host:port/database? #### Defined in -[src/drivers/types.ts:15](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L15) +src/drivers/types.ts:15 ___ @@ -79,7 +79,7 @@ Create the database if it doesn't exist? #### Defined in -[src/drivers/types.ts:37](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L37) +src/drivers/types.ts:37 ___ @@ -91,7 +91,7 @@ Name of database to open #### Defined in -[src/drivers/types.ts:34](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L34) +src/drivers/types.ts:34 ___ @@ -103,7 +103,7 @@ Database will be created in memory #### Defined in -[src/drivers/types.ts:39](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L39) +src/drivers/types.ts:39 ___ @@ -115,7 +115,7 @@ Url where we can connect to a SQLite Cloud Gateway that has a socket.io deamon w #### Defined in -[src/drivers/types.ts:59](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L59) +src/drivers/types.ts:59 ___ @@ -127,7 +127,7 @@ Host name is required unless connectionString is provided, eg: xxx.sqlitecloud.i #### Defined in -[src/drivers/types.ts:25](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L25) +src/drivers/types.ts:25 ___ @@ -139,7 +139,7 @@ Connect using plain TCP port, without TLS encryption, NOT RECOMMENDED, TEST ONLY #### Defined in -[src/drivers/types.ts:29](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L29) +src/drivers/types.ts:29 ___ @@ -151,7 +151,7 @@ Do not send columns with more than max_data bytes #### Defined in -[src/drivers/types.ts:47](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L47) +src/drivers/types.ts:47 ___ @@ -163,7 +163,7 @@ Server should chunk responses with more than maxRows #### Defined in -[src/drivers/types.ts:49](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L49) +src/drivers/types.ts:49 ___ @@ -175,7 +175,7 @@ Server should limit total number of rows in a set to maxRowset #### Defined in -[src/drivers/types.ts:51](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L51) +src/drivers/types.ts:51 ___ @@ -187,7 +187,7 @@ Server should send BLOB columns #### Defined in -[src/drivers/types.ts:45](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L45) +src/drivers/types.ts:45 ___ @@ -199,7 +199,7 @@ Request for immediate responses from the server node without waiting for lineriz #### Defined in -[src/drivers/types.ts:43](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L43) +src/drivers/types.ts:43 ___ @@ -211,7 +211,7 @@ Password is required unless connection string is provided #### Defined in -[src/drivers/types.ts:20](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L20) +src/drivers/types.ts:20 ___ @@ -223,7 +223,7 @@ True if password is hashed, default is false #### Defined in -[src/drivers/types.ts:22](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L22) +src/drivers/types.ts:22 ___ @@ -235,7 +235,7 @@ Port number for tls socket #### Defined in -[src/drivers/types.ts:27](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L27) +src/drivers/types.ts:27 ___ @@ -247,7 +247,7 @@ Optional query timeout passed directly to TLS socket #### Defined in -[src/drivers/types.ts:32](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L32) +src/drivers/types.ts:32 ___ @@ -259,7 +259,7 @@ Custom options and configurations for tls socket, eg: additional certificates #### Defined in -[src/drivers/types.ts:54](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L54) +src/drivers/types.ts:54 ___ @@ -271,7 +271,7 @@ True if we should force use of SQLite Cloud Gateway and websocket connections, d #### Defined in -[src/drivers/types.ts:57](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L57) +src/drivers/types.ts:57 ___ @@ -283,7 +283,7 @@ User name is required unless connectionString is provided #### Defined in -[src/drivers/types.ts:18](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L18) +src/drivers/types.ts:18 ___ @@ -295,4 +295,4 @@ True if connection should enable debug logs #### Defined in -[src/drivers/types.ts:64](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L64) +src/drivers/types.ts:64 diff --git a/sqlite-cloud/sdks/js/introduction.mdx b/sqlite-cloud/sdks/js/introduction.mdx new file mode 100644 index 0000000..b0af687 --- /dev/null +++ b/sqlite-cloud/sdks/js/introduction.mdx @@ -0,0 +1,61 @@ +--- +title: JS SDK Introduction +description: SQLite Cloud Javascript SDK +customClass: sdk-doc js-doc +category: sdks +status: publish +slug: sdk-js-introduction +--- + + + npm package + +
    + + Build Status + +
    + + Downloads + +
    + + Issues + +
    + + codecov + + +## Install + +```bash +npm install @sqlitecloud/drivers +``` + +## Usage + +```ts +import { Database } from '@sqlitecloud/drivers' + +let database = new Database('sqlitecloud://user:password@xxx.sqlite.cloud:8860/chinook.db') + +let name = 'Breaking The Rules' + +let results = await database.sql`SELECT * FROM tracks WHERE name = ${name}` +// => returns [{ AlbumId: 1, Name: 'Breaking The Rules', Composer: 'Angus Young... }] +``` + +Use [Database.sql](/docs/sqlite-cloud/sdks/js/classes/database#sql) to execute prepared statements or plain SQL queries asynchronously. This method returns an array of rows for SELECT queries and supports the standard syntax for UPDATE, INSERT, and DELETE. + +We aim for full compatibility with the established sqlite3 API, with the primary distinction being that our driver connects to SQLiteCloud databases. This allows you to migrate your SQLite to the cloud while continuing to use your existing codebase. + +The package is developed entirely in TypeScript and is fully compatible with JavaScript. It doesn't require any native libraries. This makes it a straightforward and effective tool for managing cloud-based databases in a familiar SQLite environment. + +## More + +How do I deploy SQLite in the cloud? +
    +How do I connect SQLite cloud with Javascript? +
    +How can I contribute or suggest features? diff --git a/sqlite-cloud/sdks/js/modules.md b/sqlite-cloud/sdks/js/modules.md index 23c8f07..4b9c81d 100644 --- a/sqlite-cloud/sdks/js/modules.md +++ b/sqlite-cloud/sdks/js/modules.md @@ -1,26 +1,27 @@ --- title: Modules description: SQLite Cloud Javascript SDK -customClass: sdk-doc badge-doc js-doc +customClass: sdk-doc js-doc category: sdks status: publish +slug: sdk-js-modules --- ## Table of contents ### Classes -- [Database](classes/database) -- [SQLiteCloudConnection](classes/sqlitecloudconnection) -- [SQLiteCloudError](classes/sqliteclouderror) -- [SQLiteCloudRow](classes/sqlitecloudrow) -- [SQLiteCloudRowset](classes/sqlitecloudrowset) -- [Statement](classes/statement) +- [Database](sqlite-cloud/sdks/js/classes/database) +- [SQLiteCloudConnection](sqlite-cloud/sdks/js/classes/sqlitecloudconnection) +- [SQLiteCloudError](sqlite-cloud/sdks/js/classes/sqliteclouderror) +- [SQLiteCloudRow](sqlite-cloud/sdks/js/classes/sqlitecloudrow) +- [SQLiteCloudRowset](sqlite-cloud/sdks/js/classes/sqlitecloudrowset) +- [Statement](sqlite-cloud/sdks/js/classes/statement) ### Interfaces -- [SQLCloudRowsetMetadata](interfaces/sqlcloudrowsetmetadata) -- [SQLiteCloudConfig](interfaces/sqlitecloudconfig) +- [SQLCloudRowsetMetadata](sqlite-cloud/sdks/js/interfaces/sqlcloudrowsetmetadata) +- [SQLiteCloudConfig](sqlite-cloud/sdks/js/interfaces/sqlitecloudconfig) ### Type Aliases @@ -55,7 +56,7 @@ status: publish #### Defined in -[src/drivers/types.ts:120](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/types.ts#L120) +src/drivers/types.ts:120 ## Functions @@ -77,7 +78,7 @@ Takes a generic value and escapes it so it can replace ? as a binding in a prepa #### Defined in -[src/drivers/utilities.ts:70](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/utilities.ts#L70) +src/drivers/utilities.ts:70 ___ @@ -99,7 +100,7 @@ Parse connectionString like sqlitecloud://username:password@host:port/database?o #### Defined in -[src/drivers/utilities.ts:210](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/utilities.ts#L210) +src/drivers/utilities.ts:210 ___ @@ -122,7 +123,7 @@ Take a sql statement and replaces ? or $named parameters that are properly seria #### Defined in -[src/drivers/utilities.ts:105](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/utilities.ts#L105) +src/drivers/utilities.ts:105 ___ @@ -144,4 +145,4 @@ Validate configuration, apply defaults, throw if something is missing or misconf #### Defined in -[src/drivers/utilities.ts:173](https://github.com/sqlitecloud/sqlitecloud-js/blob/f7cd658/src/drivers/utilities.ts#L173) +src/drivers/utilities.ts:173 diff --git a/sqlite-cloud/sdks/php/getting-started.mdx b/sqlite-cloud/sdks/php/getting-started.mdx deleted file mode 100644 index bdf9084..0000000 --- a/sqlite-cloud/sdks/php/getting-started.mdx +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: PHP SDK Getting Started -description: Get started with SQLite Cloud using PHP. -customClass: sdk-doc badge-doc php-doc -category: sdks -status: publish ---- - - -[![Test and QA][test-qa-img]][test-qa-url] -[![codecov][codecov-img]][codecov-url] -[![Packagist Version][packagist-version-img]][packagist-url] -[![PHP][php-img]][packagist-url] - -## Install - -```bash -$ composer require sqlitecloud/sqlitecloud -``` - -SQLite Cloud is a powerful PHP package that allows you to interact with the SQLite Cloud database seamlessly. It provides methods for various database operations. -This package is designed to simplify database operations in PHP applications, making it easier than ever to work with SQLite Cloud. - -## Example - -```php -connectWithString('sqlitecloud://myhost.sqlite.cloud:8860?apikey=myapikey'); - -// You can autoselect the database during the connect call -// by adding the database name as path of the SQLite Cloud -// connection string, eg: -// $sqlite->connectWithString("sqlitecloud://myhost.sqlite.cloud:8860/mydatabase?apikey=myapikey"); -$db_name = 'chinook.sqlite'; -$sqlite->execute("USE DATABASE {$db_name}"); - - /** @var SQLiteCloudRowset */ -$rowset = $sqlite->execute('SELECT * FROM albums WHERE ArtistId = 2'); - -printf('%d rows' . PHP_EOL, $rowset->nrows); -printf('%s | %s | %s' . PHP_EOL, $rowset->name(0), $rowset->name(1), $rowset->name(2)); -for ($i = 0; $i < $rowset->nrows; $i++) { - printf('%s | %s | %s' . PHP_EOL, $rowset->value($i, 0), $rowset->value($i, 1), $rowset->value($i, 2)); -} - -$sqlite->disconnect(); -``` - -## PHP Admin -To better understand the PHP APIs usage we developed a simple PHP Admin interface that can be used to administer any SQLite Cloud node. - -You can login using admin credentials: -![PHP Admin Login](@docs-website-assets/php/admin_login.png) - -And then administer your node with a convenient user interface: -![PHP Admin Overview](@docs-website-assets/php/admin_overview.png) - -PHP Admin source code is available in a [GitHub repo](https://github.com/sqlitecloud/sqlitecloud-php/tree/main/admin). - -## More -[test-qa-img]: https://github.com/sqlitecloud/sqlitecloud-php/actions/workflows/deploy.yaml/badge.svg?branch=main -[test-qa-url]: https://github.com/sqlitecloud/sqlitecloud-php/actions/workflows/deploy.yaml -[codecov-img]: https://codecov.io/gh/sqlitecloud/sqlitecloud-php/graph/badge.svg?token=3FFHULGCOY -[codecov-url]: https://codecov.io/gh/sqlitecloud/sqlitecloud-php -[packagist-version-img]: https://img.shields.io/packagist/v/sqlitecloud/sqlitecloud -[packagist-url]: https://packagist.org/packages/sqlitecloud/sqlitecloud -[php-img]: https://img.shields.io/packagist/dependency-v/sqlitecloud/sqlitecloud/php \ No newline at end of file diff --git a/sqlite-cloud/sdks/php/introduction.mdx b/sqlite-cloud/sdks/php/introduction.mdx new file mode 100644 index 0000000..2d9603a --- /dev/null +++ b/sqlite-cloud/sdks/php/introduction.mdx @@ -0,0 +1,100 @@ +--- +title: PHP SDK Getting Started +description: Get started with SQLite Cloud using PHP. +category: sdks +status: publish +slug: sdk-php-introduction +--- + +This powerful package provides methods that simplify performing database operations in PHP applications, making it easier than ever to work with SQLite in the cloud. We encourage all users to log encountered issues in the SDK’s issues backlog. + +## Install + + - Run the following command to initialize a PHP project and install the SDK. + +```bash +$ composer require sqlitecloud/sqlitecloud +``` + +## Configure your database connection + + - In your SQLite Cloud account dashboard, click on `Show connection strings`, copy the Connection String, and replace `` below. + +```php +$sqlite->connectWithString(""); +``` + + - You can modify the connection string to include the name of the database to query. + - Here, the provided port (`8860`) and database (`chinook.sqlite`) will query the sample dataset that comes pre-loaded with SQLite Cloud. Replace to query your own datasets. + +```php +$sqlite->connectWithString('sqlitecloud://{hostname}:8860/chinook.sqlite?apikey={apikey}'); +``` + +## Connect and query + + - Include the following snippet in a new `example.php` file. + - NOTE: `$sqlite->execute("USE DATABASE {$db_name}");` is only necessary if your connection string does NOT specify the name of the database to query. + +```php +connectWithString(""); + +$db_name = 'chinook.sqlite'; +$sqlite->execute("USE DATABASE {$db_name}"); + +/** @var SQLiteCloudRowset */ +$rowset = $sqlite->execute('SELECT * FROM albums WHERE ArtistId = 2'); + +printf('%d rows' . PHP_EOL, $rowset->nrows); +printf('%s | %s | %s' . PHP_EOL, $rowset->name(0), $rowset->name(1), $rowset->name(2)); +for ($i = 0; $i < $rowset->nrows; $i++) { + printf('%s | %s | %s' . PHP_EOL, $rowset->value($i, 0), $rowset->value($i, 1), $rowset->value($i, 2)); +} + +$sqlite->disconnect(); +``` + + - Run your app! + +``` +php example.php +``` + +## PHP Admin Dashboard + +You can use SQLite Cloud's simplified PHP Admin interface to administer any node. + + - Clone the PHP SDK, install lock file dependencies, and run the dashboard locally. + +```bash +git clone https://github.com/sqlitecloud/sqlitecloud-php.git + +composer update # or composer install +cd admin +php -S localhost:8000 +``` + + - Login as your admin user. + - In your SQLite Cloud account dashboard, click on `Show connection strings`, copy the Deployment string, and paste in `Hostname`. + - In your dashboard left nav, select Settings, then Users. Copy your admin user's username and paste in `Username`. + - In your User's row, click the down chevron, then Edit. Enter a Password and Save. Paste in `Password`. + +![PHP Admin Login](@docs-website-assets/php/admin_login.png) + +![PHP Admin Overview](@docs-website-assets/php/admin_overview.png) + +[test-qa-img]: https://github.com/sqlitecloud/sqlitecloud-php/actions/workflows/deploy.yaml/badge.svg?branch=main +[test-qa-url]: https://github.com/sqlitecloud/sqlitecloud-php/actions/workflows/deploy.yaml +[codecov-img]: https://codecov.io/gh/sqlitecloud/sqlitecloud-php/graph/badge.svg?token=3FFHULGCOY +[codecov-url]: https://codecov.io/gh/sqlitecloud/sqlitecloud-php +[packagist-version-img]: https://img.shields.io/packagist/v/sqlitecloud/sqlitecloud +[packagist-url]: https://packagist.org/packages/sqlitecloud/sqlitecloud +[php-img]: https://img.shields.io/packagist/dependency-v/sqlitecloud/sqlitecloud/php \ No newline at end of file diff --git a/sqlite-cloud/sdks/php/methods.mdx b/sqlite-cloud/sdks/php/methods.mdx index 6aa8c79..4d8618e 100644 --- a/sqlite-cloud/sdks/php/methods.mdx +++ b/sqlite-cloud/sdks/php/methods.mdx @@ -1,9 +1,9 @@ --- title: PHP SDK Methods description: Methods available in the SQLite Cloud PHP SDK. -customClass: sdk-doc badge-doc php-doc category: sdks status: publish +slug: sdk-php-methods --- diff --git a/sqlite-cloud/sdks/python/introduction.mdx b/sqlite-cloud/sdks/python/introduction.mdx index 516dfdd..885af17 100644 --- a/sqlite-cloud/sdks/python/introduction.mdx +++ b/sqlite-cloud/sdks/python/introduction.mdx @@ -1,7 +1,7 @@ --- title: Python SDK Introduction description: SQLite Cloud Python SDK -customClass: sdk-doc badge-doc js-doc +customClass: sdk-doc js-doc category: sdks status: publish slug: sdk-python-introduction @@ -15,7 +15,7 @@ pip install sqlitecloud ## Basic Usage -We aim for full compatibility with the established [sqlite3 API](https://docs.python.org/3/library/sqlite3.html), with the primary distinction being that our driver connects to SQLite Cloud databases. This allows you to migrate your [SQLite to the cloud](https://sqlitecloud.io) while continuing to use your existing codebase. +We aim for full compatibility with the established sqlite3 API, with the primary distinction being that our driver connects to SQLite Cloud databases. This allows you to migrate your SQLite to the cloud while continuing to use your existing codebase. ```python import sqlitecloud @@ -57,6 +57,7 @@ dfprices = pd.read_csv( ) ) +# Your SQLite Cloud connection string conn = sqlitecloud.connect("sqlitecloud://myhost.sqlite.cloud:8860/mydatabase.sqlite?apikey=myapikey") conn.executemany("DROP TABLE IF EXISTS ?", [("PRICES",)]) @@ -76,3 +77,61 @@ query_result = df_actual_prices.query("PRICE > 50.00") print(query_result) ``` +## Using SQLite Cloud with SQLAlchemy + +```bash +pip install sqlalchemy-sqlitecloud +``` + +```python +import sqlalchemy +from sqlalchemy import Column, ForeignKey, Integer, String +from sqlalchemy.dialects import registry +from sqlalchemy.orm import backref, declarative_base, relationship, sessionmaker + +Base = declarative_base() + + +class Artist(Base): + __tablename__ = "artists" + + ArtistId = Column("ArtistId", Integer, primary_key=True) + Name = Column("Name", String) + Albums = relationship("Album", backref=backref("artist")) + + +class Album(Base): + __tablename__ = "albums" + + AlbumId = Column("AlbumId", Integer, primary_key=True) + ArtistId = Column("ArtistId", Integer, ForeignKey("artists.ArtistId")) + Title = Column("Title", String) + +# Your SQLite Cloud connection string +connection_string = "sqlitecloud://myhost.sqlite.cloud:8860/mydatabase.sqlite?apikey=myapikey" + +engine = sqlalchemy.create_engine(connection_string) +Session = sessionmaker(bind=engine) +session = Session() + +name = "John Doe" +query = sqlalchemy.insert(Artist).values(Name=name) +result_insert = session.execute(query) + +title = "The Album" +query = sqlalchemy.insert(Album).values( + ArtistId=result_insert.lastrowid, Title=title +) +session.execute(query) + +query = ( + sqlalchemy.select(Artist, Album) + .join(Album, Artist.ArtistId == Album.ArtistId) + .where(Artist.ArtistId == result_insert.lastrowid) +) + +result = session.execute(query).fetchone() + +print("Artist Name: " + result[0].Name) +print("Album Title: " + result[1].Title) +``` \ No newline at end of file diff --git a/sqlite-cloud/sdks/swift/introduction.mdx b/sqlite-cloud/sdks/swift/introduction.mdx new file mode 100644 index 0000000..6d7b0b7 --- /dev/null +++ b/sqlite-cloud/sdks/swift/introduction.mdx @@ -0,0 +1,91 @@ +--- +title: Swift SDK Introduction +description: Get started with SQLite Cloud using Swift. +category: sdks +status: publish +slug: sdk-swift-introduction +--- + +This powerful package provides methods that perform DB operations, and enables real-time notifications in Swift apps, making it easier than ever to work with SQLite in the cloud. We encourage all users to log encountered issues in the SDK's issues backlog. + +## Install + + - In `Package.swift`, add the `swift` package to `dependencies`. + +```swift +let package = Package( + ..., + dependencies: [ + ..., + .package(url: "https://github.com/sqlitecloud/swift.git", from: "0.2.1") + ], + ... +) +``` + +## 3 ways to configure your database connection + +1. **RECOMMENDED**: Use the `apikey` connection string. + + - In your SQLite Cloud account dashboard, click on `Show connection strings`, copy the Connection String, and replace `` below. + +```swift +let configuration = SQLiteCloudConfig(connectionString: "") +``` + + - You can modify the connection string to include the name of the database to query. + +```swift +let configuration = SQLiteCloudConfig(connectionString: "sqlitecloud://{hostname}:8860/{database}?apikey={apikey}") +``` + +2. Use a parameterized connection string. + + - In your SQLite Cloud account dashboard, click on `Show connection strings`, copy the Deployment string, and replace `{hostname}` below. + - In your dashboard left nav, select Settings, then Users. Copy your username and replace `{username}`. + - In your User's row, click the down chevron, then Edit. Enter a Password and Save. Replace `{password}`. + - Here, the provided port (`8860`) and database (`chinook.sqlite`) will query the sample dataset that comes pre-loaded with SQLite Cloud. Replace to query your own datasets. + +```swift +let configuration = SQLiteCloudConfig(connectionString: "sqlitecloud://{username}:{password}@{hostname}:8860/chinook.sqlite") +``` + +3. Pass each connection string parameter explicitly. + +```swift +let configuration = SQLiteCloudConfig(hostname: {hostname}, username: {username}, password: {password}, port: .default) +``` + +## Connect and query + + - The following snippet includes variable types, which may be optional for your app. + - NOTE: `USE DATABASE chinook.sqlite;` is only necessary in the query if your `configuration` does not specify the name of the database to query. + - Once you've incorporated the following, build and run your app! + +```swift +import SQLiteCloud + +let configuration: SQLiteCloudConfig? = SQLiteCloudConfig(connectionString: "") + +let sqliteCloud: SQLiteCloud = SQLiteCloud(config: configuration!) + +do { + try await sqliteCloud.connect() + debugPrint("connected") + + let sqlQuery: String = "USE DATABASE chinook.sqlite; SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist FROM albums INNER JOIN artists WHERE artists.ArtistId = albums.ArtistId LIMIT 20;" + + let result: SQLiteCloudResult = try await sqliteCloud.execute(query: sqlQuery) + + try await sqliteCloud.disconnect() + + return result.stringValue! +} catch { + return "Connection error" +} +``` + +## Troubleshooting + + - If you get errors indicating SQLite Cloud-specific constructs are out of scope (i.e. `error: cannot find 'SQLiteCloudConfig' in scope`), verify the `SQLiteCloud` package is correctly imported. + - Confirm `https://github.com/sqlitecloud/swift` package is listed in `Package.resolved`. \ No newline at end of file diff --git a/sqlite-cloud/sqlite-ai/ai-overview.mdx b/sqlite-cloud/sqlite-ai/ai-overview.mdx new file mode 100644 index 0000000..4bd7530 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/ai-overview.mdx @@ -0,0 +1,37 @@ +--- +title: Getting Started with SQLite AI +description: SQLite Cloud is a distributed relational database system built on top of the SQLite database engine. +category: getting-started +status: publish +slug: ai-overview +--- + +## Overview + +**SQLite AI** is an advanced extension of SQLite designed to bring AI capabilities directly to the edge. It transforms the world’s most deployed database into a powerful, intelligent local database engine capable of powering modern, AI-driven applications, from mobile apps to embedded systems, IoT devices, and robotics. + +At the core of the project is a belief that **AI should run where the data is** — locally, privately, and efficiently — without always relying on the cloud. + +### Key Extensions + +SQLite AI is built around several modular extensions: + +1. **SQLite-AI** + Integrates on-device AI capabilities (e.g., LLM inference, audio transcription with Whisper) directly into SQLite using extensions that wrap C-based AI libraries such as `llama.cpp`, `whisper.cpp`, and more. + +2. **SQLite-Vector** + Adds native vector search to SQLite using optimized in-database structures and distance functions (L2, cosine, dot, etc.), with support for multiple vector formats (Float32, Int8, etc.). Ideal for on-device semantic search and AI retrieval. + +3. **SQLite-Sync** + A local-first sync layer that keeps SQLite databases synchronized across devices and users, with support for CRDTs, delta-based replication, and efficient cloud coordination. + +4. **SQLite-JS** + Embed JavaScript directly into SQLite using a lightweight interpreter (e.g., QuickJS), allowing developers to define SQLite functions and logic in JavaScript for increased flexibility and expressiveness. + + +### Features + +* **Works offline-first**: No need for a server to run advanced queries or AI models. +* **Cross-platform**: Runs on iOS, Android, Windows, Linux, macOS, and WebAssembly. +* **Minimal footprint**: Optimized for constrained devices. +* **Modular and open**: Built in C with clean, embeddable APIs and no heavy dependencies. diff --git a/sqlite-cloud/sqlite-ai/aisearch-documents.mdx b/sqlite-cloud/sqlite-ai/aisearch-documents.mdx new file mode 100644 index 0000000..e3f7588 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/aisearch-documents.mdx @@ -0,0 +1,133 @@ +--- +title: Build AI Search for Your Documentation +description: SQLite AI Search for your documents and files +category: platform +status: publish +slug: aisearch-documents +--- + +import Callout from "@commons-components/Information/Callout.astro"; + +This guide shows you how to set up a ready-to-use AI semantic search for your documents and files. +Using the [sqlite-aisearch-action](https://github.com/sqliteai/sqlite-aisearch-action), you can integrate document processing into your GitHub workflow and set up a chatbot on your site in just a few steps. + +The semantic search is powered by [SQLite RAG](https://github.com/sqliteai/sqlite-rag). + +## Step 1: Set Up Your GitHub Workflow + +1. **Get Your Connection String**: Ensure you have a project on the [SQLite Cloud dashboard](https://dashboard.sqlitecloud.io). If not, sign up for [SQLite AI](https://sqlite.ai) to create one for free. + +2. **Set GitHub Secret**: Add your connection string as `SQLITECLOUD_CONNECTION_STRING` in your repository secrets. + +3. **Add to Workflow**: Create or update your GitHub workflow: + +```yaml +name: AI Search Index + +on: + push: + branches: [main] + workflow_dispatch: + +jobs: + build-search: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Build AI Search Database + uses: sqliteai/sqlite-aisearch-action@v1 + with: + connection_string: ${{ secrets.SQLITECLOUD_CONNECTION_STRING }} + base_url: https://docs.yoursite.com + database_name: aidocs_search.db + source_files: ./path/to/documents +``` + +## Step 2: Create the Search Edge Function + +To enable search functionality on your indexed database, create an Edge Function using the provided template: + +1. Access your dashboard at https://dashboard.sqlitecloud.io +2. Navigate to the same project where your database was uploaded +3. Go to the **Edge Functions** section + ![AISearch Edge Function](@docs-website-assets/aisearch-docs/edgefn_aisearch.png) +4. Create a new `Javascript Function` and copy the code from [aisearch-docs.js](https://github.com/sqliteai/sqlite-aisearch-action/blob/main/search_edge_function_template/aisearch-docs.js) into the editor +5. Deploy and test + +### How to Perform a Search + +1. Go to **Details** in the Edge Function panel and copy the **Function URL** + ![AISearch Edge Function Details](@docs-website-assets/aisearch-docs/edgefn_aisearch_details.png) +2. Execute a GET request with a URL-encoded query as the `query` parameter + + Example: + + ``` + GET https://myproject.cloud/v2/functions/aisearch-docs?query=what%27s+Offsync%3F + ``` + +## Step 3: Integrate the Docs Chatbot in Your Website + +Once you have your search edge function deployed, you can easily add an interactive AI chatbot to your website. The chatbot provides a user-friendly interface for your documentation search, powered by the indexed content. + +![Docs Chatbot](@docs-website-assets/aisearch-docs/docs_chatbot.png) + +### React Integration + +Install the chatbot package: + +```bash +npm install @sqliteai/docs-chatbot +``` + +Then add it to your React application: + +```tsx +import { DocsChatbot } from "@sqliteai/docs-chatbot"; +import "@sqliteai/docs-chatbot/style.css"; + +function App() { + return ( + + ); +} +``` + + + - Replace the `searchUrl` with your **Function URL** from Step 2 + - For the `apiKey`, you need to use an API key with read + permissions on your AI docs database. Learn how to create and manage API keys + in the [API Key documentation](/docs/apikey). + + +### Vanilla JavaScript + +For non-React applications, use the web component: + +```html + + + + + + + + + + + + + +``` + +By default, the chatbot displays as a floating button in the bottom-right corner. +For advanced configuration options including custom triggers, theming, and API reference, see the [full docs chatbot documentation](https://github.com/sqliteai/docs-chatbot). diff --git a/sqlite-cloud/sqlite-ai/mcp-server.mdx b/sqlite-cloud/sqlite-ai/mcp-server.mdx new file mode 100644 index 0000000..089c429 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/mcp-server.mdx @@ -0,0 +1,147 @@ +--- +title: AI - Model Context Protocol (MCP) +description: MCP Server for SQLite Cloud to interact with SQLite Cloud databases using the AI models +category: platform +status: publish +slug: mcp-server +--- + +The Model Context Protocol (MCP) is a standard for connecting various data sources (like your SQLite Cloud database) to Large Language Models (LLMs). The MCP Server for SQLite Cloud provides tools for executing queries, managing schemas, and analyzing query performance. + +## Features + +- **Query Execution**: Perform `SELECT`, `INSERT`, `UPDATE`, and `DELETE` SQL operations on SQLite Cloud databases. +- **Schema Management**: Create tables, list existing ones, and retrieve schema details. +- **Command Execution**: Run predefined commands supported by SQLite Cloud. +- **Performance Analysis**: Identify slow queries, analyze query plans, and reset query statistics. + +Explore the available tools here. + +## Getting Started + +To use the MCP Server, create a free account on SQLite Cloud and obtain your **Connection String**. + +### Requirements + +You need Node.js installed on your computer to run the MCP Server. To check if Node.js is installed, open a terminal: + +- **Linux**: Open the terminal from the Applications menu. +- **macOS**: Open the Terminal app from the Applications folder or use Spotlight Search (`Cmd+Space`) and type "Terminal." +- **Windows**: Press `Win + R`, type `cmd`, and press Enter to open the Command Prompt. Alternatively, search for "Command Prompt" in the Start menu. + +Then type the following command and press Enter: + +```bash +node --version +``` + +If the command returns a version number, Node.js is installed. If you see an error like "command not found" or "node is not recognized," download and install Node.js from nodejs.org. + +## Configure the AI Agent + +This guide explains how to connect the MCP Server for SQLite Cloud to common AI agents that support MCP. +Find a list of supported tools and IDEs here. + +After configuring your AI agent, try asking it questions about your SQLite Cloud database, such as: + +> What’s in my database on SQLite Cloud?" +"What are the three most popular tracks by revenue in my SQLite Cloud database? + +Explore or manipulate your database using natural language queries. + +### Claude Desktop + +Refer to the official documentation for detailed instructions. + +1. Open Claude Desktop and navigate to **Settings**. +2. Go to the **Developer** section and click on **Edit Config** to open the configuration file. +3. Add the following configuration: + + ```json + { + "mcpServers": { + "sqlitecloud-mcp-server": { + "type": "stdio", + "command": "npx", + "args": [ + "-y", + "@sqlitecloud/mcp-server", + "--connectionString", + "" + ] + } + } + } + ``` + + Replace `` with your Connection String. + +4. Save the configuration file and restart Claude Desktop. +5. You should see a _Hammer_ icon in the bottom-right corner of the input box. Click the icon to view the list of discovered tools. + +### Cursor + +Refer to the official documentation for detailed instructions. + +1. In the root of your project, create the file `.cursor/mcp.json`. +2. Add the following configuration: + + ```json + { + "mcpServers": { + "sqlitecloud-mcp-server": { + "type": "stdio", + "command": "npx", + "args": [ + "-y", + "@sqlitecloud/mcp-server", + "--connectionString", + "" + ] + } + } + } + ``` + + Replace `` with your Connection String. + +3. Save the `mcp.json` file. +4. Open the **Settings** page and navigate to the **MCP** section. You should see the MCP server with a green status indicator. +5. In the Chat panel, select the "Agent" mode to interact with the AI model using the MCP Server. + +### VSCode Copilot + +Refer to the official documentation for detailed instructions. + +1. In the root of your project, create the file `.vscode/mcp.json`. +2. Add the following configuration: + + ```json + { + "mcp": { + "inputs": [ + { + "type": "promptString", + "id": "sqlitecloud-connection-string", + "description": "Set the SQLite Cloud Connection String", + "password": true + } + ], + "servers": { + "sqlitecloud-mcp-server": { + "type": "stdio", + "command": "npx", + "args": [ + "-y", + "@sqlitecloud/mcp-server", + "--connectionString", + "${input:sqlitecloud-connection-string}" + ] + } + } + } + } + ``` + +3. Save the `mcp.json` file. +4. Open Copilot Chat and select the **Agent** mode from the menu near the **Send** button. A tool icon will appear, showing the discovered tools. Before starting the server, VSCode will prompt you to enter your Connection String. diff --git a/sqlite-cloud/sqlite-ai/sqlite-ai.mdx b/sqlite-cloud/sqlite-ai/sqlite-ai.mdx new file mode 100644 index 0000000..e2857ae --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-ai.mdx @@ -0,0 +1,13 @@ +--- +title: SQLite-AI +description: SQLite Cloud is a distributed relational database system built on top of the SQLite database engine. +category: platform +status: publish +slug: sqlite-ai +--- + +SQLite-AI is a groundbreaking extension that brings powerful AI capabilities directly into SQLite. By embedding llama and whisper, it enables local LLM inference, text generation, embedding creation, speech recognition, translation, and even multimodal support, all from within the database itself. + +With a simple SQL interface, you can chat with a model, stream tokens in real time, generate high-quality embeddings, or transcribe and translate audio using Whisper. Multimodal features allow image processing and embedding, making SQLite-AI a versatile foundation for modern AI applications. + +**SQLite-AI** is an open-source project available on GitHub. diff --git a/sqlite-cloud/sqlite-ai/sqlite-js.mdx b/sqlite-cloud/sqlite-ai/sqlite-js.mdx new file mode 100644 index 0000000..9109a86 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-js.mdx @@ -0,0 +1,13 @@ +--- +title: SQLite-JS +description: SQLite Cloud is a distributed relational database system built on top of the SQLite database engine. +category: platform +status: publish +slug: sqlite-js +--- + +SQLite-JS is a powerful extension that lets you write custom cross-platform logic directly in your SQLite database using JavaScript. With support for scalar, aggregate, window functions, and collation sequences, you can express complex operations with ease, all using familiar SQL syntax. + +By integrating SQLite-JS with [SQLite-Sync](sqlite-sync-introduction), your user-defined JavaScript functions are automatically synchronized across all clients connected to your cluster, keeping logic consistent everywhere, even offline, for a truly consistent offline-first server-side logic distribution. + +**SQLite-JS** is an open-source project available on GitHub. \ No newline at end of file diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_begin_alter.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_begin_alter.md new file mode 100644 index 0000000..e5ce51e --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_begin_alter.md @@ -0,0 +1,25 @@ +--- +title: "cloudsync_begin_alter(table_name)" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-begin-alter +--- + +**Description:** Prepares a synchronized table for schema changes. This function must be called before altering the table. Failure to use `cloudsync_begin_alter` and `cloudsync_commit_alter` can lead to synchronization errors and data divergence. + +**Parameters:** + +- `table_name` (TEXT): The name of the table that will be altered. + +**Returns:** None. + +**Example:** + +```sql +SELECT cloudsync_init('my_table'); +-- ... later +SELECT cloudsync_begin_alter('my_table'); +ALTER TABLE my_table ADD COLUMN new_column TEXT; +SELECT cloudsync_commit_alter('my_table'); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_cleanup.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_cleanup.md new file mode 100644 index 0000000..8d364d8 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_cleanup.md @@ -0,0 +1,23 @@ +--- +title: "cloudsync_cleanup(table_name)" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-cleanup +--- + +**Description:** Removes the `sqlite-sync` synchronization mechanism from a specified table or all tables. This operation drops the associated `_cloudsync` metadata table and removes triggers from the target table(s). Use this function when synchronization is no longer desired for a table. + +**Parameters:** + +- `table_name` (TEXT): The name of the table to clean up. + +**Returns:** None. + +**Example:** + +```sql +-- Clean up a single table +SELECT cloudsync_cleanup('my_table'); + +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_commit_alter.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_commit_alter.md new file mode 100644 index 0000000..73e56d7 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_commit_alter.md @@ -0,0 +1,25 @@ +--- +title: "cloudsync_commit_alter(table_name)" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-commit-alter +--- + +**Description:** Finalizes schema changes for a synchronized table. This function must be called after altering the table's schema, completing the process initiated by `cloudsync_begin_alter` and ensuring CRDT data consistency. + +**Parameters:** + +- `table_name` (TEXT): The name of the table that was altered. + +**Returns:** None. + +**Example:** + +```sql +SELECT cloudsync_init('my_table'); +-- ... later +SELECT cloudsync_begin_alter('my_type'); +ALTER TABLE my_table ADD COLUMN new_column TEXT; +SELECT cloudsync_commit_alter('my_table'); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_db_version.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_db_version.md new file mode 100644 index 0000000..cdef894 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_db_version.md @@ -0,0 +1,19 @@ +--- +title: "cloudsync_db_version()" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-db-version +--- + +**Description:** Returns the current database version. + +**Parameters:** None. + +**Returns:** The database version as an INTEGER. + +**Example:** + +```sql +SELECT cloudsync_db_version(); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_disable.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_disable.md new file mode 100644 index 0000000..0c13f8b --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_disable.md @@ -0,0 +1,21 @@ +--- +title: "cloudsync_disable(table_name)" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-disable +--- + +**Description:** Disables synchronization for the specified table. + +**Parameters:** + +- `table_name` (TEXT): The name of the table to disable. + +**Returns:** None. + +**Example:** + +```sql +SELECT cloudsync_disable('my_table'); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_enable.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_enable.md new file mode 100644 index 0000000..d13c31e --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_enable.md @@ -0,0 +1,21 @@ +--- +title: "cloudsync_enable(table_name)" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-enable +--- + +**Description:** Enables synchronization for the specified table. + +**Parameters:** + +- `table_name` (TEXT): The name of the table to enable. + +**Returns:** None. + +**Example:** + +```sql +SELECT cloudsync_enable('my_table'); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_init.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_init.md new file mode 100644 index 0000000..16b0d7f --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_init.md @@ -0,0 +1,52 @@ +--- +title: "cloudsync_init(table_name, [crdt_algo], [force])" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-init +--- + +**Description:** Initializes a table for `sqlite-sync` synchronization. This function is idempotent and needs to be called only once per table on each site; configurations are stored in the database and automatically loaded with the extension. + +Before initialization, `cloudsync_init` performs schema sanity checks to ensure compatibility with CRDT requirements and best practices. These checks include: + +- Primary keys should not be auto-incrementing integers; GUIDs (UUIDs, ULIDs) are highly recommended to prevent multi-node collisions. +- All primary key columns must be `NOT NULL`. +- All non-primary key `NOT NULL` columns must have a `DEFAULT` value. + +**Schema Design Considerations:** + +When designing your database schema for SQLite Sync, follow these essential requirements: + +- **Primary Keys**: Use TEXT primary keys with `cloudsync_uuid()` for globally unique identifiers. Avoid auto-incrementing integers. +- **Column Constraints**: All NOT NULL columns (except primary keys) must have DEFAULT values to prevent synchronization errors. +- **UNIQUE Constraints**: In multi-tenant scenarios, use composite UNIQUE constraints (e.g., `UNIQUE(tenant_id, email)`) instead of global uniqueness. +- **Foreign Key Compatibility**: Be aware of potential conflicts during CRDT merge operations and RLS policy interactions. +- **Trigger Compatibility**: Triggers may cause duplicate operations or be called multiple times due to column-by-column processing. + +For comprehensive guidelines, see the [Database Schema Recommendations](/docs/sqlite-sync-best-practices) section. + +The function supports three overloads: + +- `cloudsync_init(table_name)`: Uses the default 'cls' CRDT algorithm. +- `cloudsync_init(table_name, crdt_algo)`: Specifies a CRDT algorithm ('cls', 'dws', 'aws', 'gos'). +- `cloudsync_init(table_name, crdt_algo, force)`: Specifies an algorithm and, if `force` is `true` (or `1`), skips the integer primary key check (use with caution, GUIDs are strongly recommended). + +**Parameters:** + +- `table_name` (TEXT): The name of the table to initialize. +- `crdt_algo` (TEXT, optional): The CRDT algorithm to use. Can be "cls", "dws", "aws", "gos". Defaults to "cls". +- `force` (BOOLEAN, optional): If `true` (or `1`), it skips the check that prevents the use of a single-column INTEGER primary key. Defaults to `false`. It is strongly recommended to use globally unique primary keys instead of integers. + +**Returns:** None. + +**Example:** + +```sql +-- Initialize a single table for synchronization with the Causal-Length Set (CLS) Algorithm (default) +SELECT cloudsync_init('my_table'); + +-- Initialize a single table for synchronization with a different algorithm Delete-Wins Set (DWS) +SELECT cloudsync_init('my_table', 'dws'); + +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_is_enabled.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_is_enabled.md new file mode 100644 index 0000000..3f72554 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_is_enabled.md @@ -0,0 +1,21 @@ +--- +title: "cloudsync_is_enabled(table_name)" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-is-enabled +--- + +**Description:** Checks if synchronization is enabled for the specified table. + +**Parameters:** + +- `table_name` (TEXT): The name of the table to check. + +**Returns:** 1 if enabled, 0 otherwise. + +**Example:** + +```sql +SELECT cloudsync_is_enabled('my_table'); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_check_changes.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_check_changes.md new file mode 100644 index 0000000..5e3b809 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_check_changes.md @@ -0,0 +1,29 @@ +--- +title: "cloudsync_network_check_changes()" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-network-check-changes +--- + +**Description:** Checks the remote server for new changes and applies them to the local database. + +If a package of new changes is already available for the local site, the server returns it immediately, and the changes are applied. If no package is ready, the server returns an empty response and starts an asynchronous process to prepare a new package. This new package can be retrieved with a subsequent call to this function. + +This function is designed to be called periodically to keep the local database in sync. +To force an update and wait for changes (with a timeout), use `cloudsync_network_sync(wait_ms, max_retries)`. + +If the network is misconfigured or the remote server is unreachable, the function returns an error. +On success, it returns `SQLITE_OK`, and the return value indicates how many changes were downloaded and applied. + +**Parameters:** None. + +**Returns:** The number of changes downloaded. Errors are reported via the SQLite return code. + +**Errors:** See [Network Errors](#network-errors) for common error conditions. + +**Example:** + +```sql +SELECT cloudsync_network_check_changes(); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_cleanup.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_cleanup.md new file mode 100644 index 0000000..bf1dbc0 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_cleanup.md @@ -0,0 +1,19 @@ +--- +title: "cloudsync_network_cleanup()" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-network-cleanup +--- + +**Description:** Cleans up the `sqlite-sync` network component, releasing all resources allocated by `cloudsync_network_init` (memory, cURL handles). + +**Parameters:** None. + +**Returns:** None. + +**Example:** + +```sql +SELECT cloudsync_network_cleanup(); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_has_unsent_changes.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_has_unsent_changes.md new file mode 100644 index 0000000..fcbad04 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_has_unsent_changes.md @@ -0,0 +1,19 @@ +--- +title: "cloudsync_network_has_unsent_changes()" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-network-has-unsent-changes +--- + +**Description:** Checks if there are any local changes that have not yet been sent to the remote server. + +**Parameters:** None. + +**Returns:** 1 if there are unsent changes, 0 otherwise. + +**Example:** + +```sql +SELECT cloudsync_network_has_unsent_changes(); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_init.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_init.md new file mode 100644 index 0000000..52bda2d --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_init.md @@ -0,0 +1,21 @@ +--- +title: "cloudsync_network_init(connection_string)" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-network-init +--- + +**Description:** Initializes the `sqlite-sync` network component. This function parses the connection string to configure change checking and upload endpoints, and initializes the cURL library. + +**Parameters:** + +- `connection_string` (TEXT): The connection string for the remote synchronization server. The format is `sqlitecloud://:/?`. + +**Returns:** None. + +**Example:** + +```sql +SELECT cloudsync_network_init('.sqlite.cloud/.sqlite'); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_logout.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_logout.md new file mode 100644 index 0000000..ba565d9 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_logout.md @@ -0,0 +1,19 @@ +--- +title: "cloudsync_network_logout()" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-network-logout +--- + +**Description:** Logs out the current user and cleans up all local data from synchronized tables. This function deletes and then re-initializes synchronized tables, useful for switching users or resetting the local database. **Warning:** This function deletes all data from synchronized tables. Use with caution. + +**Parameters:** None. + +**Returns:** None. + +**Example:** + +```sql +SELECT cloudsync_network_logout(); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_reset_sync_version.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_reset_sync_version.md new file mode 100644 index 0000000..ff92454 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_reset_sync_version.md @@ -0,0 +1,19 @@ +--- +title: "cloudsync_network_reset_sync_version()" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-network-reset-sync-version +--- + +**Description:** Resets local synchronization version numbers, forcing the next sync to fetch all changes from the server. + +**Parameters:** None. + +**Returns:** None. + +**Example:** + +```sql +SELECT cloudsync_network_reset_sync_version(); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_send_changes.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_send_changes.md new file mode 100644 index 0000000..45e8d1b --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_send_changes.md @@ -0,0 +1,19 @@ +--- +title: "cloudsync_network_send_changes()" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-network-send-changes +--- + +**Description:** Sends all unsent local changes to the remote server. + +**Parameters:** None. + +**Returns:** None. + +**Example:** + +```sql +SELECT cloudsync_network_send_changes(); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_set_apikey.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_set_apikey.md new file mode 100644 index 0000000..ed47ee2 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_set_apikey.md @@ -0,0 +1,21 @@ +--- +title: "cloudsync_network_set_apikey(apikey)" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-network-set-apikey +--- + +**Description:** Sets the API key for network requests. This key is included in the `Authorization` header of all subsequent requests. + +**Parameters:** + +- `apikey` (TEXT): The API key. + +**Returns:** None. + +**Example:** + +```sql +SELECT cloudsync_network_set_apikey('your_api_key'); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_set_token.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_set_token.md new file mode 100644 index 0000000..fdc0bb0 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_set_token.md @@ -0,0 +1,21 @@ +--- +title: "cloudsync_network_set_token(token)" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-network-set-token +--- + +**Description:** Sets the authentication token to be used for network requests. This token will be included in the `Authorization` header of all subsequent requests. For more information, refer to the [Access Tokens documentation](/docs/access-tokens). + +**Parameters:** + +- `token` (TEXT): The authentication token. + +**Returns:** None. + +**Example:** + +```sql +SELECT cloudsync_network_set_token('your_auth_token'); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_sync.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_sync.md new file mode 100644 index 0000000..0761156 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_network_sync.md @@ -0,0 +1,29 @@ +--- +title: "cloudsync_network_sync([wait_ms], [max_retries])" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-network-sync +--- + +**Description:** Performs a full synchronization cycle. This function has two overloads: + +- `cloudsync_network_sync()`: Performs one send operation and one check operation. +- `cloudsync_network_sync(wait_ms, max_retries)`: Performs one send operation and then repeatedly tries to download remote changes until at least one change is downloaded or `max_retries` times has been reached, waiting `wait_ms` between retries. + +**Parameters:** + +- `wait_ms` (INTEGER, optional): The time to wait in milliseconds between retries. Defaults to 100. +- `max_retries` (INTEGER, optional): The maximum number of times to retry the synchronization. Defaults to 1. + +**Returns:** The number of changes downloaded. Errors are reported via the SQLite return code. + +**Example:** + +```sql +-- Perform a single synchronization cycle +SELECT cloudsync_network_sync(); + +-- Perform a synchronization cycle with custom retry settings +SELECT cloudsync_network_sync(500, 3); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_siteid.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_siteid.md new file mode 100644 index 0000000..49e6c30 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_siteid.md @@ -0,0 +1,19 @@ +--- +title: "cloudsync_siteid()" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-siteid +--- + +**Description:** Returns the unique ID of the local site. + +**Parameters:** None. + +**Returns:** The site ID as a BLOB. + +**Example:** + +```sql +SELECT cloudsync_siteid(); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_terminate.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_terminate.md new file mode 100644 index 0000000..a8e646e --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_terminate.md @@ -0,0 +1,20 @@ +--- +title: "cloudsync_terminate()" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-terminate +--- + +**Description:** Releases all internal resources used by the `sqlite-sync` extension for the current database connection. This function should be called before closing the database connection to ensure that all prepared statements and allocated memory are freed. Failing to call this function can result in memory leaks or a failed `sqlite3_close` operation due to pending statements. + +**Parameters:** None. + +**Returns:** None. + +**Example:** + +```sql +-- Before closing the database connection +SELECT cloudsync_terminate(); +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_uuid.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_uuid.md new file mode 100644 index 0000000..fa976bb --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_uuid.md @@ -0,0 +1,19 @@ +--- +title: "cloudsync_uuid()" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-uuid +--- + +**Description:** Generates a new universally unique identifier (UUIDv7). This is useful for creating globally unique primary keys for new records, which is a best practice for CRDTs. + +**Parameters:** None. + +**Returns:** A new UUID as a TEXT value. + +**Example:** + +```sql +INSERT INTO products (id, name) VALUES (cloudsync_uuid(), 'New Product'); +``` \ No newline at end of file diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_version.md b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_version.md new file mode 100644 index 0000000..f1033e6 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/api-reference/cloudsync_version.md @@ -0,0 +1,20 @@ +--- +title: "cloudsync_version()" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-api-cloudsync-version +--- + +**Description:** Returns the version of the `sqlite-sync` library. + +**Parameters:** None. + +**Returns:** The library version as a string. + +**Example:** + +```sql +SELECT cloudsync_version(); +-- e.g., '1.0.0' +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/best-practices.md b/sqlite-cloud/sqlite-ai/sqlite-sync/best-practices.md new file mode 100644 index 0000000..5e77af8 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/best-practices.md @@ -0,0 +1,117 @@ +--- +title: SQLite-Sync Best Practices +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-best-practices +--- + +## Database Schema Recommendations + +When designing your database schema for SQLite Sync, follow these best practices to ensure optimal CRDT performance and conflict resolution: + +### Primary Key Requirements + +- **Use globally unique identifiers**: Always use TEXT primary keys with UUIDs, ULIDs, or similar globally unique identifiers +- **Avoid auto-incrementing integers**: Integer primary keys can cause conflicts across multiple devices +- **Use `cloudsync_uuid()`**: The built-in function generates UUIDv7 identifiers optimized for distributed systems +- **All primary keys must be explicitly declared as `NOT NULL`**. + +```sql +-- ✅ Recommended: Globally unique TEXT primary key +CREATE TABLE users ( + id TEXT PRIMARY KEY NOT NULL, -- Use cloudsync_uuid() + name TEXT NOT NULL, + email TEXT UNIQUE NOT NULL +); + +-- ❌ Avoid: Auto-incrementing integer primary key +CREATE TABLE users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, -- Causes conflicts + name TEXT NOT NULL, + email TEXT UNIQUE NOT NULL +); +``` + +### Column Constraint Guidelines + +- **Provide DEFAULT values**: All `NOT NULL` columns (except primary keys) must have `DEFAULT` values +- **Consider nullable columns**: For optional data, use nullable columns instead of empty strings + +```sql +-- ✅ Recommended: Proper constraints and defaults +CREATE TABLE tasks ( + id TEXT PRIMARY KEY, + title TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'pending', + priority INTEGER NOT NULL DEFAULT 1, + created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), + assigned_to TEXT -- Nullable for optional assignment +); +``` + +### UNIQUE Constraint Considerations + +When converting from single-tenant to multi-tenant database schemas with Row-Level Security, **UNIQUE constraints must be globally unique** across all tenants in the cloud database. For columns that should only be unique within a tenant, use composite UNIQUE constraints. + +```sql +-- ❌ Single-tenant: Unique email per database +CREATE TABLE users ( + id TEXT PRIMARY KEY, + email TEXT UNIQUE NOT NULL -- Problem: Not unique across tenants +); + +-- ✅ Multi-tenant: Composite unique constraint +CREATE TABLE users ( + id TEXT PRIMARY KEY, + tenant_id TEXT NOT NULL, + email TEXT NOT NULL, + UNIQUE(tenant_id, email) -- Unique email per tenant +); +``` + +### Foreign Key Compatibility + +When using foreign key constraints with SQLite Sync, be aware that interactions with the CRDT merge algorithm and Row-Level Security policies may cause constraint violations. + +#### Potential Conflicts + +**CRDT Merge Algorithm and DEFAULT Values** + +- CRDT changes are applied column-by-column during synchronization +- Columns may be temporarily assigned DEFAULT values during the merge process +- If a foreign key column has a DEFAULT value, that value must exist in the referenced table + +**Row-Level Security and CASCADE Actions** + +- RLS policies may block operations required for maintaining referential integrity +- CASCADE DELETE/UPDATE operations may fail if RLS prevents access to related rows + +#### Recommendations + +**Database Design Patterns** + +- Prefer application-level cascade logic over database-level CASCADE actions +- Design RLS policies to accommodate referential integrity operations +- Use nullable foreign keys where appropriate to avoid DEFAULT value issues +- Alternatively, ensure DEFAULT values for foreign key columns exist in their referenced tables + +**Testing and Validation** + +- Test synchronization scenarios with foreign key constraints enabled +- Monitor for constraint violations during sync operations in development + +### Trigger Compatibility + +Be aware that certain types of triggers can cause errors during synchronization due to SQLite Sync's merge logic. + +**Duplicate Operations** + +- If a trigger modifies a table that is also synchronized with SQLite Sync, changes performed by the trigger may be applied twice during the merge operation +- This can lead to constraint violations or unexpected data states depending on the table's constraints + +**Column-by-Column Processing** + +- SQLite Sync applies changes column-by-column during synchronization +- UPDATE triggers may be called multiple times for a single row as each column is processed +- This can result in unexpected trigger behavior diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/getting-started.md b/sqlite-cloud/sqlite-ai/sqlite-sync/getting-started.md new file mode 100644 index 0000000..35d7697 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/getting-started.md @@ -0,0 +1,126 @@ +--- +title: "Getting Started" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-getting-started +--- + +Here's a quick example to get started with SQLite Sync: + +### Prerequisites + +1. **SQLite Cloud Account**: Sign up at SQLite Cloud +2. **SQLite Sync Extension**: Download from Releases + +### SQLite Cloud Setup + +1. Create a new project and database in your SQLite Cloud Dashboard +2. Copy your connection string and API key from the dashboard +3. Create tables with identical schema in both local and cloud databases +4. [Enable synchronization](/docs/offsync#:~:text=in%20the%20cloud.-,Configuring%20OffSync,-You%20can%20enable): go to Databases > Offsync page and select each table you want to synchronize in your database + +### Local Database Setup + +```bash +# Start SQLite CLI +sqlite3 myapp.db +``` + +```sql +-- Load the extension +.load ./cloudsync + +-- Create a table (primary key MUST be TEXT for global uniqueness) +CREATE TABLE IF NOT EXISTS my_data ( + id TEXT PRIMARY KEY NOT NULL, + value TEXT NOT NULL DEFAULT '', + created_at TEXT DEFAULT CURRENT_TIMESTAMP +); + +-- Initialize table for synchronization +SELECT cloudsync_init('my_data'); + +-- Use your local database normally: read and write data using standard SQL queries +-- The CRDT system automatically tracks all changes for synchronization + +-- Example: Insert data (always use cloudsync_uuid() for globally unique IDs) +INSERT INTO my_data (id, value) VALUES + (cloudsync_uuid(), 'Hello from device A!'), + (cloudsync_uuid(), 'Working offline is seamless!'); + +-- Example: Update and delete operations work normally +UPDATE my_data SET value = 'Updated: Hello from device A!' WHERE value LIKE 'Hello from device A!'; + +-- View your data +SELECT * FROM my_data ORDER BY created_at; + +-- Configure network connection before using the network sync functions +SELECT cloudsync_network_init('sqlitecloud://your-project-id.sqlite.cloud/database.sqlite'); +SELECT cloudsync_network_set_apikey('your-api-key-here'); +-- Or use token authentication (required for Row-Level Security) +-- SELECT cloudsync_network_set_token('your_auth_token'); + +-- Sync with cloud: send local changes, then check the remote server for new changes +-- and, if a package with changes is ready to be downloaded, applies them to the local database +SELECT cloudsync_network_sync(); +-- Keep calling periodically. The function returns > 0 if data was received +-- In production applications, you would typically call this periodically +-- rather than manually (e.g., every few seconds) +SELECT cloudsync_network_sync(); + +-- Before closing the database connection +SELECT cloudsync_terminate(); +-- Close the database connection +.quit +``` + +```sql +-- On another device (or create another database for testing: sqlite3 myapp_2.db) +-- Follow the same setup steps: load extension, create table, init sync, configure network + +-- Load extension and create identical table structure +.load ./cloudsync +CREATE TABLE IF NOT EXISTS my_data ( + id TEXT PRIMARY KEY NOT NULL, + value TEXT NOT NULL DEFAULT '', + created_at TEXT DEFAULT CURRENT_TIMESTAMP +); +SELECT cloudsync_init('my_data'); + +-- Connect to the same cloud database +SELECT cloudsync_network_init('sqlitecloud://your-project-id.sqlite.cloud/database.sqlite'); +SELECT cloudsync_network_set_apikey('your-api-key-here'); + +-- Sync to get data from the first device +SELECT cloudsync_network_sync(); +-- repeat until data is received (returns > 0) +SELECT cloudsync_network_sync(); + +-- View synchronized data +SELECT * FROM my_data ORDER BY created_at; + +-- Add data from this device to test bidirectional sync +INSERT INTO my_data (id, value) VALUES + (cloudsync_uuid(), 'Hello from device B!'); + +-- Sync again to send this device's changes +SELECT cloudsync_network_sync(); + +-- The CRDT system ensures all devices eventually have the same data, +-- with automatic conflict resolution and no data loss + +-- Before closing the database connection +SELECT cloudsync_terminate(); +-- Close the database connection +.quit +``` + +### For a Complete Example + +See the examples directory for a comprehensive walkthrough including: + +- Multi-device collaboration +- Offline scenarios +- Row-level security setup +- Conflict resolution demonstrations diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/introduction.md b/sqlite-cloud/sqlite-ai/sqlite-sync/introduction.md new file mode 100644 index 0000000..7d5bd64 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/introduction.md @@ -0,0 +1,97 @@ +--- +title: "Introduction to SQLite Sync" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-introduction +--- + +SQLite Sync is a multi-platform extension that brings a true **local-first experience** to your applications with minimal effort. It extends standard SQLite tables with built-in support for offline work and automatic synchronization, allowing multiple devices to operate independently—even without a network connection—and seamlessly stay in sync. With SQLite Sync, developers can easily build **distributed, collaborative applications** while continuing to rely on the **simplicity, reliability, and performance of SQLite**. + +Under the hood, SQLite Sync uses advanced **CRDT (Conflict-free Replicated Data Type)** algorithms and data structures designed specifically for **collaborative, distributed systems**. This means: + +- Devices can update data independently, even without a network connection. +- When they reconnect, all changes are **merged automatically and without conflicts**. +- **No data loss. No overwrites. No manual conflict resolution.** + +In simple terms, CRDTs make it possible for multiple users to **edit shared data at the same time**, from anywhere, and everything just works. + +## Key Features + +- **Offline-First by Design**: Works seamlessly even when devices are offline. Changes are queued locally and synced automatically when connectivity is restored. +- **CRDT-Based Conflict Resolution**: Merges updates deterministically and efficiently, ensuring eventual consistency across all replicas without the need for complex merge logic. +- **Embedded Network Layer**: No external libraries or sync servers required. SQLiteSync handles connection setup, message encoding, retries, and state reconciliation internally. +- **Drop-in Simplicity**: Just load the extension into SQLite and start syncing. No need to implement custom protocols or state machines. +- **Efficient and Resilient**: Optimized binary encoding, automatic batching, and robust retry logic make synchronization fast and reliable even on flaky networks. + +Whether you're building a mobile app, IoT device, or desktop tool, SQLite Sync simplifies distributed data management and unlocks the full potential of SQLite in decentralized environments. + +## Built-in Network Layer + +Unlike traditional sync systems that require you to build and maintain a complex backend, **SQLite Sync includes a built-in network layer** that works out of the box: + +- Sync your database with the cloud using **a single function call**. +- Compatible with **any language or framework** that supports SQLite. +- **No backend setup required** — SQLite Sync handles networking, change tracking, and conflict resolution for you. + +The sync layer is tightly integrated with **SQLite Cloud**, enabling seamless and secure data sharing across devices, users, and platforms. You get the power of cloud sync without the complexity. + +## Row-Level Security + +Thanks to the underlying SQLite Cloud infrastructure, **SQLite Sync supports Row-Level Security (RLS)**—allowing you to define **precise access control at the row level**: + +- Control not just who can read or write a table, but **which specific rows** they can access. +- Enforce security policies on the server—no need for client-side filtering. + +For example: + +- User A can only see and edit their own data. +- User B can access a different set of rows—even within the same shared table. + +**Benefits of RLS**: + +- **Data isolation**: Ensure users only access what they’re authorized to see. +- **Built-in privacy**: Security policies are enforced at the database level. +- **Simplified development**: Reduce or eliminate complex permission logic in your application code. + +## What Can You Build with SQLite Sync? + +SQLite Sync is ideal for building collaborative and distributed apps across web, mobile, desktop, and edge platforms. Some example use cases include: + +#### 📋 Productivity & Collaboration + +- **Shared To-Do Lists**: Users independently update tasks and sync effortlessly. +- **Note-Taking Apps**: Real-time collaboration with offline editing. +- **Markdown Editors**: Work offline, sync when back online—no conflicts. + +#### 📱 Mobile & Edge + +- **Field Data Collection**: For remote inspections, agriculture, or surveys. +- **Point-of-Sale Systems**: Offline-first retail solutions with synced inventory. +- **Health & Fitness Apps**: Sync data across devices with strong privacy controls. + +#### 🏢 Enterprise Workflows + +- **CRM Systems**: Sync leads and clients per user with row-level access control. +- **Project Management Tools**: Offline-friendly planning and task management. +- **Expense Trackers**: Sync team expenses securely and automatically. + +#### 🧠 Personal Apps + +- **Journaling & Diaries**: Private, encrypted entries that sync across devices. +- **Bookmarks & Reading Lists**: Personal or collaborative content management. +- **Habit Trackers**: Sync progress with data security and consistency. + +#### 🌍 Multi-User, Multi-Tenant Systems + +- **SaaS Platforms**: Row-level access for each user or team. +- **Collaborative Design Tools**: Merge visual edits and annotations offline. +- **Educational Apps**: Shared learning content with per-student access controls. + +## Integrations + +Use SQLite-Sync alongside: + +- **SQLite-AI** – on-device inference, embedding generation, and model interaction directly into your database +- **SQLite-Vector** – vector search from SQL +- **SQLite-JS** – define SQLite functions in JavaScript diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/android.mdx b/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/android.mdx new file mode 100644 index 0000000..6aef820 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/android.mdx @@ -0,0 +1,192 @@ +--- +title: "Android Quick Start Guide" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-quick-start-android +--- + +import Callout from "@commons-components/Information/Callout.astro"; + +This guide shows how to integrate sqlite-sync extension into your Android application. + +### 1. Add Dependencies + +You can add sqlite-sync as a dependency to your Android project. + +
    +Groovy DSL + +```groovy +repositories { + google() + mavenCentral() + maven { url 'https://jitpack.io' } +} +dependencies { + // ... + // Use requery's SQLite instead of Android's built-in SQLite to support loading custom extensions + implementation 'com.github.requery:sqlite-android:3.49.0' + // Both packages below are identical - use either one + implementation 'ai.sqlite:sync:0.8.39' // Maven Central + // implementation 'com.github.sqliteai:sqlite-sync:0.8.39' // JitPack (alternative) +} +``` + +
    + +
    +Kotlin DSL + +```kotlin +repositories { + google() + mavenCentral() + maven(url = "https://jitpack.io") +} +dependencies { + // ... + // Use requery's SQLite instead of Android's built-in SQLite to support loading custom extensions + implementation("com.github.requery:sqlite-android:3.49.0") + // Both packages below are identical - use either one + implementation("ai.sqlite:sync:0.8.39") // Maven Central + // implementation("com.github.sqliteai:sqlite-sync:0.8.39") // JitPack (alternative) +} +``` + +
    + +### 2. Update AndroidManifest.xml + +Add `android:extractNativeLibs="true"` to your `` tag: + +```xml + +``` + +### 3. Basic Integration + +Here’s a complete example showing how to load the extension, create a table, initialize CloudSync, and perform network sync. + + + Replace the following placeholders with your actual values: + - `database_name` - Your database name + - `table_name` - Your table name + - `` - Your SQLiteCloud connection string + - `` - Your SQLiteCloud API key + + +```kotlin +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.lifecycle.lifecycleScope +import io.requery.android.database.sqlite.SQLiteCustomExtension +import io.requery.android.database.sqlite.SQLiteDatabase +import io.requery.android.database.sqlite.SQLiteDatabaseConfiguration +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + // --- Create extension configuration --- + val cloudsyncExtension = SQLiteCustomExtension(applicationInfo.nativeLibraryDir + "/cloudsync", null) + + // --- Configure database with extension --- + val config = SQLiteDatabaseConfiguration( + cacheDir.path + "/database_name.db", + SQLiteDatabase.CREATE_IF_NECESSARY or SQLiteDatabase.OPEN_READWRITE, + emptyList(), + emptyList(), + listOf(cloudsyncExtension) + ) + + // --- Open database --- + val db = SQLiteDatabase.openDatabase(config, null, null) + val tableName = "table_name" + + lifecycleScope.launch { + withContext(Dispatchers.IO) { + // --- Check CloudSync version --- + val version = db.rawQuery("SELECT cloudsync_version();", null).use { cursor -> + if (cursor.moveToFirst()) cursor.getString(0) else null + } + + if (version == null) { + println("CLOUDSYNC-TEST: Failed to load SQLite Sync extension") + return@withContext + } + + println("CLOUDSYNC-TEST: SQLite Sync loaded successfully. Version: $version") + + try { + // --- Create test table --- + val createTableSQL = """ + CREATE TABLE IF NOT EXISTS $tableName ( + id TEXT PRIMARY KEY NOT NULL, + value TEXT NOT NULL DEFAULT '', + created_at TEXT DEFAULT CURRENT_TIMESTAMP + ); + """.trimIndent() + db.execSQL(createTableSQL) + + // --- Initialize CloudSync for table --- + val initResult = db.rawQuery("SELECT cloudsync_init('$tableName');", null).use { it.moveToFirst() } + + // --- Insert sample data --- + db.execSQL(""" + INSERT INTO $tableName (id, value) VALUES + (cloudsync_uuid(), 'test1'), + (cloudsync_uuid(), 'test2'); + """.trimIndent()) + + // --- Initialize network connection --- + db.rawQuery( + "SELECT cloudsync_network_init('');", + null + ).use { it.moveToFirst() } + + // --- Set API key --- + db.rawQuery( + "SELECT cloudsync_network_set_apikey('');", + null + ).use { it.moveToFirst() } + + // --- Run network sync multiple times --- + // Note: cloudsync_network_sync() returns > 0 if data was sent/received. + // It should ideally be called periodically to ensure both sending local + // changes and receiving remote changes work reliably. + repeat(2) { attempt -> + try { + val syncResult = db.rawQuery("SELECT cloudsync_network_sync();", null).use { cursor -> + if (cursor.moveToFirst()) cursor.getInt(0) else 0 + } + println("CLOUDSYNC-TEST: Network sync attempt ${attempt + 1}: result = $syncResult") + } catch (e: Exception) { + println("CLOUDSYNC-TEST: Sync attempt ${attempt + 1} failed: ${e.message}") + } + } + } catch (e: Exception) { + println("CLOUDSYNC-TEST: Error - ${e.message}") + } finally { + // --- Terminate CloudSync --- + db.rawQuery("SELECT cloudsync_terminate();", null).use { it.moveToFirst() } + + // Close the database + db.close() + } + } + } + } +} +``` + + + CloudSync functions must be executed with `SELECT`. In Android, use + `rawQuery()` to call them, and always call `moveToFirst()` (or `moveToNext()`) + on the cursor to ensure the query actually executes. + \ No newline at end of file diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/ios.md b/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/ios.md new file mode 100644 index 0000000..0128f78 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/ios.md @@ -0,0 +1,207 @@ +--- +title: "iOS Quick Start Guide" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-quick-start-ios +--- + +This guide will walk you through setting up SQLite in Swift to load CloudsSync extensions. + +## 1. Create a New Swift Project + +1. Open Xcode +2. Create a new project +3. Select **Multiplatform** → **App** + +## 2. Download and Add CloudSync Framework + +1. Download the latest version of `cloudsync-apple-xcframework` from here + +2. In Xcode, click on your project name in the source tree (top left with the Xcode logo) + +3. In the new tab that opens, navigate to the left column under the **Targets** section and click on the first target + +4. You should now be in the **General** tab. Scroll down to **"Frameworks, Libraries, and Embedded Content"** + +5. Click the **+** button → **Add Other...** → **Add Files...** + +6. Select the downloaded `CloudSync.xcframework` folder + +7. Switch to the **Build Phases** tab and verify that `CloudSync.xcframework` appears under **Embedded Frameworks** + +## 3. Handle Security Permissions (macOS) + +When you return to the main ContentView file, you may encounter an Apple security error: + +1. Click **Done** when the security dialog appears +2. Open **System Settings** → **Privacy & Security** +3. Scroll to the bottom and find the message "Mac blocked CloudSync" +4. Click **Allow Anyway** +5. Close and reopen ContentView in Xcode +6. The same error should appear but now with a third button **Open Anyway** - click it +7. If errors persist, try reopening and closing ContentView multiple times or repeat the security steps above + +## 4. Set Up SQLite with Extension Loading + +You need a version of SQLite that supports loading extensions. You have two options: + +### Option A: Download SQLite Amalgamation (Recommended) + +1. Download the amalgamation from here +2. Create a new folder called **SQLite** in your Swift project in Xcode +3. Copy `sqlite3.c` and `sqlite3.h` into this folder by dragging them in +4. Enable all targets and confirm + +### Option B: Use CocoaPods + +## 5. Configure Objective-C Bridging Header + +1. When you add the SQLite files, a popup will appear asking **"Would you like to configure an Objective-C bridging header?"** +2. Click **Create Bridging Header** +3. In the newly created bridging header file, import the SQLite headers: + ```objc + #import "sqlite3.h" + ``` + +## 6. Test the Setup + +To verify that the extension loads correctly in your Swift project, replace your ContentView.swift content with this test code: + +```swift +import SwiftUI + +struct ContentView: View { + @State private var statusLines: [String] = [] + private var statusText: String { statusLines.joined(separator: "\n") } + + var body: some View { + VStack(spacing: 12) { + Image(systemName: "globe") + .imageScale(.large) + .foregroundStyle(.tint) + Text("Hello, world!") + + Divider() + + Text("Status") + .font(.headline) + + ScrollView { + Text(statusText.isEmpty ? "No status yet." : statusText) + .font(.system(.footnote, design: .monospaced)) + .frame(maxWidth: .infinity, alignment: .leading) + .textSelection(.enabled) + .padding(.vertical, 4) + } + .frame(maxHeight: 260) + } + .padding() + .task { + log("Starting...") + var db: OpaquePointer? + + // Open an in-memory database just for demonstrating status updates. + // Replace with your own URL/path if needed. + var rc = sqlite3_open(":memory:", &db) + if rc != SQLITE_OK { + let msg = db.flatMap { sqlite3_errmsg($0) }.map { String(cString: $0) } ?? "Unknown error" + log("sqlite3_open failed (\(rc)): \(msg)") + if let db { sqlite3_close(db) } + return + } + log("Database opened.") + + // Enable loadable extensions + rc = sqlite3_enable_load_extension(db, 1) + log("sqlite3_enable_load_extension rc=\(rc)") + + // Locate the extension in the bundle (adjust as needed) + let vendorBundle = Bundle(identifier: "ai.sqlite.cloudsync") + let candidatePaths: [String?] = [ + vendorBundle?.path(forResource: "CloudSync", ofType: "dylib"), + vendorBundle?.path(forResource: "CloudSync", ofType: ""), + Bundle.main.path(forResource: "CloudSync", ofType: "dylib"), + Bundle.main.path(forResource: "CloudSync", ofType: "") + ] + let cloudsyncPath = candidatePaths.compactMap { $0 }.first + log("cloudsyncPath: \(cloudsyncPath ?? "Not found")") + + var loaded = false + if let path = cloudsyncPath { + var errMsg: UnsafeMutablePointer? = nil + rc = sqlite3_load_extension(db, path, nil, &errMsg) + if rc != SQLITE_OK { + let message = errMsg.map { String(cString: $0) } ?? String(cString: sqlite3_errmsg(db)) + if let e = errMsg { sqlite3_free(e) } + log("sqlite3_load_extension failed rc=\(rc): \(message)") + } else { + loaded = true + log("sqlite3_load_extension succeeded.") + } + + // Optionally disable further extension loading + _ = sqlite3_enable_load_extension(db, 0) + } else { + log("Skipping load: extension file not found in bundle.") + } + + // Run SELECT cloudsync_version() and log the result + if loaded { + let sql = "SELECT cloudsync_version()" + log("Running query: \(sql)") + var stmt: OpaquePointer? + rc = sqlite3_prepare_v2(db, sql, -1, &stmt, nil) + if rc != SQLITE_OK { + let msg = String(cString: sqlite3_errmsg(db)) + log("sqlite3_prepare_v2 failed (\(rc)): \(msg)") + } else { + defer { sqlite3_finalize(stmt) } + rc = sqlite3_step(stmt) + if rc == SQLITE_ROW { + if let cstr = sqlite3_column_text(stmt, 0) { + let version = String(cString: cstr) + log("cloudsync_version(): \(version)") + } else { + log("cloudsync_version(): (null)") + } + } else if rc == SQLITE_DONE { + log("cloudsync_version() returned no rows") + } else { + let msg = String(cString: sqlite3_errmsg(db)) + log("sqlite3_step failed (\(rc)): \(msg)") + } + } + } else { + log("Extension not loaded; skipping cloudsync_version() query.") + } + + if let db { sqlite3_close(db) } + log("Done.") + } + } + + @MainActor + private func log(_ line: String) { + statusLines.append(line) + } +} + +#Preview { + ContentView() +} +``` + +## Expected Results + +When you run the test app, you should see status messages in the UI indicating: + +- Database connection success +- Extension loading status +- CloudSync version information (if successfully loaded) + +This confirms that CloudSync is properly integrated and functional in your Swift project. + +## Usage Example + +Check out the Swift Multiplatform app for a complete implementation of using the SQLite CloudSync extension to sync data across devices. diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/linux.md b/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/linux.md new file mode 100644 index 0000000..516e07e --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/linux.md @@ -0,0 +1,66 @@ +--- +title: Linux Quick Start +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-quick-start-linux +--- + +SQLite on Linux supports dynamic extension loading via `.so` shared libraries. + +This guide walks through how to load an extension named `cloudsync.so` on common Linux distributions via SQLite3 Command Line. + +--- + +## 1. Install SQLite (Per Distribution) + +### Ubuntu / Debian + +```bash +sudo apt install sqlite3 +``` + +### Fedora + +```bash +sudo dnf install sqlite +``` + +### Arch Linux + +```bash +pacman -Sy sqlite3 +``` + +### Alpine Linux + +```bash +apk add sqlite +``` + +## 2. Download the Extension + +Go to sqlite-sync releases and download the extension. + +> For Alpine Linux: ensure to download the extension specifically for `musl-x86_64` or `musl-arm64` targets. + +## 3. Load Extension from CLI + +```bash +sqlite3 +``` + +```sql +.load ./cloudsync.so +SELECT cloudsync_version(); +``` + +--- + +## Troubleshooting + +| Problem | Solution | +| -------------------------------------------- | ----------------------------------------------------------------- | +| `no such file or directory` | Ensure path to `.so` is correct and matches your platform. | +| `incompatible architecture` | Download extension for your Linux system (e.g., x86_64 vs arm64). | +| `Failed to load extension: symbol not found` | Download the extension for `musl-x86_64` or `musl-arm64` targets | diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/macos.md b/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/macos.md new file mode 100644 index 0000000..66a8553 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/macos.md @@ -0,0 +1,107 @@ +--- +title: "MacOS Quick Start Guide" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-quick-start-macos +--- + +This guide explains how to install SQLite on macOS with support for loading extensions. + +## macOS and xcframework + +On recent versions of macOS, the recommended way to load a SQLite extension is through the .xcframework approach, the same method used on iOS. + +## macOS and dylib + +On macOS, dynamic libraries (`.dylib`) can be loaded at runtime using SQLite’s `sqlite3_load_extension` API. + +### Step 1: Add Bridging Header (if using Swift only) + +Create a `bridging-header.h` file: + +```c +#include +``` + +Set it in your Xcode project under **Build Settings → Objective-C Bridging Header**. + +### Step 2: Swift Code to Load Extension + +```swift +import Foundation +import SQLite3 + +let dbPath = ":memory:" // or a real file path +var db: OpaquePointer? + +if sqlite3_open(dbPath, &db) != SQLITE_OK { + fatalError("Failed to open database") +} + +// Enable loading extensions +if sqlite3_enable_load_extension(db, 1) != SQLITE_OK { + let err = String(cString: sqlite3_errmsg(db)) + fatalError("Enable extension loading failed: \(err)") +} + +// Load the extension +let extensionPath = Bundle.main.path(forResource: "my_extension", ofType: "dylib")! +if sqlite3_load_extension(db, extensionPath, nil, nil) != SQLITE_OK { + let err = String(cString: sqlite3_errmsg(db)) + fatalError("Extension loading failed: \(err)") +} + +print("Extension loaded successfully.") +``` + +> ⚠️ Gatekeeper may block unsigned `.dylib` files. You might need to codesign or use `spctl --add`. + +## Python on macOS + +The default Python on macOS doesn't support loading SQLite extensions. +Install Python from the official package or use Homebrew Python instead: + +```bash +brew install python +``` + +Verify that you are using the Homebrew-installed `python3` by running: + +```bash +which python3 + +# /opt/homebrew/bin/python3 +``` + +After installing Python with Homebrew, the `python` command now uses the Homebrew version. +You can now load SQLite extensions in Python as shown here. + +```python +import sqlite3 +import os + +# Path to your compiled extension (.dylib for macOS/iOS) +EXTENSION_PATH = os.path.abspath("cloudsync") + +# Connect to SQLite and enable extension loading +conn = sqlite3.connect(":memory:") +conn.enable_load_extension(True) + +# Load the extension +try: + conn.load_extension(EXTENSION_PATH) + print("Extension loaded successfully.") +except sqlite3.OperationalError as e: + print(f"Failed to load extension: {e}") + +conn.enable_load_extension(False) + +# Optionally test it (e.g., call a custom SQL function) +cursor = conn.execute("SELECT cloudsync_version();") +print(cursor.fetchone()) +``` + +## Usage Example + +Check out the Swift Multiplatform app for a complete implementation of using the SQLite CloudSync extension to sync data across devices. diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/react-native-expo.md b/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/react-native-expo.md new file mode 100644 index 0000000..fe9c73e --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/react-native-expo.md @@ -0,0 +1,169 @@ +--- +title: "React Native - Expo Quick Start Guide" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-quick-start-expo +--- + +This guide shows how to integrate CloudSync extensions in Expo and React Native applications using OP-SQLite. + +## Getting Started + +Before setting up SQLite extensions, you'll need to create and initialize your project: + +### Create a New Expo Project + +```bash +# Create a new project +npx create-expo-app MyApp + +# Or use our pre-configured template with SQLite extensions +npx create-expo-app MyApp --template @sqliteai/todoapp +``` + +### Initialize for Native Code + +Since SQLite extensions require native code, you must initialize your project: + +```bash +cd MyApp +npx expo prebuild +``` + +> **Important**: This setup requires native code generation. Run `npx expo prebuild` after any changes to native dependencies or extension files. + +## Android Setup + +### Step 1: Download Android Extension + +1. Go to sqlite-sync releases +2. Download your preferred .zip architecture releases: + - arm64-v8a - Modern 64-bit ARM devices (recommended for most users) + - x86_64 - 64-bit x86 emulators and Intel-based devices + +### Step 2: Place Extension Files + +Extract the `.so` files in the following directory structure: + +``` +/android + /app + /src + /main + /jniLibs + /arm64-v8a + cloudsync.so + /x86_64 + cloudsync.so +``` + +> **Note:** Create the `jniLibs` directory structure if it doesn't exist. + +## iOS Setup + +### Step 1: Download iOS Extension + +1. Go to sqlite-sync releases +2. Download the `cloudsync-apple-xcframework-*.zip` +3. Extract `CloudSync.xcframework` + +### Step 2: Add Framework to Project + +1. Place the framework in your project: + + ``` + /ios + /[app-name] + /Frameworks + /CloudSync.xcframework + ``` + +2. **Open Xcode:** + + - Open Existing Project → Select your Expo app's `ios` folder + - Click on your app name (top left, with Xcode logo) + +3. **Configure Target:** + + - Go to **Targets** → **[app-name]** → **General** tab + - Scroll down to **"Frameworks, Libraries, and Embedded Content"** + - Click **"+"** → **"Add Other…"** → **"Add Files…"** + - Select `/ios/[app-name]/Frameworks/CloudSync.xcframework` + +4. **Set Embed Options:** + + - Ensure the **"Embed"** column shows either: + - **"Embed & Sign"** (recommended) + - **"Embed Without Signing"** + +5. **Verify Build Phases:** + + - Go to **"Build Phases"** tab + - Check that **"Embed Frameworks"** section contains **CloudSync** + +6. Close Xcode + +## Install OP-SQLite + +### For React Native: + +```bash +npm install @op-engineering/op-sqlite +npx pod-install +``` + +### For Expo: + +```bash +npx expo install @op-engineering/op-sqlite +npx expo prebuild +``` + +## Implementation + +### Basic Setup + +```javascript +import { getDylibPath, open } from "@op-engineering/op-sqlite"; +import { Platform } from "react-native"; + +// Open database connection +const db = open({ name: "to-do-app" }); +``` + +### Load Extension + +```javascript +const loadCloudSyncExtension = async () => { + let extensionPath; + + console.log("Loading CloudSync extension..."); + + try { + if (Platform.OS === "ios") { + extensionPath = getDylibPath("ai.sqlite.cloudsync", "CloudSync"); + } else { + extensionPath = "cloudsync"; + } + + // Load the extension + db.loadExtension(extensionPath); + + // Verify extension loaded successfully + const version = await db.execute("SELECT cloudsync_version();"); + console.log( + `CloudSync extension loaded successfully, version: ${version.rows[0]["cloudsync_version()"]}` + ); + + return true; + } catch (error) { + console.error("Error loading CloudSync extension:", error); + return false; + } +}; +``` + +## Usage Example + +Check out the Expo to-do-app for comprehensive usage examples and best practices. diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/wasm.md b/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/wasm.md new file mode 100644 index 0000000..18c84d4 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/wasm.md @@ -0,0 +1,100 @@ +--- +title: "WASM Quick Start Guide" +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-quick-start-wasm +--- + +1. Install the WebAssembly (WASM) version of SQLite with the SQLite Sync extension enabled from npm: + + ```bash + npm install @sqliteai/sqlite-wasm + ``` + +2. Create an HTML file that imports the SQLite WASM module using an import map and references the JavaScript loader: + + ```html + + + + + + SQLite WASM Extension Example + + +

    SQLite WASM with SQLite Sync Example

    +

    Open the directory in the terminal and type: npx serve .

    +

    Check the browser console for output.

    + + + + + + ``` + +3. Create the JavaScript file (load_extension.js) that initializes the SQLite WASM worker and verifies the extension is loaded: + + ```javascript + /** + * This example uses the package `@sqliteai/sqlite-wasm`. + * This version of SQLite WASM is bundled with SQLite Sync and SQLite Vector extensions. + * Extensions cannot be loaded at runtime in the browser environment. + * + * Run: `npx serve .` + */ + + import { sqlite3Worker1Promiser } from '@sqliteai/sqlite-wasm'; + + const log = console.log; + const error = console.error; + + const initializeSQLite = async () => { + try { + log('Loading and initializing SQLite3 module with sqlite-sync extension...'); + + const promiser = await new Promise((resolve) => { + const _promiser = sqlite3Worker1Promiser({ + onready: () => resolve(_promiser), + }); + }); + + const configResponse = await promiser('config-get', {}); + log('Running SQLite3 version', configResponse.result.version.libVersion); + + const openResponse = await promiser('open', { + filename: 'file:mydb.sqlite3', + }); + const { dbId } = openResponse; + + await promiser('exec', { + dbId, + sql: 'SELECT cloudsync_version();', // or vector_version() + callback: (result) => { + if (!result.row) { + return; + } + log('Include SQLite Sync version: ', result.row[0]); + } + }); + + } catch (err) { + if (!(err instanceof Error)) { + err = new Error(err.result.message); + } + error(err.name, err.message); + } + }; + + initializeSQLite(); + ``` + +## Usage Example + +Check out the React/Vite app for a complete implementation of using the SQLite CloudSync extension to sync data across devices. diff --git a/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/windows.md b/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/windows.md new file mode 100644 index 0000000..1397ad9 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-sync/quick-starts/windows.md @@ -0,0 +1,227 @@ +--- +title: Windows Quick Start +description: SQLite Sync is a multi-platform extension that brings a true local-first experience to your applications with minimal effort. +category: platform +status: publish +slug: sqlite-sync-quick-start-windows +--- + +This guide explains how to install SQLite on Windows with support for loading extensions. + +## Using SQLite with Python + +1. **Download Python** + + Get the latest Python for Windows from python.org. + +2. **Install Python** + + - Run the installer. + - Make sure to check **"Add Python to PATH"**. + - SQLite comes bundled with Python, no extra steps needed. + +3. **Check your installation** + Open Command Prompt and run: + + ```bash + python --version + python -c "import sqlite3; print('SQLite version:', sqlite3.sqlite_version)" + ``` + +4. **Download the Extension** + + Go to sqlite-sync releases and download the extension. + +5. **Load Extension** + ```python + import sqlite3 + import os + + # Path to your compiled extension (.dll for Windows) + EXTENSION_PATH = os.path.abspath("cloudsync") + + # Connect to SQLite and enable extension loading + conn = sqlite3.connect(":memory:") + conn.enable_load_extension(True) + + # Load the extension + try: + conn.load_extension(EXTENSION_PATH) + print("Extension loaded successfully.") + except sqlite3.OperationalError as e: + print(f"Failed to load extension: {e}") + + conn.enable_load_extension(False) + + # Optionally test it (e.g., call a custom SQL function) + cursor = conn.execute("SELECT cloudsync_version();") + print(cursor.fetchone()) + ``` + +## Using SQLite with C# + +This guide shows how to load a native SQLite extension (e.g., **`cloudsync.dll`**) from a C# app on **Windows** using **`Microsoft.Data.Sqlite`**. + +### Prerequisites + +- Windows x64 +- .NET 6+ SDK +- NuGet package manager +- The native extension file: `cloudsync.dll` (x64 build) - download from sqlite-sync releases + +> **Important:** Your app, `e_sqlite3.dll` (bundled by `Microsoft.Data.Sqlite`), and `cloudsync.dll` must all be the **same architecture** (typically x64). + +--- + +### 1. Install the SQLite package + +Install the `Microsoft.Data.Sqlite` NuGet package: + +```bash +dotnet add package Microsoft.Data.Sqlite +``` + +### 2. Set up your project structure + +Place `cloudsync.dll` in your project and configure it to copy to the output folder. + +Example directory structure: + +``` +MyApp/ + Program.cs + Native/ + cloudsync.dll + MyApp.csproj +``` + +Configure your `MyApp.csproj` file: + +```xml + + + Exe + net8.0 + enable + enable + + + + + + + + + + PreserveNewest + + + +``` + +### 3. Load the extension in your code + +Create your `Program.cs` file to initialize SQLite and load the extension: + +```csharp +using System; +using Microsoft.Data.Sqlite; + +class Program +{ + static void Main() + { + // Configure the database connection + var cs = new SqliteConnectionStringBuilder + { + DataSource = "example.db", + Mode = SqliteOpenMode.ReadWriteCreate + }.ToString(); + + using var conn = new SqliteConnection(cs); + conn.Open(); + + // Enable extension loading + conn.EnableExtensions(); + + // Load the native extension (DLL must be next to the EXE or on PATH) + // You can pass an absolute path if you prefer + conn.LoadExtension("cloudsync"); + + // Verify SQLite is working + using var cmd = conn.CreateCommand(); + cmd.CommandText = "SELECT sqlite_version();"; + Console.WriteLine("SQLite version: " + cmd.ExecuteScalar()); + + // Verify the extension is loaded + cmd.CommandText = "SELECT cloudsync_version();"; + Console.WriteLine("cloudsync_version(): " + cmd.ExecuteScalar()); + } +} +``` + +### 4. Run your application + +Build and run your application: + +```bash +dotnet build +dotnet run +``` + +You should see output similar to: + +``` +SQLite version: 3.45.0 +cloudsync_version(): 1.0.0 +``` + +#### Extension search locations + +SQLite searches for extensions in this order: + +1. Process working directory +2. Application base directory (where your .exe lives) +3. PATH environment variable directories +4. Full path provided to `LoadExtension(...)` + +> **Tip:** For most apps, simply copying the DLL to the output folder (next to your .exe) is sufficient. + +--- + +### Common issues and solutions + +**SqliteException: not authorized** + +- **Cause:** Extension loading not enabled +- **Fix:** Call `conn.EnableExtensions()` before loading + +**SqliteException: The specified module could not be found** + +- **Cause:** DLL not in search path or missing dependencies +- **Fix:** Place DLL next to .exe, use absolute path, or ensure dependencies are available + +**BadImageFormatException** + +- **Cause:** Architecture mismatch (e.g., mixing x86 and x64) +- **Fix:** Ensure app, `e_sqlite3.dll`, and `cloudsync.dll` are all the same architecture + +**EntryPointNotFoundException** + +- **Cause:** DLL is not a valid SQLite extension +- **Fix:** Verify the extension exports `sqlite3_extension_init` + +**Windows "blocked" DLL** + +- **Cause:** Downloaded DLL is blocked by Windows +- **Fix:** Right-click → Properties → Check "Unblock" → OK + +--- + +### Deployment + +When publishing your app, ensure the extension is included: + +```bash +dotnet publish -c Release -r win-x64 --self-contained false +``` diff --git a/sqlite-cloud/sqlite-ai/sqlite-vector.mdx b/sqlite-cloud/sqlite-ai/sqlite-vector.mdx new file mode 100644 index 0000000..fce48c8 --- /dev/null +++ b/sqlite-cloud/sqlite-ai/sqlite-vector.mdx @@ -0,0 +1,13 @@ +--- +title: SQLite-Vector +description: SQLite Cloud is a distributed relational database system built on top of the SQLite database engine. +category: platform +status: publish +slug: sqlite-vector +--- + +SQLite-Vector is a cross-platform, ultra-efficient SQLite extension that brings vector search capabilities directly into your embedded database + +Whether you're dealing with **millions of high-dimensional vectors** or operating on resource-constrained edge devices, SQLite-Vector delivers **lightning-fast performance** with a **tiny memory footprint**. + +**SQLite-Vector** is an open-source project available on GitHub. \ No newline at end of file diff --git a/sqlite-cloud/test-wrapper-multi.mdx b/sqlite-cloud/test-wrapper-multi.mdx new file mode 100644 index 0000000..3ad8132 --- /dev/null +++ b/sqlite-cloud/test-wrapper-multi.mdx @@ -0,0 +1,19 @@ +--- +title: Multi Code Component Examples +description: Multi Code Component Examples +slug: wrapper-multicode +category: getting-started +status: draft +--- +import ReactCodeExample from "@docs-website-assets/code-examples/ReactCodeExample.astro"; + + + + + + + + + + + diff --git a/sqlite-cloud/tutorials/tutorial-geopoly.mdx b/sqlite-cloud/tutorials/tutorial-geopoly.mdx new file mode 100644 index 0000000..0c75a9e --- /dev/null +++ b/sqlite-cloud/tutorials/tutorial-geopoly.mdx @@ -0,0 +1,827 @@ +--- +title: Using SQLite Extensions - Geopoly +description: Build a local attractions finder app using SQLite Cloud, SQLite's built-in Geopoly extension, Mapbox, and React. +category: getting-started +status: publish +slug: tutorial-geopoly +--- + +In this tutorial you will build a local attractions finder map-plication using GeoJSON data, a SQLite Cloud database, Mapbox GL JS (JavaScript Graphics Library), React, and SQLite's built-in Geopoly extension. + +**Time to complete: 15-20 mins.** + +If you get stuck in the tutorial or prefer to play with the finished product, check out the example app on GitHub. + +--- + +**1. Initialize your app** + - Create a new directory `sqlc-geopoly-demo`. From this directory, bootstrap a Node.js project. + +```bash +mkdir sqlc-geopoly-demo +cd sqlc-geopoly-demo +npm init -y +``` + +**2. Curate your GeoJSON data** + + - We will leverage the Overpass API (an open-source, read-only API for fetching OpenStreetMap data) to query NY attractions. + + - Visit Overpass Turbo, the Overpass GUI. Copy and paste in the below query, which: + - defines New York as the area of interest; + - fetches nodes in the specified area that are tagged with the keys `amenity`, `historic`, `tourism`, `leisure`, etc.; and + - outputs the data. + +```c +[out:json][timeout:25]; + +area[name="New York"]->.newyork; + +( + node["amenity"="events_venue"](area.newyork); + node["amenity"="exhibition_centre"](area.newyork); + node["amenity"="music_venue"](area.newyork); + node["amenity"="social_centre"](area.newyork); + node["amenity"="marketplace"](area.newyork); + node["building"="museum"](area.newyork); + node["historic"="building"](area.newyork); + node["tourism"="attraction"](area.newyork); + node["leisure"="park"](area.newyork); + node["natural"="beach"](area.newyork); + node["shop"="coffee"](area.newyork); + node["sport"="yoga"](area.newyork); +); + +out body; +>; +out skel qt; +``` + + - Run the query. + + - Click Export. Under Data, copy the GeoJSON. + + - Back in your project dir, create `data/geodata.json`. Paste the formatted GeoJSON into the file. It should look similar to the following: + +```json +{ + "type": "FeatureCollection", + "generator": "overpass-turbo", + "copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL.", + "timestamp": "2024-08-05T23:56:57Z", + "features": [ + { + "type": "Feature", + "properties": { + "@id": "node/43058007", + "ele": "190", + "gnis:feature_id": "968527", + "leisure": "park", + "name": "Kibler Park" + }, + "geometry": { + "type": "Point", + "coordinates": [-78.6723302, 43.1655945] + }, + "id": "node/43058007" + }, + ..., + { + "type": "Feature", + "properties": { + "@id": "node/12093603396", + "amenity": "events_venue", + "name": "Azteca Venue Party Center" + }, + "geometry": { + "type": "Point", + "coordinates": [-74.1244477, 40.6338683] + }, + "id": "node/12093603396" + } + ] +} +``` + - For this tutorial, we'll use the NY geodata. Once you have the app up-and-running, you can run your own Overpass queries to customize the geodata per your needs. See **Additional Guidance on Overpass** at the end of this tutorial. + +**3. Create a new SQLite Cloud database** + + - If you haven't already, sign up for a SQLite Cloud account and create a new project. + + - In your account dashboard's left nav, click Databases, then Create Database. Name your new database `geopoly-demo`. + +**4. Create a Mapbox account** + + - Sign up for an Individual Mapbox account. (We'll stay on the free tier.) + +**5. Set your environment variables** + + - In your project dir, create a `.env` file. + - This app will use `react-scripts`, which leverages Create React App under-the-hood. Create React App offers built-in support for env vars. You will not need to manually configure `webpack` or another bundler, but all vars will need to be prefixed with `REACT_APP_`. + + - Add 2 env vars to the file: + - `REACT_APP_CONNECTION_STRING`. Copy and paste your connection string from your SQLite Cloud account dashboard. + - `REACT_APP_MAPBOX_TOKEN`. In your Mapbox account dashboard's nav, click Tokens. Copy and paste your default public token. + + - Install the SQLite Cloud JS SDK and `dotenv` package as dependencies: + +```bash +npm i @sqlitecloud/drivers +npm i -D dotenv +``` + +**6. Create your database tables** + + - In your project dir, create `src/helpers/createDatabase.js`. Copy and paste in the following code: + +```js +import { Database } from '@sqlitecloud/drivers'; +import 'dotenv/config'; +import geodata from '../../data/geodata.json' assert { type: 'json' }; + +async function createDatabase() { + // open a connection to your `geopoly-demo` database + const db = new Database(process.env.REACT_APP_CONNECTION_STRING); + + const db_name = 'geopoly-demo'; + await db.sql`USE DATABASE ${db_name};`; + + // create a table with 2 columns: `rowid` and `_shape` + await db.sql`CREATE VIRTUAL TABLE polygons USING geopoly()`; + + // create a table with 5 columns: `id`, `name`, `lng`, `lat`, and `coordinates` + await db.sql`CREATE TABLE attractions (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, lng REAL NOT NULL, lat REAL NOT NULL, coordinates TEXT NOT NULL)`; + + // populate the `attractions` table using the GeoJSON FeatureCollection in `geodata.json` + for (const feature of geodata['features']) { + const { name } = feature.properties; + const { coordinates } = feature.geometry; + const [lng, lat] = coordinates; + + await db.sql`INSERT INTO attractions(name, lng, lat, coordinates) VALUES(${name}, ${lng}, ${lat}, ${JSON.stringify( + coordinates + )})`; + } + + db.close(); + + console.log('Geodata inserted!'); +} + +createDatabase(); +``` + + - Add the following to your `package.json`: + +```json +"scripts": { + "create-tables": "node src/helpers/createDatabase.js" +}, +"type": "module", +``` + + - Run `npm run create-tables`. + + - The time it will take for the command to finish creating the tables and inserting the geodata will depend on the size of your FeatureCollection. The NY Overpass query returns ~2000 Point features, so row insertion takes a couple of minutes. + + - To see the inserted NY attractions geodata, in your SQLite Cloud account dashboard's left nav, click Console. In the database dropdown, select `geopoly-demo`. Copy, paste in, and run the following query: + +```sql +SELECT * FROM attractions ORDER BY id DESC; +``` + +**7. Set up the frontend** + + - In your project dir, create `public/index.html`. Copy and paste in the following code: + +```html + + + + + + + Local Attractions Finder + + + +
    + + +``` + + - In the `src` dir, add 3 files: `index.css` (for app styling), `index.js` (the app entrypoint file), and `App.js` (the app's sole component). Copy and paste in the following code for each file: + +`index.css` +```css +@import url('https://fonts.googleapis.com/css2?family=Inter+Tight:wght@100..900&display=swap'); + +* { + box-sizing: border-box; +} + +body { + margin: 0; + padding: 0; + font: 400 15px/22px 'Inter Tight', sans-serif; + -webkit-font-smoothing: antialiased; +} + +.legend { + padding: 10px; + background-color: #23374b; + color: #fff; + font-family: monospace; +} + +.sidebar { + position: absolute; + width: 25%; + height: 100%; + overflow: hidden; +} + +.map-container { + position: absolute; + left: 25%; + width: 75%; + top: 0; + bottom: 0; +} + +.heading { + padding: 0 10px; + border-bottom: 1px solid #eee; +} + +.listings { + height: 72%; + overflow: auto; + padding-bottom: 15px; +} + +.listings .item { + padding: 10px; + border-bottom: 1px solid #eee; +} + +.listings .item.active { + background-color: #cfe1f8; +} + +.listings .item:last-child { + border-bottom: none; +} + +.listings .item .title { + color: #5a5877; + font-weight: 700; + text-decoration: none; +} + +.listings .item.active .title, +.listings .item .title:hover { + color: #000; +} + +::-webkit-scrollbar { + width: 5px; +} + +::-webkit-scrollbar-track { + background: none; +} + +::-webkit-scrollbar-thumb { + background: #23374b; +} + +.mapboxgl-popup { + padding-bottom: 20px; +} + +.mapboxgl-popup-close-button { + display: none; +} + +.mapboxgl-popup-content { + padding: 0; +} + +.mapboxgl-popup-content h3 { + background: #cfe1f8; + color: #000; + margin: 0; + padding: 10px; + border-radius: 3px 3px 0 0; + font-weight: 700; + margin-top: -15px; +} + +.mapboxgl-popup-content h4 { + margin: 0; + padding: 10px; + font-weight: 400; +} + +.marker { + border: none; + cursor: pointer; + width: 32px; + height: 40px; + background-image: url('https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png'); +} + +.mapboxgl-ctrl-geocoder { + border: 0; + border-radius: 0; + position: relative; + top: 0; + width: 800px; + margin-top: 0; +} + +.mapboxgl-ctrl-geocoder > div { + min-width: 100%; + margin-left: 0; +} +``` + + - NOTE: To simplify this tutorial, `.marker.background-image` uses a custom Mapbox marker for the pins marking attractions on the map. The example app on GitHub uses a custom marker image included in the repo's `images` dir (excluded here). + +`index.js` +```js +import React from 'react'; +import { createRoot } from 'react-dom/client'; +import 'mapbox-gl/dist/mapbox-gl.css'; +import './index.css'; +import App from './App.js'; + +const container = document.querySelector('#root'); +const root = createRoot(container); +root.render( + + + +); +``` + +`App.js` +```js +import { useState, useEffect, useRef } from 'react'; +import mapboxgl from 'mapbox-gl'; +import '@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css'; +import MapboxGeocoder from '@mapbox/mapbox-gl-geocoder'; +import { point, distance } from '@turf/turf'; +import { Database } from '@sqlitecloud/drivers'; +import { getBbox } from './helpers/getBbox.js'; + +mapboxgl.accessToken = process.env.REACT_APP_MAPBOX_TOKEN; + +function App() { + const mapContainerRef = useRef(); + const mapRef = useRef(); + + const [lng, setLng] = useState(-73.9654897); + const [lat, setLat] = useState(40.7824635); + const [zoom, setZoom] = useState(12); + + const [places, setPlaces] = useState([]); + const [geometry, setGeometry] = useState([]); + + const units = 'miles'; + + async function queryGeopoly(searchedLng, searchedLat) { + // open a connection to your `geopoly-demo` database + const db = new Database(process.env.REACT_APP_CONNECTION_STRING); + + const db_name = 'geopoly-demo'; + + const radius = 0.05; // must be a positive number + const sides = 50; // 3-1000 + + // generate a new polygon to be added to your `polygons` table + const polygonCoords = + await db.sql`USE DATABASE ${db_name}; INSERT INTO polygons(_shape) VALUES(geopoly_regular(${searchedLng}, ${searchedLat}, ${radius}, ${sides})) RETURNING geopoly_json(_shape);`; + + // point-in-polygon query to get all attractions in the generated polygon's area + const attractionsInPolygon = + await db.sql`USE DATABASE ${db_name}; SELECT name, coordinates FROM attractions WHERE geopoly_contains_point(${polygonCoords[0]['geopoly_json(_shape)']}, lng, lat);`; + + db.close(); + + // remove unnamed attractions + const namedAttractions = attractionsInPolygon.filter( + (attraction) => attraction.name !== null + ); + + const attractionFeatures = namedAttractions.map((attraction, index) => { + const attractionCoordinates = JSON.parse(attraction['coordinates']); + + const attractionFeature = { + type: 'Feature', + geometry: { + type: 'Point', + coordinates: attractionCoordinates, + }, + properties: { + id: index, + title: attraction['name'], + // use Turf.js to calculate the distance between the searched location and the current attraction + distance: distance( + point([searchedLng, searchedLat]), + point(attractionCoordinates), + { + units, // either miles or kilometers + } + ), + }, + }; + + // apply clickable markers for all attractions + const marker = document.createElement('div'); + marker.key = `marker-${attractionFeature.properties.id}`; + marker.id = `marker-${attractionFeature.properties.id}`; + marker.className = 'marker'; + + marker.addEventListener('click', (e) => { + handleClick(attractionFeature); + }); + + new mapboxgl.Marker(marker) + .setLngLat(attractionCoordinates) + .addTo(mapRef.current); + + return attractionFeature; + }); + + // upsort attractions nearest the user's searched location + attractionFeatures.sort((a, b) => { + if (a.properties.distance > b.properties.distance) { + return 1; + } + if (a.properties.distance < b.properties.distance) { + return -1; + } + return 0; + }); + + setPlaces(attractionFeatures); + + // use a helper function (defined in the next step) to fit/ zoom the map view to the searched location and its nearest attraction + if (attractionFeatures[0]) { + const bbox = getBbox(attractionFeatures, searchedLng, searchedLat); + mapRef.current.fitBounds(bbox, { + padding: 100, + }); + + new mapboxgl.Popup({ closeOnClick: false }) + .setLngLat(attractionFeatures[0].geometry.coordinates) + .setHTML( + `

    ${ + attractionFeatures[0].properties.title + }

    ${attractionFeatures[0].properties.distance.toFixed( + 2 + )} ${units} away

    ` + ) + .addTo(mapRef.current); + } + + // update the `geometry` state to hold the returned Polygon and attraction Point features + setGeometry([ + { + type: 'Feature', + geometry: { + type: 'Polygon', + coordinates: [JSON.parse(polygonCoords[0]['geopoly_json(_shape)'])], + }, + }, + ...attractionFeatures, + ]); + } + + function drawFeatureCollection() { + const sourceId = 'newyork'; + + if (!mapRef.current.getSource(sourceId)) { + mapRef.current.addSource(sourceId, { + type: 'geojson', + data: { + type: 'FeatureCollection', + features: geometry, + }, + }); + + mapRef.current.addLayer({ + id: 'polygon', + type: 'fill', + source: sourceId, + paint: { + 'fill-color': '#888888', + 'fill-opacity': 0.4, + }, + filter: ['==', '$type', 'Polygon'], + }); + + mapRef.current.addLayer({ + id: 'outline', + type: 'line', + source: sourceId, + layout: {}, + paint: { + 'line-color': '#000', + 'line-width': 1, + }, + }); + } else { + mapRef.current.getSource(sourceId).setData({ + type: 'FeatureCollection', + features: geometry, + }); + } + } + + function handleClick(feature) { + const center = feature.geometry.coordinates; + const { id, title, distance } = feature.properties; + + mapRef.current.flyTo({ + center, + zoom: 15, + }); + + const popUps = document.getElementsByClassName('mapboxgl-popup'); + if (popUps[0]) { + popUps[0].remove(); + } + + new mapboxgl.Popup({ closeOnClick: false }) + .setLngLat(center) + .setHTML(`

    ${title}

    ${distance.toFixed(2)} ${units} away

    `) + .addTo(mapRef.current); + + const activeItem = document.getElementsByClassName('active'); + if (activeItem[0]) { + activeItem[0].classList.remove('active'); + } + + const listing = document.getElementById(`listing-${id}`); + listing.classList.add('active'); + } + + useEffect(() => { + // create, style, and center the map + mapRef.current = new mapboxgl.Map({ + container: mapContainerRef.current, + style: 'mapbox://styles/mapbox/streets-v12', + center: [lng, lat], + zoom, + }); + + // apply 3 controls to the top right of the map + // an address search input + const geocoder = new MapboxGeocoder({ + accessToken: mapboxgl.accessToken, + mapboxgl, + zoom: 12, + }); + + // toggle fullscreen mode + const fullscreenCtrl = new mapboxgl.FullscreenControl({ + container: mapContainerRef.current, + }); + + // locate the user on the map + const geolocateCtrl = new mapboxgl.GeolocateControl({ + fitBoundsOptions: { + maxZoom: 12, + }, + positionOptions: { + enableHighAccuracy: true, + }, + trackUserLocation: true, + }); + + mapRef.current.addControl(geocoder); + mapRef.current.addControl(fullscreenCtrl); + mapRef.current.addControl(geolocateCtrl); + + // track the map center coordinates and zoom level (displayed on the top left of the app) + function updateCoordinates() { + const { lng, lat } = mapRef.current.getCenter(); + setLng(lng.toFixed(4)); + setLat(lat.toFixed(4)); + setZoom(mapRef.current.getZoom().toFixed(2)); + } + + mapRef.current.on('move', updateCoordinates); + + // call the `queryGeopoly` function when the user clicks a geocoder result + geocoder.on('result', (e) => { + const existingMarkers = document.getElementsByClassName('marker'); + while (existingMarkers[0]) { + existingMarkers[0].remove(); + } + + const popUps = document.getElementsByClassName('mapboxgl-popup'); + while (popUps[0]) { + popUps[0].remove(); + } + + const [lng, lat] = e.result.geometry.coordinates; + queryGeopoly(lng, lat); + }); + + return () => { + mapRef.current.removeControl(geocoder); + mapRef.current.removeControl(fullscreenCtrl); + mapRef.current.removeControl(geolocateCtrl); + mapRef.current.off('move', updateCoordinates); + mapRef.current.remove(); + }; + }, []); // eslint-disable-line react-hooks/exhaustive-deps + + // triggered by a `geometry` state update + useEffect(() => { + if (geometry.length !== 0) { + // draw the returned Polygon, its outline, and attraction Points on the map + drawFeatureCollection(); + } + }, [geometry]); // eslint-disable-line react-hooks/exhaustive-deps + + return ( + <> +
    +
    +

    Center Lat: {lat}

    +

    Center Long: {lng}

    +

    Current Zoom: {zoom}

    +
    +
    +

    Attractions Nearby:

    +
    + +
    + {places.map((place, index) => ( +
    + handleClick(place)}> + {place.properties.title} + +
    + {place.properties.distance.toFixed(2)} {units} away +
    +
    + ))} +
    +
    +
    + + ); +} + +export default App; +``` + +**8. Create a helper function** + + - Create `src/helpers/getBbox.js`. Copy and paste in the following code: + +```js +export function getBbox(sortedEvents, locationLng, locationLat) { + const lons = [ + sortedEvents[0].geometry.coordinates[0], + locationLng, + ]; + const lats = [ + sortedEvents[0].geometry.coordinates[1], + locationLat, + ]; + const sortedLons = lons.sort((a, b) => { + if (a > b) { + return 1; + } + if (a.distance < b.distance) { + return -1; + } + return 0; + }); + const sortedLats = lats.sort((a, b) => { + if (a > b) { + return 1; + } + if (a.distance < b.distance) { + return -1; + } + return 0; + }); + + // return a bounding box, defined by a southwest coordinate pair and northeast coordinate pair + return [ + [sortedLons[0], sortedLats[0]], + [sortedLons[1], sortedLats[1]], + ]; +} +``` + +**9. Run your app!** + + - Replace your `package.json` code with the following, which includes all dependencies needed to run the app: + +```json +{ + "name": "sqlc-geopoly-demo", + "version": "1.0.0", + "private": true, + "description": "", + "main": "index.js", + "scripts": { + "start": "react-scripts start", + "build": "react-scripts build", + "create-tables": "node src/helpers/createDatabase.js" + }, + "eslintConfig": { + "extends": [ + "react-app" + ] + }, + "browserslist": [ + "defaults", + "not ie 11" + ], + "author": "", + "license": "ISC", + "type": "module", + "dependencies": { + "@mapbox/mapbox-gl-geocoder": "^5.0.2", + "@sqlitecloud/drivers": "^1.0.193", + "@turf/turf": "^7.0.0", + "mapbox-gl": "^3.5.2", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-scripts": "^5.0.1" + }, + "devDependencies": { + "@babel/plugin-proposal-private-property-in-object": "^7.21.11", + "dotenv": "^16.4.5" + } +} +``` + + - From your project dir, install the dependencies and start your local dev server. + +```bash +npm i +npm start +``` + + - Visit `http://localhost:3000/` (adjust the port as-needed) in your browser to view the app. + +**10. Find attractions!** + + - On app load, the map is centered on Central Park, NY. + + - In the geocoder (i.e. search input) at the top right of the map, enter "Empire" and click on the "Empire State Building" result. You can also search coordinates (see reverse geocoding). + + - When you select a geocoder result: + - a polygon is generated by Geopoly, added to your `polygons` table, and displayed on the map; and + + - all attractions in your `attractions` table inside the polygon area are listed in the left sidebar AND marked on the map. NOTE: the sidebar upsorts attractions nearest your searched location, in this case the "Empire State Building". + + - To see the inserted polygon data, in your SQLite Cloud account dashboard's left nav, click Console. In the database dropdown, select `geopoly-demo`. Copy, paste in, and run the following query. + + - The `geopoly_json` function parses the `_shape` column's `[object ArrayBuffer]` data into an array of coordinate pairs representing the polygon's vertices: `[[-73.9355,40.7485],[-73.9359,40.7547], ...,[-73.9359,40.7422],[-73.9355,40.7485]]`. The array should contain (1 + # of polygon sides) coordinate pairs. The polygon is closed, so the first and last pairs both represent the same vertex. + +```sql +SELECT rowid, geopoly_json(_shape) FROM polygons; +``` + + - The map zooms in to the nearest attraction to your searched location and highlights its corresponding top listing in the sidebar. + + - You can click on any attraction listing or marker to fly/ zoom to and center on that attraction on the map. + + - Turf.js uses the Haversine formula to account for global curvature when calculating the distance between your searched location and each attraction. However, you should still expect discrepancies between this app's calculated distances vs, say, Google or Apple Maps. + +And that’s it! You’ve successfully built a local attractions finder app that utilizes Geopoly to write geodata to and read from a SQLite Cloud database. + +### Additional Guidance on Overpass: + + - To fetch other attractions or any other kind of location data in NY or another area of interest to you, refer to OpenStreetMap's Map features documentation. As a starting point, modify the area or key-value pairs in the NY query. + + - NOTE: The app works only with Point features (represented in the Map features tables' `Element` columns by an icon with a single dot). Be sure to query only nodes and the key-value pairs that can return Point data. For example, don't use most of the values available for the Boundary key. + + - To implement more complex or granular Point queries, refer to the Overpass QL documentation. + + - If you run a custom Overpass query: + - Add to or replace the FeatureCollection in `geodata.json`. + - In your SQLite Cloud account dashboard's left nav, click Databases. In the `geopoly-demo` row, click the down chevron and then Delete Database. + - Create Database with the same name. + - From your project dir, run `npm run create-tables`. Your database tables will be re-created, and the `attractions` table will be populated with your updated geodata. + + - If you queried and stored attractions near your location, then after the app's initial load, click on the GeolocateControl icon at the top right of the map and allow the browser to quickly center the map on your location. Search away! \ No newline at end of file diff --git a/sqlite-cloud/write-data.mdx b/sqlite-cloud/write-data.mdx index 64d5acf..42e629a 100644 --- a/sqlite-cloud/write-data.mdx +++ b/sqlite-cloud/write-data.mdx @@ -3,48 +3,49 @@ title: Writing data to your database description: Learn how to write data to your SQLite Cloud cluster. category: getting-started status: publish +slug: write-data --- +import VideoPlayer from '@commons-components/Video/VideoPlayer.astro'; +import studioInsert from '@docs-website-assets/introduction/video/dashboard_studio.mp4'; After you've created a database in SQLite Cloud, you can start writing data to it. You can write data to your cluster using the SQLite Cloud UI, API, or client libraries. +--- + ## Writing data with the SQLite Cloud UI -Navigate to the console tab in the left-hand navigation. From here, you can run SQL commands against your cluster. Use the optional dropdown menus to select a database and table. +Navigate to the Studio tab from the left-hand navigation. From here, you can run SQL commands directly on your cluster. +If needed, use the dropdown menus to select the database and table where you want to insert or update data. + +Alternatively, you can also interact directly with the table view to add new records or update existing ones without writing SQL manually. + -![Dashboard Projects](@docs-website-assets/introduction/dashboard_console.png) + ### Example ```sql -- If you haven't selected a database yet, run the USE DATABASE command -USE DATABASE mydatabase.sqlite; +USE DATABASE .sqlite; -- Create your table -CREATE TABLE sports_cars (sc_id INTEGER PRIMARY KEY, sc_name TEXT NOT NULL, sc_year INTEGER NOT NULL, image BLOB); +CREATE TABLE sports_cars (sc_id INTEGER PRIMARY KEY, sc_make TEXT NOT NULL, sc_year INTEGER NOT NULL); -- Insert data into your table -INSERT INTO sports_cars (sc_name, sc_year, image) VALUES ('Ferrari', 2021, 'https://example.com/ferrari.jpg'); +INSERT INTO sports_cars (sc_make, sc_year) VALUES ('Ferrari', 2021); ``` -## Writing data with the Weblite API -You can use the SQLite Cloud API to write data to your cluster. - -To upload a local SQLite database via weblite, make a POST request to the `/v2/weblite/.sqlite` endpoint. - -```bash -curl -X 'POST' \ - 'https://.sqlite.cloud:8090/v2/weblite/.sqlite' \ - -H 'accept: application/json' \ - -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=.sqlite.cloud:8090/v2/weblite/sql' \ -H 'accept: application/json' \ -H 'Authorization: Bearer sqlitecloud://.sqlite.cloud:8860?apikey=' \ - -d '' + -d '' ``` +--- + ## Writing data with client libraries To write data to your cluster using a client library, use the INSERT INTO SQL command. @@ -52,11 +53,12 @@ To write data to your cluster using a client library, use the INSERT INTO SQL co import { Database } from '@sqlitecloud/drivers'; const db = new Database('sqlitecloud://.sqlite.cloud:?apikey=') -db.exec('USE DATABASE mydatabase.sqlite;') -db.exec('CREATE TABLE sports_cars (sc_id INTEGER PRIMARY KEY, sc_name TEXT NOT NULL, sc_year INTEGER NOT NULL, image BLOB);') +db.exec('USE DATABASE .sqlite;') +db.exec('CREATE TABLE sports_cars (sc_id INTEGER PRIMARY KEY, sc_make TEXT NOT NULL, sc_year INTEGER NOT NULL);') db.commit() -const insertData = async () => await db.sql`INSERT INTO sports_cars (sc_name, sc_year, image) VALUES ('Ferrari', 2021, 'https://example.com/ferrari.jpg');`; +const insertData = async () => await db.sql('INSERT INTO sports_cars (sc_make, sc_year) VALUES (?, ?)', 'Ferrari', 2021); insertData().then((res) => console.log(res)); // "OK" ``` + diff --git a/sqlite/json1.md b/sqlite/json1.md index 5ebf204..5085945 100644 --- a/sqlite/json1.md +++ b/sqlite/json1.md @@ -10,8 +10,8 @@ status: publish ## 1. Overview By default, SQLite supports twenty-nine functions and two operators for -dealing with JSON values. There are also two [table-valued -functions](https://sqlite.org/vtab.html#tabfunc2) that can be used to +dealing with JSON values. There are also two table-valued +functions that can be used to decompose a JSON string. There are 25 scalar functions and operators: @@ -52,7 +52,7 @@ There are four [aggregate SQL functions](lang_aggfunc.html): 3. [json_group_object](#jgroupobject)(*label*,*value*) 4. [jsonb_group_object](#jgroupobjectb)(name,*value*) -The two [table-valued functions](https://sqlite.org/vtab.html#tabfunc2) +The two table-valued functions are: 1. [json_each](#jeach)(*json*) @@ -91,11 +91,11 @@ function will usually throw an error. (Exceptions to this rule are [json_valid()](json1#jvalid), [json_quote()](json1#jquote), and [json_error_position()](json1#jerr).) -These routines understand all [rfc-8259 JSON -syntax](https://www.rfc-editor.org/rfc/rfc8259.txt) and also [JSON5 -extensions](https://spec.json5.org/). JSON text generated by these -routines always strictly conforms to the [canonical JSON -definition](https://json.org) and does not contain any JSON5 or other +These routines understand all rfc-8259 JSON +syntax and also JSON5 +extensions. JSON text generated by these +routines always strictly conforms to the canonical JSON +definition and does not contain any JSON5 or other extensions. The ability to read and understand JSON5 was added in version 3.42.0 (2023-05-16). Prior versions of SQLite would only read canonical JSON. @@ -126,7 +126,7 @@ JSONB is a binary representation of JSON used by SQLite and is intended for internal use by SQLite only. Applications should not use JSONB outside of SQLite nor try to reverse-engineer the JSONB format. -The "JSONB" name is inspired by [PostgreSQL](https://postgresql.org), +The "JSONB" name is inspired by PostgreSQL, but the on-disk format for SQLite's JSONB is not the same as PostgreSQL's. The two formats have the same name, but are not binary compatible. The PostgreSQL JSONB format claims to offer O(1) lookup of @@ -240,19 +240,19 @@ The current implementation of this JSON library uses a recursive descent parser. In order to avoid using excess stack space, any JSON input that has more than 1000 levels of nesting is considered invalid. Limits on nesting depth are allowed for compatible implementations of JSON by -[RFC-8259 section 9](https://tools.ietf.org/html/rfc8259#section-9). +RFC-8259 section 9. ## 3.6. JSON5 Extensions Beginning in version 3.42.0 (2023-05-16), these routines will read and -interpret input JSON text that includes [JSON5](https://spec.json5.org/) +interpret input JSON text that includes JSON5 extensions. However, JSON text generated by these routines will always -be strictly conforming to the [canonical definition of -JSON](https://json.org). +be strictly conforming to the canonical definition of +JSON. -Here is a synopsis of JSON5 extensions (adapted from the [JSON5 -specification](https://spec.json5.org/#introduction)): +Here is a synopsis of JSON5 extensions (adapted from the JSON5 +specification): - Object keys may be unquoted identifiers. - Objects may have a single trailing comma. @@ -699,7 +699,7 @@ is returned in the binary JSONB format. ## 4.14. The json_patch() function The json_patch(T,P) SQL function runs the -[RFC-7396](https://tools.ietf.org/html/rfc7396) MergePatch algorithm to +RFC-7396 MergePatch algorithm to apply patch P against input T. The patched copy of T is returned. MergePatch can add, modify, or delete elements of a JSON Object, and so @@ -919,8 +919,8 @@ the same except that they return their result in the binary ## 4.22. The json_each() and json_tree() table-valued functions -The json_each(X) and json_tree(X) [table-valued -functions](https://www.sqlite.org/vtab.html#tabfunc2) walk the JSON +The json_each(X) and json_tree(X) table-valued +functions walk the JSON value provided as their first argument and return one row for each element. The json_each(X) function only walks the immediate children of the top-level array or object, or just the top-level element itself if