Referência do arquivo de configuração do SQL Connect

A CLI do Firebase permite gerenciar seus projetos do Firebase em um diretório de projeto local com controle de versão. Isso inclui serviços do SQL Connect nos seus projetos, conectores para esses serviços e recursos como esquema, consulta e fontes de mutação para cada conector. A CLI também permite instalar e operar o emulador do Firebase SQL Connect. A CLI é uma alternativa eficiente para trabalhar no console do Firebase.

Para instruções sobre como instalar o experimento da CLI Firebase para o programa de pré-lançamento particular e comandos da CLI relacionados a SQL Connect, consulte a referência da CLI Firebase.

Este guia de referência documenta:

  • Entradas específicas do SQL Connect no arquivo de configuração do projeto do firebase.json.
  • Configurações de SQL Connect em dataconnect.yaml e connector.yaml.
  • Variáveis de ambiente do emulador SQL Connect.

Arquivos de configuração do projeto do Firebase

Referência de configuração do firebase.json

Use as chaves dataconnect e emulators.dataconnect no arquivo firebase.json para configurar um ou mais serviços do SQL Connect e o emulador local no seu projeto:

{
  "dataconnect": {
    "source": "dataconnect"
  },
  "emulators": {
    "dataconnect": {
      "host": "localhost",
      "port": 9399,
      "postgresPort": 5432,
      "dataDir": "dataconnect/.dataconnect/pgliteData"
    }
  }
}

O arquivo firebase.json aceita as seguintes chaves SQL Connect:

  • dataconnect: obrigatório para projetos SQL Connect. Aceita um único objeto ou uma matriz de objetos quando o projeto tem vários serviços.
    • source: obrigatório. Caminho para o diretório que contém o arquivo de serviço dataconnect.yaml.
    • predeploy e postdeploy: opcional. Strings de comando ou matrizes de comandos para executar antes ou depois de implantar recursos SQL Connect.
  • emulators.dataconnect: configuração opcional para o emulador SQL Connect.
    • host: opcional. Nome do host do emulador. O padrão é "localhost".
    • port: opcional. Porta para o emulador SQL Connect. O padrão é 9399.
    • postgresPort: opcional. Porta para o servidor PostgreSQL PGlite integrado. O padrão é 5432. Ignorado quando a variável de ambiente FIREBASE_DATACONNECT_POSTGRESQL_STRING está definida.
    • dataDir: opcional. Diretório em que o emulador mantém automaticamente os dados do banco de dados PGlite local entre as execuções. Ignorado quando a variável de ambiente FIREBASE_DATACONNECT_POSTGRESQL_STRING está definida.

Referência de configuração do dataconnect.yaml

O arquivo dataconnect.yaml armazena informações de configuração sobre os locais das origens do esquema do aplicativo, das origens do conector e das informações de conexão da fonte de dados. O arquivo também serve como um significante de diretório de projeto para a CLI Firebase.

A chave schemaValidation controla o nível de validação de esquema realizada quando os esquemas são migrados durante a implantação. Sem nenhum valor definido, no modo interativo, o comando firebase dataconnect:sql:migrate solicita que você aplique as mudanças compatíveis necessárias e, em seguida, solicita que você execute as mudanças estritas opcionais. Para o comportamento de --force e --non-interactive, consulte dataconnect:sql:migrate. Quando definido, o comportamento é o seguinte:

  • Modo STRICT O esquema do banco de dados precisa corresponder exatamente ao esquema do aplicativo antes que o esquema do aplicativo possa ser implantado. Todas as tabelas ou colunas que não forem usadas no esquema SQL Connect serão excluídas do banco de dados.
  • Modo COMPATIBLE O esquema do banco de dados precisa ser compatível com o esquema do aplicativo antes que ele possa ser implantado. Todas as outras alterações são consideradas opcionais. Compatível significa que as migrações de esquema são baseadas no esquema de aplicativo que você escreve. Os elementos no banco de dados que não são usados pelo esquema do aplicativo não são modificados. Portanto, após a implantação, seu back-end pode conter esquemas, tabelas e colunas não utilizados.

