@@ -227,3 +227,77 @@ func GetAllMapsKeys(maps ...map[string]interface{}) map[string]bool {
227227
228228 return keys
229229}
230+
231+ // DatasourceSchemaFromResourceSchema is a recursive func that
232+ // converts an existing Resource schema to a Datasource schema.
233+ // All schema elements are copied, but certain attributes are ignored or changed:
234+ // - all attributes have Computed = true
235+ // - all attributes have ForceNew, Required = false
236+ // - Validation funcs and attributes (e.g. MaxItems) are not copied
237+ func DatasourceSchemaFromResourceSchema (rs map [string ]* schema.Schema ) map [string ]* schema.Schema {
238+ ds := make (map [string ]* schema.Schema , len (rs ))
239+ for k , v := range rs {
240+ dv := & schema.Schema {
241+ Computed : true ,
242+ ForceNew : false ,
243+ Required : false ,
244+ Description : v .Description ,
245+ Type : v .Type ,
246+ }
247+
248+ switch v .Type {
249+ case schema .TypeSet :
250+ dv .Set = v .Set
251+ fallthrough
252+ case schema .TypeList :
253+ // List & Set types are generally used for 2 cases:
254+ // - a list/set of simple primitive values (e.g. list of strings)
255+ // - a sub resource
256+ if elem , ok := v .Elem .(* schema.Resource ); ok {
257+ // handle the case where the Element is a sub-resource
258+ dv .Elem = & schema.Resource {
259+ Schema : DatasourceSchemaFromResourceSchema (elem .Schema ),
260+ }
261+ } else {
262+ // handle simple primitive case
263+ dv .Elem = v .Elem
264+ }
265+
266+ default :
267+ // Elem of all other types are copied as-is
268+ dv .Elem = v .Elem
269+
270+ }
271+ ds [k ] = dv
272+
273+ }
274+ return ds
275+ }
276+
277+ // fixDatasourceSchemaFlags is a convenience func that toggles the Computed,
278+ // Optional + Required flags on a schema element. This is useful when the schema
279+ // has been generated (using `DatasourceSchemaFromResourceSchema` above for
280+ // example) and therefore the attribute flags were not set appropriately when
281+ // first added to the schema definition. Currently only supports top-level
282+ // schema elements.
283+ func FixDatasourceSchemaFlags (schema map [string ]* schema.Schema , required bool , keys ... string ) {
284+ for _ , v := range keys {
285+ schema [v ].Computed = false
286+ schema [v ].Optional = ! required
287+ schema [v ].Required = required
288+ }
289+ }
290+
291+ func AddRequiredFieldsToSchema (schema map [string ]* schema.Schema , keys ... string ) {
292+ FixDatasourceSchemaFlags (schema , true , keys ... )
293+ }
294+
295+ func AddOptionalFieldsToSchema (schema map [string ]* schema.Schema , keys ... string ) {
296+ FixDatasourceSchemaFlags (schema , false , keys ... )
297+ }
298+
299+ func DeleteFieldsFromSchema (schema map [string ]* schema.Schema , keys ... string ) {
300+ for _ , key := range keys {
301+ delete (schema , key )
302+ }
303+ }
0 commit comments