从谷歌云存储导入csv自动导入谷歌云

时间:2016-08-18 05:38:05

标签: javascript google-apps-script google-cloud-storage google-cloud-sql

我想将谷歌云存储中的csv文件导入谷歌云sql,为此我使用以下查询。当我在应用程序脚本中执行查询时,我遇到以下错误 * getservice()未定义 参数----参数(219473067) 服务----未定义 令牌----未定义 结果-----未定义 我-----未定义 ˚F----未定义 路径-----未定义 有效载荷-----未定义

我使用的java脚本是

function uploadtoCloudSQL() {

var service = getService();

  if (!service.hasAccess()) {
    Logger.log(service.getAuthorizationUrl());
    return;
  }

  var token = service.getAccessToken();

  // Getting list of files to be processed

var result = JSON.parse(
    UrlFetchApp.fetch('https://www.googleapis.com/storage/v1/b/test/o', {
      method: "GET",
      headers: {
        Authorization: 'Bearer ' + token
      }
    }).getContentText());

 for (var i = 0; i < result.items.length; i++) {
    if (result.items[i].name.indexOf(".") !== -1) {
      files.push(result.items[i].name);
    }
  }

  for (var f = 0; f < files.length; f++) {

    var path = files[f].split("/");

    var payload =
      '{"importContext" : { "csvImportOptions": {"table":"test_table"}, "fileType": "CSV", "database": "nmp", "uri": "gs://revealer_test/data/Sample_data.csv"}}'
      .replace("data", path[0])
      .replace("Sample_data.csv", path[1]);

    UrlFetchApp.fetch('https://www.googleapis.com/sql/v1beta4/projects/PROJECT/instances/INSTANCE/import', {
      method: "POST",
      contentType: "application/json",
      headers: {
        Authorization: 'Bearer ' + token
      },
      payload: payload,
      muteHttpExceptions: true
    });

    UrlFetchApp.fetch('https://www.googleapis.com/storage/v1/b/test/o/' + encodeURIComponent(files[f]), {
      method: "DELETE",
      headers: {
        Authorization: 'Bearer ' + token
      }
    });

    // Wait for the previous import job to end
    Utilities.sleep(5000);

  }

}

请帮我纠正错误.. 谢谢

1 个答案:

答案 0 :(得分:0)

Wrt Cloud SQL部分,您是否在googleapis网址中使用了正确的项目名称和实例名称?

我看到https://www.googleapis.com/sql/v1beta4/projects/PROJECT/instances/INSTANCE/import。您应该用自己的值替换PROJECT和INSTANCE。