Os valores de outras chaves neste arquivo são explicados nos comentários abaixo.

# The top-level Firebase SQL Connect YAML file.

# The Firebase SQL Connect API version to target.
# Optional. Defaults to the latest version.
specVersion: string

# The ID of the Firebase SQL Connect service resource.
# Required.
serviceId: string

# The location of the Firebase SQL Connect service.
# Required.
location: string

# Required.
schema:
  # Relative path to the directory for schema definitions.
  # Recursively loads all .gql files in this directory.
  # Required. Typically "./schema" (set by firebase init).
  source: string
  # Datasource connection information.
  # Required.
  datasource:
    # Required.
    postgresql:
      # The name of the PostgreSQL database.
      # Required.
      database: string
      cloudSql:
        # The ID of the Cloud SQL instance resource.
        # Required. For supported PostgreSQL versions, see:
        # https://firebase.google.com/docs/sql-connect/manage-services-and-databases#supported-postgres-versions
        instanceId: string
      # Schema validation mode for schema migrations.
      # Optional. If unspecified, migrations prompt for required compatible
      # changes and then optional strict changes.
      # Set to "STRICT" or "COMPATIBLE".
      schemaValidation: string

# Required.
# Relative paths to directories for connector definitions.
# Recursively loads all .gql files in the listed directories.
# All directories specified MUST contain a connector.yaml file.
connectorDirs: [string]

O arquivo YAML pressupõe uma estrutura de diretório padrão (mas configurável) de:

./(project root)
   /dataconnect
      dataconnect.yaml
      /schema
        *.gql
      /example
        connector.yaml
        *.gql

Referência de configuração do connector.yaml

Use o arquivo connector.yaml para configurar o ID do conector e as opções de geração do SDK.

# The connector-level YAML file.

# Required. The connector name of the Firebase SQL Connect connector resource.
connectorId: string

