Hello everyone,
I’m trying to create new scope and collection with following code in c#.
// ... Other codes
bucket.Cluster.QueryAsync<dynamic>($"CREATE SCOPE MyBucket.{scope} IF NOT EXISTS");
//...
but it throwing that exception "syntax error - at IF [3000]"
When I trying without IF NOT EXISTS
, there is no problem, it’s working.
Could you help me related for this?
Where is the problem?
I used the following reference resource for this operation.
CREATE SCOPE | Couchbase Docs
I’m not 100% sure, but looking at the docs I believe IF NOT EXISTS was added in 7.1. It’s not included in the 7.0 docs: CREATE SCOPE | Couchbase Docs
Which server version are you using?
Also, note that recent versions of the SDK include a management API for managing scopes that may be easier to use: Interface ICouchbaseCollectionManager | 3.3.1
Thanks for your help,
I’m updated my code with the following and it’s work for me.
Following codes if a scope or collection isn’t exist, it is creating while on Configure method is working in startup file.
public static async Task CreateCollectionsIfNotExistAsync<T>(this IBucket bucket) where T : BucketContext
{
if (bucket == null)
throw new ArgumentNullException(nameof(bucket));
var props = typeof(T).GetProperties();
var documentSets = props.Where(i => i.PropertyType.Name == "IDocumentSet`1").ToList();
var scopes = (await bucket.Collections.GetAllScopesAsync()).ToList();
var scopeNames = scopes.Select(i => i.Name).ToList();
var collectionNames = scopes.SelectMany(i => i.Collections.Select(x => x.Name)).ToList();
var defaultScope = (await bucket.DefaultScopeAsync()).Name;
foreach (var docSetItem in documentSets)
{
var attrs = docSetItem.GetCustomAttributesData();
var couchbaseCollectionAttr =
attrs.FirstOrDefault(i => i.AttributeType.Name == "CouchbaseCollectionAttribute");
if (couchbaseCollectionAttr == null)
await bucket.Collections.CreateCollectionAsync(new CollectionSpec(defaultScope, docSetItem.Name));
else
{
var attrData = couchbaseCollectionAttr.ConstructorArguments;
var scope = attrData.First().Value?.ToString() ?? defaultScope;
var collection = attrData.Last().Value?.ToString() ?? docSetItem.Name;
if (!scopeNames.Contains(scope))
{
await bucket.Collections.CreateScopeAsync(scope);
scopeNames.Add(scope);
}
if (!collectionNames.Contains(collection))
await bucket.Collections.CreateCollectionAsync(new CollectionSpec(scope, collection));
}
}
}