# Database ## List D1 Databases `client.D1.Database.List(ctx, params) (*V4PagePaginationArray[DatabaseListResponse], error)` **get** `/accounts/{account_id}/d1/database` Returns a list of D1 databases. ### Parameters - `params DatabaseListParams` - `AccountID param.Field[string]` Path param: Account identifier tag. - `Name param.Field[string]` Query param: a database name to search for. - `Page param.Field[float64]` Query param: Page number of paginated results. - `PerPage param.Field[float64]` Query param: Number of items per page. ### Returns - `type DatabaseListResponse struct{…}` - `CreatedAt Time` Specifies the timestamp the resource was created as an ISO8601 string. - `Jurisdiction DatabaseListResponseJurisdiction` Specify the location to restrict the D1 database to run and store data. If this option is present, the location hint is ignored. - `const DatabaseListResponseJurisdictionEu DatabaseListResponseJurisdiction = "eu"` - `const DatabaseListResponseJurisdictionFedramp DatabaseListResponseJurisdiction = "fedramp"` - `Name string` D1 database name. - `UUID string` D1 database identifier (UUID). - `Version string` ### Example ```go package main import ( "context" "fmt" "github.com/cloudflare/cloudflare-go" "github.com/cloudflare/cloudflare-go/d1" "github.com/cloudflare/cloudflare-go/option" ) func main() { client := cloudflare.NewClient( option.WithAPIToken("Sn3lZJTBX6kkg7OdcBUAxOO963GEIyGQqnFTOFYY"), ) page, err := client.D1.Database.List(context.TODO(), d1.DatabaseListParams{ AccountID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"), }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } ``` #### Response ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "result": [ { "created_at": "2022-11-15T18:25:44.442097Z", "jurisdiction": "eu", "name": "my-database", "uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "version": "production" } ], "success": true, "result_info": { "count": 1, "page": 1, "per_page": 20, "total_count": 2000 } } ``` ## Get D1 Database `client.D1.Database.Get(ctx, databaseID, query) (*D1, error)` **get** `/accounts/{account_id}/d1/database/{database_id}` Returns the specified D1 database. ### Parameters - `databaseID string` D1 database identifier (UUID). - `query DatabaseGetParams` - `AccountID param.Field[string]` Account identifier tag. ### Returns - `type D1 struct{…}` The details of the D1 database. - `CreatedAt Time` Specifies the timestamp the resource was created as an ISO8601 string. - `FileSize float64` The D1 database's size, in bytes. - `Jurisdiction D1Jurisdiction` Specify the location to restrict the D1 database to run and store data. If this option is present, the location hint is ignored. - `const D1JurisdictionEu D1Jurisdiction = "eu"` - `const D1JurisdictionFedramp D1Jurisdiction = "fedramp"` - `Name string` D1 database name. - `NumTables float64` - `ReadReplication D1ReadReplication` Configuration for D1 read replication. - `Mode D1ReadReplicationMode` The read replication mode for the database. Use 'auto' to create replicas and allow D1 automatically place them around the world, or 'disabled' to not use any database replicas (it can take a few hours for all replicas to be deleted). - `const D1ReadReplicationModeAuto D1ReadReplicationMode = "auto"` - `const D1ReadReplicationModeDisabled D1ReadReplicationMode = "disabled"` - `UUID string` D1 database identifier (UUID). - `Version string` ### Example ```go package main import ( "context" "fmt" "github.com/cloudflare/cloudflare-go" "github.com/cloudflare/cloudflare-go/d1" "github.com/cloudflare/cloudflare-go/option" ) func main() { client := cloudflare.NewClient( option.WithAPIToken("Sn3lZJTBX6kkg7OdcBUAxOO963GEIyGQqnFTOFYY"), ) d1, err := client.D1.Database.Get( context.TODO(), "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", d1.DatabaseGetParams{ AccountID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"), }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", d1.UUID) } ``` #### Response ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "result": { "created_at": "2022-11-15T18:25:44.442097Z", "file_size": 12, "jurisdiction": "eu", "name": "my-database", "num_tables": 12, "read_replication": { "mode": "auto" }, "uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "version": "production" }, "success": true } ``` ## Create D1 Database `client.D1.Database.New(ctx, params) (*D1, error)` **post** `/accounts/{account_id}/d1/database` Returns the created D1 database. ### Parameters - `params DatabaseNewParams` - `AccountID param.Field[string]` Path param: Account identifier tag. - `Name param.Field[string]` Body param: D1 database name. - `Jurisdiction param.Field[DatabaseNewParamsJurisdiction]` Body param: Specify the location to restrict the D1 database to run and store data. If this option is present, the location hint is ignored. - `const DatabaseNewParamsJurisdictionEu DatabaseNewParamsJurisdiction = "eu"` - `const DatabaseNewParamsJurisdictionFedramp DatabaseNewParamsJurisdiction = "fedramp"` - `PrimaryLocationHint param.Field[DatabaseNewParamsPrimaryLocationHint]` Body param: Specify the region to create the D1 primary, if available. If this option is omitted, the D1 will be created as close as possible to the current user. - `const DatabaseNewParamsPrimaryLocationHintWnam DatabaseNewParamsPrimaryLocationHint = "wnam"` - `const DatabaseNewParamsPrimaryLocationHintEnam DatabaseNewParamsPrimaryLocationHint = "enam"` - `const DatabaseNewParamsPrimaryLocationHintWeur DatabaseNewParamsPrimaryLocationHint = "weur"` - `const DatabaseNewParamsPrimaryLocationHintEeur DatabaseNewParamsPrimaryLocationHint = "eeur"` - `const DatabaseNewParamsPrimaryLocationHintApac DatabaseNewParamsPrimaryLocationHint = "apac"` - `const DatabaseNewParamsPrimaryLocationHintOc DatabaseNewParamsPrimaryLocationHint = "oc"` ### Returns - `type D1 struct{…}` The details of the D1 database. - `CreatedAt Time` Specifies the timestamp the resource was created as an ISO8601 string. - `FileSize float64` The D1 database's size, in bytes. - `Jurisdiction D1Jurisdiction` Specify the location to restrict the D1 database to run and store data. If this option is present, the location hint is ignored. - `const D1JurisdictionEu D1Jurisdiction = "eu"` - `const D1JurisdictionFedramp D1Jurisdiction = "fedramp"` - `Name string` D1 database name. - `NumTables float64` - `ReadReplication D1ReadReplication` Configuration for D1 read replication. - `Mode D1ReadReplicationMode` The read replication mode for the database. Use 'auto' to create replicas and allow D1 automatically place them around the world, or 'disabled' to not use any database replicas (it can take a few hours for all replicas to be deleted). - `const D1ReadReplicationModeAuto D1ReadReplicationMode = "auto"` - `const D1ReadReplicationModeDisabled D1ReadReplicationMode = "disabled"` - `UUID string` D1 database identifier (UUID). - `Version string` ### Example ```go package main import ( "context" "fmt" "github.com/cloudflare/cloudflare-go" "github.com/cloudflare/cloudflare-go/d1" "github.com/cloudflare/cloudflare-go/option" ) func main() { client := cloudflare.NewClient( option.WithAPIToken("Sn3lZJTBX6kkg7OdcBUAxOO963GEIyGQqnFTOFYY"), ) d1, err := client.D1.Database.New(context.TODO(), d1.DatabaseNewParams{ AccountID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"), Name: cloudflare.F("my-database"), }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", d1.UUID) } ``` #### Response ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "result": { "created_at": "2022-11-15T18:25:44.442097Z", "file_size": 12, "jurisdiction": "eu", "name": "my-database", "num_tables": 12, "read_replication": { "mode": "auto" }, "uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "version": "production" }, "success": true } ``` ## Update D1 Database `client.D1.Database.Update(ctx, databaseID, params) (*D1, error)` **put** `/accounts/{account_id}/d1/database/{database_id}` Updates the specified D1 database. ### Parameters - `databaseID string` D1 database identifier (UUID). - `params DatabaseUpdateParams` - `AccountID param.Field[string]` Path param: Account identifier tag. - `ReadReplication param.Field[DatabaseUpdateParamsReadReplication]` Body param: Configuration for D1 read replication. - `Mode DatabaseUpdateParamsReadReplicationMode` The read replication mode for the database. Use 'auto' to create replicas and allow D1 automatically place them around the world, or 'disabled' to not use any database replicas (it can take a few hours for all replicas to be deleted). - `const DatabaseUpdateParamsReadReplicationModeAuto DatabaseUpdateParamsReadReplicationMode = "auto"` - `const DatabaseUpdateParamsReadReplicationModeDisabled DatabaseUpdateParamsReadReplicationMode = "disabled"` ### Returns - `type D1 struct{…}` The details of the D1 database. - `CreatedAt Time` Specifies the timestamp the resource was created as an ISO8601 string. - `FileSize float64` The D1 database's size, in bytes. - `Jurisdiction D1Jurisdiction` Specify the location to restrict the D1 database to run and store data. If this option is present, the location hint is ignored. - `const D1JurisdictionEu D1Jurisdiction = "eu"` - `const D1JurisdictionFedramp D1Jurisdiction = "fedramp"` - `Name string` D1 database name. - `NumTables float64` - `ReadReplication D1ReadReplication` Configuration for D1 read replication. - `Mode D1ReadReplicationMode` The read replication mode for the database. Use 'auto' to create replicas and allow D1 automatically place them around the world, or 'disabled' to not use any database replicas (it can take a few hours for all replicas to be deleted). - `const D1ReadReplicationModeAuto D1ReadReplicationMode = "auto"` - `const D1ReadReplicationModeDisabled D1ReadReplicationMode = "disabled"` - `UUID string` D1 database identifier (UUID). - `Version string` ### Example ```go package main import ( "context" "fmt" "github.com/cloudflare/cloudflare-go" "github.com/cloudflare/cloudflare-go/d1" "github.com/cloudflare/cloudflare-go/option" ) func main() { client := cloudflare.NewClient( option.WithAPIToken("Sn3lZJTBX6kkg7OdcBUAxOO963GEIyGQqnFTOFYY"), ) d1, err := client.D1.Database.Update( context.TODO(), "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", d1.DatabaseUpdateParams{ AccountID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"), ReadReplication: cloudflare.F(d1.DatabaseUpdateParamsReadReplication{ Mode: cloudflare.F(d1.DatabaseUpdateParamsReadReplicationModeAuto), }), }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", d1.UUID) } ``` #### Response ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "result": { "created_at": "2022-11-15T18:25:44.442097Z", "file_size": 12, "jurisdiction": "eu", "name": "my-database", "num_tables": 12, "read_replication": { "mode": "auto" }, "uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "version": "production" }, "success": true } ``` ## Update D1 Database partially `client.D1.Database.Edit(ctx, databaseID, params) (*D1, error)` **patch** `/accounts/{account_id}/d1/database/{database_id}` Updates partially the specified D1 database. ### Parameters - `databaseID string` D1 database identifier (UUID). - `params DatabaseEditParams` - `AccountID param.Field[string]` Path param: Account identifier tag. - `ReadReplication param.Field[DatabaseEditParamsReadReplication]` Body param: Configuration for D1 read replication. - `Mode DatabaseEditParamsReadReplicationMode` The read replication mode for the database. Use 'auto' to create replicas and allow D1 automatically place them around the world, or 'disabled' to not use any database replicas (it can take a few hours for all replicas to be deleted). - `const DatabaseEditParamsReadReplicationModeAuto DatabaseEditParamsReadReplicationMode = "auto"` - `const DatabaseEditParamsReadReplicationModeDisabled DatabaseEditParamsReadReplicationMode = "disabled"` ### Returns - `type D1 struct{…}` The details of the D1 database. - `CreatedAt Time` Specifies the timestamp the resource was created as an ISO8601 string. - `FileSize float64` The D1 database's size, in bytes. - `Jurisdiction D1Jurisdiction` Specify the location to restrict the D1 database to run and store data. If this option is present, the location hint is ignored. - `const D1JurisdictionEu D1Jurisdiction = "eu"` - `const D1JurisdictionFedramp D1Jurisdiction = "fedramp"` - `Name string` D1 database name. - `NumTables float64` - `ReadReplication D1ReadReplication` Configuration for D1 read replication. - `Mode D1ReadReplicationMode` The read replication mode for the database. Use 'auto' to create replicas and allow D1 automatically place them around the world, or 'disabled' to not use any database replicas (it can take a few hours for all replicas to be deleted). - `const D1ReadReplicationModeAuto D1ReadReplicationMode = "auto"` - `const D1ReadReplicationModeDisabled D1ReadReplicationMode = "disabled"` - `UUID string` D1 database identifier (UUID). - `Version string` ### Example ```go package main import ( "context" "fmt" "github.com/cloudflare/cloudflare-go" "github.com/cloudflare/cloudflare-go/d1" "github.com/cloudflare/cloudflare-go/option" ) func main() { client := cloudflare.NewClient( option.WithAPIToken("Sn3lZJTBX6kkg7OdcBUAxOO963GEIyGQqnFTOFYY"), ) d1, err := client.D1.Database.Edit( context.TODO(), "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", d1.DatabaseEditParams{ AccountID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"), }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", d1.UUID) } ``` #### Response ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "result": { "created_at": "2022-11-15T18:25:44.442097Z", "file_size": 12, "jurisdiction": "eu", "name": "my-database", "num_tables": 12, "read_replication": { "mode": "auto" }, "uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "version": "production" }, "success": true } ``` ## Delete D1 Database `client.D1.Database.Delete(ctx, databaseID, body) (*DatabaseDeleteResponse, error)` **delete** `/accounts/{account_id}/d1/database/{database_id}` Deletes the specified D1 database. ### Parameters - `databaseID string` D1 database identifier (UUID). - `body DatabaseDeleteParams` - `AccountID param.Field[string]` Account identifier tag. ### Returns - `type DatabaseDeleteResponse interface{…}` ### Example ```go package main import ( "context" "fmt" "github.com/cloudflare/cloudflare-go" "github.com/cloudflare/cloudflare-go/d1" "github.com/cloudflare/cloudflare-go/option" ) func main() { client := cloudflare.NewClient( option.WithAPIToken("Sn3lZJTBX6kkg7OdcBUAxOO963GEIyGQqnFTOFYY"), ) database, err := client.D1.Database.Delete( context.TODO(), "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", d1.DatabaseDeleteParams{ AccountID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"), }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", database) } ``` #### Response ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "result": {}, "success": true } ``` ## Query D1 Database `client.D1.Database.Query(ctx, databaseID, params) (*SinglePage[QueryResult], error)` **post** `/accounts/{account_id}/d1/database/{database_id}/query` Returns the query result as an object. ### Parameters - `databaseID string` D1 database identifier (UUID). - `params DatabaseQueryParams` - `AccountID param.Field[string]` Path param: Account identifier tag. - `Sql param.Field[string]` Body param: Your SQL query. Supports multiple statements, joined by semicolons, which will be executed as a batch. - `Params param.Field[[]string]` Body param ### Returns - `type QueryResult struct{…}` - `Meta QueryResultMeta` - `ChangedDB bool` Denotes if the database has been altered in some way, like deleting rows. - `Changes float64` Rough indication of how many rows were modified by the query, as provided by SQLite's `sqlite3_total_changes()`. - `Duration float64` The duration of the SQL query execution inside the database. Does not include any network communication. - `LastRowID float64` The row ID of the last inserted row in a table with an `INTEGER PRIMARY KEY` as provided by SQLite. Tables created with `WITHOUT ROWID` do not populate this. - `RowsRead float64` Number of rows read during the SQL query execution, including indices (not all rows are necessarily returned). - `RowsWritten float64` Number of rows written during the SQL query execution, including indices. - `ServedByColo string` The three letters airport code of the colo that handled the query. - `ServedByPrimary bool` Denotes if the query has been handled by the database primary instance. - `ServedByRegion QueryResultMetaServedByRegion` Region location hint of the database instance that handled the query. - `const QueryResultMetaServedByRegionWnam QueryResultMetaServedByRegion = "WNAM"` - `const QueryResultMetaServedByRegionEnam QueryResultMetaServedByRegion = "ENAM"` - `const QueryResultMetaServedByRegionWeur QueryResultMetaServedByRegion = "WEUR"` - `const QueryResultMetaServedByRegionEeur QueryResultMetaServedByRegion = "EEUR"` - `const QueryResultMetaServedByRegionApac QueryResultMetaServedByRegion = "APAC"` - `const QueryResultMetaServedByRegionOc QueryResultMetaServedByRegion = "OC"` - `SizeAfter float64` Size of the database after the query committed, in bytes. - `Timings QueryResultMetaTimings` Various durations for the query. - `SqlDurationMs float64` The duration of the SQL query execution inside the database. Does not include any network communication. - `Results []unknown` - `Success bool` ### Example ```go package main import ( "context" "fmt" "github.com/cloudflare/cloudflare-go" "github.com/cloudflare/cloudflare-go/d1" "github.com/cloudflare/cloudflare-go/option" ) func main() { client := cloudflare.NewClient( option.WithAPIToken("Sn3lZJTBX6kkg7OdcBUAxOO963GEIyGQqnFTOFYY"), ) page, err := client.D1.Database.Query( context.TODO(), "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", d1.DatabaseQueryParams{ AccountID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"), Body: d1.DatabaseQueryParamsBodyD1SingleQuery{ Sql: cloudflare.F("SELECT * FROM myTable WHERE field = ? OR field = ?;"), }, }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } ``` #### Response ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "result": [ { "meta": { "changed_db": true, "changes": 0, "duration": 0, "last_row_id": 0, "rows_read": 0, "rows_written": 0, "served_by_colo": "LHR", "served_by_primary": true, "served_by_region": "EEUR", "size_after": 0, "timings": { "sql_duration_ms": 0 } }, "results": [ {} ], "success": true } ], "success": true } ``` ## Raw D1 Database query `client.D1.Database.Raw(ctx, databaseID, params) (*SinglePage[DatabaseRawResponse], error)` **post** `/accounts/{account_id}/d1/database/{database_id}/raw` Returns the query result rows as arrays rather than objects. This is a performance-optimized version of the /query endpoint. ### Parameters - `databaseID string` D1 database identifier (UUID). - `params DatabaseRawParams` - `AccountID param.Field[string]` Path param: Account identifier tag. - `Sql param.Field[string]` Body param: Your SQL query. Supports multiple statements, joined by semicolons, which will be executed as a batch. - `Params param.Field[[]string]` Body param ### Returns - `type DatabaseRawResponse struct{…}` - `Meta DatabaseRawResponseMeta` - `ChangedDB bool` Denotes if the database has been altered in some way, like deleting rows. - `Changes float64` Rough indication of how many rows were modified by the query, as provided by SQLite's `sqlite3_total_changes()`. - `Duration float64` The duration of the SQL query execution inside the database. Does not include any network communication. - `LastRowID float64` The row ID of the last inserted row in a table with an `INTEGER PRIMARY KEY` as provided by SQLite. Tables created with `WITHOUT ROWID` do not populate this. - `RowsRead float64` Number of rows read during the SQL query execution, including indices (not all rows are necessarily returned). - `RowsWritten float64` Number of rows written during the SQL query execution, including indices. - `ServedByColo string` The three letters airport code of the colo that handled the query. - `ServedByPrimary bool` Denotes if the query has been handled by the database primary instance. - `ServedByRegion DatabaseRawResponseMetaServedByRegion` Region location hint of the database instance that handled the query. - `const DatabaseRawResponseMetaServedByRegionWnam DatabaseRawResponseMetaServedByRegion = "WNAM"` - `const DatabaseRawResponseMetaServedByRegionEnam DatabaseRawResponseMetaServedByRegion = "ENAM"` - `const DatabaseRawResponseMetaServedByRegionWeur DatabaseRawResponseMetaServedByRegion = "WEUR"` - `const DatabaseRawResponseMetaServedByRegionEeur DatabaseRawResponseMetaServedByRegion = "EEUR"` - `const DatabaseRawResponseMetaServedByRegionApac DatabaseRawResponseMetaServedByRegion = "APAC"` - `const DatabaseRawResponseMetaServedByRegionOc DatabaseRawResponseMetaServedByRegion = "OC"` - `SizeAfter float64` Size of the database after the query committed, in bytes. - `Timings DatabaseRawResponseMetaTimings` Various durations for the query. - `SqlDurationMs float64` The duration of the SQL query execution inside the database. Does not include any network communication. - `Results DatabaseRawResponseResults` - `Columns []string` - `Rows [][]unknown` - `unknown` - `Success bool` ### Example ```go package main import ( "context" "fmt" "github.com/cloudflare/cloudflare-go" "github.com/cloudflare/cloudflare-go/d1" "github.com/cloudflare/cloudflare-go/option" ) func main() { client := cloudflare.NewClient( option.WithAPIToken("Sn3lZJTBX6kkg7OdcBUAxOO963GEIyGQqnFTOFYY"), ) page, err := client.D1.Database.Raw( context.TODO(), "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", d1.DatabaseRawParams{ AccountID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"), Body: d1.DatabaseRawParamsBodyD1SingleQuery{ Sql: cloudflare.F("SELECT * FROM myTable WHERE field = ? OR field = ?;"), }, }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", page) } ``` #### Response ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "result": [ { "meta": { "changed_db": true, "changes": 0, "duration": 0, "last_row_id": 0, "rows_read": 0, "rows_written": 0, "served_by_colo": "LHR", "served_by_primary": true, "served_by_region": "EEUR", "size_after": 0, "timings": { "sql_duration_ms": 0 } }, "results": { "columns": [ "string" ], "rows": [ [ 0 ] ] }, "success": true } ], "success": true } ``` ## Export D1 Database as SQL `client.D1.Database.Export(ctx, databaseID, params) (*DatabaseExportResponse, error)` **post** `/accounts/{account_id}/d1/database/{database_id}/export` Returns a URL where the SQL contents of your D1 can be downloaded. Note: this process may take some time for larger DBs, during which your D1 will be unavailable to serve queries. To avoid blocking your DB unnecessarily, an in-progress export must be continually polled or will automatically cancel. ### Parameters - `databaseID string` D1 database identifier (UUID). - `params DatabaseExportParams` - `AccountID param.Field[string]` Path param: Account identifier tag. - `OutputFormat param.Field[DatabaseExportParamsOutputFormat]` Body param: Specifies that you will poll this endpoint until the export completes - `const DatabaseExportParamsOutputFormatPolling DatabaseExportParamsOutputFormat = "polling"` - `CurrentBookmark param.Field[string]` Body param: To poll an in-progress export, provide the current bookmark (returned by your first polling response) - `DumpOptions param.Field[DatabaseExportParamsDumpOptions]` Body param - `NoData bool` Export only the table definitions, not their contents - `NoSchema bool` Export only each table's contents, not its definition - `Tables []string` Filter the export to just one or more tables. Passing an empty array is the same as not passing anything and means: export all tables. ### Returns - `type DatabaseExportResponse struct{…}` - `AtBookmark string` The current time-travel bookmark for your D1, used to poll for updates. Will not change for the duration of the export task. - `Error string` Only present when status = 'error'. Contains the error message. - `Messages []string` Logs since the last time you polled - `Result DatabaseExportResponseResult` Only present when status = 'complete' - `Filename string` The generated SQL filename. - `SignedURL string` The URL to download the exported SQL. Available for one hour. - `Status DatabaseExportResponseStatus` - `const DatabaseExportResponseStatusComplete DatabaseExportResponseStatus = "complete"` - `const DatabaseExportResponseStatusError DatabaseExportResponseStatus = "error"` - `Success bool` - `Type DatabaseExportResponseType` - `const DatabaseExportResponseTypeExport DatabaseExportResponseType = "export"` ### Example ```go package main import ( "context" "fmt" "github.com/cloudflare/cloudflare-go" "github.com/cloudflare/cloudflare-go/d1" "github.com/cloudflare/cloudflare-go/option" ) func main() { client := cloudflare.NewClient( option.WithAPIToken("Sn3lZJTBX6kkg7OdcBUAxOO963GEIyGQqnFTOFYY"), ) response, err := client.D1.Database.Export( context.TODO(), "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", d1.DatabaseExportParams{ AccountID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"), OutputFormat: cloudflare.F(d1.DatabaseExportParamsOutputFormatPolling), }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.AtBookmark) } ``` #### Response ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "result": { "at_bookmark": "at_bookmark", "error": "error", "messages": [ "string" ], "result": { "filename": "filename", "signed_url": "signed_url" }, "status": "complete", "success": true, "type": "export" }, "success": true } ``` ## Import SQL into your D1 Database `client.D1.Database.Import(ctx, databaseID, params) (*DatabaseImportResponse, error)` **post** `/accounts/{account_id}/d1/database/{database_id}/import` Generates a temporary URL for uploading an SQL file to, then instructing the D1 to import it and polling it for status updates. Imports block the D1 for their duration. ### Parameters - `databaseID string` D1 database identifier (UUID). - `params DatabaseImportParams` - `AccountID param.Field[string]` Path param: Account identifier tag. - `Action param.Field[DatabaseImportParamsInitAction]` Body param: Indicates you have a new SQL file to upload. - `const DatabaseImportParamsInitActionInit DatabaseImportParamsInitAction = "init"` - `Etag param.Field[string]` Body param: Required when action is 'init' or 'ingest'. An md5 hash of the file you're uploading. Used to check if it already exists, and validate its contents before ingesting. ### Returns - `type DatabaseImportResponse struct{…}` - `AtBookmark string` The current time-travel bookmark for your D1, used to poll for updates. Will not change for the duration of the import. Only returned if an import process is currently running or recently finished. - `Error string` Only present when status = 'error'. Contains the error message that prevented the import from succeeding. - `Filename string` Derived from the database ID and etag, to use in avoiding repeated uploads. Only returned when for the 'init' action. - `Messages []string` Logs since the last time you polled - `Result DatabaseImportResponseResult` Only present when status = 'complete' - `FinalBookmark string` The time-travel bookmark if you need restore your D1 to directly after the import succeeded. - `Meta DatabaseImportResponseResultMeta` - `ChangedDB bool` Denotes if the database has been altered in some way, like deleting rows. - `Changes float64` Rough indication of how many rows were modified by the query, as provided by SQLite's `sqlite3_total_changes()`. - `Duration float64` The duration of the SQL query execution inside the database. Does not include any network communication. - `LastRowID float64` The row ID of the last inserted row in a table with an `INTEGER PRIMARY KEY` as provided by SQLite. Tables created with `WITHOUT ROWID` do not populate this. - `RowsRead float64` Number of rows read during the SQL query execution, including indices (not all rows are necessarily returned). - `RowsWritten float64` Number of rows written during the SQL query execution, including indices. - `ServedByColo string` The three letters airport code of the colo that handled the query. - `ServedByPrimary bool` Denotes if the query has been handled by the database primary instance. - `ServedByRegion DatabaseImportResponseResultMetaServedByRegion` Region location hint of the database instance that handled the query. - `const DatabaseImportResponseResultMetaServedByRegionWnam DatabaseImportResponseResultMetaServedByRegion = "WNAM"` - `const DatabaseImportResponseResultMetaServedByRegionEnam DatabaseImportResponseResultMetaServedByRegion = "ENAM"` - `const DatabaseImportResponseResultMetaServedByRegionWeur DatabaseImportResponseResultMetaServedByRegion = "WEUR"` - `const DatabaseImportResponseResultMetaServedByRegionEeur DatabaseImportResponseResultMetaServedByRegion = "EEUR"` - `const DatabaseImportResponseResultMetaServedByRegionApac DatabaseImportResponseResultMetaServedByRegion = "APAC"` - `const DatabaseImportResponseResultMetaServedByRegionOc DatabaseImportResponseResultMetaServedByRegion = "OC"` - `SizeAfter float64` Size of the database after the query committed, in bytes. - `Timings DatabaseImportResponseResultMetaTimings` Various durations for the query. - `SqlDurationMs float64` The duration of the SQL query execution inside the database. Does not include any network communication. - `NumQueries float64` The total number of queries that were executed during the import. - `Status DatabaseImportResponseStatus` - `const DatabaseImportResponseStatusComplete DatabaseImportResponseStatus = "complete"` - `const DatabaseImportResponseStatusError DatabaseImportResponseStatus = "error"` - `Success bool` - `Type DatabaseImportResponseType` - `const DatabaseImportResponseTypeImport DatabaseImportResponseType = "import"` - `UploadURL string` The R2 presigned URL to use for uploading. Only returned when for the 'init' action. ### Example ```go package main import ( "context" "fmt" "github.com/cloudflare/cloudflare-go" "github.com/cloudflare/cloudflare-go/d1" "github.com/cloudflare/cloudflare-go/option" ) func main() { client := cloudflare.NewClient( option.WithAPIToken("Sn3lZJTBX6kkg7OdcBUAxOO963GEIyGQqnFTOFYY"), ) response, err := client.D1.Database.Import( context.TODO(), "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", d1.DatabaseImportParams{ AccountID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"), Body: d1.DatabaseImportParamsBodyInit{ Action: cloudflare.F(d1.DatabaseImportParamsBodyInitActionInit), Etag: cloudflare.F("etag"), }, }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.AtBookmark) } ``` #### Response ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "result": { "at_bookmark": "at_bookmark", "error": "error", "filename": "filename", "messages": [ "string" ], "result": { "final_bookmark": "final_bookmark", "meta": { "changed_db": true, "changes": 0, "duration": 0, "last_row_id": 0, "rows_read": 0, "rows_written": 0, "served_by_colo": "LHR", "served_by_primary": true, "served_by_region": "EEUR", "size_after": 0, "timings": { "sql_duration_ms": 0 } }, "num_queries": 0 }, "status": "complete", "success": true, "type": "import", "upload_url": "upload_url" }, "success": true } ``` ## Domain Types ### Query Result - `type QueryResult struct{…}` - `Meta QueryResultMeta` - `ChangedDB bool` Denotes if the database has been altered in some way, like deleting rows. - `Changes float64` Rough indication of how many rows were modified by the query, as provided by SQLite's `sqlite3_total_changes()`. - `Duration float64` The duration of the SQL query execution inside the database. Does not include any network communication. - `LastRowID float64` The row ID of the last inserted row in a table with an `INTEGER PRIMARY KEY` as provided by SQLite. Tables created with `WITHOUT ROWID` do not populate this. - `RowsRead float64` Number of rows read during the SQL query execution, including indices (not all rows are necessarily returned). - `RowsWritten float64` Number of rows written during the SQL query execution, including indices. - `ServedByColo string` The three letters airport code of the colo that handled the query. - `ServedByPrimary bool` Denotes if the query has been handled by the database primary instance. - `ServedByRegion QueryResultMetaServedByRegion` Region location hint of the database instance that handled the query. - `const QueryResultMetaServedByRegionWnam QueryResultMetaServedByRegion = "WNAM"` - `const QueryResultMetaServedByRegionEnam QueryResultMetaServedByRegion = "ENAM"` - `const QueryResultMetaServedByRegionWeur QueryResultMetaServedByRegion = "WEUR"` - `const QueryResultMetaServedByRegionEeur QueryResultMetaServedByRegion = "EEUR"` - `const QueryResultMetaServedByRegionApac QueryResultMetaServedByRegion = "APAC"` - `const QueryResultMetaServedByRegionOc QueryResultMetaServedByRegion = "OC"` - `SizeAfter float64` Size of the database after the query committed, in bytes. - `Timings QueryResultMetaTimings` Various durations for the query. - `SqlDurationMs float64` The duration of the SQL query execution inside the database. Does not include any network communication. - `Results []unknown` - `Success bool` # Time Travel ## Get D1 database bookmark `client.D1.Database.TimeTravel.GetBookmark(ctx, databaseID, params) (*DatabaseTimeTravelGetBookmarkResponse, error)` **get** `/accounts/{account_id}/d1/database/{database_id}/time_travel/bookmark` Retrieves the current bookmark, or the nearest bookmark at or before a provided timestamp. Bookmarks can be used with the restore endpoint to revert the database to a previous point in time. ### Parameters - `databaseID string` D1 database identifier (UUID). - `params DatabaseTimeTravelGetBookmarkParams` - `AccountID param.Field[string]` Path param: Account identifier tag. - `Timestamp param.Field[Time]` Query param: An optional ISO 8601 timestamp. If provided, returns the nearest available bookmark at or before this timestamp. If omitted, returns the current bookmark. ### Returns - `type DatabaseTimeTravelGetBookmarkResponse struct{…}` - `Bookmark string` A bookmark representing a specific state of the database at a specific point in time. ### Example ```go package main import ( "context" "fmt" "github.com/cloudflare/cloudflare-go" "github.com/cloudflare/cloudflare-go/d1" "github.com/cloudflare/cloudflare-go/option" ) func main() { client := cloudflare.NewClient( option.WithAPIToken("Sn3lZJTBX6kkg7OdcBUAxOO963GEIyGQqnFTOFYY"), ) response, err := client.D1.Database.TimeTravel.GetBookmark( context.TODO(), "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", d1.DatabaseTimeTravelGetBookmarkParams{ AccountID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"), }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.Bookmark) } ``` #### Response ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "result": { "bookmark": "00000001-00000002-00004e2f-0a83ea2fceebc654de0640c422be4653" }, "success": true } ``` ## Restore D1 Database to a bookmark or point in time `client.D1.Database.TimeTravel.Restore(ctx, databaseID, params) (*DatabaseTimeTravelRestoreResponse, error)` **post** `/accounts/{account_id}/d1/database/{database_id}/time_travel/restore` Restores a D1 database to a previous point in time either via a bookmark or a timestamp. ### Parameters - `databaseID string` D1 database identifier (UUID). - `params DatabaseTimeTravelRestoreParams` - `AccountID param.Field[string]` Path param: Account identifier tag. - `Bookmark param.Field[string]` Query param: A bookmark to restore the database to. Required if `timestamp` is not provided. - `Timestamp param.Field[Time]` Query param: An ISO 8601 timestamp to restore the database to. Required if `bookmark` is not provided. ### Returns - `type DatabaseTimeTravelRestoreResponse struct{…}` Response from a time travel restore operation. - `Bookmark string` The new bookmark representing the state of the database after the restore operation. - `Message string` A message describing the result of the restore operation. - `PreviousBookmark string` The bookmark representing the state of the database before the restore operation. Can be used to undo the restore if needed. ### Example ```go package main import ( "context" "fmt" "github.com/cloudflare/cloudflare-go" "github.com/cloudflare/cloudflare-go/d1" "github.com/cloudflare/cloudflare-go/option" ) func main() { client := cloudflare.NewClient( option.WithAPIToken("Sn3lZJTBX6kkg7OdcBUAxOO963GEIyGQqnFTOFYY"), ) response, err := client.D1.Database.TimeTravel.Restore( context.TODO(), "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", d1.DatabaseTimeTravelRestoreParams{ AccountID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"), }, ) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.Bookmark) } ``` #### Response ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "result": { "bookmark": "00000001-00000002-00004e2f-0a83ea2fceebc654de0640c422be4653", "message": "Database restored successfully", "previous_bookmark": "00000001-00000002-00004e2f-0a83ea2fceebc654de0640c422be4653" }, "success": true } ```