# Optional. If not specified, no generated libraries (i.e. type-safe SDKs) will
# be generated.
generate:
    # Optional.
    javascriptSdk:
        # Path to the directory that will be updated with the latest generated
        # web TypeScript SDK.
        # Required.
        outputDir: string
        # Name of the Javascript package to be created.
        # Required. Example: @dataconnect/generated
        package: string
        # Path to your package.json directory. If specified, the new generated
        # SDK will be installed in this path.
        # Optional. If not provided, the package will not be auto-installed for
        # you.
        packageJsonDir: string
        # Enable React framework bindings.
        # Optional. Default to false.
        react: Boolean
        # Enable Angular framework bindings.
        # Optional. Default to false.
        angular: Boolean
        # Enable and configure client-side caching for the generated SDK.
        # Optional. If the `clientCache` key is not present, caching is disabled.
        clientCache:
            # The maximum age allowed for cached results before fetching fresh
            # values. A value of "0" means that responses are cached, but the
            # client SDK will always fetch fresh values; the cached values are
            # only used when CACHE_ONLY is specified to executeQuery() and as the
            # initial result returned from subscribe().
            # Examples: "0", "30s", "1h30m"
            # Optional. Default: "0"
            maxAge: string
            # Configures how results are to be cached.
            # Optional. Only "memory" is allowed for JavaScript SDKs.
            storage: string
    # Optional.
    dartSdk:
        # Path to the directory that will be updated with the latest generated
        # Flutter Dart SDK.
        # Required.
        outputDir: string
        # Name of the Dart package to be created.
        # Required. Example: "dataconnect_generated"
        package: string
        # Enable and configure client-side caching for the generated SDK.
        # Optional. If the `clientCache` key is not present, caching is disabled.
        clientCache:
            # The maximum age allowed for cached results before fetching fresh
            # values. A value of "0" means that responses are cached, but the
            # client SDK will always fetch fresh values; the cached values are
            # only used when CACHE_ONLY is specified to execute() and as the
            # initial result returned from subscribe().
            # Examples: "0", "30s", "1h30m"
            # Optional. Default: "0"
            maxAge: string
            # Configures whether results are to be cached in persistent storage
            # or in memory ("persistent" or "memory").
            # Optional.
            # Default: "persistent" for Android and iOS targets, "memory" for web.
            storage: string
    # Optional.
    kotlinSdk:
        # Path to the directory that will be updated with the latest generated
        # Android SDK.
        # Required.
        outputDir: string
        # Name of the package to be created.
        # Required. Example: com.google.firebase.dataconnect.generated
        package: string
        # Enable and configure client-side caching for the generated SDK.
        # Optional. If the `clientCache` key is not present, caching is disabled.
        clientCache:
            # The maximum age allowed for cached results before fetching fresh
            # values. A value of "0" means that responses are cached, but the
            # client SDK will always fetch fresh values; the cached values are
            # only used when CACHE_ONLY is specified to execute().
            # Examples: "0", "30s", "1h30m"
            # Optional. Default: "0"
            maxAge: string
            # Configures whether results are to be cached in persistent storage
            # or in memory ("persistent" or "memory").
            # Optional. Default: persistent
            storage: string
    # Optional.
    adminNodeSdk:
        # Path to the directory that will be updated with the latest generated
        # Node Admin SDK.
        # Required.
        outputDir: string
        # Path to your package.json directory. If specified, the new generated
        # SDK will be installed in this path.
        # Optional. If not provided, the package will not be auto-installed for
        # you.
        packageJsonDir: string
        # Name of the package to be created (for example: @dataconnect/admin-generated).
        # Required.
        package: string
    # Optional.
    swiftSdk:
        # Path to the directory that will be updated with the latest generated
        # iOS Swift SDK.
        # Required.
        outputDir: string
        # Name of the Swift package to be created.
        # Required. Example: "FirebaseDataConnectGenerated"
        package: string
        # Enable and configure client-side caching for the generated SDK.
        # Optional. If the `clientCache` key is not present, caching is disabled.
        clientCache:
            # The maximum age allowed for cached results before fetching fresh
            # values. A value of "0" means that responses are cached, but the
            # client SDK will always fetch fresh values; the cached values are
            # only used when CACHE_ONLY is specified to execute().
            # Examples: "0", "30s", "1h30m"
            # Optional. Default: "0"
            maxAge: string
            # Configures whether results are to be cached in persistent storage
            # or in memory ("persistent" or "memory").
            # Optional. Default: persistent
            storage: string

Variáveis de ambiente do emulador

A CLI Firebase aceita variáveis de ambiente que substituem as configurações do emulador local do SQL Connect definidas no arquivo firebase.json.

  • FIREBASE_DATACONNECT_POSTGRESQL_STRING: opcional. Um URI de conexão do PostgreSQL que usa o esquema postgres:// ou postgresql://, como postgres://USERNAME:PASSWORD@HOST:PORT?sslmode=disable.
    • Precedência: quando definido como um valor não vazio, o emulador se conecta ao servidor PostgreSQL especificado em vez de iniciar a instância integrada do PGlite. As chaves emulators.dataconnect.postgresPort e emulators.dataconnect.dataDir no arquivo firebase.json são ignoradas.
    • Seleção de banco de dados: o emulador usa o campo database em schema.datasource.postgresql no arquivo dataconnect.yaml, substituindo qualquer nome de banco de dados no URI de conexão. Se o campo database for omitido, o emulador vai usar o banco de dados postgres.
    • Snapshots e comportamento de falha: para SQL Connect, a flag --import, a flag --export-on-exit e o comando firebase emulators:export não têm efeito. Outros emuladores ainda importam e exportam normalmente. Se o URI for inválido ou o banco de dados estiver inacessível, a inicialização do emulador vai falhar em vez de voltar para o PGlite.

Para conferir as etapas de configuração, os pré-requisitos de extensão e as vantagens e desvantagens do PGlite, consulte Conectar-se a uma instância personalizada do PostgreSQL.